mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-19 16:20:01 -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:
7
launcher/.gitignore
vendored
Normal file
7
launcher/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
bin/
|
||||
obj/
|
||||
out/
|
||||
# never: anything decoded from a game (the launcher reads it at run time)
|
||||
ui/audio/
|
||||
ui/img/game/
|
||||
ui/img/save*.jpg
|
||||
194
launcher/App/Backend.Bench.cs
Normal file
194
launcher/App/Backend.Bench.cs
Normal file
@@ -0,0 +1,194 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>Settings > Find my best settings. The game runs its own benchmark mode (it loads the newest save by itself, flies
|
||||
/// through four scenes with its panel on screen, writes its results and quits: Triforce.Logic.Benchmark.RunOnceAsync); the
|
||||
/// launcher says beforehand what will happen, shows that it is running, then the results and what to change. "Compare with
|
||||
/// DLSS" (or FSR 3.1) is a second run on request, not a hidden one.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
CancellationTokenSource? benchCts;
|
||||
BenchRun? benchRun, benchRun2;
|
||||
(int upscaler, string name)? benchSecond;
|
||||
IReadOnlyList<SettingChange>? benchRecs;
|
||||
string? benchLast;
|
||||
|
||||
void RegisterBench()
|
||||
{
|
||||
On("bench", _ => BenchAsk());
|
||||
OnAsync("bench.go", m => (string?)m["id"] == "go" ? RunBench(compare: false) : Task.CompletedTask);
|
||||
OnAsync("bench.compare", _ => RunBench(compare: true));
|
||||
On("benchstop", _ => { try { benchCts?.Cancel(); } catch { } });
|
||||
On("benchapply", _ => ApplyBench());
|
||||
new Benchmark(ctx).RestoreIfLeft(); // (a run cut off last time: the player's options back first)
|
||||
}
|
||||
|
||||
/// <summary>The benchmark card's state for the Settings page.</summary>
|
||||
JsonObject BenchState()
|
||||
{
|
||||
var g = GameDir;
|
||||
var exe = g != null ? new Game(ctx).FindExe(g) : null;
|
||||
var ready = exe != null && new Benchmark(ctx).Ready(exe);
|
||||
return new JsonObject
|
||||
{
|
||||
["available"] = g != null, ["ready"] = ready,
|
||||
["last"] = !ready && g != null ? "Comes with the next update: your game was built before the benchmark existed." : benchLast ?? "Not run yet on this PC",
|
||||
};
|
||||
}
|
||||
|
||||
void BenchAsk()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null) { Toast("Build the game first.", "error"); return; }
|
||||
if (benchCts != null) { Go("brun"); return; }
|
||||
var exe = new Game(ctx).FindExe(g);
|
||||
if (exe == null || !new Benchmark(ctx).Ready(exe)) { Toast("The benchmark comes with the next update: your game was built before it existed.", "error"); return; }
|
||||
Ask("Find my best settings",
|
||||
"<p>The game opens full screen, loads your newest save by itself and flies through four places: Hyrule Field, " +
|
||||
"Castle Town Market, Kokiri Forest and Lake Hylia. Its own panel shows where it is and the frame rate.</p>" +
|
||||
"<p><b>About 2 minutes.</b> Leave the controls alone meanwhile. Esc in the game stops it.</p>" +
|
||||
"<p>Your saves are not touched, and your settings are put back as they were. Then this window shows what it found.</p>",
|
||||
"bench.go", new[] { ("no", "Not now", false), ("go", "Start", true) });
|
||||
}
|
||||
|
||||
async Task RunBench(bool compare)
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null || benchCts != null) return;
|
||||
if (compare && benchRun == null) return;
|
||||
using var cts = benchCts = new CancellationTokenSource();
|
||||
var pic = new Saves(ctx).Newest(g) is { } newest ? SavePicUrl(newest) : null;
|
||||
var bm = new Benchmark(ctx);
|
||||
(int, string)? second = null;
|
||||
if (compare)
|
||||
{
|
||||
second = benchSecond ?? bm.SecondPass(g, BenchIni.Read(Path.Combine(g, GameOptionsSchema.FileName)));
|
||||
if (second == null) { Toast("You already use an upscaler: there is nothing to compare it with.", "error"); return; }
|
||||
}
|
||||
var t0 = DateTime.UtcNow;
|
||||
void Running(string line) => Send(new JsonObject
|
||||
{
|
||||
["t"] = "bench", ["phase"] = "run", ["pass"] = compare ? "Comparing with " + second!.Value.Item2 : "Finding your best settings",
|
||||
["frac"] = Math.Min(0.97, (DateTime.UtcNow - t0).TotalSeconds / 150), ["fps"] = null,
|
||||
["place"] = new JsonObject { ["name"] = "Running in the game window", ["img"] = pic },
|
||||
["line"] = line + " · " + BuildClock.Span(DateTime.UtcNow - t0),
|
||||
});
|
||||
Running("Starting the game");
|
||||
var last = DateTime.MinValue;
|
||||
var progress = new Progress<BenchmarkProgress>(p =>
|
||||
{
|
||||
if ((DateTime.UtcNow - last).TotalMilliseconds < 900) return;
|
||||
last = DateTime.UtcNow;
|
||||
Running(BenchLine(p.Text));
|
||||
});
|
||||
try
|
||||
{
|
||||
var run = await bm.RunOnceAsync(g, second, progress, cts.Token);
|
||||
if (compare) { benchRun2 = run; benchSecond = second; }
|
||||
else { benchRun = run; benchRun2 = null; benchSecond = bm.SecondPass(g, BenchIni.Read(Path.Combine(g, GameOptionsSchema.FileName))); }
|
||||
benchLast = "Last run " + DateTime.Now.ToString("d MMM, HH:mm");
|
||||
SendBenchResults();
|
||||
Sfx("success");
|
||||
host.Activate();
|
||||
}
|
||||
catch (OperationCanceledException) { Send(new JsonObject { ["t"] = "bench", ["phase"] = "stopped" }); Toast("Benchmark stopped · your settings are as they were"); host.Activate(); }
|
||||
catch (BenchmarkException e) { Send(new JsonObject { ["t"] = "bench", ["phase"] = "stopped" }); Toast(H(e.Message), "error"); host.Activate(); }
|
||||
catch (Exception e) { Log.Write("benchmark: " + e); Send(new JsonObject { ["t"] = "bench", ["phase"] = "stopped" }); Toast("The benchmark stopped: " + H(e.Message), "error"); host.Activate(); }
|
||||
finally { benchCts = null; RefreshSettingsState(); }
|
||||
}
|
||||
|
||||
/// <summary>The game's progress lines in plain words ("boot", "scene 2/4 Castle Town Market", "teleport ..."): kept short.</summary>
|
||||
static string BenchLine(string s)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(s)) return "Starting the game";
|
||||
s = s.Trim();
|
||||
return s.Length > 70 ? s[..70] + "…" : s;
|
||||
}
|
||||
|
||||
void SendBenchResults()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null || benchRun == null) return;
|
||||
var now = BenchIni.Read(Path.Combine(g, GameOptionsSchema.FileName));
|
||||
var r1 = benchRun; var r2 = benchRun2;
|
||||
benchRecs = Benchmark.Recommend(now, r1.Scenes, r2?.Scenes, r2 != null ? benchSecond : null, Benchmark.DisplayHz());
|
||||
var use2 = r2 != null && benchRecs.Any(c => c.Key == Benchmark.KUpscaler && c.Changes);
|
||||
var places = new JsonArray();
|
||||
for (var i = 0; i < r1.Scenes.Count; i++)
|
||||
{
|
||||
var a = r1.Scenes[i];
|
||||
var b = r2?.Scenes.ElementAtOrDefault(i);
|
||||
var o = new JsonObject
|
||||
{
|
||||
["name"] = a.Place, ["fps"] = Math.Round(a.AverageFps), ["low"] = Math.Round(a.OnePercentLow), ["img"] = null,
|
||||
["graph"] = Graph(a.FrameTimes),
|
||||
};
|
||||
if (b != null) { o["fps2"] = Math.Round(b.AverageFps); o["low2"] = Math.Round(b.OnePercentLow); o["graph2"] = Graph(b.FrameTimes); }
|
||||
places.Add(o);
|
||||
}
|
||||
var recs = new JsonArray();
|
||||
foreach (var c in benchRecs)
|
||||
recs.Add(new JsonObject { ["name"] = c.Label, ["from"] = BenchLabel(c.Key, c.From, benchRecs), ["to"] = BenchLabel(c.Key, c.To, benchRecs, true), ["same"] = !c.Changes });
|
||||
var gpu = r1.Gpu ?? Gpus.Main()?.Name;
|
||||
Send(new JsonObject
|
||||
{
|
||||
["t"] = "bench", ["phase"] = "done", ["places"] = places, ["recs"] = recs,
|
||||
["verdict"] = Benchmark.Summary(r1.Scenes, r2?.Scenes, r2 != null ? benchSecond?.name : null),
|
||||
["eb"] = "Benchmark finished · " + BuildClock.Span(r1.Took + (r2?.Took ?? TimeSpan.Zero)) + (gpu != null ? " · " + gpu : ""),
|
||||
["compare"] = r2 == null && benchSecond != null ? "Compare with " + benchSecond.Value.name : null,
|
||||
["second"] = r2 != null ? benchSecond?.name : null,
|
||||
["apply"] = benchRecs.Any(c => c.Changes),
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>A scene's frame times as a small graph's points (ms; at most 120).</summary>
|
||||
static JsonArray Graph(IReadOnlyList<double> ft)
|
||||
{
|
||||
var a = new JsonArray();
|
||||
if (ft.Count == 0) return a;
|
||||
var step = Math.Max(1, ft.Count / 120.0);
|
||||
for (double i = 0; i < ft.Count; i += step) a.Add(Math.Round(ft[(int)i], 2));
|
||||
return a;
|
||||
}
|
||||
|
||||
void ApplyBench()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null || benchRecs == null) { Go("settings"); return; }
|
||||
if (new Game(ctx).IsRunning(g)) { Toast("Close the game first: it keeps its own settings while it runs.", "error"); return; }
|
||||
new Benchmark(ctx).Apply(g, benchRecs);
|
||||
Log.Write("benchmark: applied " + string.Join(", ", benchRecs.Where(c => c.Changes).Select(c => c.Key + "=" + c.To)));
|
||||
benchLast = (benchLast ?? "Last run") + " · applied";
|
||||
RefreshSettingsState();
|
||||
Go("settings");
|
||||
Toast("<b>◆</b> Applied · the game uses them the next time you play", "success");
|
||||
}
|
||||
|
||||
void RefreshSettingsState()
|
||||
{
|
||||
var s = new JsonObject();
|
||||
AddSettingsState(s);
|
||||
SendState(s);
|
||||
}
|
||||
|
||||
/// <summary>The menu's own words for the values the benchmark touches (Triforce.Logic.GameOptionsSchema).</summary>
|
||||
static string BenchLabel(string key, int v, IReadOnlyList<SettingChange> all, bool after = false)
|
||||
{
|
||||
if (GameOptionsSchema.ByKey(key) is not { } row) return v.ToString();
|
||||
if (key == Benchmark.KResolution)
|
||||
{
|
||||
// (its label follows the Upscaler: "Quality (67%)" with DLSS / FSR, "67%" without)
|
||||
var up = all.FirstOrDefault(c => c.Key == Benchmark.KUpscaler) is { } u ? (after ? u.To : u.From) : 0;
|
||||
return row.Label(v, new OneValue(Benchmark.KUpscaler, up));
|
||||
}
|
||||
return row.Label(v);
|
||||
}
|
||||
|
||||
sealed class OneValue(string key, int value) : IGameOptionValues
|
||||
{
|
||||
public int Get(string k) => k == key ? value : GameOptionsSchema.ByKey(k)?.Default ?? 0;
|
||||
public string? Raw(string k) => k == key ? value.ToString() : null;
|
||||
}
|
||||
}
|
||||
639
launcher/App/Backend.Core.cs
Normal file
639
launcher/App/Backend.Core.cs
Normal file
@@ -0,0 +1,639 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Core.GameFiles;
|
||||
using Triforce.Logic;
|
||||
using LogicSource = Triforce.Logic.GameSource;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>First run (the game handed over, the reveal), the build, home, update and Play.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
readonly HttpClient http = Downloader.CreateHttp();
|
||||
Release? release;
|
||||
Failure? checkFailed;
|
||||
bool checking;
|
||||
|
||||
// first run
|
||||
LogicSource? source;
|
||||
string? outFolder;
|
||||
|
||||
// the working screen
|
||||
CancellationTokenSource? workCts;
|
||||
BuildRunner? runner;
|
||||
string? workKind; // "build" | "update"
|
||||
Func<Task>? retry;
|
||||
readonly StringBuilder logOut = new();
|
||||
Timer? logTimer;
|
||||
BuildResult? lastResult;
|
||||
|
||||
// the game
|
||||
Process? gameProc;
|
||||
Timer? runningTimer;
|
||||
|
||||
partial void AddSettingsState(JsonObject state);
|
||||
|
||||
void RegisterCore()
|
||||
{
|
||||
OnAsync("build", _ => BuildFirst());
|
||||
On("stop", _ => StopWork());
|
||||
OnAsync("retry", _ => retry != null ? retry() : Task.CompletedTask);
|
||||
On("workback", _ => { StopWork(); Go(workKind == "update" ? "home" : "reveal"); });
|
||||
On("play", _ => Play());
|
||||
On("playold", _ => Play());
|
||||
On("showgame", _ => ShowGame());
|
||||
OnAsync("update", _ => UpdateNow(start.Args.UpdateFolder));
|
||||
On("forget", _ => { source = null; UseMedia(GameDir); });
|
||||
On("choose", m =>
|
||||
{
|
||||
switch ((string?)m["id"])
|
||||
{
|
||||
case "lang":
|
||||
var cur = ctx.Settings.Language ?? Languages.Default().Code;
|
||||
Choice("Game language", "The language the game's text and voices are in.", "lang",
|
||||
Languages.All.Select(l => (l.Code, l.NativeName, l.NativeName != l.EnglishName ? l.EnglishName : (string?)null, l.Code == cur)), "Choose");
|
||||
break;
|
||||
case "folder":
|
||||
PickThen(true, "Where should the game go?", p =>
|
||||
{
|
||||
outFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(p)).Equals("Triforce", StringComparison.OrdinalIgnoreCase) ? p : Path.Combine(p, "Triforce");
|
||||
SendReveal();
|
||||
});
|
||||
break;
|
||||
case "dlss":
|
||||
var d = new Dlss(ctx);
|
||||
if (d.Chosen) { d.TurnOff(); SendReveal(); break; }
|
||||
Ask("NVIDIA DLSS", "<p>" + H(d.LicenseText).Replace("\n\n", "</p><p>").Replace("\n", "<br>") + "</p>", "dlssanswer",
|
||||
new[] { ("no", "Leave it out", false), ("yes", Dlss.AcceptLabel, true) });
|
||||
break;
|
||||
}
|
||||
});
|
||||
On("lang", m => { if ((string?)m["id"] is { } code) { ctx.Settings.Language = code; SendReveal(); } });
|
||||
On("dlssanswer", m => { if ((string?)m["id"] == "yes") new Dlss(ctx).Accept(); SendReveal(); });
|
||||
On("screen", _ => { });
|
||||
On("open", m => OpenThing((string?)m["arg"] ?? ""));
|
||||
On("report", _ => Copy(Report.ForBuild(ctx, lastResult, runner?.Details ?? "", new Tools(ctx).InstalledVersion)));
|
||||
On("sound", m =>
|
||||
{
|
||||
ctx.Settings.MusicVolume = (int)Math.Round(((double?)m["music"] ?? .4) * 100);
|
||||
ctx.Settings.SoundVolume = (int)Math.Round(((double?)m["sfx"] ?? .7) * 100);
|
||||
ctx.Settings.Muted = (bool?)m["muted"] ?? false;
|
||||
});
|
||||
On("closeanswer", m => { if ((string?)m["id"] == "yes") { StopEverything(); host.Close(); } });
|
||||
On("uninstallanswer", m =>
|
||||
{
|
||||
if ((string?)m["id"] != "yes") { host.Close(); return; }
|
||||
new Uninstaller(ctx).Run();
|
||||
host.Close();
|
||||
});
|
||||
ctx.Platform.NotificationRequested += (_, n) => { Log.Write("notice: " + n.Title + " · " + n.Text); host.Attention(n.Title, n.Text); };
|
||||
}
|
||||
|
||||
// ---------------- start ----------------
|
||||
void OnReady()
|
||||
{
|
||||
Send(new JsonObject { ["t"] = "hello", ["chrome"] = host.CustomChrome, ["os"] = OperatingSystem.IsWindows() ? "windows" : "linux" });
|
||||
var s = ctx.Settings;
|
||||
var state = new JsonObject { ["sound"] = new JsonObject { ["music"] = s.MusicVolume / 100.0, ["sfx"] = s.SoundVolume / 100.0, ["muted"] = s.Muted } };
|
||||
AddSettingsState(state);
|
||||
SendState(state);
|
||||
if (start.SignalUpWhenShown) Startup.SignalUp(ctx);
|
||||
if (start.Screen == StartScreen.Uninstall)
|
||||
{
|
||||
var plan = new Uninstaller(ctx).Describe();
|
||||
Ask("Uninstall Triforce?", "<p><b>Removes</b> " + H(string.Join(", ", plan.Removes)) + "</p><p><b>Keeps</b> " + H(string.Join(", ", plan.Keeps)) + "</p>",
|
||||
"uninstallanswer", new[] { ("no", "Keep it", false), ("yes", "Uninstall", true) });
|
||||
return;
|
||||
}
|
||||
var game = GameDir;
|
||||
if (game != null)
|
||||
{
|
||||
UseMedia(game);
|
||||
RefreshHome();
|
||||
var running = new Game(ctx).IsRunning(game);
|
||||
Go(running ? "playing" : "home");
|
||||
if (running) WatchGame();
|
||||
}
|
||||
else
|
||||
{
|
||||
SendMedia();
|
||||
Go("welcome");
|
||||
// testing: hand over a game as if dropped (test runs only)
|
||||
if (ctx.TestRoot != null && ctx.Env("TRIFORCE_TEST_INTAKE") is { Length: > 0 } ti) _ = Intake(ti);
|
||||
}
|
||||
_ = Guarded("check", CheckRelease);
|
||||
}
|
||||
|
||||
/// <summary>Asks the release server what is out (never blocks the window: home shows at once, the answer fills it in).</summary>
|
||||
async Task CheckRelease()
|
||||
{
|
||||
if (checking) return;
|
||||
checking = true;
|
||||
Exception? error = null;
|
||||
try
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));
|
||||
release = await new Updater(ctx).CheckAsync(http, cts.Token);
|
||||
}
|
||||
catch (Exception e) { error = e; }
|
||||
finally { checking = false; }
|
||||
var d = new Updater(ctx).Decide(start.Args, release, error);
|
||||
checkFailed = d.Failure;
|
||||
Log.Write("release check: " + d.Outcome + (release != null ? " " + release.Tag : "") + (d.Failure != null ? " · " + d.Failure.Title : ""));
|
||||
RefreshHome();
|
||||
// Started to carry on an update (--merge after the launcher swapped itself, or --update from the game): do it now.
|
||||
if (release != null && GameDir != null && (d.Outcome == CheckOutcome.Merge || start.Args.UpdateFolder != null))
|
||||
await UpdateNow(start.Args.UpdateFolder);
|
||||
}
|
||||
|
||||
void RequestClose()
|
||||
{
|
||||
if (runner?.Running == true || workCts != null)
|
||||
Ask(workKind == "update" ? "Close Triforce and stop the update?" : "Close Triforce and stop the build?",
|
||||
"<p>What is done so far is kept: next time it carries on from where it stopped.</p>", "closeanswer",
|
||||
new[] { ("no", "Keep going", true), ("yes", "Stop and close", false) });
|
||||
else host.Close();
|
||||
}
|
||||
|
||||
void StopEverything()
|
||||
{
|
||||
try { workCts?.Cancel(); } catch { }
|
||||
try { runner?.Stop(); } catch { }
|
||||
}
|
||||
|
||||
// ---------------- first run: the game handed over ----------------
|
||||
async Task Intake(string path)
|
||||
{
|
||||
Send(new JsonObject { ["t"] = "check", ["st"] = "checking", ["name"] = Path.GetFileName(Path.TrimEndingDirectorySeparator(path)) });
|
||||
var t0 = DateTime.UtcNow;
|
||||
string? bad = null;
|
||||
LogicSource? s = null;
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
s = GameIntake.Normalize(path, source);
|
||||
if (s == null) { bad = Path.GetFileName(Path.TrimEndingDirectorySeparator(path)) + " is not your game. Drop your .nup, or the folder with romfs and exefs in it."; return; }
|
||||
if (s.Kind == SourceKind.Folders && s.Missing is { } miss) { source = s; bad = "That folder has no " + miss + ". Drop the folder that holds both romfs and exefs, or drop the " + miss + " folder too."; return; }
|
||||
var q = GameIntake.Quick(s);
|
||||
if (!q.Ok) { bad = q.Text; return; }
|
||||
if (!q.Final && new Tools(ctx).Find() != null)
|
||||
{
|
||||
var full = await new GameIntake(ctx).CheckAsync(s);
|
||||
if (!full.Ok && !full.ToolsMissing) { bad = full.Text; return; }
|
||||
}
|
||||
if (!UseMedia(s.Kind == SourceKind.Nup ? s.Nup! : s.Romfs!)) Log.Write("intake: no art from " + path + " (the build can still go ahead)");
|
||||
}
|
||||
catch (Exception e) { bad = e.Message; Log.Write("intake: " + e); }
|
||||
});
|
||||
var shown = DateTime.UtcNow - t0;
|
||||
if (shown < TimeSpan.FromMilliseconds(700)) await Task.Delay(TimeSpan.FromMilliseconds(700) - shown);
|
||||
if (bad != null) { Send(new JsonObject { ["t"] = "check", ["st"] = "bad", ["msg"] = bad }); return; }
|
||||
source = s;
|
||||
outFolder ??= ctx.Settings.GameFolder ?? ctx.DefaultGameFolder;
|
||||
Send(new JsonObject { ["t"] = "check", ["st"] = "idle" });
|
||||
SendReveal();
|
||||
Sfx("success");
|
||||
Go("reveal");
|
||||
}
|
||||
|
||||
void SendReveal()
|
||||
{
|
||||
if (source == null) return;
|
||||
var lang = Languages.Find(ctx.Settings.Language) ?? Languages.Default();
|
||||
var space = new GameIntake(ctx).Space(outFolder!);
|
||||
var rows = new JsonArray
|
||||
{
|
||||
new JsonObject { ["label"] = "Language", ["value"] = lang.NativeName, ["act"] = "lang" },
|
||||
new JsonObject { ["label"] = "Where it goes", ["value"] = outFolder, ["act"] = "folder", ["bad"] = space.TooLittle,
|
||||
["small"] = space.Free is { } f ? $"{space.NeedWhileBuilding >> 30} GB while building · {f >> 30} GB free on {space.Disk}" + (space.TooLittle ? " · not enough" : "")
|
||||
: $"{space.NeedWhileBuilding >> 30} GB while building, about {space.NeedAfter >> 30} GB after" },
|
||||
};
|
||||
var d = new Dlss(ctx);
|
||||
if (d.Available) rows.Add(new JsonObject { ["label"] = "NVIDIA DLSS", ["value"] = d.Chosen ? "Included" : "Not included", ["act"] = "dlss", ["actLabel"] = d.Chosen ? "Leave out" : "Include" });
|
||||
var est = Estimate(false);
|
||||
var what = source.Kind == SourceKind.Nup ? string.Format("{0:0.0} GB", new FileInfo(source.Nup!).Length / 1e9) : "romfs and exefs";
|
||||
SendState(new JsonObject
|
||||
{
|
||||
["reveal"] = new JsonObject
|
||||
{
|
||||
["found"] = "<b>◆ Your game is ready to build</b> <em>· " + H(source.DisplayName) + " · " + H(what) + "</em>",
|
||||
["rows"] = rows, ["canBuild"] = !space.TooLittle,
|
||||
["under"] = est.Text + " on this PC, the tools included · you can keep using it meanwhile",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
BuildEstimate Estimate(bool update) =>
|
||||
BuildEstimator.Estimate(BuildHistory.Load(ctx.WorkFolder), update, Environment.ProcessorCount, Gpus.Main()?.Vendor);
|
||||
|
||||
// ---------------- the build (first run) ----------------
|
||||
async Task BuildFirst()
|
||||
{
|
||||
if (source == null) { Go("welcome"); return; }
|
||||
var space = new GameIntake(ctx).Space(outFolder!);
|
||||
if (space.TooLittle) { Toast("Not enough room on " + H(space.Disk) + ": the build needs " + (space.NeedWhileBuilding >> 30) + " GB free.", "error"); return; }
|
||||
retry = BuildFirst;
|
||||
workKind = "build";
|
||||
using var cts = workCts = new CancellationTokenSource();
|
||||
try
|
||||
{
|
||||
// 1. installed (Windows: the launcher copies itself to its folder, the Apps list, the shortcuts)
|
||||
if (ctx.IsWindows && ctx.InstalledDir == null)
|
||||
{
|
||||
var inst = new Installer(ctx);
|
||||
inst.Run(inst.DefaultDir, desktop: true, startMenu: true);
|
||||
}
|
||||
// 2. the tools
|
||||
await EnsureTools(cts.Token);
|
||||
// 3. the build
|
||||
var lang = (Languages.Find(ctx.Settings.Language) ?? Languages.Default()).Code;
|
||||
await RunBuild(BuildRequest.New(source, outFolder!, lang), cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { WorkStopped(); }
|
||||
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
|
||||
finally { workCts = null; }
|
||||
}
|
||||
|
||||
/// <summary>Settings: Build the game again (the folder it is in now, same language, mods on).</summary>
|
||||
public void StartRebuild()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null) { Go("welcome"); return; }
|
||||
if (workCts != null) { Go("work"); return; }
|
||||
_ = Guarded("rebuild", async () =>
|
||||
{
|
||||
retry = () => { StartRebuild(); return Task.CompletedTask; };
|
||||
workKind = "update";
|
||||
using var cts = workCts = new CancellationTokenSource();
|
||||
try
|
||||
{
|
||||
await EnsureTools(cts.Token);
|
||||
await RunBuild(BuildRequest.Update(g), cts.Token);
|
||||
}
|
||||
catch (OperationCanceledException) { WorkStopped(); }
|
||||
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
|
||||
finally { workCts = null; }
|
||||
});
|
||||
}
|
||||
|
||||
async Task EnsureTools(CancellationToken token)
|
||||
{
|
||||
var ti = new ToolsInstaller(ctx);
|
||||
if (release == null)
|
||||
{
|
||||
try { release = await new Updater(ctx).CheckAsync(http, token); }
|
||||
catch (Exception) when (new Tools(ctx).Find() != null) { return; } // offline, but tools are here: build with them
|
||||
}
|
||||
if (release == null || !ti.Needed(release) && new Tools(ctx).Find() != null) return;
|
||||
var rel = release;
|
||||
var mb = (rel.ToolsSize > 0 ? rel.ToolsSize : rel.ToolsCodeSize + rel.ToolsBaseSize) >> 20;
|
||||
var eb = workKind == "update" ? "Updating to " + rel.Tag : "Building your game";
|
||||
void Show(ToolsStep step, double f) => WorkScreen(eb, step == ToolsStep.Unpack ? "Unpacking Triforce's tools" : "Downloading Triforce's tools",
|
||||
f * 0.08, Steps((step, f, mb), null), "Keep this window open; you can minimize it.", true);
|
||||
var lastPush = DateTime.MinValue;
|
||||
ti.Progress += p => { if ((DateTime.UtcNow - lastPush).TotalMilliseconds < 200 && p.Step != ToolsStep.Done) return; lastPush = DateTime.UtcNow; Show(p.Step, p.Fraction); };
|
||||
Show(ToolsStep.Download, 0);
|
||||
Go("work");
|
||||
await ti.UpdateAsync(http, rel, token);
|
||||
Sfx("success");
|
||||
}
|
||||
|
||||
async Task RunBuild(BuildRequest req, CancellationToken token)
|
||||
{
|
||||
var r = runner = new BuildRunner(ctx);
|
||||
var est = Estimate(req.IsUpdate);
|
||||
StartLog();
|
||||
r.Line += l => { lock (logOut) logOut.AppendLine(l); };
|
||||
var last = DateTime.MinValue;
|
||||
var eb = req.IsUpdate ? (release != null && workKind == "update" ? "Updating to " + release.Tag : "Building your game again") : "Building your game";
|
||||
void Push(bool force = false)
|
||||
{
|
||||
if (!force && (DateTime.UtcNow - last).TotalMilliseconds < 250) return;
|
||||
last = DateTime.UtcNow;
|
||||
var e = r.Estimate ?? est;
|
||||
var left = BuildClock.Remaining(e, r.Tracker);
|
||||
WorkScreen(eb, BuildClock.LeftText(left), 0.08 + 0.92 * Fraction(e, r.Tracker), Steps(null, (e, r.Tracker)),
|
||||
"Keep this window open; you can minimize it. You get a notice when the game is ready.", true,
|
||||
req.IsUpdate ? null : new[] { ("Your game", "done"), ("Build", "now"), ("Play", "") });
|
||||
}
|
||||
r.Event += _ => Push();
|
||||
r.StageChanged += (_, _) => Push(true);
|
||||
Push(true);
|
||||
Go("work");
|
||||
using var reg = token.Register(() => r.Stop());
|
||||
var res = lastResult = await r.RunAsync(req, token);
|
||||
Push(true);
|
||||
FlushLog();
|
||||
logTimer?.Dispose(); logTimer = null;
|
||||
if (res.Cancelled) { WorkStopped(); return; }
|
||||
if (!res.Success) { WorkFailed("The build stopped", res.Failure ?? "It ended without saying why.", null); return; }
|
||||
// done
|
||||
if (res.Folder != null) { ctx.Settings.GameFolder = res.Folder; UseMedia(res.Folder); }
|
||||
var took = BuildClock.Span(res.Elapsed);
|
||||
var lead = res.ShadersNotPrepared != null ? "The shaders get prepared the first time you play." : "Shaders ready for your graphics card · your controller works out of the box";
|
||||
SendState(new JsonObject { ["done"] = new JsonObject { ["eb"] = (req.IsUpdate ? "Built again in " : "Built in ") + took, ["lead"] = "In " + ShortPath(res.Folder) + " · " + lead } });
|
||||
RefreshHome();
|
||||
if (req.IsUpdate) { Go("home"); Toast("<b>◆</b> " + (release != null && workKind == "update" ? "Updated to " + H(release.Tag) : "Built again") + " · your saves, mods and shaders stayed", "success"); }
|
||||
else Go("done");
|
||||
}
|
||||
|
||||
static double Fraction(BuildEstimate e, BuildTracker t)
|
||||
{
|
||||
if (t.DoneFolder != null) return 1;
|
||||
double total = 0, done = 0;
|
||||
var stages = BuildStages.All.Select(s => s.Id).ToList();
|
||||
var at = t.Stage != null ? stages.IndexOf(t.Stage) : -1;
|
||||
for (var i = 0; i < stages.Count; i++)
|
||||
{
|
||||
var mid = e.Of(stages[i])?.Mid.TotalSeconds ?? 0;
|
||||
total += mid;
|
||||
if (i < at) done += mid;
|
||||
else if (i == at) done += mid * Math.Clamp(t.StageProgress, 0, 1);
|
||||
}
|
||||
return total > 0 ? Math.Clamp(done / total, 0, 1) : 0;
|
||||
}
|
||||
|
||||
/// <summary>The steps list: the tools download (when it happens), then the build's stages, each done / now / to come with its time.</summary>
|
||||
JsonArray Steps((ToolsStep step, double frac, long mb)? tools, (BuildEstimate est, BuildTracker tr)? build)
|
||||
{
|
||||
var a = new JsonArray();
|
||||
if (tools is { } ts)
|
||||
a.Add(new JsonObject { ["name"] = "Downloading Triforce's tools", ["st"] = "n",
|
||||
["right"] = ts.step == ToolsStep.Unpack ? "unpacking" : ts.mb > 0 ? $"{(long)(ts.frac * ts.mb)} of {ts.mb} MB" : "now" });
|
||||
var stages = BuildStages.All;
|
||||
var at = build?.tr.Stage is { } cur ? stages.ToList().FindIndex(s => s.Id == cur) : -1;
|
||||
var est = build?.est ?? Estimate(false);
|
||||
var gpu = Gpus.Main();
|
||||
for (var i = 0; i < stages.Count; i++)
|
||||
{
|
||||
var s = stages[i];
|
||||
if (s.Id == "finish") continue; // (seconds: folded into Compiling for the player)
|
||||
string st, right;
|
||||
var e = est.Of(s.Id);
|
||||
if (build is not { } b) { st = ""; right = e != null ? BuildClock.About(e.Low, e.High) : ""; }
|
||||
else if (i < at || b.tr.DoneFolder != null)
|
||||
{
|
||||
st = "d";
|
||||
right = b.tr.StageSeconds.TryGetValue(s.Id, out var sec) ? BuildClock.Span(TimeSpan.FromSeconds(sec)) : "done";
|
||||
}
|
||||
else if (i == at)
|
||||
{
|
||||
st = "n";
|
||||
var p = b.tr.StageProgress;
|
||||
right = b.tr.Plan is { } pl && s.Id == "compile" ? $"{b.tr.FilesBuilt} of {pl.Changed} files" : p > 0 ? $"{(int)(p * 100)} %" : "now";
|
||||
}
|
||||
else { st = ""; right = e != null ? BuildClock.About(e.Low, e.High) : ""; }
|
||||
if (s.Id == "shaders" && st == "" && gpu != null && right.Length > 0) right += " on " + gpu.Name;
|
||||
a.Add(new JsonObject { ["name"] = s.Text, ["st"] = st, ["right"] = right });
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
void WorkScreen(string eb, string title, double frac, JsonArray steps, string note, bool canStop, (string name, string st)[]? path = null)
|
||||
{
|
||||
var p = new JsonArray();
|
||||
foreach (var (n, st) in path ?? Array.Empty<(string, string)>()) p.Add(new JsonObject { ["name"] = n, ["st"] = st });
|
||||
Send(new JsonObject
|
||||
{
|
||||
["t"] = "work", ["kind"] = workKind, ["eb"] = eb, ["title"] = title, ["lead"] = "", ["frac"] = Math.Clamp(frac, 0, 1), ["steps"] = steps,
|
||||
["note"] = note, ["canStop"] = canStop, ["error"] = null, ["path"] = p,
|
||||
["stopTitle"] = workKind == "update" ? "Stop the update?" : "Stop the build?",
|
||||
["stopText"] = "What is done so far is kept, so it carries on from here next time.",
|
||||
});
|
||||
}
|
||||
|
||||
void WorkFailed(string title, string text, Exception? e)
|
||||
{
|
||||
if (e != null) Log.Write("work failed: " + e);
|
||||
FlushLog();
|
||||
Send(new JsonObject
|
||||
{
|
||||
["t"] = "work", ["eb"] = workKind == "update" ? "Updating" : "Building your game", ["title"] = title, ["lead"] = text,
|
||||
["error"] = new JsonObject { ["msg"] = text }, ["retry"] = "Try again", ["canStop"] = false, ["path"] = new JsonArray(),
|
||||
});
|
||||
Go("work");
|
||||
}
|
||||
|
||||
void WorkStopped()
|
||||
{
|
||||
FlushLog();
|
||||
Toast(workKind == "update" ? "Update stopped · it carries on from here next time" : "Build stopped · it carries on from here next time");
|
||||
Go(workKind == "update" || GameDir != null ? "home" : "reveal");
|
||||
}
|
||||
|
||||
void StopWork()
|
||||
{
|
||||
try { workCts?.Cancel(); } catch { }
|
||||
try { runner?.Stop(); } catch { }
|
||||
}
|
||||
|
||||
void StartLog()
|
||||
{
|
||||
lock (logOut) logOut.Clear();
|
||||
logTimer?.Dispose();
|
||||
logTimer = new Timer(_ => FlushLog(), null, 300, 300);
|
||||
}
|
||||
|
||||
void FlushLog()
|
||||
{
|
||||
string text;
|
||||
lock (logOut) { if (logOut.Length == 0) return; text = logOut.ToString(); logOut.Clear(); }
|
||||
var lines = new JsonArray();
|
||||
foreach (var l in text.Split('\n')) if (l.Length > 0) lines.Add(l.TrimEnd('\r'));
|
||||
Send(new JsonObject { ["t"] = "log", ["lines"] = lines });
|
||||
}
|
||||
|
||||
// ---------------- update ----------------
|
||||
async Task UpdateNow(string? folder)
|
||||
{
|
||||
if (workCts != null) { Go("work"); return; }
|
||||
if (release == null) await CheckRelease();
|
||||
if (release == null) { Toast("Could not reach the update server. You can still play.", "error"); return; }
|
||||
var rel = release;
|
||||
var up = new Updater(ctx);
|
||||
var plan = up.Plan(start.Args, rel);
|
||||
retry = () => UpdateNow(folder);
|
||||
workKind = "update";
|
||||
using var cts = workCts = new CancellationTokenSource();
|
||||
try
|
||||
{
|
||||
if (plan.SelfUpdate)
|
||||
{
|
||||
var eb = "Updating to " + rel.Tag;
|
||||
WorkScreen(eb, "Downloading the new launcher", 0, new JsonArray(), "Your saves, mods and shaders stay.", false);
|
||||
Go("work");
|
||||
var r = await up.SelfUpdateAsync(http, rel, start.Args, start.Lock,
|
||||
p => WorkScreen(eb, "Downloading the new launcher", p.Fraction * 0.1, new JsonArray(), "Your saves, mods and shaders stay.", false),
|
||||
() => host.Minimize(), cts.Token);
|
||||
if (r == SelfUpdateResult.CloseNow) { host.Close(); return; }
|
||||
}
|
||||
if (plan.Tools) await EnsureTools(cts.Token);
|
||||
var again = up.RebuildFolderNow(start.Args) ?? folder;
|
||||
if (again != null) await RunBuild(BuildRequest.Update(again), cts.Token);
|
||||
else { RefreshHome(); Go("home"); Toast("<b>◆</b> Updated to " + H(rel.Tag), "success"); }
|
||||
}
|
||||
catch (NotStartedException e) { host.Activate(); WorkFailed("The new launcher did not start", e.Message, null); }
|
||||
catch (OperationCanceledException) { WorkStopped(); }
|
||||
catch (Exception e) { WorkFailed("The update stopped", Failure.Of(e, false).Note, e); }
|
||||
finally { workCts = null; }
|
||||
}
|
||||
|
||||
// ---------------- home ----------------
|
||||
/// <summary>Sends the home, the pill and the files strip as they are now (after a build, an import, the release check...).</summary>
|
||||
public void RefreshHome()
|
||||
{
|
||||
var g = GameDir;
|
||||
var state = new JsonObject();
|
||||
var files = new JsonArray();
|
||||
var running = g != null && new Game(ctx).IsRunning(g);
|
||||
if (g != null)
|
||||
{
|
||||
var slots = new Saves(ctx).Slots(g).Where(s => s.Used && s.Caption != null).OrderByDescending(s => s.Written).ToList();
|
||||
for (var i = 0; i < slots.Count; i++)
|
||||
{
|
||||
var s = slots[i];
|
||||
files.Add(new JsonObject
|
||||
{
|
||||
["slot"] = s.FileNumber, ["label"] = "File " + s.FileNumber, ["place"] = null, ["pic"] = SavePicUrl(s), ["last"] = i == 0,
|
||||
["when"] = When(s.Written), ["meta"] = "Saved " + When(s.Written, true), ["time"] = "",
|
||||
});
|
||||
}
|
||||
}
|
||||
state["files"] = files;
|
||||
var built = g != null ? Game.BuiltVersion(g) : null;
|
||||
var us = release != null ? new Updater(ctx).State(release) : null;
|
||||
JsonObject home, pill;
|
||||
var links = new JsonArray();
|
||||
if (g == null)
|
||||
{
|
||||
home = new JsonObject { ["mode"] = "missing", ["eb"] = "Needs attention", ["title"] = "No game built yet", ["meta"] = "Add your game to build it", ["button"] = "Add your game", ["act"] = "go:welcome" };
|
||||
pill = new JsonObject { ["text"] = "Not built", ["dot"] = "amber" };
|
||||
}
|
||||
else if (us is { Any: true })
|
||||
{
|
||||
var mb = ((us.LauncherNewer ? release!.SetupSize : 0) + (us.ToolsNewer ? Math.Max(release!.ToolsSize, release.ToolsCodeSize) : 0)) >> 20;
|
||||
home = new JsonObject
|
||||
{
|
||||
["mode"] = "update", ["eb"] = "An update is ready", ["title"] = "Version " + release!.Tag.TrimStart('v'),
|
||||
["meta"] = (mb > 0 ? mb + " MB download · " : "") + Estimate(true).Text + " · your saves and mods stay", ["button"] = "Update", ["act"] = "update",
|
||||
};
|
||||
links.Add(new JsonObject { ["html"] = "<b>Play " + H(built?.TrimStart('v') ?? "it") + " first</b>", ["act"] = "playold" });
|
||||
links.Add(new JsonObject { ["html"] = "See all changes", ["act"] = "open:changes" });
|
||||
pill = new JsonObject { ["text"] = "Update ready", ["dot"] = "amber", ["act"] = "update" };
|
||||
}
|
||||
else
|
||||
{
|
||||
home = new JsonObject { ["mode"] = files.Count > 0 ? "ready" : "nosave", ["eb"] = "Ready to play", ["title"] = "Ocarina of Time", ["meta"] = "Version " + (built?.TrimStart('v') ?? "?"), ["button"] = "Play", ["act"] = "play" };
|
||||
links.Add(new JsonObject { ["html"] = "Version " + H(built?.TrimStart('v') ?? "?") + " · <b>" + (checkFailed != null ? "offline" : release != null ? "up to date" : "checking") + "</b>" });
|
||||
links.Add(new JsonObject { ["html"] = H(g), ["act"] = "open:game" });
|
||||
pill = checkFailed != null ? new JsonObject { ["text"] = "Offline", ["dot"] = "grey" }
|
||||
: new JsonObject { ["text"] = release != null ? "Up to date · " + built?.TrimStart('v') : built?.TrimStart('v') ?? "", ["dot"] = "" };
|
||||
}
|
||||
if (running) { home["button"] = "Running"; home["off"] = true; pill = new JsonObject { ["text"] = "Playing", ["dot"] = "blue" }; }
|
||||
home["links"] = links;
|
||||
if (release?.NewIn is { Count: > 0 } ni)
|
||||
{
|
||||
var items = new JsonArray();
|
||||
foreach (var n in ni) items.Add(new JsonObject { ["b"] = n.Title, ["p"] = n.Text });
|
||||
home["news"] = new JsonObject { ["title"] = "New in " + release.Tag.TrimStart('v'), ["items"] = items, ["more"] = release.PageUrl != null };
|
||||
}
|
||||
state["home"] = home;
|
||||
state["pill"] = pill;
|
||||
AddSettingsState(state);
|
||||
SendState(state);
|
||||
}
|
||||
|
||||
/// <summary>A folder as a player reads it: short ones whole, long ones as the drive, …, and the last two parts.</summary>
|
||||
public static string ShortPath(string? p)
|
||||
{
|
||||
if (string.IsNullOrEmpty(p) || p.Length <= 44) return p ?? "";
|
||||
var parts = p.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
|
||||
return parts.Length < 4 ? p : parts[0] + Path.DirectorySeparatorChar + "…" + Path.DirectorySeparatorChar + parts[^2] + Path.DirectorySeparatorChar + parts[^1];
|
||||
}
|
||||
|
||||
static string When(DateTime? t, bool withTime = false)
|
||||
{
|
||||
if (t is not { } w) return "";
|
||||
var d = (DateTime.Now.Date - w.Date).TotalDays;
|
||||
var day = d < 1 ? "today" : d < 2 ? "yesterday" : w.Year == DateTime.Now.Year ? w.ToString("d MMM") : w.ToString("d MMM yyyy");
|
||||
return withTime && d < 2 ? day + ", " + w.ToString("HH:mm") : day;
|
||||
}
|
||||
|
||||
// ---------------- Play ----------------
|
||||
void Play()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null) { Go("welcome"); return; }
|
||||
var game = new Game(ctx);
|
||||
if (game.IsRunning(g)) { Go("playing"); ShowGame(); return; }
|
||||
gameProc = game.Play(g);
|
||||
if (gameProc == null) { Toast("The game would not start. Settings, Build the game again, repairs a broken game folder.", "error"); return; }
|
||||
Log.Write("play " + g);
|
||||
Go("playing");
|
||||
RefreshHome();
|
||||
WatchGame();
|
||||
}
|
||||
|
||||
void WatchGame()
|
||||
{
|
||||
runningTimer?.Dispose();
|
||||
runningTimer = new Timer(_ =>
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g != null && new Game(ctx).IsRunning(g)) return;
|
||||
runningTimer?.Dispose(); runningTimer = null;
|
||||
Log.Write("the game ended");
|
||||
RefreshHome();
|
||||
Go("home");
|
||||
host.Activate();
|
||||
}, null, 3000, 2000);
|
||||
}
|
||||
|
||||
void ShowGame()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
var p = gameProc is { HasExited: false } ? gameProc
|
||||
: new Game(ctx).ProcessNames.SelectMany(Process.GetProcessesByName).FirstOrDefault();
|
||||
if (p != null && p.MainWindowHandle != IntPtr.Zero) { ShowWindow(p.MainWindowHandle, 9); SetForegroundWindow(p.MainWindowHandle); }
|
||||
}
|
||||
catch (Exception e) { Log.Write("show game: " + e.Message); }
|
||||
}
|
||||
[System.Runtime.InteropServices.DllImport("user32")] static extern bool SetForegroundWindow(IntPtr h);
|
||||
[System.Runtime.InteropServices.DllImport("user32")] static extern bool ShowWindow(IntPtr h, int c);
|
||||
|
||||
// ---------------- links ----------------
|
||||
void OpenThing(string what)
|
||||
{
|
||||
string? url = what switch
|
||||
{
|
||||
"help" => BuildInfo.Home,
|
||||
"changes" => release?.PageUrl ?? BuildInfo.Home,
|
||||
_ => what.StartsWith("https://", StringComparison.Ordinal) ? what : null,
|
||||
};
|
||||
if (url != null) { try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch { } return; }
|
||||
var folder = what switch
|
||||
{
|
||||
"game" => GameDir,
|
||||
"log" => ctx.WorkFolder,
|
||||
"backups" => ctx.SaveBackupsFolder,
|
||||
_ => null,
|
||||
};
|
||||
if (folder != null && Directory.Exists(folder)) ctx.Platform.OpenFolder(folder);
|
||||
}
|
||||
|
||||
/// <summary>The picture in save file <paramref name="slot"/> (1..6) of the built game: the game's own caption.sav.</summary>
|
||||
byte[]? SavePicture(int slot)
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null) return null;
|
||||
var s = new Saves(ctx).Slots(g).FirstOrDefault(x => x.FileNumber == slot);
|
||||
return s?.Caption is { } c ? Caption.JpegFromFile(c) : null;
|
||||
}
|
||||
|
||||
/// <summary>The page's address of a slot's picture (changes when the save does, so the page loads the new one).</summary>
|
||||
public static string SavePicUrl(SaveSlot s) => "img/save" + s.FileNumber + ".jpg?v=" + (s.Written?.Ticks ?? 0);
|
||||
}
|
||||
116
launcher/App/Backend.GameOpts.cs
Normal file
116
launcher/App/Backend.GameOpts.cs
Normal file
@@ -0,0 +1,116 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>Settings > Display / Graphics / Audio / Controls / Game: the game's own Options menu (Triforce.Logic
|
||||
/// GameOptionsSchema, its rows as the menu has them), read from and written to the game folder's triforce_options.ini the way
|
||||
/// the game merges it. Refused while the game runs (it keeps its settings in memory and writes them back).</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
static readonly (GameOptionTab tab, string id, string name)[] GameTabs =
|
||||
{
|
||||
(GameOptionTab.Display, "display", "Display"), (GameOptionTab.Graphics, "graphics", "Graphics"),
|
||||
(GameOptionTab.Audio, "audio", "Audio"), (GameOptionTab.Controls, "controls", "Controls"), (GameOptionTab.System, "system", "Game"),
|
||||
};
|
||||
bool gpusHooked;
|
||||
|
||||
void RegisterGameOpts()
|
||||
{
|
||||
On("gopt.choose", m =>
|
||||
{
|
||||
var key = (string?)m["key"] ?? "";
|
||||
if (!CanChangeGame(out var f) || GameOptionsSchema.ByKey(key) is not { } row) return;
|
||||
var now = f!.Get(key);
|
||||
var text = H(row.Help ?? "") + (row.Restart ? "<br><span style=\"color:var(--text3)\">Takes effect the next time the game starts.</span>" : "");
|
||||
if (key == Benchmark.KPreset)
|
||||
text += "<br>" + string.Join("<br>", GameOptionsSchema.PresetSummaries.Select((s, i) => i == 0 ? "" : "<b>" + H(f.ChoicesOf(key).ElementAtOrDefault(i)?.Label) + "</b> " + H(s)).Where(x => x.Length > 0));
|
||||
var choices = f.ChoicesOf(key).AsEnumerable();
|
||||
if (key == Benchmark.KUpscaler)
|
||||
{
|
||||
// (as the game's menu offers them: DLSS and DLAA with an NVIDIA card and DLSS in the build; FSR 4 on AMD cards)
|
||||
var dlss = Gpus.HasNvidia() && new Game(ctx).HasDlss(GameDir!);
|
||||
var amd = Gpus.List().Any(x => x.Vendor == GpuVendor.Amd);
|
||||
choices = choices.Where(c => c.Value == now || (c.Value is not (1 or 2) || dlss) && (c.Value is not (4 or 5) || amd));
|
||||
}
|
||||
Choice(row.Name, text, "gopt.set", choices.Select(c => (c.Value.ToString(), c.Label, (string?)null, c.Value == now)), "Choose", key);
|
||||
});
|
||||
On("gopt.set", m =>
|
||||
{
|
||||
var key = (string?)m["ctx"] ?? (string?)m["key"] ?? "";
|
||||
if (!int.TryParse((string?)m["id"] ?? m["value"]?.ToString(), out var v)) return;
|
||||
SetGameOption(key, v);
|
||||
});
|
||||
On("gopt.value", m =>
|
||||
{
|
||||
var key = (string?)m["key"] ?? "";
|
||||
if (m["value"] is JsonNode n && int.TryParse(n.ToString(), out var v)) SetGameOption(key, v);
|
||||
});
|
||||
}
|
||||
|
||||
void SetGameOption(string key, int v)
|
||||
{
|
||||
if (!CanChangeGame(out var f) || GameOptionsSchema.ByKey(key) == null) { RefreshSettingsState(); return; }
|
||||
f!.Set(key, v);
|
||||
f.Save();
|
||||
Log.Write("game option " + key + "=" + f.Get(key) + (f.Changes.Count > 1 ? " (with " + string.Join(", ", f.Changes.Where(c => c.Key != key).Select(c => c.Key + "=" + c.Value)) + ")" : ""));
|
||||
RefreshSettingsState();
|
||||
}
|
||||
|
||||
/// <summary>The game's options may be written now: a built game, not running, and (a test run) the folder allowed.</summary>
|
||||
bool CanChangeGame(out GameOptionsFile? file)
|
||||
{
|
||||
file = null;
|
||||
var g = GameDir;
|
||||
if (g == null) return false;
|
||||
if (new Game(ctx).IsRunning(g)) { Toast("Close the game to change these: it keeps its own settings while it runs.", "error"); return false; }
|
||||
var path = Path.Combine(g, GameOptionsSchema.FileName);
|
||||
if (!ctx.AllowedForGame(path)) { Toast(H(ctx.TestOnly), "error"); return false; }
|
||||
file = GameOptionsFile.Load(g, MainScreen());
|
||||
return true;
|
||||
}
|
||||
|
||||
JsonObject? GameOptsState()
|
||||
{
|
||||
var g = GameDir;
|
||||
if (g == null) return null;
|
||||
if (!gpusHooked) { GameOptionsSchema.UseSystemGpus(); gpusHooked = true; }
|
||||
GameOptionsFile f;
|
||||
try { f = GameOptionsFile.Load(g, MainScreen()); }
|
||||
catch (Exception e) { Log.Write("game options: " + e.Message); return null; }
|
||||
var running = new Game(ctx).IsRunning(g);
|
||||
var tabs = new JsonArray();
|
||||
var data = new JsonObject();
|
||||
foreach (var (tab, id, name) in GameTabs)
|
||||
{
|
||||
tabs.Add(new JsonObject { ["id"] = id, ["name"] = name });
|
||||
var sections = new JsonArray();
|
||||
JsonObject? cur = null;
|
||||
foreach (var r in GameOptionsSchema.RowsOf(tab))
|
||||
{
|
||||
var h = r.Section ?? name;
|
||||
if (cur == null || (string?)cur["h"] != h) { cur = new JsonObject { ["h"] = h, ["rows"] = new JsonArray() }; sections.Add(cur); }
|
||||
var v = f.Get(r.Key);
|
||||
((JsonArray)cur["rows"]!).Add(new JsonObject
|
||||
{
|
||||
["key"] = r.Key, ["label"] = r.Name, ["value"] = f.Label(r.Key), ["v"] = v,
|
||||
["kind"] = r.Kind == GameOptionKind.Slider ? "slider" : "choice",
|
||||
["lo"] = r.Lo, ["hi"] = r.Hi, ["step"] = r.Step, ["restart"] = r.Restart, ["help"] = r.Help,
|
||||
});
|
||||
}
|
||||
data[id] = sections;
|
||||
}
|
||||
return new JsonObject
|
||||
{
|
||||
["tabs"] = tabs, ["data"] = data, ["locked"] = running,
|
||||
["note"] = running ? "Close the game to change these: it keeps its own settings while it runs." : "The same settings as the game's own menu. They take effect the next time you play.",
|
||||
};
|
||||
}
|
||||
|
||||
static (int W, int H)? MainScreen()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
try { return (GetSystemMetrics(0), GetSystemMetrics(1)); } catch { return null; }
|
||||
}
|
||||
[System.Runtime.InteropServices.DllImport("user32")] static extern int GetSystemMetrics(int i);
|
||||
}
|
||||
62
launcher/App/Backend.Media.cs
Normal file
62
launcher/App/Backend.Media.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Core.GameFiles;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>The player's own game as the page's art and sound: the title logo, Saria's Song and the menu sounds, read from
|
||||
/// the .nup they dropped (or, once built, from the game folder's romfs) and kept decoded in the launcher's cache.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
GameMedia? media;
|
||||
string? mediaFrom;
|
||||
int mediaVersion;
|
||||
|
||||
byte[]? MediaFor(string kind, string name)
|
||||
{
|
||||
var m = media;
|
||||
if (m == null) return null;
|
||||
return kind == "png" ? m.Png(name) : kind == "wav" ? m.Wav(name) : null;
|
||||
}
|
||||
|
||||
/// <summary>Use this game for the art and sounds (null: none). Decodes the logo set and the first music right away, so
|
||||
/// the reveal shows them at once.</summary>
|
||||
bool UseMedia(string? path)
|
||||
{
|
||||
if (path == mediaFrom && media != null) return true;
|
||||
if (path == null)
|
||||
{
|
||||
var gone = media; media = null; mediaFrom = null; gone?.Source.Dispose();
|
||||
SendMedia();
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
var src = GameSource.Open(path);
|
||||
var m = new GameMedia(src, Path.Combine(dataDir, "media"));
|
||||
var t = System.Diagnostics.Stopwatch.StartNew();
|
||||
foreach (var n in GameMedia.LogoSet) m.PngFile(n);
|
||||
m.WavFile("saria");
|
||||
Log.Write($"media from {path}: logo + Saria's Song ready in {t.ElapsedMilliseconds} ms");
|
||||
var old = media;
|
||||
media = m; mediaFrom = path; mediaVersion++;
|
||||
old?.Source.Dispose();
|
||||
// the rest in the background
|
||||
_ = Task.Run(() => { try { foreach (var id in GameMedia.Sounds.Keys) m.WavFile(id); } catch (Exception e) { Log.Write("media: " + e.Message); } });
|
||||
SendMedia();
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// (a source without the game's files: keep what is shown now)
|
||||
Log.Write("media from " + path + ": " + e.Message);
|
||||
if (media == null) SendMedia();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void SendMedia()
|
||||
{
|
||||
var on = media != null;
|
||||
Send(new JsonObject { ["t"] = "state", ["media"] = new JsonObject { ["art"] = on, ["music"] = on, ["sfx"] = on, ["v"] = mediaVersion } });
|
||||
}
|
||||
}
|
||||
414
launcher/App/Backend.Mods.cs
Normal file
414
launcher/App/Backend.Mods.cs
Normal file
@@ -0,0 +1,414 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>The Mods page (DESIGN 6 Mods, research/02 7): Browse = GameBanana's section for this game (public read calls only,
|
||||
/// and the downloads the player asks for), Yours = the game folder's mods folder as the game finds it (ModManager). Installing,
|
||||
/// updating, switching on and off and removing; a kit (Kits: Squadala only) is installed into kits\ and started. Code patches
|
||||
/// are built into the game, so a change of those says the game must be built again, and how long that takes.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
readonly Lazy<HttpClient> gbHttp = new(GameBanana.Create);
|
||||
GameBanana? gbApi;
|
||||
GameBanana Gb => gbApi ??= new GameBanana(gbHttp.Value);
|
||||
|
||||
readonly object modsGate = new();
|
||||
string modsTab = "browse", modsQuery = "";
|
||||
int modsPage, modsGen;
|
||||
bool modsNameFilter, modsMore, modsLoaded;
|
||||
string? modsError;
|
||||
List<GbMod> gbCards = new();
|
||||
readonly ConcurrentDictionary<string, GbDetails> gbDetails = new();
|
||||
/// <summary>What is being worked on: the item's id and the line under its name meanwhile.</summary>
|
||||
readonly ConcurrentDictionary<string, string> modsBusy = new();
|
||||
string? rebuildTime;
|
||||
|
||||
partial void RegisterMods()
|
||||
{
|
||||
OnAsync("mods.list", m => ModsList((string?)m["tab"] ?? "browse", (string?)m["q"] ?? ""));
|
||||
OnAsync("mods.more", _ => ModsMore());
|
||||
OnAsync("mods.main", m => ModsMain((string?)m["id"]));
|
||||
OnAsync("mods.file", m => ModsFileChosen((string?)m["id"], (string?)m["ctx"]));
|
||||
On("mods.remove", m => ModsRemove((string?)m["id"]));
|
||||
On("mods.page", m =>
|
||||
{
|
||||
var id = (string?)m["id"] ?? "";
|
||||
var url = CardOf(id)?.Page ?? (GameDir is { } g ? MineMods(g, false).FirstOrDefault(x => "m:" + x.Rel == id)?.Info?.Page : null) ?? KitInfo(id)?.Page;
|
||||
if (url != null) OpenLink(url);
|
||||
});
|
||||
}
|
||||
|
||||
static string CardKey(GbMod m) => "gb:" + (m.Wip ? "w" : "m") + ":" + m.Id;
|
||||
GbMod? CardOf(string id) { lock (modsGate) return gbCards.FirstOrDefault(c => CardKey(c) == id); }
|
||||
|
||||
// ---------------- lists ----------------
|
||||
|
||||
async Task ModsList(string tab, string q)
|
||||
{
|
||||
modsTab = tab == "mine" ? "mine" : "browse";
|
||||
if (modsTab == "mine") { SendMods(); return; }
|
||||
int gen;
|
||||
lock (modsGate) { gen = ++modsGen; modsQuery = q.Trim(); modsError = null; }
|
||||
try
|
||||
{
|
||||
var page = modsQuery.Length == 0 ? await Gb.ListAsync(1) : await Gb.SearchAsync(modsQuery, 1);
|
||||
lock (modsGate)
|
||||
{
|
||||
if (gen != modsGen) return;
|
||||
gbCards = page.Mods.ToList();
|
||||
modsPage = 1; modsNameFilter = page.NameFilter; modsMore = !page.Complete && page.Mods.Count > 0; modsLoaded = true;
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is HttpRequestException || e is TaskCanceledException || e is JsonException || e is IOException)
|
||||
{
|
||||
lock (modsGate)
|
||||
{
|
||||
if (gen != modsGen) return;
|
||||
gbCards = new(); modsMore = false; modsLoaded = false;
|
||||
modsError = "GameBanana could not be reached (" + e.Message + "). Check this PC's connection and open the page again.";
|
||||
}
|
||||
Log.Write("mods: " + e.Message);
|
||||
}
|
||||
if (modsTab != "browse") return; // (the player went to Yours meanwhile: the cards wait for Browse)
|
||||
SendMods();
|
||||
await FetchDetails(gen);
|
||||
}
|
||||
|
||||
async Task ModsMore()
|
||||
{
|
||||
int gen, next; string q; bool nameFilter;
|
||||
lock (modsGate) { if (!modsMore) return; gen = modsGen; next = modsPage + 1; q = modsQuery; nameFilter = modsNameFilter; }
|
||||
try
|
||||
{
|
||||
var page = q.Length == 0 ? await Gb.ListAsync(next) : await Gb.SearchAsync(q, next, nameFilter);
|
||||
lock (modsGate)
|
||||
{
|
||||
if (gen != modsGen) return;
|
||||
var have = new HashSet<string>(gbCards.Select(CardKey));
|
||||
gbCards = gbCards.Concat(page.Mods.Where(m => have.Add(CardKey(m)))).ToList();
|
||||
modsPage = next; modsMore = !page.Complete && page.Mods.Count > 0;
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is HttpRequestException || e is TaskCanceledException || e is JsonException || e is IOException)
|
||||
{
|
||||
Toast("GameBanana could not be reached (" + H(e.Message) + ").", "error");
|
||||
return;
|
||||
}
|
||||
SendMods();
|
||||
await FetchDetails(gen);
|
||||
}
|
||||
|
||||
/// <summary>Each card's details (its description and files: what a sheet shows, and whether an installed one has a newer
|
||||
/// file), four at a time, then the list again.</summary>
|
||||
async Task FetchDetails(int gen)
|
||||
{
|
||||
List<GbMod> cards;
|
||||
lock (modsGate) cards = gbCards.Where(c => !gbDetails.ContainsKey(CardKey(c))).ToList();
|
||||
if (cards.Count == 0) return;
|
||||
using var gate = new SemaphoreSlim(4);
|
||||
await Task.WhenAll(cards.Select(async c =>
|
||||
{
|
||||
await gate.WaitAsync();
|
||||
try { gbDetails[CardKey(c)] = await Gb.DetailsAsync(c.Id, c.Wip); }
|
||||
catch (Exception e) { Log.Write("mods: details of " + c.Id + ": " + e.Message); }
|
||||
finally { gate.Release(); }
|
||||
}));
|
||||
if (gen == modsGen && modsTab == "browse") SendMods();
|
||||
}
|
||||
|
||||
void SendMods()
|
||||
{
|
||||
JsonObject state;
|
||||
try { state = ModsState(); }
|
||||
catch (Exception e) { Log.Write("mods: " + e); state = new JsonObject { ["tab"] = modsTab, ["items"] = new JsonArray(), ["more"] = false, ["loaded"] = true, ["note"] = H(e.Message) }; }
|
||||
SendState(new JsonObject { ["mods"] = state });
|
||||
}
|
||||
|
||||
List<Mod> MineMods(string game, bool carried)
|
||||
{
|
||||
try { return new ModManager(ctx).ListGame(game, carried); } catch (Exception e) { Log.Write("mods: " + e.Message); return new(); }
|
||||
}
|
||||
|
||||
JsonObject ModsState()
|
||||
{
|
||||
var game = GameDir;
|
||||
var items = new JsonArray();
|
||||
string note = "";
|
||||
var tab = modsTab;
|
||||
bool more, loaded;
|
||||
if (tab == "browse")
|
||||
{
|
||||
List<GbMod> cards;
|
||||
lock (modsGate) { cards = gbCards.ToList(); more = modsMore; loaded = modsLoaded; if (modsError != null) note = H(modsError); }
|
||||
var inst = game != null ? new GameBananaInstaller(ctx).Installed(game) : Array.Empty<InstalledMod>();
|
||||
var local = game != null ? MineMods(game, false) : new List<Mod>();
|
||||
foreach (var c in cards)
|
||||
{
|
||||
var key = CardKey(c);
|
||||
gbDetails.TryGetValue(key, out var d);
|
||||
var kit = Kits.Find(c.Wip, c.Id) != null;
|
||||
var hit = inst.FirstOrDefault(i => i.Id == c.Id && i.Wip == c.Wip);
|
||||
string state;
|
||||
if (hit == null && d != null && d.Files.Count == 0) state = "page"; // (nothing to download: its page only, no button)
|
||||
else if (kit) state = hit != null ? "start" : "kit";
|
||||
else if (hit == null) state = "get";
|
||||
else if (d != null && game != null && new GameBananaInstaller(ctx).State(game, c, d).Update) state = "update";
|
||||
else state = local.Any(m => Ours(m, c) && m.On) ? "on" : "off";
|
||||
var sub = string.Join(" · ", new[] { c.Author, c.Category, c.Wip ? "work in progress" : "" }.Where(s => s.Length > 0));
|
||||
if (modsBusy.TryGetValue(key, out var busy)) { state = "busy"; sub = busy; }
|
||||
items.Add(new JsonObject
|
||||
{
|
||||
["id"] = key, ["name"] = c.Name, ["sub"] = sub, ["state"] = state,
|
||||
["img"] = c.ThumbUrl is { } t && t.StartsWith("https://", StringComparison.Ordinal) ? t : null,
|
||||
["desc"] = d != null ? Describe(d, kit) : null,
|
||||
["page"] = c.Page is { } p && p.StartsWith("https://", StringComparison.Ordinal) ? p : null,
|
||||
["removable"] = !kit && hit != null && state != "busy",
|
||||
});
|
||||
}
|
||||
if (loaded && cards.Count == 0 && note.Length == 0)
|
||||
note = modsQuery.Length > 0 ? "Nothing on GameBanana matches “" + H(modsQuery) + "”." : "GameBanana lists no mods for this game right now.";
|
||||
}
|
||||
else
|
||||
{
|
||||
more = false; loaded = true;
|
||||
if (game != null)
|
||||
{
|
||||
foreach (var m in MineMods(game, true))
|
||||
{
|
||||
var key = "m:" + m.Rel;
|
||||
var parts = new List<string>();
|
||||
if (m.Info?.Author is { Length: > 0 } a) parts.Add(a);
|
||||
parts.Add(Mods.Carries(m));
|
||||
if (m.OffAbove != null) parts.Add("off with its folder " + m.OffAbove);
|
||||
var state = m.On ? "on" : "off";
|
||||
var sub = string.Join(" · ", parts);
|
||||
if (modsBusy.TryGetValue(key, out var busy)) { state = "busy"; sub = busy; }
|
||||
items.Add(new JsonObject
|
||||
{
|
||||
["id"] = key, ["name"] = m.Info?.Name is { Length: > 0 } n ? n : m.Name, ["sub"] = sub, ["state"] = state, ["img"] = ThumbOf(m),
|
||||
["desc"] = "Its folder: mods" + Path.DirectorySeparatorChar + m.Rel.Replace('/', Path.DirectorySeparatorChar) + ". " +
|
||||
(m.Built ? "It changes the game's code, so the game is built again for it." : "Its files are read when the game starts."),
|
||||
["page"] = m.Info?.Page is { } p && p.StartsWith("https://", StringComparison.Ordinal) ? p : null,
|
||||
["removable"] = state != "busy",
|
||||
});
|
||||
}
|
||||
foreach (var k in Kits.All)
|
||||
{
|
||||
var info = KitInfo("kit:" + k.Id);
|
||||
if (info == null) continue;
|
||||
var key = "gb:" + (k.Wip ? "w" : "m") + ":" + k.Id;
|
||||
var busy = modsBusy.TryGetValue(key, out var b) ? b : null;
|
||||
items.Add(new JsonObject
|
||||
{
|
||||
["id"] = "kit:" + k.Id, ["name"] = info.Name, ["sub"] = busy ?? "A program of its own, in kits" + Path.DirectorySeparatorChar + k.Folder,
|
||||
["state"] = busy != null ? "busy" : "start", ["img"] = null,
|
||||
["desc"] = "It runs beside the game in a window of its own. Start it, then follow its steps there.",
|
||||
["page"] = info.Page, ["removable"] = false,
|
||||
});
|
||||
}
|
||||
if (items.Count == 0) note = "There are no mods in your mods folder yet. Install one from Browse, or put a mod's folder into " + H(Mods.FolderOf(game)) + ".";
|
||||
}
|
||||
}
|
||||
if (game == null) note = "Build the game first: mods go into its mods folder.";
|
||||
else if (SafeNeedsRebuild(game)) note = "Changes take effect after the game is built again: <b>" + H(RebuildTime()) + "</b>.";
|
||||
return new JsonObject { ["tab"] = tab, ["items"] = items, ["more"] = more, ["loaded"] = loaded, ["note"] = note };
|
||||
}
|
||||
|
||||
/// <summary>A mod from GameBanana: its card's picture, when Browse has shown that card.</summary>
|
||||
string? ThumbOf(Mod m)
|
||||
{
|
||||
if (m.Info is not { GameBananaId: > 0 }) return null;
|
||||
lock (modsGate) return gbCards.FirstOrDefault(c => Ours(m, c))?.ThumbUrl is { } t && t.StartsWith("https://", StringComparison.Ordinal) ? t : null;
|
||||
}
|
||||
|
||||
static bool Ours(Mod m, GbMod c) => m.Info is { } i && i.GameBananaId == c.Id && i.Wip == c.Wip;
|
||||
|
||||
bool SafeNeedsRebuild(string game)
|
||||
{
|
||||
try { return new ModManager(ctx).NeedsRebuild(game); } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// <summary>"about 12 minutes" (this PC's last update build) or a stated range, as the home says it.</summary>
|
||||
string RebuildTime()
|
||||
{
|
||||
if (rebuildTime != null) return rebuildTime;
|
||||
try
|
||||
{
|
||||
var est = BuildEstimator.Estimate(BuildHistory.Load(ctx.WorkFolder), true, Environment.ProcessorCount, Gpus.Main()?.Vendor, ctx.IsWindows);
|
||||
var t = est.Text;
|
||||
rebuildTime = t.StartsWith("About ", StringComparison.Ordinal) ? "about " + t.Substring(6) : t;
|
||||
}
|
||||
catch (Exception) { rebuildTime = "about 5 to 60 minutes"; }
|
||||
return rebuildTime;
|
||||
}
|
||||
|
||||
static string Describe(GbDetails d, bool kit)
|
||||
{
|
||||
var text = d.Text.Trim();
|
||||
var files = d.Files.Count == 0 ? "No file to download." : d.Files.Count == 1 ? "One file, " + Size(d.Files[0].Bytes) + "." : d.Files.Count + " files to choose from.";
|
||||
if (kit) files += " It is installed beside the game and started in a window of its own.";
|
||||
return (text.Length > 0 ? text + "\n\n" : "") + files;
|
||||
}
|
||||
|
||||
static string Size(long b) => b >= 1L << 30 ? (b / (double)(1L << 30)).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + " GB"
|
||||
: b >= 1L << 20 ? Math.Max(1, (int)Math.Round(b / (double)(1L << 20))) + " MB" : Math.Max(1, (int)Math.Round(b / 1024.0)) + " KB";
|
||||
|
||||
sealed record KitFile(string Name, string? Page);
|
||||
|
||||
/// <summary>An installed kit's triforce_kit.json: its name and page (null when that kit is not installed).</summary>
|
||||
KitFile? KitInfo(string id)
|
||||
{
|
||||
if (GameDir is not { } g || !id.StartsWith("kit:", StringComparison.Ordinal) || !int.TryParse(id.AsSpan(4), out var n)) return null;
|
||||
var k = Kits.All.FirstOrDefault(x => x.Id == n);
|
||||
if (k == null) return null;
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(g, "kits", k.Folder, "triforce_kit.json");
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var r = doc.RootElement;
|
||||
string? S(string p) => r.TryGetProperty(p, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
var page = S("page");
|
||||
return new KitFile(S("name") is { Length: > 0 } nm ? nm : k.Folder, page != null && page.StartsWith("https://", StringComparison.Ordinal) ? page : null);
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
// ---------------- changes ----------------
|
||||
|
||||
async Task ModsMain(string? id)
|
||||
{
|
||||
if (id == null) return;
|
||||
if (GameDir is not { } game) { Toast("Build the game first: mods go into its mods folder.", "error"); return; }
|
||||
if (modsBusy.ContainsKey(id)) return;
|
||||
if (id.StartsWith("m:", StringComparison.Ordinal))
|
||||
{
|
||||
var mod = MineMods(game, true).FirstOrDefault(m => "m:" + m.Rel == id);
|
||||
if (mod == null) { Toast("That mod is no longer in the mods folder.", "error"); SendMods(); return; }
|
||||
Switch(game, new[] { mod }, !mod.On);
|
||||
return;
|
||||
}
|
||||
GbMod? card;
|
||||
if (id.StartsWith("kit:", StringComparison.Ordinal))
|
||||
{
|
||||
var k = int.TryParse(id.AsSpan(4), out var n) ? Kits.All.FirstOrDefault(x => x.Id == n) : null;
|
||||
if (k == null) return;
|
||||
card = new GbMod(k.Id, k.Wip, KitInfo(id)?.Name ?? k.Folder, "", "", KitInfo(id)?.Page, 0, 0, 0, null);
|
||||
}
|
||||
else card = CardOf(id);
|
||||
if (card == null) return;
|
||||
var key = CardKey(card);
|
||||
var kit = Kits.Find(card.Wip, card.Id) != null;
|
||||
if (!kit)
|
||||
{
|
||||
// (installed and current: the main button switches it)
|
||||
var hit = new GameBananaInstaller(ctx).Installed(game).FirstOrDefault(i => i.Id == card.Id && i.Wip == card.Wip);
|
||||
gbDetails.TryGetValue(key, out var known);
|
||||
if (hit != null && !(known != null && new GameBananaInstaller(ctx).State(game, card, known).Update))
|
||||
{
|
||||
var folders = MineMods(game, true).Where(m => Ours(m, card)).ToList();
|
||||
var anyOn = folders.Any(m => m.On);
|
||||
Switch(game, anyOn ? folders.Where(m => m.On).ToList() : folders.Take(1).ToList(), !anyOn);
|
||||
return;
|
||||
}
|
||||
}
|
||||
GbDetails d;
|
||||
try { d = gbDetails.TryGetValue(key, out var have) ? have : gbDetails[key] = await Gb.DetailsAsync(card.Id, card.Wip); }
|
||||
catch (Exception e) when (e is HttpRequestException || e is TaskCanceledException || e is JsonException)
|
||||
{
|
||||
Toast("GameBanana could not be reached (" + H(e.Message) + ").", "error");
|
||||
return;
|
||||
}
|
||||
if (d.Files.Count == 0) { Toast("This one has no file to download on GameBanana.", "error"); return; }
|
||||
if (!kit && d.Files.Count > 1)
|
||||
{
|
||||
var first = d.DefaultFile(false);
|
||||
Choice("Which file?", "<b>" + H(card.Name) + "</b> comes as " + d.Files.Count + " files. Most players want just one.", "mods.file",
|
||||
d.Files.Select((f, i) => (i.ToString(), f.Name, (string?)(Size(f.Bytes) + (f.Description.Length > 0 ? " · " + f.Description : "")), i == first)), "Install", key);
|
||||
return;
|
||||
}
|
||||
await Install(game, card, d.Files[d.DefaultFile(kit)]);
|
||||
}
|
||||
|
||||
async Task ModsFileChosen(string? id, string? key)
|
||||
{
|
||||
if (id == null || key == null || GameDir is not { } game || !int.TryParse(id, out var i)) return;
|
||||
var card = CardOf(key);
|
||||
if (card == null || !gbDetails.TryGetValue(key, out var d) || i < 0 || i >= d.Files.Count) return;
|
||||
await Install(game, card, d.Files[i]);
|
||||
}
|
||||
|
||||
async Task Install(string game, GbMod card, GbFile file)
|
||||
{
|
||||
var key = CardKey(card);
|
||||
if (!modsBusy.TryAdd(key, "Downloading " + Size(file.Bytes))) return;
|
||||
SendMods();
|
||||
var last = DateTime.MinValue;
|
||||
void Progress(DownloadProgress p)
|
||||
{
|
||||
if ((DateTime.UtcNow - last).TotalMilliseconds < 700) return;
|
||||
last = DateTime.UtcNow;
|
||||
modsBusy[key] = p.Fraction >= 1 ? "Unpacking" : "Downloading, " + (int)(p.Fraction * 100) + " % of " + Size(p.Total > 0 ? p.Total : file.Bytes);
|
||||
SendMods();
|
||||
}
|
||||
try
|
||||
{
|
||||
var msg = await new GameBananaInstaller(ctx).InstallAsync(gbHttp.Value, card, file, game, Progress, CancellationToken.None);
|
||||
Toast(H(msg), "success");
|
||||
}
|
||||
catch (Exception e) when (e is ModsException || e is InvalidOperationException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is TaskCanceledException)
|
||||
{
|
||||
Log.Write("mods: install " + card.Id + ": " + e);
|
||||
Toast(H(e.Message), "error");
|
||||
}
|
||||
finally
|
||||
{
|
||||
modsBusy.TryRemove(key, out _);
|
||||
SendMods();
|
||||
}
|
||||
}
|
||||
|
||||
void Switch(string game, IReadOnlyList<Mod> list, bool on)
|
||||
{
|
||||
if (list.Count == 0) return;
|
||||
var mm = new ModManager(ctx);
|
||||
try
|
||||
{
|
||||
foreach (var m in list) mm.SetOn(Mods.FolderOf(game), m, on);
|
||||
var name = list[0].Info?.Name is { Length: > 0 } n ? n : list[0].Name;
|
||||
Toast("<b>" + H(name) + "</b> is " + (on ? "on" : "off") + ".", "success");
|
||||
}
|
||||
catch (Exception e) when (e is ModsException || e is InvalidOperationException || e is IOException)
|
||||
{
|
||||
Toast(H(e.Message), "error");
|
||||
}
|
||||
SendMods();
|
||||
}
|
||||
|
||||
void ModsRemove(string? id)
|
||||
{
|
||||
if (id == null || GameDir is not { } game) return;
|
||||
var all = MineMods(game, true);
|
||||
List<Mod> list;
|
||||
if (id.StartsWith("m:", StringComparison.Ordinal)) list = all.Where(m => "m:" + m.Rel == id).ToList();
|
||||
else if (CardOf(id) is { } card) list = all.Where(m => Ours(m, card)).ToList();
|
||||
else return;
|
||||
if (list.Count == 0) { Toast("That mod is no longer in the mods folder.", "error"); SendMods(); return; }
|
||||
var mm = new ModManager(ctx);
|
||||
try
|
||||
{
|
||||
// (deepest first: a mod inside another's folder goes before the folder it is in)
|
||||
foreach (var m in list.OrderByDescending(m => m.Rel.Length)) mm.Remove(Mods.FolderOf(game), m);
|
||||
var name = list[0].Info?.Name is { Length: > 0 } n ? n : list[0].Name;
|
||||
Toast("<b>" + H(name) + "</b> is removed. Its folder is kept in mods" + Path.DirectorySeparatorChar + Mods.Removed + ", should you want it back.", "success");
|
||||
}
|
||||
catch (Exception e) when (e is ModsException || e is InvalidOperationException || e is IOException)
|
||||
{
|
||||
Toast(H(e.Message), "error");
|
||||
}
|
||||
SendMods();
|
||||
}
|
||||
}
|
||||
222
launcher/App/Backend.Saves.cs
Normal file
222
launcher/App/Backend.Saves.cs
Normal file
@@ -0,0 +1,222 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>The Saves page (DESIGN 6 Saves, research/02 6): the six files of the built game, and bringing saves in from an
|
||||
/// emulator or a folder, or copying them out, each as two steps over the page (choose where, then a plain question that
|
||||
/// names what is replaced and that it is backed up first). Refused while a game or emulator runs, with that reason.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
/// <summary>Save sets waiting for the player's answer, by the key the question carries.</summary>
|
||||
readonly ConcurrentDictionary<string, SaveSet> savesPending = new();
|
||||
/// <summary>The emulators' saves found when a flow was opened (the choice's ids are indexes into it).</summary>
|
||||
List<SaveSet> savesFound = new();
|
||||
|
||||
partial void RegisterSaves()
|
||||
{
|
||||
On("saves.list", _ => SendSaves());
|
||||
On("saves.import", _ => SavesFlow(true));
|
||||
On("saves.export", _ => SavesFlow(false));
|
||||
On("saves.from", m => SavesChosen(true, (string?)m["id"]));
|
||||
On("saves.to", m => SavesChosen(false, (string?)m["id"]));
|
||||
OnAsync("saves.confirm", m => SavesConfirm((string?)m["id"], (string?)m["ctx"]));
|
||||
On("saves.open", _ =>
|
||||
{
|
||||
if (GameDir is not { } g) { Toast("There is no game folder yet. Build the game first."); return; }
|
||||
var s = new Saves(ctx);
|
||||
var folder = s.TriforceFolder(g);
|
||||
OpenPlace(Directory.Exists(folder) ? folder : g);
|
||||
});
|
||||
On("saves.backups", _ =>
|
||||
{
|
||||
if (!Directory.Exists(ctx.SaveBackupsFolder)) { Toast("Nothing has been backed up yet. A copy of your saves is made there before anything replaces them."); return; }
|
||||
OpenPlace(ctx.SaveBackupsFolder);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------- the page's state ----------------
|
||||
|
||||
void SendSaves() => SendState(new JsonObject { ["saves"] = SavesState() });
|
||||
|
||||
JsonObject SavesState()
|
||||
{
|
||||
var game = GameDir;
|
||||
var items = new JsonArray();
|
||||
var saves = new Saves(ctx);
|
||||
var slots = game != null ? saves.Slots(game) : Saves.SlotsIn(Path.Combine(dataDir, "no-game-folder")); // (six empty files)
|
||||
var newest = game != null ? saves.Newest(game) : null;
|
||||
foreach (var s in slots)
|
||||
{
|
||||
var label = "File " + s.FileNumber;
|
||||
if (!s.Used)
|
||||
{
|
||||
items.Add(new JsonObject { ["slot"] = s.FileNumber, ["label"] = label, ["empty"] = true });
|
||||
continue;
|
||||
}
|
||||
items.Add(new JsonObject
|
||||
{
|
||||
["slot"] = s.FileNumber, ["label"] = label, ["place"] = null,
|
||||
["when"] = s.Written is { } w ? DayWord(w) : "",
|
||||
["time"] = "",
|
||||
["meta"] = s.Written is { } w2 ? "Saved " + DayWord(w2) + ", " + w2.ToString("HH:mm") : "",
|
||||
["pic"] = s.Caption != null ? SavePicUrl(s) : "",
|
||||
["last"] = newest != null && newest.Index == s.Index,
|
||||
["empty"] = false,
|
||||
});
|
||||
}
|
||||
var used = slots.Count(s => s.Used);
|
||||
var eb = game == null ? "No game folder yet" : used == 0 ? "No saves yet in your game folder" : "Six files in your game folder";
|
||||
List<SaveSet> found;
|
||||
try { found = saves.FindEmulatorSaves(); } catch (Exception e) { Log.Write("saves: " + e.Message); found = new(); }
|
||||
var line = "From an emulator on this PC, or a folder.";
|
||||
if (found.Count > 0)
|
||||
line += " Found: " + string.Join(", ", found.Take(3).Select(f => f.Name + " (" + Files(f.Slots) + ")")) + (found.Count > 3 ? " and " + (found.Count - 3) + " more" : "") + ".";
|
||||
return new JsonObject { ["eb"] = eb, ["found"] = line, ["items"] = items };
|
||||
}
|
||||
|
||||
static string Files(int n) => n == 1 ? "1 file" : n + " files";
|
||||
|
||||
static readonly string[] MonthNames = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
|
||||
|
||||
/// <summary>"today", "yesterday", "16 Nov" (with the year when it is another year's).</summary>
|
||||
static string DayWord(DateTime t)
|
||||
{
|
||||
var d = (DateTime.Today - t.Date).Days;
|
||||
if (d == 0) return "today";
|
||||
if (d == 1) return "yesterday";
|
||||
return t.Day + " " + MonthNames[t.Month - 1] + (t.Year != DateTime.Today.Year ? " " + t.Year : "");
|
||||
}
|
||||
|
||||
static string SetLine(SaveSet s) =>
|
||||
(s.Slots > 0 ? Files(s.Slots) : "no files") + (s.Last > DateTime.MinValue ? ", saved " + DayWord(s.Last) : "");
|
||||
|
||||
// ---------------- bring in / copy out ----------------
|
||||
|
||||
/// <summary>Step one: where from (in) or where to (out). Refused at once while a game or emulator runs.</summary>
|
||||
void SavesFlow(bool into)
|
||||
{
|
||||
var game = GameDir;
|
||||
if (game == null) { Toast(into ? "Build the game first: your saves go into its folder." : "There is no game folder yet, so there are no saves to copy out.", "error"); return; }
|
||||
var saves = new Saves(ctx);
|
||||
if (saves.RunningGame() is { } running) { Toast("Close " + H(running) + " first: it would write its own saves back over the copy when it closes.", "error"); return; }
|
||||
if (!into && !Saves.IsSaveSet(saves.TriforceNewest(game))) { Toast("Triforce has no saves yet to copy out.", "error"); return; }
|
||||
List<SaveSet> found;
|
||||
try { found = saves.FindEmulatorSaves(); } catch (Exception e) { Log.Write("saves: " + e.Message); found = new(); }
|
||||
savesFound = found;
|
||||
var options = found.Select((f, i) => ("s" + i, f.Name, (string?)SetLine(f), i == 0)).ToList();
|
||||
options.Add(("folder", "A folder…", "Choose it yourself", found.Count == 0));
|
||||
if (into)
|
||||
Choice("Bring saves in", found.Count > 0 ? "Where are the saves you want to play with?" : "No emulator saves were found on this PC. Choose the folder they are in.",
|
||||
"saves.from", options, "Next");
|
||||
else
|
||||
Choice("Copy saves out", "Where should Triforce's saves go?", "saves.to", options, "Next");
|
||||
}
|
||||
|
||||
/// <summary>Step one answered: a found save set, or a folder to pick first.</summary>
|
||||
void SavesChosen(bool into, string? id)
|
||||
{
|
||||
if (id == null) return;
|
||||
if (id == "folder")
|
||||
{
|
||||
PickThen(true, into ? "Choose the folder with your saves" : "Choose where the saves go", path => SavesFolderPicked(into, path));
|
||||
return;
|
||||
}
|
||||
if (!id.StartsWith('s') || !int.TryParse(id.AsSpan(1), out var i) || i < 0 || i >= savesFound.Count) return;
|
||||
SavesAsk(into, savesFound[i]);
|
||||
}
|
||||
|
||||
void SavesFolderPicked(bool into, string path)
|
||||
{
|
||||
if (Saves.FindIn(path) is { } found)
|
||||
{
|
||||
SavesAsk(into, Saves.Describe(Path.GetFileName(found.TrimEnd('\\', '/')) is { Length: > 0 } n ? "the folder " + n : "that folder", found));
|
||||
return;
|
||||
}
|
||||
if (into) { Toast("There are no saves of this game in that folder.", "error"); return; }
|
||||
// (out: an empty folder takes the saves as they are; anything else gets a folder of their own inside it, never its own files replaced)
|
||||
var empty = !Directory.Exists(path) || !Directory.EnumerateFileSystemEntries(path).Any();
|
||||
var target = empty ? path : Path.Combine(path, "Triforce saves");
|
||||
if (!empty && Directory.Exists(target) && Directory.EnumerateFileSystemEntries(target).Any() && !Saves.IsSaveSet(target))
|
||||
{
|
||||
Toast("That folder already has a \"Triforce saves\" folder with other files in it. Choose an empty folder.", "error");
|
||||
return;
|
||||
}
|
||||
SavesAsk(false, Saves.Describe(empty ? "the folder " + Path.GetFileName(path.TrimEnd('\\', '/')) : "a new folder, Triforce saves", target));
|
||||
}
|
||||
|
||||
/// <summary>Step two: a plain question that names what gets replaced, and that it is backed up first.</summary>
|
||||
void SavesAsk(bool into, SaveSet set)
|
||||
{
|
||||
var game = GameDir;
|
||||
if (game == null) return;
|
||||
var key = (into ? "in:" : "out:") + Guid.NewGuid().ToString("N");
|
||||
savesPending[key] = set;
|
||||
var ours = Saves.Describe("Triforce", new Saves(ctx).TriforceNewest(game));
|
||||
string html;
|
||||
if (into)
|
||||
html = $"<p>The saves from <b>{H(set.Name)}</b> ({H(SetLine(set))}) become Triforce's.</p>" +
|
||||
(ours.Empty ? "<p>Triforce has no saves yet, so nothing is replaced.</p>"
|
||||
: $"<p>Triforce's own saves ({H(SetLine(ours))}) are replaced. They are backed up first, so you can go back to them.</p>");
|
||||
else
|
||||
html = $"<p>Triforce's saves ({H(SetLine(ours))}) are copied to <b>{H(set.Name)}</b>.</p>" +
|
||||
(set.Empty ? "<p>Nothing is there yet, so nothing is replaced.</p>"
|
||||
: $"<p>What is there now ({H(SetLine(set))}) is replaced. It is backed up first, so you can go back to it.</p>") +
|
||||
$"<p style=\"color:var(--text3);font-size:12.5px;overflow-wrap:anywhere\">{H(set.Folder)}</p>";
|
||||
Ask(into ? "Bring saves in" : "Copy saves out", html, "saves.confirm",
|
||||
new[] { ("cancel", "Cancel", false), ("go", into ? "Bring saves in" : "Copy saves out", true) }, key);
|
||||
}
|
||||
|
||||
async Task SavesConfirm(string? id, string? key)
|
||||
{
|
||||
if (key == null || !savesPending.TryRemove(key, out var set) || id != "go") return;
|
||||
var game = GameDir;
|
||||
if (game == null) return;
|
||||
var into = key.StartsWith("in:", StringComparison.Ordinal);
|
||||
var saves = new Saves(ctx);
|
||||
string? backup;
|
||||
try
|
||||
{
|
||||
backup = into ? await saves.ImportAsync(set, game) : await saves.ExportAsync(game, set);
|
||||
}
|
||||
catch (Exception e) when (e is SavesException || e is InvalidOperationException || e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
Log.Write("saves: " + e.Message);
|
||||
Toast(H(e.Message), "error");
|
||||
return;
|
||||
}
|
||||
var kept = backup != null ? " The ones they replaced are backed up in save-backups." : "";
|
||||
Toast((into ? "Your saves are in." : "Your saves are copied to " + H(set.Name) + ".") + kept, "success");
|
||||
SendSaves();
|
||||
if (into) RefreshHome();
|
||||
}
|
||||
|
||||
// ---------------- folders and links (shared by the three pages) ----------------
|
||||
|
||||
/// <summary>A folder in the system's file window. A test run opens no windows: it says so instead.</summary>
|
||||
void OpenPlace(string folder)
|
||||
{
|
||||
if (!Directory.Exists(folder)) { Toast("That folder is not there: " + H(folder), "error"); return; }
|
||||
if (ctx.TestRoot != null) { Toast("Test run: no window opens. " + H(folder)); Log.Write("open folder (test run, not opened): " + folder); return; }
|
||||
ctx.Platform.OpenFolder(folder);
|
||||
}
|
||||
|
||||
/// <summary>A web page in the player's browser (https only). A test run opens nothing: it says so instead.</summary>
|
||||
void OpenLink(string url)
|
||||
{
|
||||
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (ctx.TestRoot != null) { Toast("Test run: no browser opens. " + H(url)); Log.Write("open link (test run, not opened): " + url); return; }
|
||||
try
|
||||
{
|
||||
if (OperatingSystem.IsWindows()) System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true })?.Dispose();
|
||||
else
|
||||
{
|
||||
var si = new System.Diagnostics.ProcessStartInfo("xdg-open") { UseShellExecute = false };
|
||||
si.ArgumentList.Add(url);
|
||||
System.Diagnostics.Process.Start(si)?.Dispose();
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Log.Write("open " + url + ": " + e.Message); Toast("The page could not be opened: " + H(url), "error"); }
|
||||
}
|
||||
}
|
||||
348
launcher/App/Backend.Settings.cs
Normal file
348
launcher/App/Backend.Settings.cs
Normal file
@@ -0,0 +1,348 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Core.GameFiles;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>The Settings page (DESIGN 6 Settings): a plain list in groups, Launcher, Game, Shortcuts, Help, Remove. The page
|
||||
/// draws the list the launcher sends (state "settings"); pressing a row sends cmd 'setting' {id}. The two volume sliders are the
|
||||
/// page's and the core's ('sound'); they are only listed here. The benchmark (Backend.Bench.cs) is offered once a game is built.</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
const string DiscordUrl = "https://discord.gg/triforce";
|
||||
|
||||
partial void RegisterSettings()
|
||||
{
|
||||
On("settings.list", _ => SendSettings());
|
||||
On("setting", m => SettingPressed((string?)m["id"] ?? (string?)m["arg"]));
|
||||
On("settings.lang", m => LanguageChosen((string?)m["id"]));
|
||||
On("settings.dlss", m =>
|
||||
{
|
||||
if ((string?)m["id"] != "yes") return;
|
||||
new Dlss(ctx).Accept();
|
||||
Toast("NVIDIA DLSS is included from the next build.", "success");
|
||||
SendSettings();
|
||||
});
|
||||
On("settings.uninstall", m =>
|
||||
{
|
||||
if ((string?)m["id"] != "yes") return;
|
||||
Log.Write("uninstall from Settings");
|
||||
try { new Uninstaller(ctx).Run(); }
|
||||
catch (Exception e) { Log.Write("uninstall: " + e); Toast("Triforce could not be removed: " + H(e.Message), "error"); return; }
|
||||
host.Close();
|
||||
});
|
||||
}
|
||||
|
||||
partial void AddSettingsState(JsonObject state)
|
||||
{
|
||||
state["settings"] = SettingsRows();
|
||||
state["bench"] = BenchState();
|
||||
state["gameopts"] = GameOptsState();
|
||||
}
|
||||
|
||||
void SendSettings()
|
||||
{
|
||||
var o = new JsonObject();
|
||||
AddSettingsState(o);
|
||||
SendState(o);
|
||||
}
|
||||
|
||||
// ---------------- the list ----------------
|
||||
|
||||
static JsonObject Head(string h) => new() { ["h"] = h };
|
||||
|
||||
static JsonObject Row(string id, string label, string? value, string act, bool danger = false, bool off = false)
|
||||
{
|
||||
var o = new JsonObject { ["id"] = id, ["label"] = label, ["value"] = value ?? "", ["actLabel"] = act };
|
||||
if (danger) o["danger"] = true;
|
||||
if (off) o["off"] = true;
|
||||
return o;
|
||||
}
|
||||
|
||||
JsonArray SettingsRows()
|
||||
{
|
||||
var game = GameDir;
|
||||
var rows = new JsonArray
|
||||
{
|
||||
Head("Launcher"),
|
||||
new JsonObject { ["id"] = "music", ["label"] = "Music", ["kind"] = "slider" },
|
||||
new JsonObject { ["id"] = "sfx", ["label"] = "Sounds", ["kind"] = "slider" },
|
||||
Head("Game"),
|
||||
Row("folder", "Game folder", game ?? "Not built yet", "Open", off: game == null),
|
||||
};
|
||||
|
||||
// language: the one chosen, and whether the game folder was built in it
|
||||
var chosen = Languages.Find(ctx.Settings.Language) ?? (game != null ? Languages.Find(Game.FolderLanguage(game)) : null) ?? Languages.Default();
|
||||
var built = game != null ? Game.FolderLanguage(game) : null;
|
||||
rows.Add(Row("lang", "Game language", chosen.NativeName + (game != null && built != null && built != chosen.Code ? " · needs a build again" : ""), "Change"));
|
||||
|
||||
var dlss = new Dlss(ctx);
|
||||
if (dlss.Available)
|
||||
{
|
||||
var inGame = game != null && new Game(ctx).HasDlss(game);
|
||||
var value = dlss.Chosen ? (game != null && !inGame ? "Included · needs a build again" : "Included") : (inGame ? "Left out · needs a build again" : "Left out");
|
||||
rows.Add(Row("dlss", "NVIDIA DLSS", value, dlss.Chosen ? "Leave out" : "Include"));
|
||||
}
|
||||
rows.Add(Row("rebuild", "Build the game again", game != null ? Capital(RebuildTime()) : "Build the game first", "Build", off: game == null));
|
||||
|
||||
rows.Add(Head("Shortcuts"));
|
||||
rows.Add(Row("desktop", "Desktop shortcut", HasShortcut(ShortcutPlace.Desktop) ? "On" : "Off", HasShortcut(ShortcutPlace.Desktop) ? "Remove" : "Make"));
|
||||
var menu = ctx.IsWindows ? "Start menu" : "Applications menu";
|
||||
rows.Add(Row("startmenu", menu, HasShortcut(ShortcutPlace.StartMenu) ? "On" : "Off", HasShortcut(ShortcutPlace.StartMenu) ? "Remove" : "Make"));
|
||||
rows.Add(SteamRow(game));
|
||||
|
||||
rows.Add(Head("Help"));
|
||||
rows.Add(Row("log", "Log folder", ctx.Platform.LogFolder(ctx.Home), "Open"));
|
||||
rows.Add(Row("report", "Report", "What to paste when you ask for help", "Copy"));
|
||||
rows.Add(Row("discord", "Discord", "discord.gg/triforce", "Open"));
|
||||
rows.Add(Row("versions", "Versions", VersionsLine(game), "Copy"));
|
||||
|
||||
rows.Add(Head("Remove"));
|
||||
rows.Add(Row("uninstall", "Uninstall Triforce", "Your game folders and saves stay", "Uninstall", danger: true));
|
||||
return rows;
|
||||
}
|
||||
|
||||
static string Capital(string s) => s.Length > 0 ? char.ToUpperInvariant(s[0]) + s.Substring(1) : s;
|
||||
|
||||
string VersionsLine(string? game) =>
|
||||
"launcher " + BuildInfo.Version + " · tools " + (new Tools(ctx).InstalledVersion ?? "none") + " · game " + (game != null ? Game.BuiltVersion(game) ?? "unknown" : "not built");
|
||||
|
||||
bool HasShortcut(ShortcutPlace place)
|
||||
{
|
||||
try { return File.Exists(ctx.Platform.ShortcutPath(place)); } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
JsonObject SteamRow(string? game)
|
||||
{
|
||||
var steam = new SteamLibrary(ctx);
|
||||
string? root;
|
||||
try { root = steam.Root(); } catch (Exception) { root = null; }
|
||||
if (root == null) return Row("steam", "Steam", "Steam is not on this PC", "Add", off: true);
|
||||
if (game == null) return Row("steam", "Steam", "Build the game first", "Add", off: true);
|
||||
var user = steam.User();
|
||||
if (user == null) return Row("steam", "Steam", "Sign in to Steam once first", "Add", off: true);
|
||||
var running = steam.Running(root) ? " · close Steam first" : "";
|
||||
var exe = steam.ShortcutTarget(game);
|
||||
return steam.Added(user, exe)
|
||||
? Row("steam", "Steam", "In your library" + running, "Remove")
|
||||
: Row("steam", "Steam", "Not in your library" + running, "Add");
|
||||
}
|
||||
|
||||
// ---------------- a row pressed ----------------
|
||||
|
||||
void SettingPressed(string? id)
|
||||
{
|
||||
var game = GameDir;
|
||||
switch (id)
|
||||
{
|
||||
case "folder":
|
||||
if (game == null) { Toast("There is no game folder yet. Build the game first.", "error"); return; }
|
||||
OpenPlace(game);
|
||||
break;
|
||||
case "lang":
|
||||
{
|
||||
var cur = Languages.Find(ctx.Settings.Language) ?? (game != null ? Languages.Find(Game.FolderLanguage(game)) : null) ?? Languages.Default();
|
||||
Choice("Game language", "The game's text and voices. A change takes effect when the game is built again.", "settings.lang",
|
||||
Languages.All.Select(l => (l.Code, l.NativeName, (string?)(l.NativeName != l.EnglishName ? l.EnglishName : null), l.Code == cur.Code)), "Choose");
|
||||
break;
|
||||
}
|
||||
case "dlss":
|
||||
{
|
||||
var dlss = new Dlss(ctx);
|
||||
if (dlss.Chosen)
|
||||
{
|
||||
dlss.TurnOff();
|
||||
Toast("NVIDIA DLSS is left out from the next build.", "success");
|
||||
SendSettings();
|
||||
return;
|
||||
}
|
||||
var html = string.Join("", dlss.LicenseText.Split("\n\n").Select(p => "<p>" + H(p).Replace("\n", "<br>") + "</p>"));
|
||||
Ask("NVIDIA DLSS", html, "settings.dlss", new[] { ("no", "Cancel", false), ("yes", Dlss.AcceptLabel, true) });
|
||||
break;
|
||||
}
|
||||
case "rebuild":
|
||||
if (game == null) { Toast("Build the game first.", "error"); return; }
|
||||
StartRebuild();
|
||||
break;
|
||||
case "desktop":
|
||||
case "startmenu":
|
||||
ToggleShortcut(id == "desktop" ? ShortcutPlace.Desktop : ShortcutPlace.StartMenu);
|
||||
break;
|
||||
case "steam":
|
||||
SteamPressed(game);
|
||||
break;
|
||||
case "log":
|
||||
OpenPlace(ctx.Platform.LogFolder(ctx.Home));
|
||||
break;
|
||||
case "report":
|
||||
Copy(SettingsReport(game));
|
||||
break;
|
||||
case "discord":
|
||||
OpenLink(DiscordUrl);
|
||||
break;
|
||||
case "versions":
|
||||
Copy("Triforce " + VersionsLine(game));
|
||||
break;
|
||||
case "uninstall":
|
||||
{
|
||||
var plan = new Uninstaller(ctx).Describe();
|
||||
string List(IEnumerable<string> l) => "<ul style=\"margin:4px 0 0 20px\">" + string.Join("", l.Select(x => "<li>" + H(Capital(x)) + "</li>")) + "</ul>";
|
||||
Ask("Uninstall Triforce", "<p>This removes:</p>" + List(plan.Removes) + "<p>This keeps:</p>" + List(plan.Keeps), "settings.uninstall",
|
||||
new[] { ("no", "Keep Triforce", false), ("yes", "Uninstall", true) });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void LanguageChosen(string? code)
|
||||
{
|
||||
if (Languages.Find(code) is not { } lang) return;
|
||||
ctx.Settings.Language = lang.Code;
|
||||
var game = GameDir;
|
||||
if (game != null && Game.FolderLanguage(game) != lang.Code)
|
||||
Toast(H(lang.NativeName) + " is used from the next build. Build the game again to play in it.", "success");
|
||||
else Toast("The game's language is " + H(lang.NativeName) + ".", "success");
|
||||
SendSettings();
|
||||
}
|
||||
|
||||
void ToggleShortcut(ShortcutPlace place)
|
||||
{
|
||||
var path = ctx.Platform.ShortcutPath(place);
|
||||
try
|
||||
{
|
||||
ctx.Require(path);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
if (place == ShortcutPlace.Desktop) ctx.Settings.Desktop = false; else ctx.Settings.StartMenu = false;
|
||||
Toast("The shortcut is removed.", "success");
|
||||
}
|
||||
else
|
||||
{
|
||||
var exe = ctx.IsWindows ? (ctx.InstalledDir is { } d ? Path.Combine(d, BuildInfo.SetupAsset) : ctx.SelfPath) : ctx.Env("APPIMAGE") ?? ctx.SelfPath;
|
||||
ctx.Platform.CreateShortcut(place, new Shortcut(exe, "", Path.GetDirectoryName(exe)!, exe, "Play Triforce"));
|
||||
if (place == ShortcutPlace.Desktop) ctx.Settings.Desktop = true; else ctx.Settings.StartMenu = true;
|
||||
Toast(File.Exists(path) ? "The shortcut is made." : "The shortcut could not be made.", File.Exists(path) ? "success" : "error");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Write("shortcut: " + e.Message);
|
||||
Toast("The shortcut could not be changed: " + H(e.Message), "error");
|
||||
}
|
||||
SendSettings();
|
||||
}
|
||||
|
||||
void SteamPressed(string? game)
|
||||
{
|
||||
var steam = new SteamLibrary(ctx);
|
||||
var root = steam.Root();
|
||||
if (root == null) { Toast("Steam is not on this PC.", "error"); return; }
|
||||
if (game == null) { Toast("Build the game first, then add it to Steam.", "error"); return; }
|
||||
var user = steam.User();
|
||||
if (user == null) { Toast("Start Steam, sign in once, close it, then try again.", "error"); return; }
|
||||
if (steam.Running(root)) { Toast(H(SteamLibrary.CloseFirst), "error"); return; }
|
||||
var exe = steam.ShortcutTarget(game);
|
||||
try
|
||||
{
|
||||
if (steam.Added(user, exe))
|
||||
{
|
||||
steam.Remove(user, exe);
|
||||
Toast("Triforce is out of your Steam library.", "success");
|
||||
}
|
||||
else
|
||||
{
|
||||
steam.Add(user, exe, SteamPictures());
|
||||
Toast("Triforce is in your Steam library. Start Steam to see it.", "success");
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is SteamException || e is InvalidOperationException || e is IOException)
|
||||
{
|
||||
Toast(H(e.Message), "error");
|
||||
}
|
||||
SendSettings();
|
||||
}
|
||||
|
||||
/// <summary>Steam's pictures, made from the game's own title logo: the logo centred on the launcher's dark (the "logo" kind,
|
||||
/// drawn over Steam's own hero picture, without the dark). None when the game's art is not read.</summary>
|
||||
Dictionary<string, byte[]> SteamPictures()
|
||||
{
|
||||
var pics = new Dictionary<string, byte[]>();
|
||||
try
|
||||
{
|
||||
if (MediaFor("png", "Logo_USEU_00") is not { } png) return pics;
|
||||
var (lw, lh, rgba) = Png.Decode(png);
|
||||
foreach (var (kind, _, w, h) in SteamVdf.Pictures)
|
||||
{
|
||||
var clear = kind == "logo";
|
||||
var fill = kind == "icon" ? 0.92 : kind == "logo" ? 0.96 : 0.72;
|
||||
pics[kind] = Png.Encode(Compose(rgba, lw, lh, w, h, fill, clear), w, h);
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Log.Write("steam art: " + e.Message); }
|
||||
return pics;
|
||||
}
|
||||
|
||||
/// <summary>A w x h picture: #0a0908 (or clear), the logo scaled to fit fill of it, centred (bilinear, over the background).</summary>
|
||||
static byte[] Compose(byte[] src, int sw, int sh, int w, int h, double fill, bool clear)
|
||||
{
|
||||
var o = new byte[w * h * 4];
|
||||
if (!clear)
|
||||
for (var i = 0; i < w * h; i++) { o[i * 4] = 0x0a; o[i * 4 + 1] = 0x09; o[i * 4 + 2] = 0x08; o[i * 4 + 3] = 255; }
|
||||
var k = Math.Min(w * fill / sw, h * fill / sh);
|
||||
int dw = Math.Max(1, (int)(sw * k)), dh = Math.Max(1, (int)(sh * k)), x0 = (w - dw) / 2, y0 = (h - dh) / 2;
|
||||
for (var y = 0; y < dh; y++)
|
||||
{
|
||||
var fy = Math.Clamp((y + 0.5) / k - 0.5, 0, sh - 1);
|
||||
int ya = (int)fy, yb = Math.Min(sh - 1, ya + 1);
|
||||
var ty = fy - ya;
|
||||
for (var x = 0; x < dw; x++)
|
||||
{
|
||||
var fx = Math.Clamp((x + 0.5) / k - 0.5, 0, sw - 1);
|
||||
int xa = (int)fx, xb = Math.Min(sw - 1, xa + 1);
|
||||
var tx = fx - xa;
|
||||
// (premultiplied, so the edges of the logo do not take on the colour of its clear pixels)
|
||||
double r = 0, g = 0, b = 0, a = 0;
|
||||
void Tap(int px, int py, double wt)
|
||||
{
|
||||
var p = (py * sw + px) * 4;
|
||||
var al = src[p + 3] / 255.0 * wt;
|
||||
r += src[p] * al; g += src[p + 1] * al; b += src[p + 2] * al; a += al;
|
||||
}
|
||||
Tap(xa, ya, (1 - tx) * (1 - ty)); Tap(xb, ya, tx * (1 - ty)); Tap(xa, yb, (1 - tx) * ty); Tap(xb, yb, tx * ty);
|
||||
var q = ((y0 + y) * w + x0 + x) * 4;
|
||||
if (clear)
|
||||
{
|
||||
if (a > 0) { o[q] = (byte)Math.Round(r / a); o[q + 1] = (byte)Math.Round(g / a); o[q + 2] = (byte)Math.Round(b / a); }
|
||||
o[q + 3] = (byte)Math.Round(a * 255);
|
||||
}
|
||||
else
|
||||
{
|
||||
o[q] = (byte)Math.Round(r + o[q] * (1 - a)); o[q + 1] = (byte)Math.Round(g + o[q + 1] * (1 - a)); o[q + 2] = (byte)Math.Round(b + o[q + 2] * (1 - a));
|
||||
}
|
||||
}
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>What a player pastes where they ask for help: versions, system, the game folder, the graphics card, the choices,
|
||||
/// the mods, then setup.log's last lines; the account's folder reads %USERPROFILE%.</summary>
|
||||
string SettingsReport(string? game)
|
||||
{
|
||||
var known = new List<string>
|
||||
{
|
||||
"Triforce " + VersionsLine(game) + ", " + Environment.OSVersion.VersionString,
|
||||
"Game folder: " + (game ?? ctx.Settings.GameFolder ?? "none") + (game != null ? " (language " + (Game.FolderLanguage(game) ?? "unknown") + (new Game(ctx).HasDlss(game) ? ", with NVIDIA DLSS" : "") + ")" : ""),
|
||||
"Graphics: " + (string.Join(", ", Gpus.List().Select(g => g.Name)) is { Length: > 0 } gpus ? gpus : "unknown"),
|
||||
"Launcher: " + ctx.Home + (ctx.TestRoot != null ? " (test run in " + ctx.TestRoot + ")" : ""),
|
||||
};
|
||||
if (game != null)
|
||||
{
|
||||
var mods = MineMods(game, false);
|
||||
known.Add("Mods: " + mods.Count + " (" + mods.Count(m => m.On) + " on)" + (mods.Count > 0 ? ": " + string.Join(", ", mods.Select(m => (m.On ? "" : "off ") + m.Rel)) : ""));
|
||||
}
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
return Report.NoName(string.Join(Environment.NewLine, known) + Environment.NewLine + Environment.NewLine + "---- setup.log's last lines ----" + Environment.NewLine +
|
||||
Report.Tail(ctx.Log.ReadAll(), Report.Lines), profile);
|
||||
}
|
||||
}
|
||||
141
launcher/App/Backend.cs
Normal file
141
launcher/App/Backend.cs
Normal file
@@ -0,0 +1,141 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Launcher.Host;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>The launcher's side of the page: takes the page's messages (JSON with a "t" type; commands are
|
||||
/// {t:'cmd', c:name, ...}) and answers with state. The logic lives in Triforce.Logic (install, release, build, saves, mods)
|
||||
/// and Triforce.Core (the game's files). Each area is its own partial file and registers its commands:
|
||||
/// Backend.Core.cs first run, build, home, update, Play (RegisterCore)
|
||||
/// Backend.Saves.cs the Saves page (RegisterSaves)
|
||||
/// Backend.Mods.cs the Mods page (RegisterMods)
|
||||
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)</summary>
|
||||
public sealed partial class Backend
|
||||
{
|
||||
readonly IHost host;
|
||||
readonly Content content;
|
||||
readonly string dataDir;
|
||||
readonly TriforceContext ctx;
|
||||
readonly StartupResult start;
|
||||
readonly Dictionary<string, Action<JsonNode, string[]>> cmds = new();
|
||||
|
||||
public Backend(IHost host, Content content, TriforceContext ctx, StartupResult start, string dataDir)
|
||||
{
|
||||
this.host = host; this.content = content; this.ctx = ctx; this.start = start; this.dataDir = dataDir;
|
||||
content.Media = MediaFor;
|
||||
content.SavePicture = SavePicture;
|
||||
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts();
|
||||
}
|
||||
|
||||
partial void RegisterSaves();
|
||||
partial void RegisterMods();
|
||||
partial void RegisterSettings();
|
||||
|
||||
/// <summary>A command from the page: {t:'cmd', c:name, ...}. Handlers run on a worker thread; anything slow is fine.</summary>
|
||||
void On(string name, Action<JsonNode, string[]> handler) => cmds[name] = handler;
|
||||
void On(string name, Action<JsonNode> handler) => cmds[name] = (m, _) => handler(m);
|
||||
void OnAsync(string name, Func<JsonNode, Task> handler) => cmds[name] = (m, f) => { _ = Guarded(name, () => handler(m)); };
|
||||
|
||||
async Task Guarded(string what, Func<Task> f)
|
||||
{
|
||||
try { await f(); }
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Write(what + ": " + e);
|
||||
Toast("Something went wrong: " + H(e.Message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
public void OnMessage(string json, string[] files)
|
||||
{
|
||||
JsonNode? m;
|
||||
try { m = JsonNode.Parse(json); } catch { Log.Write("bad message " + json); return; }
|
||||
if (m == null) return;
|
||||
var t = (string?)m["t"];
|
||||
try
|
||||
{
|
||||
switch (t)
|
||||
{
|
||||
case "ready": OnReady(); break;
|
||||
case "win":
|
||||
switch ((string?)m["a"])
|
||||
{
|
||||
case "min": host.Minimize(); break;
|
||||
case "max": host.ToggleMaximize(); break;
|
||||
case "close": RequestClose(); break;
|
||||
}
|
||||
break;
|
||||
case "log": Log.Write("page: " + (string?)m["s"]); break;
|
||||
case "pick": OnPick((string?)m["kind"] == "folder"); break;
|
||||
case "drop": if (files.Length > 0) _ = Intake(files[0]); break;
|
||||
case "cmd":
|
||||
var c = (string?)m["c"] ?? "";
|
||||
if (cmds.TryGetValue(c, out var h))
|
||||
Task.Run(() => { try { h(m, files); } catch (Exception e) { Log.Write("cmd " + c + ": " + e); Toast("Something went wrong: " + H(e.Message), "error"); } });
|
||||
else Log.Write("unhandled cmd " + c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Write("message " + t + ": " + e);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- talking to the page ----------------
|
||||
public void Send(JsonNode n) => host.Post(n.ToJsonString());
|
||||
/// <summary>Parts of the page's state, e.g. SendState(new() { ["saves"] = ... }).</summary>
|
||||
public void SendState(JsonObject parts) { parts["t"] = "state"; Send(parts); }
|
||||
public void Go(string screen) => Send(new JsonObject { ["t"] = "go", ["s"] = screen });
|
||||
public void Sfx(string id) => Send(new JsonObject { ["t"] = "sfx", ["id"] = id });
|
||||
/// <summary>A short line at the top (HTML: keep it to b/em/span; encode anything from outside with H()).</summary>
|
||||
public void Toast(string html, string? sfx = null)
|
||||
{
|
||||
var o = new JsonObject { ["t"] = "toast", ["html"] = html };
|
||||
if (sfx != null) o["sfx"] = sfx;
|
||||
Send(o);
|
||||
}
|
||||
public void Copy(string text) => Send(new JsonObject { ["t"] = "copy", ["text"] = text });
|
||||
|
||||
/// <summary>A list to choose one from. The choice comes back as the command <paramref name="reply"/> with {id, ctx}.</summary>
|
||||
public void Choice(string title, string? textHtml, string reply, IEnumerable<(string id, string name, string? sub, bool sel)> options, string ok = "Choose", string? context = null)
|
||||
{
|
||||
var arr = new JsonArray();
|
||||
foreach (var (id, name, sub, sel) in options) arr.Add(new JsonObject { ["id"] = id, ["name"] = name, ["sub"] = sub, ["sel"] = sel });
|
||||
Send(new JsonObject { ["t"] = "choice", ["title"] = title, ["text"] = textHtml, ["reply"] = reply, ["options"] = arr, ["ok"] = ok, ["ctx"] = context });
|
||||
}
|
||||
|
||||
/// <summary>A question with buttons. The pressed button's id comes back as the command <paramref name="reply"/> with {id, ctx}.
|
||||
/// One button at most is the main (gold) one.</summary>
|
||||
public void Ask(string title, string html, string reply, IEnumerable<(string id, string label, bool main)> buttons, string? context = null)
|
||||
{
|
||||
var arr = new JsonArray();
|
||||
foreach (var (id, label, main) in buttons) arr.Add(new JsonObject { ["id"] = id, ["label"] = label, ["main"] = main });
|
||||
Send(new JsonObject { ["t"] = "ask", ["title"] = title, ["html"] = html, ["reply"] = reply, ["buttons"] = arr, ["ctx"] = context });
|
||||
}
|
||||
|
||||
public static string H(string? s) => System.Net.WebUtility.HtmlEncode(s ?? "");
|
||||
|
||||
/// <summary>The built game folder (null before the first build).</summary>
|
||||
public string? GameDir => new Game(ctx).Current;
|
||||
|
||||
/// <summary>A file / folder picker on the window's thread (it must be), then the answer on a worker.</summary>
|
||||
public void PickThen(bool folder, string title, Action<string> then, string filterName = "All files", string pattern = "*.*")
|
||||
{
|
||||
host.Invoke(() =>
|
||||
{
|
||||
var path = folder ? host.PickFolder(title) : host.PickFile(title, filterName, pattern);
|
||||
if (path != null) Task.Run(() => { try { then(path); } catch (Exception e) { Log.Write("pick: " + e); Toast("Something went wrong: " + H(e.Message), "error"); } });
|
||||
});
|
||||
}
|
||||
|
||||
void OnPick(bool folder) =>
|
||||
PickThen(folder, folder ? "Choose the folder with romfs and exefs in it" : "Choose your game", p => _ = Intake(p), "Game file (*.nup)", "*.nup");
|
||||
|
||||
public void Shutdown()
|
||||
{
|
||||
try { StopEverything(); } catch { }
|
||||
try { start.Lock?.Dispose(); } catch { }
|
||||
}
|
||||
}
|
||||
79
launcher/App/Content.cs
Normal file
79
launcher/App/Content.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using System.Reflection;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>What the page asks the window for, by path under the origin:
|
||||
/// ui/... the page itself (embedded in the exe)
|
||||
/// media/png/NAME a texture from the player's own game (Core/GameFiles), e.g. the title logo
|
||||
/// media/wav/ID music or a sound from the player's own game
|
||||
/// save/N.jpg the picture in save file N (the game's own caption.sav)
|
||||
/// Anything not there answers 404, and the page falls back (no game yet: no game art, no music).</summary>
|
||||
public sealed class Content
|
||||
{
|
||||
public delegate byte[]? MediaSource(string kind, string name);
|
||||
|
||||
readonly Assembly asm = typeof(Content).Assembly;
|
||||
readonly Dictionary<string, string> names;
|
||||
public MediaSource? Media;
|
||||
public Func<int, byte[]?>? SavePicture;
|
||||
|
||||
public Content()
|
||||
{
|
||||
// Resource names come out as "ui/img\crest.png" on Windows builds: make them all forward slashes.
|
||||
names = asm.GetManifestResourceNames().ToDictionary(n => n.Replace('\\', '/'), n => n, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public (byte[] data, string mime)? Get(string path)
|
||||
{
|
||||
path = Uri.UnescapeDataString(path.Split('?', '#')[0]).TrimStart('/');
|
||||
// The page names the game's art and sounds as its own files (as the prototype did); they come from the game.
|
||||
if (path.StartsWith("ui/img/game/", StringComparison.Ordinal)) path = "media/png/" + path["ui/img/game/".Length..];
|
||||
else if (path.StartsWith("ui/audio/", StringComparison.Ordinal)) path = "media/wav/" + path["ui/audio/".Length..];
|
||||
else if (path.StartsWith("ui/img/save", StringComparison.Ordinal) && path.EndsWith(".jpg")) path = "save/" + path["ui/img/save".Length..];
|
||||
try
|
||||
{
|
||||
if (path.StartsWith("ui/", StringComparison.Ordinal))
|
||||
{
|
||||
if (!names.TryGetValue(path, out var res)) return null;
|
||||
using var s = asm.GetManifestResourceStream(res)!;
|
||||
using var m = new MemoryStream();
|
||||
s.CopyTo(m);
|
||||
return (m.ToArray(), Mime(path));
|
||||
}
|
||||
if (path.StartsWith("media/", StringComparison.Ordinal))
|
||||
{
|
||||
var parts = path.Split('/');
|
||||
if (parts.Length != 3 || Media == null) return null;
|
||||
var name = Path.GetFileNameWithoutExtension(parts[2]);
|
||||
var data = Media(parts[1], name);
|
||||
return data == null ? null : (data, parts[1] == "png" ? "image/png" : "audio/wav");
|
||||
}
|
||||
if (path.StartsWith("save/", StringComparison.Ordinal) && SavePicture != null &&
|
||||
int.TryParse(Path.GetFileNameWithoutExtension(path)[..Math.Min(2, Path.GetFileNameWithoutExtension(path).Length)], out var n))
|
||||
{
|
||||
var j = SavePicture(n);
|
||||
return j == null ? null : (j, "image/jpeg");
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Write("content " + path + ": " + e.Message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static string Mime(string p) => Path.GetExtension(p).ToLowerInvariant() switch
|
||||
{
|
||||
".html" => "text/html; charset=utf-8",
|
||||
".css" => "text/css; charset=utf-8",
|
||||
".js" => "text/javascript; charset=utf-8",
|
||||
".png" => "image/png",
|
||||
".jpg" or ".jpeg" => "image/jpeg",
|
||||
".svg" => "image/svg+xml",
|
||||
".woff2" => "font/woff2",
|
||||
".ttf" => "font/ttf",
|
||||
".wav" => "audio/wav",
|
||||
".json" => "application/json",
|
||||
_ => "application/octet-stream",
|
||||
};
|
||||
}
|
||||
37
launcher/App/Host/IHost.cs
Normal file
37
launcher/App/Host/IHost.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
namespace Triforce.Launcher.Host;
|
||||
|
||||
/// <summary>The window the page lives in. Windows: WinHost (WebView2 in our own frameless window). Linux: LinuxHost
|
||||
/// (Photino, WebKitGTK, the desktop's own window frame).</summary>
|
||||
public interface IHost
|
||||
{
|
||||
/// <summary>Opens the window on the page and returns when it closes. Call on the thread that made the host.</summary>
|
||||
void Run();
|
||||
|
||||
/// <summary>Sends one JSON message to the page. Any thread.</summary>
|
||||
void Post(string json);
|
||||
|
||||
/// <summary>Runs an action on the window's thread.</summary>
|
||||
void Invoke(Action a);
|
||||
|
||||
/// <summary>A message from the page: its JSON, and the full paths of any files dropped with it (Windows hands those over
|
||||
/// with the drop; Linux hands over file:// links in the JSON instead).</summary>
|
||||
event Action<string, string[]> Message;
|
||||
|
||||
void Minimize();
|
||||
void ToggleMaximize();
|
||||
void Close();
|
||||
void Activate();
|
||||
/// <summary>Asks for the player's eye without taking the focus (Windows: the taskbar button flashes until the window is
|
||||
/// in front; Linux: a desktop notification).</summary>
|
||||
void Attention(string title, string text);
|
||||
|
||||
/// <summary>The system's file picker. Null when cancelled.</summary>
|
||||
string? PickFile(string title, string filterName, string pattern);
|
||||
string? PickFolder(string title);
|
||||
|
||||
/// <summary>True when the page draws the title bar itself (Windows); false when the desktop draws it (Linux).</summary>
|
||||
bool CustomChrome { get; }
|
||||
|
||||
/// <summary>Where the page is served from, e.g. https://app.triforce/ (ends with a slash).</summary>
|
||||
string Origin { get; }
|
||||
}
|
||||
89
launcher/App/Host/LinuxHost.cs
Normal file
89
launcher/App/Host/LinuxHost.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Photino.NET;
|
||||
|
||||
namespace Triforce.Launcher.Host;
|
||||
|
||||
/// <summary>Linux: Photino (WebKitGTK) in a window the desktop frames (on a Steam Deck in Game Mode, gamescope shows it full
|
||||
/// screen). Photino will not open a page on its own scheme as the first page, so the page is handed over as a string with
|
||||
/// a base address on app://localhost/ui/, and everything it loads after that comes through the app:// scheme.
|
||||
/// Dropped files: WebKitGTK puts file:// links in the drop's text/uri-list, so the page sends them in the JSON.</summary>
|
||||
public sealed class LinuxHost : IHost
|
||||
{
|
||||
public string Origin => "app://localhost/";
|
||||
public bool CustomChrome => false;
|
||||
public event Action<string, string[]>? Message;
|
||||
|
||||
readonly Content content;
|
||||
readonly PhotinoWindow win;
|
||||
readonly List<string> early = new();
|
||||
bool pageReady;
|
||||
|
||||
public LinuxHost(Content content, string dataDir, bool devTools)
|
||||
{
|
||||
this.content = content;
|
||||
win = new PhotinoWindow()
|
||||
.SetTitle("Triforce")
|
||||
.SetUseOsDefaultSize(false).SetSize(1280, 800).SetMinSize(1024, 640).Center()
|
||||
.SetResizable(true)
|
||||
.SetDevToolsEnabled(devTools).SetContextMenuEnabled(devTools)
|
||||
.SetGrantBrowserPermissions(true)
|
||||
.SetTemporaryFilesPath(dataDir)
|
||||
.RegisterCustomSchemeHandler("app", Serve)
|
||||
.RegisterWebMessageReceivedHandler((_, m) => OnMessage(m));
|
||||
var icon = Path.Combine(AppContext.BaseDirectory, "triforce.png");
|
||||
if (File.Exists(icon)) win.SetIconFile(icon);
|
||||
}
|
||||
|
||||
Stream Serve(object sender, string scheme, string url, out string contentType)
|
||||
{
|
||||
var path = url.Substring(url.IndexOf("://", StringComparison.Ordinal) + 3);
|
||||
path = path.Substring(path.IndexOf('/') is var i and >= 0 ? i : path.Length);
|
||||
var got = content.Get(path);
|
||||
if (got is { } g) { contentType = g.mime; return new MemoryStream(g.data); }
|
||||
contentType = "text/plain";
|
||||
return new MemoryStream(Array.Empty<byte>());
|
||||
}
|
||||
|
||||
void OnMessage(string json)
|
||||
{
|
||||
var files = new List<string>();
|
||||
foreach (Match m in Regex.Matches(json, "\"file://([^\"]+)\""))
|
||||
files.Add(Uri.UnescapeDataString(m.Groups[1].Value));
|
||||
if (json.Contains("\"t\":\"ready\"")) { pageReady = true; foreach (var p in early) win.SendWebMessage(p); early.Clear(); }
|
||||
Message?.Invoke(json, files.ToArray());
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
var page = content.Get("ui/index.html")!.Value.data;
|
||||
var html = Encoding.UTF8.GetString(page).Replace("<head>", "<head><base href=\"" + Origin + "ui/\">");
|
||||
win.LoadRawString(html);
|
||||
win.WaitForClose();
|
||||
}
|
||||
|
||||
public void Post(string json) => Invoke(() =>
|
||||
{
|
||||
if (!pageReady) { early.Add(json); return; }
|
||||
win.SendWebMessage(json);
|
||||
});
|
||||
|
||||
public void Invoke(Action a) => win.Invoke(a);
|
||||
public void Minimize() => Invoke(() => win.SetMinimized(true));
|
||||
public void ToggleMaximize() => Invoke(() => win.SetMaximized(!win.Maximized));
|
||||
public void Close() => Invoke(() => win.Close());
|
||||
public void Attention(string title, string text) => Invoke(() => { try { win.SendNotification(title, text); } catch { } });
|
||||
public void Activate() => Invoke(() => win.SetMinimized(false));
|
||||
|
||||
public string? PickFile(string title, string filterName, string pattern)
|
||||
{
|
||||
var r = win.ShowOpenFile(title, null, false, new (string, string[])[] { (filterName, new[] { pattern }), ("All files", new[] { "*" }) });
|
||||
return r is { Length: > 0 } ? r[0] : null;
|
||||
}
|
||||
|
||||
public string? PickFolder(string title)
|
||||
{
|
||||
var r = win.ShowOpenFolder(title, null, false);
|
||||
return r is { Length: > 0 } ? r[0] : null;
|
||||
}
|
||||
}
|
||||
360
launcher/App/Host/WinHost.cs
Normal file
360
launcher/App/Host/WinHost.cs
Normal file
@@ -0,0 +1,360 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Web.WebView2.Core;
|
||||
|
||||
namespace Triforce.Launcher.Host;
|
||||
|
||||
/// <summary>Windows: a plain Win32 window with no frame of its own (the page draws the bar and the three window buttons),
|
||||
/// WebView2 filling it. The page is served from https://app.triforce/ by WebResourceRequested (a real secure origin, so
|
||||
/// the page behaves exactly as in a browser). Dropped files arrive with their full paths
|
||||
/// (chrome.webview.postMessageWithAdditionalObjects), which a page alone can never see.</summary>
|
||||
public sealed class WinHost : IHost
|
||||
{
|
||||
public const string Host = "app.triforce";
|
||||
public string Origin => "https://" + Host + "/";
|
||||
public bool CustomChrome => true;
|
||||
public event Action<string, string[]>? Message;
|
||||
|
||||
readonly Content content;
|
||||
readonly string dataDir;
|
||||
readonly bool devTools;
|
||||
readonly int width, height;
|
||||
IntPtr hwnd;
|
||||
WndProc? proc; // kept alive: the window calls it
|
||||
CoreWebView2Environment? env;
|
||||
CoreWebView2Controller? ctl;
|
||||
CoreWebView2? web;
|
||||
readonly ConcurrentQueue<Action> queue = new();
|
||||
readonly List<string> early = new(); // messages posted before the page could take them
|
||||
bool pageReady;
|
||||
|
||||
public WinHost(Content content, string dataDir, bool devTools, int width = 1280, int height = 800)
|
||||
{
|
||||
this.content = content; this.dataDir = dataDir; this.devTools = devTools; this.width = width; this.height = height;
|
||||
}
|
||||
|
||||
/// <summary>Is the WebView2 runtime on this PC? (Windows 11 always; Windows 10 nearly always via Edge.) The old Setup
|
||||
/// rolls back when the new exe exits nonzero fast, so the caller checks this first and exits 3 when it is missing.</summary>
|
||||
public static string? RuntimeVersion()
|
||||
{
|
||||
try { return CoreWebView2Environment.GetAvailableBrowserVersionString(); } catch { return null; }
|
||||
}
|
||||
|
||||
public void Run()
|
||||
{
|
||||
SetProcessDpiAwarenessContext(new IntPtr(-4)); // per monitor v2 (the manifest says so too)
|
||||
var hinst = GetModuleHandle(null);
|
||||
proc = WindowProc;
|
||||
var wc = new WNDCLASSEX
|
||||
{
|
||||
cbSize = Marshal.SizeOf<WNDCLASSEX>(), style = 0x0003, lpfnWndProc = proc, hInstance = hinst,
|
||||
hCursor = LoadCursor(IntPtr.Zero, 32512), hbrBackground = CreateSolidBrush(0x00080a0a), lpszClassName = "TriforceLauncher",
|
||||
hIcon = LoadIcon(hinst, new IntPtr(32512)), hIconSm = LoadIcon(hinst, new IntPtr(32512)),
|
||||
};
|
||||
RegisterClassEx(ref wc);
|
||||
|
||||
// Size: 1280 x 800 at the system's scale, never bigger than 92 % of the work area (keeps the 16:10 shape).
|
||||
var dpi = GetDpiForSystem();
|
||||
var work = new RECT(); SystemParametersInfo(0x0030, 0, ref work, 0);
|
||||
double k = dpi / 96.0, ww = work.right - work.left, wh = work.bottom - work.top;
|
||||
k = Math.Min(k, Math.Min(ww * .92 / width, wh * .92 / height));
|
||||
int w = (int)(width * k), h = (int)(height * k);
|
||||
int x = work.left + (int)(ww - w) / 2, y = work.top + (int)(wh - h) / 2;
|
||||
const uint style = 0x00CF0000 & ~0x00040000u; // overlapped window, minus the sizing border (fixed size, maximize allowed)
|
||||
hwnd = CreateWindowEx(0, "TriforceLauncher", "Triforce", style, x, y, w, h, IntPtr.Zero, IntPtr.Zero, hinst, IntPtr.Zero);
|
||||
var m = new MARGINS { cyBottomHeight = 1 };
|
||||
DwmExtendFrameIntoClientArea(hwnd, ref m); // keeps Windows' own shadow and rounded corners
|
||||
int dark = 1; DwmSetWindowAttribute(hwnd, 20, ref dark, 4);
|
||||
SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, 0x0027); // frame changed: our WM_NCCALCSIZE takes effect
|
||||
|
||||
SynchronizationContext.SetSynchronizationContext(new Ctx(this));
|
||||
_ = StartWebView();
|
||||
ShowWindow(hwnd, 5);
|
||||
UpdateWindow(hwnd);
|
||||
|
||||
while (GetMessage(out var msg, IntPtr.Zero, 0, 0) > 0)
|
||||
{
|
||||
TranslateMessage(ref msg);
|
||||
DispatchMessage(ref msg);
|
||||
}
|
||||
try { ctl?.Close(); } catch { }
|
||||
}
|
||||
|
||||
async Task StartWebView()
|
||||
{
|
||||
try
|
||||
{
|
||||
var opt = new CoreWebView2EnvironmentOptions("--autoplay-policy=no-user-gesture-required --disable-features=msSmartScreenProtection");
|
||||
env = await CoreWebView2Environment.CreateAsync(null, dataDir, opt);
|
||||
ctl = await env.CreateCoreWebView2ControllerAsync(hwnd);
|
||||
ctl.DefaultBackgroundColor = System.Drawing.Color.FromArgb(255, 10, 9, 8);
|
||||
Resize();
|
||||
web = ctl.CoreWebView2;
|
||||
var s = web.Settings;
|
||||
s.AreDevToolsEnabled = devTools;
|
||||
s.AreDefaultContextMenusEnabled = devTools;
|
||||
s.AreBrowserAcceleratorKeysEnabled = devTools;
|
||||
s.IsZoomControlEnabled = false;
|
||||
s.IsStatusBarEnabled = false;
|
||||
s.IsPinchZoomEnabled = false;
|
||||
s.IsSwipeNavigationEnabled = false;
|
||||
s.IsPasswordAutosaveEnabled = false;
|
||||
s.IsGeneralAutofillEnabled = false;
|
||||
s.IsNonClientRegionSupportEnabled = true; // CSS app-region: drag = our title bar (move, snap, double-click)
|
||||
web.AddWebResourceRequestedFilter("https://" + Host + "/*", CoreWebView2WebResourceContext.All);
|
||||
web.WebResourceRequested += OnRequest;
|
||||
web.WebMessageReceived += OnMessage;
|
||||
web.NewWindowRequested += (_, e) => { e.Handled = true; OpenUrl(e.Uri); };
|
||||
web.NavigationStarting += (_, e) =>
|
||||
{
|
||||
// Only our own page lives in this window; a link elsewhere opens in the player's browser.
|
||||
if (!e.Uri.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenUrl(e.Uri); }
|
||||
};
|
||||
web.ProcessFailed += (_, e) => Log.Write("webview process failed: " + e.ProcessFailedKind);
|
||||
web.Navigate(Origin + "ui/index.html" + Environment.GetEnvironmentVariable("TRIFORCE_START"));
|
||||
ctl.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Write("webview: " + e);
|
||||
MessageBox(hwnd, "Triforce could not open its window (Microsoft Edge WebView2 failed to start).\n\n" + e.Message, "Triforce", 0x10);
|
||||
Environment.Exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
void OnRequest(object? sender, CoreWebView2WebResourceRequestedEventArgs e)
|
||||
{
|
||||
var path = new Uri(e.Request.Uri).AbsolutePath;
|
||||
var got = content.Get(path);
|
||||
e.Response = got is { } g
|
||||
? env!.CreateWebResourceResponse(new MemoryStream(g.data), 200, "OK", "Content-Type: " + g.mime + "\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: *")
|
||||
: env!.CreateWebResourceResponse(null, 404, "Not Found", "Cache-Control: no-store");
|
||||
}
|
||||
|
||||
void OnMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
|
||||
{
|
||||
string json;
|
||||
try { json = e.TryGetWebMessageAsString(); } catch { json = e.WebMessageAsJson; }
|
||||
var files = new List<string>();
|
||||
try
|
||||
{
|
||||
if (e.AdditionalObjects != null)
|
||||
foreach (var o in e.AdditionalObjects) if (o is CoreWebView2File f) files.Add(f.Path);
|
||||
}
|
||||
catch { }
|
||||
if (json.Contains("\"t\":\"ready\""))
|
||||
{
|
||||
pageReady = true; foreach (var p in early) web!.PostWebMessageAsString(p); early.Clear();
|
||||
if (Environment.GetEnvironmentVariable("TRIFORCE_SHOT") is { Length: > 0 } shot) _ = Shot(shot);
|
||||
}
|
||||
Message?.Invoke(json, files.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>Testing: TRIFORCE_SHOT="a.png@3000;b.png@9000" saves the page as drawn at those times (ms after the page is up),
|
||||
/// then closes the window (a single "a.png" uses TRIFORCE_SHOT_DELAY, default 2500). TRIFORCE_SHOT_JS runs in the page first.
|
||||
/// Lets a change be checked without anyone looking at the screen.</summary>
|
||||
async Task Shot(string spec)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("TRIFORCE_SHOT_JS") is { Length: > 0 } js) await web!.ExecuteScriptAsync(js);
|
||||
var t0 = DateTime.UtcNow;
|
||||
var def = int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_SHOT_DELAY"), out var d) ? d : 2500;
|
||||
foreach (var part in spec.Split(';', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
var at = part.LastIndexOf('@');
|
||||
var (file, ms) = at > 2 && int.TryParse(part[(at + 1)..], out var m) ? (part[..at], m) : (part, def);
|
||||
var wait = TimeSpan.FromMilliseconds(ms) - (DateTime.UtcNow - t0);
|
||||
if (wait > TimeSpan.Zero) await Task.Delay(wait);
|
||||
using (var f = File.Create(file)) await web!.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, f);
|
||||
Log.Write("shot " + file);
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Log.Write("shot: " + e.Message); }
|
||||
Close();
|
||||
}
|
||||
|
||||
public void Post(string json) => Invoke(() =>
|
||||
{
|
||||
if (web == null || !pageReady) { early.Add(json); return; }
|
||||
web.PostWebMessageAsString(json);
|
||||
});
|
||||
|
||||
public void Invoke(Action a)
|
||||
{
|
||||
queue.Enqueue(a);
|
||||
PostMessage(hwnd, WM_RUN, IntPtr.Zero, IntPtr.Zero);
|
||||
}
|
||||
|
||||
public void Minimize() => Invoke(() => ShowWindow(hwnd, 6));
|
||||
public void ToggleMaximize() => Invoke(() => ShowWindow(hwnd, IsZoomed(hwnd) ? 9 : 3));
|
||||
public void Close() => Invoke(() => PostMessage(hwnd, 0x0010, IntPtr.Zero, IntPtr.Zero));
|
||||
public void Attention(string title, string text) => Invoke(() =>
|
||||
{
|
||||
if (GetForegroundWindow() == hwnd) return;
|
||||
var f = new FLASHWINFO { cbSize = (uint)Marshal.SizeOf<FLASHWINFO>(), hwnd = hwnd, dwFlags = 3 | 12 /* all, until foreground */ };
|
||||
FlashWindowEx(ref f);
|
||||
});
|
||||
[StructLayout(LayoutKind.Sequential)] struct FLASHWINFO { public uint cbSize; public IntPtr hwnd; public uint dwFlags, uCount, dwTimeout; }
|
||||
[DllImport("user32")] static extern bool FlashWindowEx(ref FLASHWINFO f);
|
||||
[DllImport("user32")] static extern IntPtr GetForegroundWindow();
|
||||
|
||||
public void Activate() => Invoke(() => { if (IsIconic(hwnd)) ShowWindow(hwnd, 9); SetForegroundWindow(hwnd); });
|
||||
|
||||
void Resize()
|
||||
{
|
||||
if (ctl == null) return;
|
||||
GetClientRect(hwnd, out var r);
|
||||
ctl.Bounds = new System.Drawing.Rectangle(0, 0, r.right - r.left, r.bottom - r.top);
|
||||
}
|
||||
|
||||
const uint WM_RUN = 0x8001;
|
||||
IntPtr WindowProc(IntPtr h, uint msg, IntPtr wp, IntPtr lp)
|
||||
{
|
||||
switch (msg)
|
||||
{
|
||||
case WM_RUN:
|
||||
while (queue.TryDequeue(out var a)) { try { a(); } catch (Exception ex) { Log.Write("ui: " + ex); } }
|
||||
return IntPtr.Zero;
|
||||
case 0x0083: // WM_NCCALCSIZE: the whole window is client area (the page draws the bar)
|
||||
if (wp != IntPtr.Zero)
|
||||
{
|
||||
if (IsZoomed(h))
|
||||
{
|
||||
// Maximized windows overhang the screen by the frame; pull the client back inside the monitor.
|
||||
var p = Marshal.PtrToStructure<NCCALCSIZE_PARAMS>(lp);
|
||||
var mon = MonitorFromWindow(h, 2);
|
||||
var mi = new MONITORINFO { cbSize = Marshal.SizeOf<MONITORINFO>() };
|
||||
GetMonitorInfo(mon, ref mi);
|
||||
p.rgrc0 = mi.rcWork;
|
||||
Marshal.StructureToPtr(p, lp, false);
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
break;
|
||||
case 0x0005: // WM_SIZE
|
||||
Resize();
|
||||
Post("{\"t\":\"max\",\"on\":" + (IsZoomed(h) ? "true" : "false") + "}");
|
||||
return IntPtr.Zero;
|
||||
case 0x0003: // WM_MOVE
|
||||
ctl?.NotifyParentWindowPositionChanged();
|
||||
break;
|
||||
case 0x0006: // WM_ACTIVATE: give the page the keyboard back (and so the controller)
|
||||
if ((wp.ToInt64() & 0xFFFF) != 0) ctl?.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
|
||||
break;
|
||||
case 0x02E0: // WM_DPICHANGED: take the size Windows suggests
|
||||
var rc = Marshal.PtrToStructure<RECT>(lp);
|
||||
SetWindowPos(h, IntPtr.Zero, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, 0x0014);
|
||||
return IntPtr.Zero;
|
||||
case 0x0002: // WM_DESTROY
|
||||
PostQuitMessage(0);
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
return DefWindowProc(h, msg, wp, lp);
|
||||
}
|
||||
|
||||
static void OpenUrl(string url)
|
||||
{
|
||||
if (!url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && !url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) return;
|
||||
try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true }); } catch { }
|
||||
}
|
||||
|
||||
// ---------------- file pickers (the system's own: IFileOpenDialog) ----------------
|
||||
public string? PickFile(string title, string filterName, string pattern) => Pick(title, false, filterName, pattern);
|
||||
public string? PickFolder(string title) => Pick(title, true, null, null);
|
||||
|
||||
string? Pick(string title, bool folder, string? filterName, string? pattern)
|
||||
{
|
||||
var dlg = (IFileOpenDialog)new FileOpenDialogRCW();
|
||||
try
|
||||
{
|
||||
dlg.GetOptions(out var o);
|
||||
dlg.SetOptions(o | 0x40 /*FORCEFILESYSTEM*/ | (folder ? 0x20u /*PICKFOLDERS*/ : 0) | 0x1000 /*FILEMUSTEXIST*/);
|
||||
dlg.SetTitle(title);
|
||||
if (!folder && filterName != null)
|
||||
dlg.SetFileTypes(2, new[] { new COMDLG_FILTERSPEC { pszName = filterName, pszSpec = pattern! }, new COMDLG_FILTERSPEC { pszName = "All files", pszSpec = "*.*" } });
|
||||
if (dlg.Show(hwnd) != 0) return null;
|
||||
dlg.GetResult(out var item);
|
||||
item.GetDisplayName(0x80058000 /*SIGDN_FILESYSPATH*/, out var path);
|
||||
return path;
|
||||
}
|
||||
catch (Exception e) { Log.Write("picker: " + e.Message); return null; }
|
||||
finally { Marshal.ReleaseComObject(dlg); }
|
||||
}
|
||||
|
||||
sealed class Ctx(WinHost host) : SynchronizationContext
|
||||
{
|
||||
public override void Post(SendOrPostCallback d, object? state) => host.Invoke(() => d(state));
|
||||
public override void Send(SendOrPostCallback d, object? state) => host.Invoke(() => d(state));
|
||||
public override SynchronizationContext CreateCopy() => this;
|
||||
}
|
||||
|
||||
// ---------------- Win32 ----------------
|
||||
delegate IntPtr WndProc(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
struct WNDCLASSEX
|
||||
{
|
||||
public int cbSize; public uint style; public WndProc lpfnWndProc; public int cbClsExtra, cbWndExtra; public IntPtr hInstance, hIcon, hCursor, hbrBackground;
|
||||
public string? lpszMenuName; public string lpszClassName; public IntPtr hIconSm;
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)] struct RECT { public int left, top, right, bottom; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr hwnd; public uint message; public IntPtr wParam, lParam; public uint time; public int x, y; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct MARGINS { public int cxLeftWidth, cxRightWidth, cyTopHeight, cyBottomHeight; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct NCCALCSIZE_PARAMS { public RECT rgrc0, rgrc1, rgrc2; public IntPtr lppos; }
|
||||
[StructLayout(LayoutKind.Sequential)] struct MONITORINFO { public int cbSize; public RECT rcMonitor, rcWork; public uint dwFlags; }
|
||||
|
||||
[DllImport("user32", CharSet = CharSet.Unicode)] static extern ushort RegisterClassEx(ref WNDCLASSEX c);
|
||||
[DllImport("user32", CharSet = CharSet.Unicode)] static extern IntPtr CreateWindowEx(uint ex, string cls, string name, uint style, int x, int y, int w, int h, IntPtr parent, IntPtr menu, IntPtr inst, IntPtr p);
|
||||
[DllImport("user32")] static extern IntPtr DefWindowProc(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[DllImport("user32")] static extern int GetMessage(out MSG m, IntPtr h, uint a, uint b);
|
||||
[DllImport("user32")] static extern bool TranslateMessage(ref MSG m);
|
||||
[DllImport("user32")] static extern IntPtr DispatchMessage(ref MSG m);
|
||||
[DllImport("user32")] static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
|
||||
[DllImport("user32")] static extern void PostQuitMessage(int c);
|
||||
[DllImport("user32")] static extern bool ShowWindow(IntPtr h, int c);
|
||||
[DllImport("user32")] static extern bool UpdateWindow(IntPtr h);
|
||||
[DllImport("user32")] static extern bool IsZoomed(IntPtr h);
|
||||
[DllImport("user32")] static extern bool IsIconic(IntPtr h);
|
||||
[DllImport("user32")] static extern bool SetForegroundWindow(IntPtr h);
|
||||
[DllImport("user32")] static extern bool GetClientRect(IntPtr h, out RECT r);
|
||||
[DllImport("user32")] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int hh, uint f);
|
||||
[DllImport("user32")] static extern IntPtr LoadCursor(IntPtr i, int id);
|
||||
[DllImport("user32")] static extern IntPtr LoadIcon(IntPtr i, IntPtr id);
|
||||
[DllImport("user32")] static extern uint GetDpiForSystem();
|
||||
[DllImport("user32")] static extern bool SetProcessDpiAwarenessContext(IntPtr v);
|
||||
[DllImport("user32")] static extern bool SystemParametersInfo(uint a, uint b, ref RECT r, uint c);
|
||||
[DllImport("user32")] static extern IntPtr MonitorFromWindow(IntPtr h, uint f);
|
||||
[DllImport("user32")] static extern bool GetMonitorInfo(IntPtr m, ref MONITORINFO i);
|
||||
[DllImport("user32", CharSet = CharSet.Unicode)] static extern int MessageBox(IntPtr h, string t, string c, uint f);
|
||||
[DllImport("gdi32")] static extern IntPtr CreateSolidBrush(uint c);
|
||||
[DllImport("kernel32", CharSet = CharSet.Unicode)] static extern IntPtr GetModuleHandle(string? n);
|
||||
[DllImport("dwmapi")] static extern int DwmExtendFrameIntoClientArea(IntPtr h, ref MARGINS m);
|
||||
[DllImport("dwmapi")] static extern int DwmSetWindowAttribute(IntPtr h, int a, ref int v, int s);
|
||||
|
||||
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] class FileOpenDialogRCW { }
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct COMDLG_FILTERSPEC { public string pszName, pszSpec; }
|
||||
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface IShellItem
|
||||
{
|
||||
void BindToHandler(); void GetParent();
|
||||
void GetDisplayName(uint sigdn, [MarshalAs(UnmanagedType.LPWStr)] out string name);
|
||||
void GetAttributes(); void Compare();
|
||||
}
|
||||
[ComImport, Guid("d57c7288-d4ad-4768-be02-9d969532d960"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
interface IFileOpenDialog
|
||||
{
|
||||
[PreserveSig] int Show(IntPtr parent);
|
||||
void SetFileTypes(uint n, [MarshalAs(UnmanagedType.LPArray)] COMDLG_FILTERSPEC[] specs);
|
||||
void SetFileTypeIndex(uint i); void GetFileTypeIndex(out uint i);
|
||||
void Advise(); void Unadvise();
|
||||
void SetOptions(uint o); void GetOptions(out uint o);
|
||||
void SetDefaultFolder(IShellItem i); void SetFolder(IShellItem i); void GetFolder(out IShellItem i); void GetCurrentSelection(out IShellItem i);
|
||||
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string n); void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string n);
|
||||
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string t);
|
||||
void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string t); void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string t);
|
||||
void GetResult(out IShellItem i);
|
||||
void AddPlace(IShellItem i, int fdap); void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string e);
|
||||
void Close(int hr); void SetClientGuid(ref Guid g); void ClearClientData(); void SetFilter(IntPtr f);
|
||||
void GetResults(out IntPtr e); void GetSelectedItems(out IntPtr e);
|
||||
}
|
||||
}
|
||||
22
launcher/App/Log.cs
Normal file
22
launcher/App/Log.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
/// <summary>A plain text log beside the launcher's data (launcher.log). Never throws.</summary>
|
||||
public static class Log
|
||||
{
|
||||
static readonly object gate = new();
|
||||
public static string? FilePath;
|
||||
|
||||
public static void Write(string line)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
var s = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + line + Environment.NewLine;
|
||||
if (FilePath != null) File.AppendAllText(FilePath, s);
|
||||
else Console.Error.Write(s);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
63
launcher/App/Program.cs
Normal file
63
launcher/App/Program.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
using Triforce.Launcher.Host;
|
||||
|
||||
namespace Triforce.Launcher;
|
||||
|
||||
static class Program
|
||||
{
|
||||
/// <summary>Exit codes the old Setup understands when it swaps itself for this exe (research/02 §2): nonzero before the
|
||||
/// "up" event = roll back to the old one. 3 = no web view on this PC.</summary>
|
||||
[STAThread]
|
||||
static int Main(string[] args)
|
||||
{
|
||||
var dataDir = DataDir();
|
||||
Directory.CreateDirectory(dataDir);
|
||||
Log.FilePath = Path.Combine(dataDir, "launcher.log");
|
||||
Log.Write("start " + string.Join(' ', args));
|
||||
var dev = args.Contains("--devtools") || Environment.GetEnvironmentVariable("TRIFORCE_DEVTOOLS") == "1";
|
||||
|
||||
// The old Setup's start contract (research/02): arguments, one instance, the "up" event, the old exe removed.
|
||||
var ctx = Triforce.Logic.TriforceContext.Create();
|
||||
var start = Triforce.Logic.Startup.Run(ctx, args);
|
||||
Log.Write("startup: " + start.Screen + (start.Message != null ? " (" + start.Message + ")" : ""));
|
||||
if (start.Screen == Triforce.Logic.StartScreen.Exit) return start.ExitCode;
|
||||
|
||||
var content = new Content();
|
||||
IHost host;
|
||||
#if WINDOWS
|
||||
if (WinHost.RuntimeVersion() == null)
|
||||
{
|
||||
Log.Write("no WebView2 runtime");
|
||||
return 3;
|
||||
}
|
||||
host = new WinHost(content, Path.Combine(dataDir, "webview"), dev);
|
||||
#else
|
||||
// What Photino.Native links (GTK 3, WebKitGTK 4.1, libnotify). One missing: exit 4, and AppRun opens the classic
|
||||
// builder window instead.
|
||||
foreach (var lib in new[] { "libgtk-3.so.0", "libwebkit2gtk-4.1.so.0", "libnotify.so.4" })
|
||||
if (!System.Runtime.InteropServices.NativeLibrary.TryLoad(lib, out _))
|
||||
{
|
||||
Log.Write("missing " + lib + ": the classic builder window opens instead");
|
||||
return 4;
|
||||
}
|
||||
host = new LinuxHost(content, Path.Combine(dataDir, "webview"), dev);
|
||||
#endif
|
||||
var app = new Backend(host, content, ctx, start, dataDir);
|
||||
host.Message += app.OnMessage;
|
||||
host.Run();
|
||||
app.Shutdown();
|
||||
Log.Write("end");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>The launcher's own working data (web view cache, log, decoded game media). Under TRIFORCE_TEST_ROOT
|
||||
/// everything stays inside that folder.</summary>
|
||||
static string DataDir()
|
||||
{
|
||||
var test = Environment.GetEnvironmentVariable("TRIFORCE_TEST_ROOT");
|
||||
if (!string.IsNullOrEmpty(test)) return Path.Combine(Path.GetFullPath(test), "launcher");
|
||||
if (OperatingSystem.IsWindows())
|
||||
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Triforce", "launcher");
|
||||
var xdg = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
|
||||
return Path.Combine(string.IsNullOrEmpty(xdg) ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache") : xdg, "triforce-launcher");
|
||||
}
|
||||
}
|
||||
63
launcher/App/Triforce.Launcher.csproj
Normal file
63
launcher/App/Triforce.Launcher.csproj
Normal file
@@ -0,0 +1,63 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- One launcher, two window hosts: Windows draws with WebView2 directly (file paths from drops, a real custom title bar),
|
||||
Linux with Photino (WebKitGTK). The page (ui/) and the logic (Core) are the same on both. -->
|
||||
<PropertyGroup>
|
||||
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
||||
<TargetFrameworks>net10.0-windows;net10.0</TargetFrameworks>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<AssemblyName>Triforce</AssemblyName>
|
||||
<RootNamespace>Triforce.Launcher</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<Version>1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'net10.0-windows'">
|
||||
<DefineConstants>$(DefineConstants);WINDOWS</DefineConstants>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<!-- Old installs update by downloading the release asset TriforceSetup.exe and starting it (research/02 §2): this IS it. -->
|
||||
<AssemblyName>TriforceSetup</AssemblyName>
|
||||
<ApplicationIcon Condition="Exists('$(MSBuildThisFileDirectory)obj/gen/triforce.ico')">obj/gen/triforce.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'net10.0'">
|
||||
<AssemblyName>triforce-launcher</AssemblyName>
|
||||
</PropertyGroup>
|
||||
<!-- one self-contained file per system (no .NET needed on the player's PC) -->
|
||||
<PropertyGroup Condition="'$(RuntimeIdentifier)' != ''">
|
||||
<SelfContained>true</SelfContained>
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
|
||||
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
|
||||
<DebugType>none</DebugType>
|
||||
<PublishReadyToRun>false</PublishReadyToRun>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Core\Triforce.Core.csproj" />
|
||||
<ProjectReference Include="..\Logic\Triforce.Logic.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0-windows'">
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
|
||||
<!-- only the Core API is used: leave the WinForms/WPF controls out of the build -->
|
||||
<Reference Remove="Microsoft.Web.WebView2.WinForms" /><Reference Remove="Microsoft.Web.WebView2.Wpf" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
|
||||
<PackageReference Include="Photino.NET" Version="4.0.16" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0-windows'">
|
||||
<Compile Remove="Host\LinuxHost.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup Condition="'$(TargetFramework)' == 'net10.0'">
|
||||
<Compile Remove="Host\WinHost.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- The page, its styles, scripts, fonts and our own crest ride inside the exe. Nothing of the game is in here: its logo,
|
||||
music and sounds are read from the player's own files at run time (Core/GameFiles). -->
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="..\ui\**\*" LogicalName="ui/%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
13
launcher/App/app.manifest
Normal file
13
launcher/App/app.manifest
Normal file
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="Triforce.Launcher"/>
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
|
||||
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/></application>
|
||||
</compatibility>
|
||||
</assembly>
|
||||
1570
launcher/Core/GameFiles/Astc.cs
Normal file
1570
launcher/Core/GameFiles/Astc.cs
Normal file
File diff suppressed because it is too large
Load Diff
70
launcher/Core/GameFiles/BlockLinear.cs
Normal file
70
launcher/Core/GameFiles/BlockLinear.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
// SPDX-FileCopyrightText: Copyright 2025 suyu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// SPDX-FileCopyrightText: Copyright 2018 yuzu Emulator Project
|
||||
// SPDX-License-Identifier: GPL-2.0-or-later
|
||||
|
||||
// (Triforce) The Tegra GPU's block-linear texture layout undone, ported from suyu's video_core/textures/decoders.cpp
|
||||
// (SwizzleImpl with TO_LINEAR false, depth 1). A texture is stored in GOBs (64 bytes by 8 rows, 512 bytes), stacked
|
||||
// 2^blockHeight GOBs tall into blocks; blocks run left to right, then the next row of blocks.
|
||||
//
|
||||
// Inside a GOB this is the Switch 2's order, as in our suyu's decoders.h: the Tegra X1's (x bits 0-3, 5, 8 / y bits 4,
|
||||
// 6, 7) with offset bits 5 and 6 swapped, so x bit 4 lands on bit 6 and y bit 1 on bit 5. (The X1's order, which most
|
||||
// Switch tools use, scrambles this game's textures in 4x4-block patches.)
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>Tegra block-linear to linear.</summary>
|
||||
public static class BlockLinear
|
||||
{
|
||||
const int GobSizeXShift = 6; // 64 bytes
|
||||
const int GobSizeYShift = 3; // 8 rows
|
||||
const int GobSizeShift = GobSizeXShift + GobSizeYShift; // 512 bytes
|
||||
|
||||
/// <summary>The position of a byte inside its GOB: pdep of x into SWIZZLE_X_BITS 0b1_0100_1111 and of y into
|
||||
/// SWIZZLE_Y_BITS 0b0_1011_0000.</summary>
|
||||
static int SwizzleX(int x) => (x & 15) | (x & 16) << 2 | (x & 32) << 3;
|
||||
static int SwizzleY(int y) => (y & 3) << 4 | (y & 4) << 5;
|
||||
|
||||
/// <summary>The size a block-linear image takes, in bytes.</summary>
|
||||
public static long Size(int width, int height, int bytesPerElement, int blockHeightLog2)
|
||||
{
|
||||
var alignedWidth = (width * bytesPerElement + 63) & ~63;
|
||||
var rows = 1 << (GobSizeYShift + blockHeightLog2);
|
||||
var alignedHeight = (height + rows - 1) / rows * rows;
|
||||
return (long)alignedWidth * alignedHeight;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A block-linear image made linear. width and height count elements (pixels, or blocks of a compressed format);
|
||||
/// bytesPerElement is 1, 2, 4, 8 or 16. The result is width * height * bytesPerElement bytes, rows one after another.
|
||||
/// </summary>
|
||||
public static byte[] Deswizzle(ReadOnlySpan<byte> input, int width, int height, int bytesPerElement, int blockHeightLog2)
|
||||
{
|
||||
if (bytesPerElement is not (1 or 2 or 4 or 8 or 16))
|
||||
throw new NotSupportedException(bytesPerElement + " bytes per element");
|
||||
var pitch = width * bytesPerElement;
|
||||
var output = new byte[pitch * height];
|
||||
var gobsInX = (pitch + 63) >> GobSizeXShift;
|
||||
var blockSize = gobsInX << (GobSizeShift + blockHeightLog2);
|
||||
var blockHeightMask = (1 << blockHeightLog2) - 1;
|
||||
var xShift = GobSizeShift + blockHeightLog2;
|
||||
|
||||
if (Size(width, height, bytesPerElement, blockHeightLog2) > input.Length)
|
||||
throw new InvalidDataException("the texture's data is shorter than its size calls for");
|
||||
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var swizzledY = SwizzleY(y);
|
||||
var blockY = y >> GobSizeYShift;
|
||||
var offsetY = (blockY >> blockHeightLog2) * blockSize + ((blockY & blockHeightMask) << GobSizeShift);
|
||||
var row = output.AsSpan(y * pitch, pitch);
|
||||
for (var x = 0; x < pitch; x += bytesPerElement)
|
||||
{
|
||||
var offsetX = (x >> GobSizeXShift) << xShift;
|
||||
var at = offsetY + offsetX + (SwizzleX(x & 63) | swizzledY);
|
||||
input.Slice(at, bytesPerElement).CopyTo(row.Slice(x, bytesPerElement));
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
317
launcher/Core/GameFiles/Bntx.cs
Normal file
317
launcher/Core/GameFiles/Bntx.cs
Normal file
@@ -0,0 +1,317 @@
|
||||
// BNTX: the Switch's texture archive (the game's UI art is in these, inside .bntx.zs files). Offsets as the lab's
|
||||
// research/scratch/t09_bntx.py reads them, little-endian:
|
||||
//
|
||||
// BNTX header 0x24 u32 texture count, 0x28 u64 offset of the table of BRTI offsets
|
||||
// BRTI 0x12 u16 tile mode (0 block-linear, 1 linear), 0x16 u16 mip count, 0x1C u32 format,
|
||||
// 0x24 u32 width, 0x28 u32 height, 0x34 u32 block height (log2, in GOBs), 0x50 u32 image size,
|
||||
// 0x58 u8[4] channel sources (R, G, B, A: 0 zero, 1 one, 2 red, 3 green, 4 blue, 5 alpha),
|
||||
// 0x60 u64 name offset (u16 length, then the name), 0x70 u64 offset of the mip offsets (u64 each)
|
||||
//
|
||||
// The format's high byte is the kind (0x0b RGBA8, 0x1a-0x1e BC1-BC5, 0x2d-0x3a ASTC 4x4 to 12x12), the low byte the
|
||||
// number type (1 unorm, 6 sRGB...). Only mip 0 of the first layer is decoded, as the launcher shows the art at full size.
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>One texture of a BNTX archive.</summary>
|
||||
public sealed record BntxTexture(string Name, int Width, int Height, uint Format, int MipCount, int TileMode,
|
||||
int BlockHeightLog2, long DataOffset, long ImageSize, byte[] ChannelSources)
|
||||
{
|
||||
/// <summary>The format's kind (high byte), e.g. 0x2d for ASTC 4x4.</summary>
|
||||
public int Kind => (int)(Format >> 8);
|
||||
|
||||
/// <summary>A readable format name.</summary>
|
||||
public string FormatName => Bntx.FormatName(Format);
|
||||
}
|
||||
|
||||
/// <summary>A parsed BNTX archive, with decoding of its textures to RGBA8.</summary>
|
||||
public sealed class Bntx
|
||||
{
|
||||
readonly byte[] data;
|
||||
readonly Dictionary<string, BntxTexture> byName = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyList<BntxTexture> Textures { get; }
|
||||
|
||||
public Bntx(byte[] data)
|
||||
{
|
||||
this.data = data;
|
||||
if (data.Length < 0x30 || data[0] != 'B' || data[1] != 'N' || data[2] != 'T' || data[3] != 'X')
|
||||
throw new InvalidDataException("not a BNTX archive");
|
||||
var count = U32(0x24);
|
||||
var table = (long)U64(0x28);
|
||||
var list = new List<BntxTexture>();
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var p = (long)U64(table + 8 * i);
|
||||
if (data[p] != 'B' || data[p + 1] != 'R' || data[p + 2] != 'T' || data[p + 3] != 'I')
|
||||
throw new InvalidDataException("BNTX texture " + i + " has no BRTI header");
|
||||
var nameAt = (long)U64(p + 0x60);
|
||||
var nameLength = U16(nameAt);
|
||||
var name = Encoding.UTF8.GetString(data, (int)nameAt + 2, nameLength);
|
||||
var mips = (long)U64(p + 0x70);
|
||||
var tex = new BntxTexture(name, (int)U32(p + 0x24), (int)U32(p + 0x28), U32(p + 0x1C), U16(p + 0x16), U16(p + 0x12),
|
||||
(int)(U32(p + 0x34) & 7), (long)U64(mips), U32(p + 0x50), data[(int)(p + 0x58)..(int)(p + 0x5C)]);
|
||||
list.Add(tex);
|
||||
byName.TryAdd(name, tex);
|
||||
}
|
||||
Textures = list;
|
||||
}
|
||||
|
||||
ushort U16(long at) => BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan((int)at));
|
||||
uint U32(long at) => BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan((int)at));
|
||||
ulong U64(long at) => BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan((int)at));
|
||||
|
||||
/// <summary>The texture of that name, or null.</summary>
|
||||
public BntxTexture? Find(string name) => byName.GetValueOrDefault(name);
|
||||
|
||||
/// <summary>
|
||||
/// A texture's first mip decoded to RGBA8 (Width * Height * 4 bytes). The texels are as stored: an sRGB texture is not
|
||||
/// made linear, and a one-channel format (BC4, R8) comes out grey and opaque. With applyChannelSources the texture's own
|
||||
/// channel sources are applied as the GPU would (BC4 art in this game is then white, with the channel as alpha).
|
||||
/// </summary>
|
||||
public byte[] DecodeRgba(BntxTexture t, bool applyChannelSources = false)
|
||||
{
|
||||
var (blockW, blockH, bytesPerBlock) = BlockInfo(t.Format);
|
||||
var wBlocks = (t.Width + blockW - 1) / blockW;
|
||||
var hBlocks = (t.Height + blockH - 1) / blockH;
|
||||
var source = data.AsSpan((int)t.DataOffset, (int)Math.Min(t.ImageSize, data.Length - t.DataOffset));
|
||||
var linear = t.TileMode == 1
|
||||
? source[..(wBlocks * hBlocks * bytesPerBlock)].ToArray()
|
||||
: BlockLinear.Deswizzle(source, wBlocks, hBlocks, bytesPerBlock, t.BlockHeightLog2);
|
||||
|
||||
byte[] rgba = (t.Format >> 8) switch
|
||||
{
|
||||
>= 0x2d and <= 0x3a => Astc.Decompress(linear, t.Width, t.Height, blockW, blockH),
|
||||
0x1a => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC1),
|
||||
0x1b => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC2),
|
||||
0x1c => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC3),
|
||||
0x1d => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC4),
|
||||
0x1e => BlockCompression.Decode(linear, t.Width, t.Height, BlockCompression.Kind.BC5),
|
||||
0x0b => linear,
|
||||
0x0c => Swap(linear, 2, 1, 0, 3),
|
||||
0x02 => Expand(linear, 1),
|
||||
0x09 => Expand(linear, 2),
|
||||
_ => throw new NotSupportedException(t.Name + ": texture format " + FormatName(t.Format) + " is not supported"),
|
||||
};
|
||||
if (applyChannelSources)
|
||||
ApplySources(rgba, t.ChannelSources);
|
||||
return rgba;
|
||||
}
|
||||
|
||||
/// <summary>The block size and bytes per block of a format (1x1 for an uncompressed one).</summary>
|
||||
static (int W, int H, int Bytes) BlockInfo(uint format) => (format >> 8) switch
|
||||
{
|
||||
0x02 => (1, 1, 1),
|
||||
0x09 => (1, 1, 2),
|
||||
0x0b or 0x0c => (1, 1, 4),
|
||||
0x1a or 0x1d => (4, 4, 8),
|
||||
0x1b or 0x1c or 0x1e => (4, 4, 16),
|
||||
var k and >= 0x2d and <= 0x3a => (AstcBlocks[k - 0x2d].W, AstcBlocks[k - 0x2d].H, 16),
|
||||
_ => throw new NotSupportedException("texture format " + FormatName(format) + " is not supported"),
|
||||
};
|
||||
|
||||
static readonly (int W, int H)[] AstcBlocks =
|
||||
{
|
||||
(4, 4), (5, 4), (5, 5), (6, 5), (6, 6), (8, 5), (8, 6), (8, 8), (10, 5), (10, 6), (10, 8), (10, 10), (12, 10), (12, 12),
|
||||
};
|
||||
|
||||
public static string FormatName(uint format)
|
||||
{
|
||||
var kind = (int)(format >> 8);
|
||||
var type = (format & 0xFF) switch { 1 => "unorm", 2 => "snorm", 5 => "float", 6 => "srgb", var n => "type" + n };
|
||||
var name = kind switch
|
||||
{
|
||||
0x02 => "R8",
|
||||
0x09 => "R8G8",
|
||||
0x0b => "R8G8B8A8",
|
||||
0x0c => "B8G8R8A8",
|
||||
>= 0x1a and <= 0x20 => "BC" + (kind - 0x19),
|
||||
>= 0x2d and <= 0x3a => "ASTC_" + AstcBlocks[kind - 0x2d].W + "x" + AstcBlocks[kind - 0x2d].H,
|
||||
_ => "0x" + kind.ToString("x2"),
|
||||
};
|
||||
return name + "_" + type + " (0x" + format.ToString("x4") + ")";
|
||||
}
|
||||
|
||||
static byte[] Swap(byte[] p, int r, int g, int b, int a)
|
||||
{
|
||||
var o = new byte[p.Length];
|
||||
for (var i = 0; i < p.Length; i += 4)
|
||||
{
|
||||
o[i] = p[i + r];
|
||||
o[i + 1] = p[i + g];
|
||||
o[i + 2] = p[i + b];
|
||||
o[i + 3] = p[i + a];
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>R8 to grey (R, R, R, 255); R8G8 to (R, G, 0, 255).</summary>
|
||||
static byte[] Expand(byte[] p, int channels)
|
||||
{
|
||||
var n = p.Length / channels;
|
||||
var o = new byte[n * 4];
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var r = p[i * channels];
|
||||
o[4 * i] = r;
|
||||
o[4 * i + 1] = channels == 1 ? r : p[i * channels + 1];
|
||||
o[4 * i + 2] = channels == 1 ? r : (byte)0;
|
||||
o[4 * i + 3] = 255;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>The texture's channel sources applied (0 zero, 1 one, 2-5 red, green, blue, alpha of the decoded texel).</summary>
|
||||
static void ApplySources(byte[] rgba, byte[] sources)
|
||||
{
|
||||
if (sources.Length < 4 || (sources[0] == 2 && sources[1] == 3 && sources[2] == 4 && sources[3] == 5))
|
||||
return;
|
||||
Span<byte> texel = stackalloc byte[4];
|
||||
for (var i = 0; i < rgba.Length; i += 4)
|
||||
{
|
||||
rgba.AsSpan(i, 4).CopyTo(texel);
|
||||
// (one-channel formats decode grey here: their "red" is that grey)
|
||||
for (var c = 0; c < 4; c++)
|
||||
rgba[i + c] = sources[c] switch { 0 => 0, 1 => 255, >= 2 and <= 5 => texel[sources[c] - 2], _ => texel[c] };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>BC1-BC5 (DXT1, DXT3, DXT5, RGTC1, RGTC2) decoding to RGBA8. BC4 decodes grey and opaque, BC5 to red and green.</summary>
|
||||
public static class BlockCompression
|
||||
{
|
||||
public enum Kind { BC1, BC2, BC3, BC4, BC5 }
|
||||
|
||||
public static byte[] Decode(ReadOnlySpan<byte> blocks, int width, int height, Kind kind)
|
||||
{
|
||||
var bytesPerBlock = kind is Kind.BC1 or Kind.BC4 ? 8 : 16;
|
||||
var wBlocks = (width + 3) / 4;
|
||||
var hBlocks = (height + 3) / 4;
|
||||
var output = new byte[width * height * 4];
|
||||
Span<byte> texels = stackalloc byte[64];
|
||||
Span<byte> channel = stackalloc byte[16];
|
||||
for (var by = 0; by < hBlocks; by++)
|
||||
for (var bx = 0; bx < wBlocks; bx++)
|
||||
{
|
||||
var block = blocks.Slice((by * wBlocks + bx) * bytesPerBlock, bytesPerBlock);
|
||||
switch (kind)
|
||||
{
|
||||
case Kind.BC1:
|
||||
Color(block, texels, true);
|
||||
break;
|
||||
case Kind.BC2:
|
||||
Color(block[8..], texels, false);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
var nibble = (block[i / 2] >> (4 * (i & 1))) & 15;
|
||||
texels[4 * i + 3] = (byte)(nibble * 17);
|
||||
}
|
||||
break;
|
||||
case Kind.BC3:
|
||||
Color(block[8..], texels, false);
|
||||
Channel(block, channel);
|
||||
for (var i = 0; i < 16; i++)
|
||||
texels[4 * i + 3] = channel[i];
|
||||
break;
|
||||
case Kind.BC4:
|
||||
Channel(block, channel);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
texels[4 * i] = texels[4 * i + 1] = texels[4 * i + 2] = channel[i];
|
||||
texels[4 * i + 3] = 255;
|
||||
}
|
||||
break;
|
||||
case Kind.BC5:
|
||||
Channel(block, channel);
|
||||
for (var i = 0; i < 16; i++)
|
||||
texels[4 * i] = channel[i];
|
||||
Channel(block[8..], channel);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
texels[4 * i + 1] = channel[i];
|
||||
texels[4 * i + 2] = 0;
|
||||
texels[4 * i + 3] = 255;
|
||||
}
|
||||
break;
|
||||
}
|
||||
for (var y = 0; y < 4 && by * 4 + y < height; y++)
|
||||
{
|
||||
var count = Math.Min(4, width - bx * 4);
|
||||
texels.Slice(y * 16, count * 4).CopyTo(output.AsSpan(((by * 4 + y) * width + bx * 4) * 4));
|
||||
}
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>A BC1 color block: two RGB565 endpoints and 2-bit indexes. With punchThrough (BC1), c0 <= c1 selects the
|
||||
/// three-color mode whose fourth color is transparent black.</summary>
|
||||
static void Color(ReadOnlySpan<byte> b, Span<byte> texels, bool punchThrough)
|
||||
{
|
||||
var c0 = BinaryPrimitives.ReadUInt16LittleEndian(b);
|
||||
var c1 = BinaryPrimitives.ReadUInt16LittleEndian(b[2..]);
|
||||
Span<int> pal = stackalloc int[16];
|
||||
Rgb565(c0, pal[..4]);
|
||||
Rgb565(c1, pal.Slice(4, 4));
|
||||
if (c0 > c1 || !punchThrough)
|
||||
{
|
||||
for (var k = 0; k < 3; k++)
|
||||
{
|
||||
pal[8 + k] = (2 * pal[k] + pal[4 + k] + 1) / 3;
|
||||
pal[12 + k] = (pal[k] + 2 * pal[4 + k] + 1) / 3;
|
||||
}
|
||||
pal[11] = pal[15] = 255;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (var k = 0; k < 3; k++)
|
||||
{
|
||||
pal[8 + k] = (pal[k] + pal[4 + k] + 1) / 2;
|
||||
pal[12 + k] = 0;
|
||||
}
|
||||
pal[11] = 255;
|
||||
pal[15] = 0;
|
||||
}
|
||||
var bits = BinaryPrimitives.ReadUInt32LittleEndian(b[4..]);
|
||||
for (var i = 0; i < 16; i++)
|
||||
{
|
||||
var idx = (int)(bits >> (2 * i)) & 3;
|
||||
for (var k = 0; k < 4; k++)
|
||||
texels[4 * i + k] = (byte)pal[4 * idx + k];
|
||||
}
|
||||
}
|
||||
|
||||
static void Rgb565(ushort c, Span<int> into)
|
||||
{
|
||||
int r = (c >> 11) & 31, g = (c >> 5) & 63, b = c & 31;
|
||||
into[0] = (r << 3) | (r >> 2);
|
||||
into[1] = (g << 2) | (g >> 4);
|
||||
into[2] = (b << 3) | (b >> 2);
|
||||
into[3] = 255;
|
||||
}
|
||||
|
||||
/// <summary>A BC4/BC3-alpha block: two 8-bit endpoints and 3-bit indexes over 6 or 4 interpolated values, rounded
|
||||
/// to nearest (as the reference decoder the launcher's art was approved with).</summary>
|
||||
static void Channel(ReadOnlySpan<byte> b, Span<byte> values)
|
||||
{
|
||||
int a0 = b[0], a1 = b[1];
|
||||
Span<int> pal = stackalloc int[8];
|
||||
pal[0] = a0;
|
||||
pal[1] = a1;
|
||||
if (a0 > a1)
|
||||
for (var k = 1; k <= 6; k++)
|
||||
pal[k + 1] = ((7 - k) * a0 + k * a1 + 3) / 7;
|
||||
else
|
||||
{
|
||||
for (var k = 1; k <= 4; k++)
|
||||
pal[k + 1] = ((5 - k) * a0 + k * a1 + 2) / 5;
|
||||
pal[6] = 0;
|
||||
pal[7] = 255;
|
||||
}
|
||||
ulong bits = 0;
|
||||
for (var k = 0; k < 6; k++)
|
||||
bits |= (ulong)b[2 + k] << (8 * k);
|
||||
for (var i = 0; i < 16; i++)
|
||||
values[i] = (byte)pal[(int)(bits >> (3 * i)) & 7];
|
||||
}
|
||||
}
|
||||
221
launcher/Core/GameFiles/Bwav.cs
Normal file
221
launcher/Core/GameFiles/Bwav.cs
Normal file
@@ -0,0 +1,221 @@
|
||||
// BWAV: the game's sound files (romfs "Sound/Resource/Stream/<name>.bwav"). Ported from setup/Sound.cs (Bwav.Decode,
|
||||
// from NX2navi's runtime/menu_sound.c) and the lab's research/scratch/bwav2wav.py and mixwav.py, which made the sounds the
|
||||
// launcher's design was approved with; this decodes and mixes the same way, sample for sample.
|
||||
//
|
||||
// Layout: "BWAV", a byte order mark, a version, a CRC32, a prefetch flag (u16) and the channel count (u16 at 0x0E), then
|
||||
// 0x4C bytes per channel: codec (u16: 0 PCM16, 1 DSP-ADPCM), pan (u16: 0 left, 1 right, 2 middle), sample rate (u32),
|
||||
// sample count (u32), the count again, 16 DSP coefficients (s16), the place of the samples in the file (u32 at 0x30), ...
|
||||
// DSP-ADPCM is frames of 8 bytes: a header (the coefficient pair's index, the scale's exponent) and 14 samples of four bits.
|
||||
// All numbers little-endian. Other codecs (the title music's codec 2) are not decoded.
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>16-bit stereo sound: left and right samples in turn.</summary>
|
||||
public sealed class Pcm
|
||||
{
|
||||
public int Rate { get; init; }
|
||||
public short[] Samples { get; init; } = Array.Empty<short>();
|
||||
public int Frames => Samples.Length / 2;
|
||||
public double Seconds => Rate > 0 ? (double)Frames / Rate : 0;
|
||||
|
||||
/// <summary>The loudest sample's size (0 for silence).</summary>
|
||||
public int Peak
|
||||
{
|
||||
get
|
||||
{
|
||||
var peak = 0;
|
||||
foreach (var s in Samples)
|
||||
peak = Math.Max(peak, Math.Abs((int)s));
|
||||
return peak;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class Bwav
|
||||
{
|
||||
/// <summary>The share of full scale the loudest sample is set to by Mix and Normalize (as mixwav.py: 70 %).</summary>
|
||||
public const double DefaultPeak = 0.7;
|
||||
|
||||
static int U16(byte[] b, long at) => b[at] | b[at + 1] << 8;
|
||||
static long U32(byte[] b, long at) => b[at] | (long)b[at + 1] << 8 | (long)b[at + 2] << 16 | (long)b[at + 3] << 24;
|
||||
|
||||
/// <summary>
|
||||
/// A BWAV file decoded to 16-bit stereo, as bwav2wav.py does at gain 1: each channel goes to its side by its pan (left,
|
||||
/// right, or both), a one-channel sound is lowered by 0.7071 to sound as loud in both, and each sample is cut toward
|
||||
/// zero to a whole number and clamped. Throws InvalidDataException for anything that is not a whole BWAV file of one or
|
||||
/// two channels of PCM16 or DSP-ADPCM.
|
||||
/// </summary>
|
||||
public static Pcm Decode(byte[] b)
|
||||
{
|
||||
if (b.Length < 0x10 || b[0] != 'B' || b[1] != 'W' || b[2] != 'A' || b[3] != 'V')
|
||||
throw new InvalidDataException("not a BWAV file");
|
||||
var channels = U16(b, 0x0E);
|
||||
if (channels < 1 || channels > 2 || 0x10 + channels * 0x4C > b.Length)
|
||||
throw new InvalidDataException("BWAV with " + channels + " channels (one or two are decoded)");
|
||||
long rate = U32(b, 0x10 + 4), frames = U32(b, 0x10 + 8);
|
||||
if (rate < 8000 || rate > 96000 || frames == 0 || frames > rate * 3600)
|
||||
throw new InvalidDataException("BWAV with a rate of " + rate + " and " + frames + " samples");
|
||||
for (var c = 0; c < channels; c++)
|
||||
if (!Whole(b, 0x10 + c * 0x4C, frames))
|
||||
throw new InvalidDataException("BWAV channel " + c + " is cut off or of an unknown codec (" + U16(b, 0x10 + c * 0x4C) + ")");
|
||||
|
||||
// (the sides summed as whole numbers, as bwav2wav.py does: two channels panned to the same side add up)
|
||||
var left = new int[frames];
|
||||
var right = new int[frames];
|
||||
for (var c = 0; c < channels; c++)
|
||||
Channel(b, 0x10 + c * 0x4C, left, right, frames);
|
||||
|
||||
var samples = new short[frames * 2];
|
||||
for (long i = 0; i < frames; i++)
|
||||
{
|
||||
double l = left[i], r = right[i];
|
||||
if (channels == 1)
|
||||
{
|
||||
l *= 0.7071;
|
||||
r *= 0.7071;
|
||||
}
|
||||
samples[2 * i] = (short)Math.Clamp((int)l, -32768, 32767);
|
||||
samples[2 * i + 1] = (short)Math.Clamp((int)r, -32768, 32767);
|
||||
}
|
||||
return new Pcm { Rate = (int)rate, Samples = samples };
|
||||
}
|
||||
|
||||
/// <summary>Is the channel one of the two codecs, with all of its samples (as many as the sound has, at most) inside the
|
||||
/// file?</summary>
|
||||
static bool Whole(byte[] b, long info, long frames)
|
||||
{
|
||||
var codec = U16(b, info);
|
||||
long count = Math.Min(U32(b, info + 8), frames), at = U32(b, info + 0x30);
|
||||
// (DSP-ADPCM: the last frame may be cut to the bytes its samples use, its header and one byte per two samples; the
|
||||
// game's music files end that way, so asking for the whole 8 bytes would refuse them)
|
||||
var rest = count % 14;
|
||||
var bytes = count / 14 * 8 + (rest == 0 ? 0 : 1 + (rest + 1) / 2);
|
||||
return codec == 0 ? at + count * 2 <= b.Length : codec == 1 && at + bytes <= b.Length;
|
||||
}
|
||||
|
||||
/// <summary>One channel added into its side: pan 0 left, 1 right, anything else both.</summary>
|
||||
static void Channel(byte[] b, long info, int[] left, int[] right, long frames)
|
||||
{
|
||||
int codec = U16(b, info), pan = U16(b, info + 2);
|
||||
long count = Math.Min(U32(b, info + 8), frames), at = U32(b, info + 0x30);
|
||||
if (codec == 0)
|
||||
{
|
||||
for (long i = 0; i < count; i++)
|
||||
{
|
||||
int v = (short)U16(b, at + 2 * i);
|
||||
if (pan != 1) left[i] += v;
|
||||
if (pan != 0) right[i] += v;
|
||||
}
|
||||
return;
|
||||
}
|
||||
var pairs = new int[16];
|
||||
for (var i = 0; i < 16; i++)
|
||||
pairs[i] = (short)U16(b, info + 0x10 + 2 * i);
|
||||
long h1 = 0, h2 = 0;
|
||||
for (long i = 0; i < count; i++)
|
||||
{
|
||||
var frame = at + i / 14 * 8;
|
||||
var k = (int)(i % 14);
|
||||
int index = b[frame] >> 4 & 7, shift = b[frame] & 15;
|
||||
var nibble = b[frame + 1 + k / 2] >> ((k & 1) != 0 ? 0 : 4) & 15;
|
||||
if (nibble >= 8)
|
||||
nibble -= 16;
|
||||
var s = ((long)nibble << shift << 11) + pairs[2 * index] * h1 + pairs[2 * index + 1] * h2;
|
||||
var v = (int)Math.Max(-32768, Math.Min(32767, (s + 1024) >> 11));
|
||||
h2 = h1;
|
||||
h1 = v;
|
||||
if (pan != 1) left[i] += v;
|
||||
if (pan != 0) right[i] += v;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tracks of the same rate summed sample by sample (a shorter one is silence after its end), then scaled so the loudest
|
||||
/// sample is at `peak` of full scale, each sample cut toward zero: mixwav.py. One track in gives that track normalized.
|
||||
/// Saria's Song is the eight BGM_LostWood_0 .. _7 layers mixed this way.
|
||||
/// </summary>
|
||||
public static Pcm Mix(double peak, params Pcm[] tracks)
|
||||
{
|
||||
if (tracks.Length == 0)
|
||||
throw new ArgumentException("nothing to mix");
|
||||
var length = tracks.Max(t => t.Samples.Length);
|
||||
var rate = tracks[^1].Rate;
|
||||
var sum = new int[length];
|
||||
foreach (var t in tracks)
|
||||
{
|
||||
if (t.Rate != rate)
|
||||
throw new ArgumentException("tracks of different rates (" + t.Rate + ", " + rate + ") cannot be mixed");
|
||||
var s = t.Samples;
|
||||
for (var i = 0; i < s.Length; i++)
|
||||
sum[i] += s[i];
|
||||
}
|
||||
var loudest = 1;
|
||||
foreach (var v in sum)
|
||||
loudest = Math.Max(loudest, Math.Abs(v));
|
||||
var gain = peak * 32767 / loudest;
|
||||
var output = new short[length];
|
||||
for (var i = 0; i < length; i++)
|
||||
output[i] = (short)Math.Clamp((int)(sum[i] * gain), -32768, 32767);
|
||||
return new Pcm { Rate = rate, Samples = output };
|
||||
}
|
||||
|
||||
/// <summary>Mix at the default peak (70 % of full scale).</summary>
|
||||
public static Pcm Mix(params Pcm[] tracks) => Mix(DefaultPeak, tracks);
|
||||
|
||||
/// <summary>One track with its loudest sample at `peak` of full scale (Mix of one track).</summary>
|
||||
public static Pcm Normalize(Pcm track, double peak = DefaultPeak) => Mix(peak, track);
|
||||
|
||||
/// <summary>One track made louder or quieter by a factor, clamped at full scale.</summary>
|
||||
public static Pcm Gain(Pcm track, double gain)
|
||||
{
|
||||
var s = track.Samples;
|
||||
var output = new short[s.Length];
|
||||
for (var i = 0; i < s.Length; i++)
|
||||
output[i] = (short)Math.Clamp((int)(s[i] * gain), -32768, 32767);
|
||||
return new Pcm { Rate = track.Rate, Samples = output };
|
||||
}
|
||||
|
||||
/// <summary>The sound as a WAV file's bytes: 16-bit stereo PCM with the usual 44-byte header.</summary>
|
||||
public static byte[] ToWav(Pcm pcm)
|
||||
{
|
||||
var data = pcm.Samples.Length * 2;
|
||||
var wav = new byte[44 + data];
|
||||
void Tag(int at, string tag) { for (var i = 0; i < 4; i++) wav[at + i] = (byte)tag[i]; }
|
||||
void Put(int at, int value, int bytes) { for (var i = 0; i < bytes; i++) wav[at + i] = (byte)(value >> 8 * i); }
|
||||
Tag(0, "RIFF"); Put(4, 36 + data, 4); Tag(8, "WAVE");
|
||||
Tag(12, "fmt "); Put(16, 16, 4); Put(20, 1, 2); Put(22, 2, 2); Put(24, pcm.Rate, 4); Put(28, pcm.Rate * 4, 4); Put(32, 4, 2); Put(34, 16, 2);
|
||||
Tag(36, "data"); Put(40, data, 4);
|
||||
System.Runtime.InteropServices.MemoryMarshal.AsBytes(pcm.Samples.AsSpan()).CopyTo(wav.AsSpan(44));
|
||||
if (!BitConverter.IsLittleEndian)
|
||||
for (var i = 44; i + 1 < wav.Length; i += 2)
|
||||
(wav[i], wav[i + 1]) = (wav[i + 1], wav[i]);
|
||||
return wav;
|
||||
}
|
||||
|
||||
/// <summary>A 16-bit stereo WAV file read back (for comparing with references; the data chunk is found by its tag).</summary>
|
||||
public static Pcm FromWav(byte[] wav)
|
||||
{
|
||||
if (wav.Length < 12 || wav[0] != 'R' || wav[8] != 'W')
|
||||
throw new InvalidDataException("not a WAV file");
|
||||
int rate = 0, at = 12;
|
||||
while (at + 8 <= wav.Length)
|
||||
{
|
||||
var tag = System.Text.Encoding.ASCII.GetString(wav, at, 4);
|
||||
var n = (int)U32(wav, at + 4);
|
||||
if (tag == "fmt ")
|
||||
{
|
||||
if (U16(wav, at + 8 + 2) != 2 || U16(wav, at + 8 + 14) != 16)
|
||||
throw new NotSupportedException("only 16-bit stereo WAV files are read");
|
||||
rate = (int)U32(wav, at + 8 + 4);
|
||||
}
|
||||
else if (tag == "data")
|
||||
{
|
||||
n = Math.Min(n, wav.Length - at - 8);
|
||||
var samples = new short[n / 2];
|
||||
System.Runtime.InteropServices.MemoryMarshal.Cast<byte, short>(wav.AsSpan(at + 8, n / 2 * 2)).CopyTo(samples);
|
||||
return new Pcm { Rate = rate, Samples = samples };
|
||||
}
|
||||
at += 8 + n + (n & 1);
|
||||
}
|
||||
throw new InvalidDataException("WAV without data");
|
||||
}
|
||||
}
|
||||
30
launcher/Core/GameFiles/Caption.cs
Normal file
30
launcher/Core/GameFiles/Caption.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
// A save slot's picture: each slot folder of the game's saves (slot_00 .. slot_05) has a caption.sav that holds, among
|
||||
// the slot's details, a JPEG of the place the player saved (research/scratch/t09_caption.py). The JPEG is taken as the
|
||||
// bytes from its first start marker (FF D8 FF) to its last end marker (FF D9), which needs no knowledge of the .sav layout.
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
public static class Caption
|
||||
{
|
||||
/// <summary>The JPEG inside a caption.sav's bytes, or null when there is none.</summary>
|
||||
public static byte[]? Jpeg(ReadOnlySpan<byte> captionSav)
|
||||
{
|
||||
ReadOnlySpan<byte> start = stackalloc byte[] { 0xFF, 0xD8, 0xFF };
|
||||
ReadOnlySpan<byte> end = stackalloc byte[] { 0xFF, 0xD9 };
|
||||
var from = captionSav.IndexOf(start);
|
||||
if (from < 0)
|
||||
return null;
|
||||
var to = captionSav.LastIndexOf(end);
|
||||
if (to < from)
|
||||
return null;
|
||||
return captionSav[from..(to + 2)].ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The JPEG of a caption.sav file (read only, shared with the game), or null when there is none.</summary>
|
||||
public static byte[]? JpegFromFile(string captionSavPath)
|
||||
{
|
||||
using var f = new FileStream(captionSavPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
var data = new byte[f.Length];
|
||||
f.ReadExactly(data);
|
||||
return Jpeg(data);
|
||||
}
|
||||
}
|
||||
59
launcher/Core/GameFiles/FolderSource.cs
Normal file
59
launcher/Core/GameFiles/FolderSource.cs
Normal file
@@ -0,0 +1,59 @@
|
||||
// A game the player keeps unpacked: the folder that holds romfs/ (and exefs/), or the romfs folder itself.
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>Reads romfs files straight from a folder. Never writes to it.</summary>
|
||||
public sealed class FolderSource : IGameSource
|
||||
{
|
||||
/// <summary>The romfs folder in use.</summary>
|
||||
public string Romfs { get; }
|
||||
|
||||
/// <param name="path">The game folder holding romfs/, or the romfs folder itself (it is taken as one when it has the
|
||||
/// folders every romfs of this game has: Pack and Sound).</param>
|
||||
public FolderSource(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
if (Directory.Exists(Path.Combine(full, "romfs")))
|
||||
Romfs = Path.Combine(full, "romfs");
|
||||
else if (Directory.Exists(Path.Combine(full, "Pack")) || Directory.Exists(Path.Combine(full, "Sound")))
|
||||
Romfs = full;
|
||||
else
|
||||
throw new DirectoryNotFoundException("No romfs folder in " + full + " (choose the game folder that holds romfs and exefs)");
|
||||
}
|
||||
|
||||
public string Describe => "folder " + Romfs;
|
||||
|
||||
string Full(string romfsPath) => Path.Combine(Romfs, GameSource.Clean(romfsPath).Replace('/', Path.DirectorySeparatorChar));
|
||||
|
||||
public bool Exists(string romfsPath) => File.Exists(Full(romfsPath));
|
||||
|
||||
public byte[] Read(string romfsPath)
|
||||
{
|
||||
var file = Full(romfsPath);
|
||||
// (FileShare.ReadWrite: another program, the game itself, may have the file open; we only ever read)
|
||||
using var f = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1, FileOptions.SequentialScan);
|
||||
var data = new byte[f.Length];
|
||||
f.ReadExactly(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
public IEnumerable<string> List(string dir)
|
||||
{
|
||||
var clean = GameSource.Clean(dir);
|
||||
var folder = clean.Length == 0 ? Romfs : Full(clean);
|
||||
if (!Directory.Exists(folder))
|
||||
yield break;
|
||||
var prefix = clean.Length == 0 ? "" : clean + "/";
|
||||
foreach (var d in Directory.EnumerateDirectories(folder))
|
||||
yield return prefix + Path.GetFileName(d) + "/";
|
||||
foreach (var f in Directory.EnumerateFiles(folder))
|
||||
yield return prefix + Path.GetFileName(f);
|
||||
}
|
||||
|
||||
public string? Stamp(string romfsPath)
|
||||
{
|
||||
var info = new FileInfo(Full(romfsPath));
|
||||
return info.Exists ? info.Length + "-" + info.LastWriteTimeUtc.Ticks : null;
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
150
launcher/Core/GameFiles/GameMedia.cs
Normal file
150
launcher/Core/GameFiles/GameMedia.cs
Normal file
@@ -0,0 +1,150 @@
|
||||
// What the launcher shows and plays from the player's own game: the title art as PNG and the music and interface sounds as
|
||||
// WAV, decoded at run time from their .nup or game folder (DESIGN.md section 10 lists the sounds and where each plays).
|
||||
// Results are kept as files in a cache folder the caller gives (in the user's own app data, never the repository or the
|
||||
// install folder), keyed by a cheap identity of the source files, so the second start of the launcher reads them back at
|
||||
// once and a changed game file (another dump, an update, a mod) is decoded again.
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>The game's art and audio for the launcher, decoded on first use and cached. Thread-safe: two calls for the
|
||||
/// same item decode it once; different items decode side by side.</summary>
|
||||
public sealed class GameMedia
|
||||
{
|
||||
/// <summary>Changes whenever a decoder's output would change, so older cache files are not used.</summary>
|
||||
const string CacheVersion = "gamemedia-1";
|
||||
|
||||
/// <summary>The title screen's texture archive.</summary>
|
||||
public const string TitleArchive = "UI/Layout2Archive/Title.Product.100.Nin_Ounce_NVN2.bntx.zs";
|
||||
|
||||
/// <summary>The textures the launcher shows (the logo set): the logo, its aura, the button ornament and the logo's glow.</summary>
|
||||
public static readonly IReadOnlyList<string> LogoSet = new[] { "Logo_USEU_00", "TitleLogoAura_00", "TitleBtnDeco_00", "Logo_GlowL_USEU_00" };
|
||||
|
||||
/// <summary>The sounds by the launcher's name for them, each the game's stream file(s) mixed (DESIGN.md section 10).</summary>
|
||||
public static readonly IReadOnlyDictionary<string, string[]> Sounds = new Dictionary<string, string[]>
|
||||
{
|
||||
// music
|
||||
["saria"] = Enumerable.Range(0, 8).Select(i => "BGM_LostWood_" + i).ToArray(), // the 8 layers at once: the whole song
|
||||
["fairy"] = new[] { "BGM_GreatFairyFountain" },
|
||||
["temple"] = new[] { "BGM_ShrineOfTime_Child" },
|
||||
["itemget"] = new[] { "BGM_ItemGet_Large" },
|
||||
// interface sounds
|
||||
["cursor"] = new[] { "SE_Sys_SysMenu_Cursor00" },
|
||||
["tab_l"] = new[] { "SE_Sys_MinusMenu_TabMove_L00" },
|
||||
["tab_r"] = new[] { "SE_Sys_MinusMenu_TabMove_R00" },
|
||||
["decide"] = new[] { "SE_Sys_SysMenu_DecideS00" },
|
||||
["decide_l"] = new[] { "SE_Sys_SysMenu_DecideL00" },
|
||||
["cancel"] = new[] { "SE_Sys_Cancel00" },
|
||||
["open"] = new[] { "SE_Sys_PlusMenu_Open00" },
|
||||
["close"] = new[] { "SE_Sys_PlusMenu_Close00" },
|
||||
["success"] = new[] { "SE_Sys_OcarinaWindow_Success00" },
|
||||
["error"] = new[] { "SE_Sys_SysMenu_Error00" },
|
||||
};
|
||||
|
||||
/// <summary>A stream file's romfs path.</summary>
|
||||
public static string StreamPath(string name) => "Sound/Resource/Stream/" + name + ".bwav";
|
||||
|
||||
readonly IGameSource source;
|
||||
readonly string cacheDir;
|
||||
readonly Zs zs;
|
||||
readonly ConcurrentDictionary<string, Lazy<Bntx>> archives = new(StringComparer.Ordinal);
|
||||
// (one lock per cache file, for the whole process: two instances on the same cache folder decode an item once)
|
||||
static readonly ConcurrentDictionary<string, object> gates = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public GameMedia(IGameSource source, string cacheDir)
|
||||
{
|
||||
this.source = source;
|
||||
this.cacheDir = Path.GetFullPath(cacheDir);
|
||||
zs = new Zs(source);
|
||||
}
|
||||
|
||||
public IGameSource Source => source;
|
||||
|
||||
/// <summary>A texture of the title archive as a PNG file's bytes.</summary>
|
||||
public byte[] Png(string textureName) => Png(TitleArchive, textureName);
|
||||
|
||||
/// <summary>A texture of any BNTX archive in the romfs (a .bntx.zs or a plain .bntx) as a PNG file's bytes.</summary>
|
||||
public byte[] Png(string archive, string textureName) => File.ReadAllBytes(PngFile(archive, textureName));
|
||||
|
||||
/// <summary>A sound (one of <see cref="Sounds"/>' names) as a WAV file's bytes.</summary>
|
||||
public byte[] Wav(string id) => File.ReadAllBytes(WavFile(id));
|
||||
|
||||
/// <summary>The cache file holding the texture's PNG, decoded first when it is not there (for a page that loads it by
|
||||
/// path or URL).</summary>
|
||||
public string PngFile(string archive, string textureName) =>
|
||||
Cached(Safe(textureName) + ".png", new[] { archive, Zs.DictionaryPack }, () =>
|
||||
{
|
||||
var bntx = Archive(archive);
|
||||
var texture = bntx.Find(textureName)
|
||||
?? throw new KeyNotFoundException("The game's " + archive + " has no texture " + textureName);
|
||||
var rgba = bntx.DecodeRgba(texture);
|
||||
return GameFiles.Png.Encode(rgba, texture.Width, texture.Height);
|
||||
});
|
||||
|
||||
public string PngFile(string textureName) => PngFile(TitleArchive, textureName);
|
||||
|
||||
/// <summary>The cache file holding the sound's WAV, decoded first when it is not there.</summary>
|
||||
public string WavFile(string id)
|
||||
{
|
||||
if (!Sounds.TryGetValue(id, out var names))
|
||||
throw new KeyNotFoundException("No sound called " + id + " (known: " + string.Join(", ", Sounds.Keys) + ")");
|
||||
var paths = names.Select(StreamPath).ToArray();
|
||||
return Cached(Safe(id) + ".wav", paths, () =>
|
||||
{
|
||||
// (the layers of a mixed song are read and decoded side by side)
|
||||
var tracks = new Pcm[paths.Length];
|
||||
Parallel.For(0, paths.Length, i => tracks[i] = Bwav.Decode(source.Read(paths[i])));
|
||||
return Bwav.ToWav(Bwav.Mix(tracks));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The names of the textures in an archive (to check a name, or to pick another piece of art).</summary>
|
||||
public IReadOnlyList<BntxTexture> Textures(string archive = TitleArchive) => Archive(archive).Textures;
|
||||
|
||||
/// <summary>Lets go of the unpacked archives kept for further textures (about 30 MB for the title archive).</summary>
|
||||
public void Trim() => archives.Clear();
|
||||
|
||||
Bntx Archive(string archive) => archives.GetOrAdd(archive, a => new Lazy<Bntx>(() =>
|
||||
new Bntx(a.EndsWith(".zs", StringComparison.Ordinal) ? zs.Unpack(a) : source.Read(a)))).Value;
|
||||
|
||||
/// <summary>
|
||||
/// The cache file for an item: "<name>-<key>.<ext>", the key a hash of the decoders' version and the
|
||||
/// source files' stamps. Made by `make` when it is not there (written beside and then moved into place, so a reader
|
||||
/// never sees half a file); other versions of the same item are removed then.
|
||||
/// </summary>
|
||||
string Cached(string fileName, string[] inputs, Func<byte[]> make)
|
||||
{
|
||||
var identity = new StringBuilder(CacheVersion).Append('|').Append(fileName);
|
||||
foreach (var input in inputs)
|
||||
identity.Append('|').Append(input).Append('=').Append(source.Stamp(input)
|
||||
?? throw new FileNotFoundException("The game has no " + input + " (" + source.Describe + ")", input));
|
||||
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity.ToString())), 0, 8).ToLowerInvariant();
|
||||
var stem = Path.GetFileNameWithoutExtension(fileName);
|
||||
var ext = Path.GetExtension(fileName);
|
||||
var path = Path.Combine(cacheDir, stem + "-" + key + ext);
|
||||
|
||||
lock (gates.GetOrAdd(path, _ => new object()))
|
||||
{
|
||||
if (File.Exists(path))
|
||||
return path;
|
||||
var bytes = make();
|
||||
Directory.CreateDirectory(cacheDir);
|
||||
var part = path + "." + Environment.ProcessId + ".part";
|
||||
File.WriteAllBytes(part, bytes);
|
||||
File.Move(part, path, overwrite: true);
|
||||
foreach (var old in Directory.EnumerateFiles(cacheDir, stem + "-*" + ext))
|
||||
if (!string.Equals(old, path, StringComparison.OrdinalIgnoreCase) && Path.GetFileName(old).Length == Path.GetFileName(path).Length)
|
||||
try { File.Delete(old); } catch (IOException) { } catch (UnauthorizedAccessException) { }
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A name made safe as a file name.</summary>
|
||||
static string Safe(string name)
|
||||
{
|
||||
var chars = name.Select(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '.' ? c : '_').ToArray();
|
||||
return new string(chars);
|
||||
}
|
||||
}
|
||||
46
launcher/Core/GameFiles/IGameSource.cs
Normal file
46
launcher/Core/GameFiles/IGameSource.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
// The player's own game files, wherever they are: a .nup dump (NupSource) or a folder holding romfs/ and exefs/
|
||||
// (FolderSource). Everything the launcher shows from the game (title art, music, sounds) is read through this, at run time,
|
||||
// from the player's copy. Nothing read here is ever written into the repository or a release.
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>
|
||||
/// A read-only view of a game's romfs. Paths are romfs paths with "/" between the parts and no leading slash, for example
|
||||
/// "UI/Layout2Archive/Title.Product.100.Nin_Ounce_NVN2.bntx.zs". All members are safe to call from several threads.
|
||||
/// </summary>
|
||||
public interface IGameSource : IDisposable
|
||||
{
|
||||
/// <summary>Whether the romfs has this file.</summary>
|
||||
bool Exists(string romfsPath);
|
||||
|
||||
/// <summary>The file's bytes, as the game sees them (a .zs file stays zstd: see <see cref="Zs"/>). Throws
|
||||
/// FileNotFoundException when there is no such file.</summary>
|
||||
byte[] Read(string romfsPath);
|
||||
|
||||
/// <summary>What a romfs folder holds, one level deep, as romfs paths: files as they are, folders with a trailing "/".
|
||||
/// "" lists the romfs root. Empty for a folder that does not exist.</summary>
|
||||
IEnumerable<string> List(string dir);
|
||||
|
||||
/// <summary>A short description for logs: what kind of source, and where.</summary>
|
||||
string Describe { get; }
|
||||
|
||||
/// <summary>A cheap identity of one file (size and time, or where it sits in the package): it changes when the file
|
||||
/// can have changed. Used to key caches. Null when there is no such file.</summary>
|
||||
string? Stamp(string romfsPath);
|
||||
}
|
||||
|
||||
/// <summary>Opening a source from whatever the player dropped or chose.</summary>
|
||||
public static class GameSource
|
||||
{
|
||||
/// <summary>A .nup file, a game folder (holding romfs/) or a romfs folder itself.</summary>
|
||||
public static IGameSource Open(string path)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
return new NupSource(path);
|
||||
if (Directory.Exists(path))
|
||||
return new FolderSource(path);
|
||||
throw new FileNotFoundException("No game file or folder at " + path, path);
|
||||
}
|
||||
|
||||
/// <summary>A romfs path made uniform: "/" between the parts, no leading or trailing "/".</summary>
|
||||
internal static string Clean(string romfsPath) => romfsPath.Replace('\\', '/').Trim('/');
|
||||
}
|
||||
367
launcher/Core/GameFiles/NupSource.cs
Normal file
367
launcher/Core/GameFiles/NupSource.cs
Normal file
@@ -0,0 +1,367 @@
|
||||
// A .nup package: a decrypted Switch 2 dump in one file, holding one or more titles (the game, its update), each with an
|
||||
// exefs/ and a romfs/ tree. Ported from nx2/nup.py (the reader the build uses); the layout, as worked out there
|
||||
// (little-endian):
|
||||
//
|
||||
// 0x000 "NUP\x01"; u64 TOC offset at +0x08, u64 TOC size at +0x10, u64 blob offset at +0x38, u64 file size at +0x40
|
||||
// 0x080 "TOC\x01", u32 titles, u64 dirs, u64 files, u64 strings offset (from 0x80), u64 strings size
|
||||
// 0x0b0 titles, 0x40 each: u64 title id, u32 root dir, u32 exefs dir, u32 romfs dir, u32 version, ...
|
||||
// then dirs, 24 bytes each: u32 name offset, u32 name length, u32 first child, u32 children, u64 0
|
||||
// then files, 80 bytes each: u32 name offset, u32 name length, u64 size, u64 data offset, u64 stored size,
|
||||
// 32-byte hash, u8 codec (0 raw, 1 zstd), u8 flags, u16 reserved, 12 bytes reserved
|
||||
// then the child list, u32 each: a node index; below the dir count a dir, else (index - dirs) a file
|
||||
// then the name strings (not 0-terminated)
|
||||
//
|
||||
// A file's data is stored as is at its data offset, or as a zstd frame whose content is the file (codec 1; in older
|
||||
// packages codec 0 with a frame whose stated content size is the file's size). A romfs .zs file is zstd in the game too:
|
||||
// that one is not unpacked here (Zs does it, with the game's dictionaries).
|
||||
//
|
||||
// The package is opened for reading only (FileAccess.Read, FileShare.Read) and never written. Opening reads the header and
|
||||
// maps the index; no file data is read until a file is asked for.
|
||||
using System.IO.MemoryMappedFiles;
|
||||
using System.Text;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using ZstdSharp;
|
||||
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>One title in a .nup package: the base game or an update.</summary>
|
||||
public readonly record struct NupTitle(int Index, ulong Id, uint Version)
|
||||
{
|
||||
/// <summary>The title id as the Switch writes it (16 hex digits).</summary>
|
||||
public string IdHex => Id.ToString("x16");
|
||||
public override string ToString() => IdHex + " v" + Version;
|
||||
}
|
||||
|
||||
/// <summary>Reads romfs files out of a .nup package. The newest title (the update) is looked in first, then the others.</summary>
|
||||
public sealed class NupSource : IGameSource
|
||||
{
|
||||
static readonly byte[] ZstdMagic = { 0x28, 0xB5, 0x2F, 0xFD };
|
||||
const uint None = 0xFFFFFFFF;
|
||||
|
||||
readonly FileStream file;
|
||||
readonly SafeFileHandle handle;
|
||||
readonly MemoryMappedFile map;
|
||||
readonly MemoryMappedViewAccessor index;
|
||||
readonly long length;
|
||||
readonly DateTime written;
|
||||
readonly uint dirCount, fileCount;
|
||||
readonly long dirsAt, filesAt, kidsAt, stringsAt;
|
||||
readonly (uint Root, uint Exefs, uint Romfs)[] trees;
|
||||
// (each folder's children by name, made the first time the folder is looked into)
|
||||
readonly Dictionary<uint, Dictionary<string, uint>> children = new();
|
||||
|
||||
/// <summary>The package's file.</summary>
|
||||
public string Path { get; }
|
||||
|
||||
/// <summary>The titles in the package, newest version first (the update before the base game).</summary>
|
||||
public IReadOnlyList<NupTitle> Titles { get; }
|
||||
|
||||
/// <summary>The newest title's version: the game version the player has (for this game, 131072 is 2.0.0).</summary>
|
||||
public uint Version => Titles[0].Version;
|
||||
|
||||
public NupSource(string path)
|
||||
{
|
||||
Path = System.IO.Path.GetFullPath(path);
|
||||
file = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read, 1, FileOptions.RandomAccess);
|
||||
try
|
||||
{
|
||||
handle = file.SafeFileHandle;
|
||||
var info = new FileInfo(Path);
|
||||
length = file.Length;
|
||||
written = info.LastWriteTimeUtc;
|
||||
|
||||
var head = new byte[0xB0];
|
||||
if (RandomAccess.Read(handle, head, 0) != head.Length || !head.AsSpan(0, 4).SequenceEqual("NUP\x01"u8))
|
||||
throw new InvalidDataException(Path + " is not a .nup package");
|
||||
var declared = (long)BitConverter.ToUInt64(head, 0x40);
|
||||
// (a package that ends early, a download or copy that did not finish: said now, with the sizes)
|
||||
if (declared != 0 && length < declared)
|
||||
throw new InvalidDataException(string.Format("The .nup file is incomplete: it is {0} MB, its header says {1} MB. " +
|
||||
"Copy or download it again.", length >> 20, declared >> 20));
|
||||
if (!head.AsSpan(0x80, 4).SequenceEqual("TOC\x01"u8))
|
||||
throw new InvalidDataException(Path + ": no table of contents at 0x80");
|
||||
var titleCount = BitConverter.ToUInt32(head, 0x84);
|
||||
var nd = BitConverter.ToUInt64(head, 0x88);
|
||||
var nf = BitConverter.ToUInt64(head, 0x90);
|
||||
var stringsOffset = BitConverter.ToUInt64(head, 0x98);
|
||||
var stringsSize = BitConverter.ToUInt64(head, 0xA0);
|
||||
if (titleCount == 0 || titleCount > 64 || nd > int.MaxValue || nf > int.MaxValue)
|
||||
throw new InvalidDataException(Path + ": the table of contents makes no sense");
|
||||
dirCount = (uint)nd;
|
||||
fileCount = (uint)nf;
|
||||
dirsAt = 0xB0 + 0x40L * titleCount;
|
||||
filesAt = dirsAt + 24L * dirCount;
|
||||
kidsAt = filesAt + 80L * fileCount;
|
||||
stringsAt = 0x80 + (long)stringsOffset;
|
||||
var indexEnd = stringsAt + (long)stringsSize;
|
||||
if (stringsAt < kidsAt || indexEnd > length)
|
||||
throw new InvalidDataException(Path + ": the table of contents runs past the end of the file");
|
||||
|
||||
// (the index is mapped, not read: only the pages a lookup touches are read from the disk)
|
||||
map = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true);
|
||||
index = map.CreateViewAccessor(0, indexEnd, MemoryMappedFileAccess.Read);
|
||||
|
||||
var titles = new List<NupTitle>();
|
||||
trees = new (uint, uint, uint)[titleCount];
|
||||
for (var i = 0; i < titleCount; i++)
|
||||
{
|
||||
var at = 0xB0 + 0x40L * i;
|
||||
titles.Add(new NupTitle(i, index.ReadUInt64(at), index.ReadUInt32(at + 20)));
|
||||
trees[i] = (index.ReadUInt32(at + 8), index.ReadUInt32(at + 12), index.ReadUInt32(at + 16));
|
||||
}
|
||||
titles.Sort((a, b) => b.Version.CompareTo(a.Version));
|
||||
Titles = titles;
|
||||
}
|
||||
catch
|
||||
{
|
||||
index?.Dispose();
|
||||
map?.Dispose();
|
||||
file.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public string Describe => string.Format("nup {0} ({1:0.00} GB; titles {2})", Path, length / 1e9, string.Join(", ", Titles));
|
||||
|
||||
// ---- the index ----
|
||||
|
||||
string Name(uint offset, uint count)
|
||||
{
|
||||
var bytes = new byte[count];
|
||||
index.ReadArray(stringsAt + offset, bytes, 0, (int)count);
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
string NodeName(uint node) => node < dirCount
|
||||
? Name(index.ReadUInt32(dirsAt + 24L * node), index.ReadUInt32(dirsAt + 24L * node + 4))
|
||||
: Name(index.ReadUInt32(filesAt + 80L * (node - dirCount)), index.ReadUInt32(filesAt + 80L * (node - dirCount) + 4));
|
||||
|
||||
/// <summary>A folder's children by name (node indexes).</summary>
|
||||
Dictionary<string, uint> Children(uint dir)
|
||||
{
|
||||
lock (children)
|
||||
{
|
||||
if (children.TryGetValue(dir, out var known))
|
||||
return known;
|
||||
var first = index.ReadUInt32(dirsAt + 24L * dir + 8);
|
||||
var count = index.ReadUInt32(dirsAt + 24L * dir + 12);
|
||||
var kids = new uint[count];
|
||||
index.ReadArray(kidsAt + 4L * first, kids, 0, (int)count);
|
||||
var names = new Dictionary<string, uint>((int)count, StringComparer.Ordinal);
|
||||
foreach (var kid in kids)
|
||||
if (kid < dirCount + fileCount)
|
||||
names.TryAdd(NodeName(kid), kid);
|
||||
children[dir] = names;
|
||||
return names;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The node a romfs path names in one title's romfs (a dir below dirCount, a file above), or None.</summary>
|
||||
uint Find(uint romfsDir, string romfsPath)
|
||||
{
|
||||
var node = romfsDir;
|
||||
var clean = GameSource.Clean(romfsPath);
|
||||
if (clean.Length == 0)
|
||||
return node;
|
||||
foreach (var part in clean.Split('/'))
|
||||
{
|
||||
if (node >= dirCount || !Children(node).TryGetValue(part, out node))
|
||||
return None;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/// <summary>The file record for a romfs path, from the newest title that has it.</summary>
|
||||
bool FindFile(string romfsPath, out uint fileIndex)
|
||||
{
|
||||
foreach (var t in Titles)
|
||||
{
|
||||
var romfs = trees[t.Index].Romfs;
|
||||
if (romfs == None || romfs >= dirCount)
|
||||
continue;
|
||||
var node = Find(romfs, romfsPath);
|
||||
if (node != None && node >= dirCount)
|
||||
{
|
||||
fileIndex = node - dirCount;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
fileIndex = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool Exists(string romfsPath) => FindFile(romfsPath, out _);
|
||||
|
||||
public IEnumerable<string> List(string dir)
|
||||
{
|
||||
var clean = GameSource.Clean(dir);
|
||||
var prefix = clean.Length == 0 ? "" : clean + "/";
|
||||
var seen = new SortedSet<string>(StringComparer.Ordinal);
|
||||
foreach (var t in Titles)
|
||||
{
|
||||
var romfs = trees[t.Index].Romfs;
|
||||
if (romfs == None || romfs >= dirCount)
|
||||
continue;
|
||||
var node = Find(romfs, clean);
|
||||
if (node == None || node >= dirCount)
|
||||
continue;
|
||||
foreach (var (name, kid) in Children(node))
|
||||
seen.Add(prefix + name + (kid < dirCount ? "/" : ""));
|
||||
}
|
||||
return seen;
|
||||
}
|
||||
|
||||
public string? Stamp(string romfsPath)
|
||||
{
|
||||
if (!FindFile(romfsPath, out var i))
|
||||
return null;
|
||||
var at = filesAt + 80L * i;
|
||||
return string.Format("{0}-{1}-{2}-{3}", length, written.Ticks, index.ReadUInt64(at + 16), index.ReadUInt64(at + 8));
|
||||
}
|
||||
|
||||
// ---- the data ----
|
||||
|
||||
public byte[] Read(string romfsPath)
|
||||
{
|
||||
if (!FindFile(romfsPath, out var i))
|
||||
throw new FileNotFoundException("The game has no " + romfsPath + " (" + Path + ")", romfsPath);
|
||||
var at = filesAt + 80L * i;
|
||||
var size = (long)index.ReadUInt64(at + 8);
|
||||
var offset = (long)index.ReadUInt64(at + 16);
|
||||
var stored = (long)index.ReadUInt64(at + 24);
|
||||
var codec = index.ReadByte(at + 64);
|
||||
if (size == 0)
|
||||
return Array.Empty<byte>();
|
||||
if (size > int.MaxValue || offset < 0 || offset > length)
|
||||
throw new InvalidDataException(romfsPath + ": the package's record for it makes no sense");
|
||||
|
||||
if (codec == 1)
|
||||
{
|
||||
// (the package states the frame's own size: exactly that is read)
|
||||
if (stored <= 0 || stored > length - offset)
|
||||
throw new InvalidDataException(romfsPath + ": its compressed data runs past the end of the package");
|
||||
var frame = ReadAt(offset, (int)stored);
|
||||
var output = new byte[size];
|
||||
using var z = new Decompressor();
|
||||
if (z.Unwrap(frame, output) != size)
|
||||
throw new InvalidDataException(romfsPath + ": it unpacked to the wrong size");
|
||||
return output;
|
||||
}
|
||||
if (IsPackedLegacy(romfsPath, offset, size))
|
||||
return UnpackLegacy(romfsPath, offset, size);
|
||||
if (size > length - offset)
|
||||
throw new InvalidDataException(romfsPath + ": its data runs past the end of the package (the .nup is incomplete)");
|
||||
return ReadAt(offset, (int)size);
|
||||
}
|
||||
|
||||
byte[] ReadAt(long offset, int count)
|
||||
{
|
||||
var data = new byte[count];
|
||||
var done = 0;
|
||||
while (done < count)
|
||||
{
|
||||
var n = RandomAccess.Read(handle, data.AsSpan(done), offset + done);
|
||||
if (n <= 0)
|
||||
throw new EndOfStreamException("The .nup file ends early: it is incomplete. Copy or download it again.");
|
||||
done += n;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>The content size a zstd frame header states, or -1 when it states none (nup.py frame_content_size).</summary>
|
||||
static long FrameContentSize(ReadOnlySpan<byte> head)
|
||||
{
|
||||
if (head.Length < 18 || !head[..4].SequenceEqual(ZstdMagic))
|
||||
return -1;
|
||||
var fhd = head[4];
|
||||
var single = (fhd >> 5) & 1;
|
||||
var at = 5 + (single != 0 ? 0 : 1) + new[] { 0, 1, 2, 4 }[fhd & 3];
|
||||
var n = new[] { single != 0 ? 1 : 0, 2, 4, 8 }[fhd >> 6];
|
||||
if (n == 0)
|
||||
return -1;
|
||||
long size = 0;
|
||||
for (var k = n - 1; k >= 0; k--)
|
||||
size = size << 8 | head[at + k];
|
||||
return n == 2 ? size + 256 : size;
|
||||
}
|
||||
|
||||
/// <summary>Older packages (codec 0) may still keep a file as a zstd frame: nup.py is_packed, the same rules. A .zs file
|
||||
/// is zstd in the game too; it counts as packed only when what the frame holds is zstd again.</summary>
|
||||
bool IsPackedLegacy(string name, long offset, long size)
|
||||
{
|
||||
var head = new byte[18];
|
||||
if (RandomAccess.Read(handle, head, offset) < 18 || !head.AsSpan(0, 4).SequenceEqual(ZstdMagic))
|
||||
return false;
|
||||
var content = FrameContentSize(head);
|
||||
if (name.EndsWith(".zs", StringComparison.Ordinal) && (content < 0 || content == size))
|
||||
return content == size && InnerIsZstd(offset, size);
|
||||
if (content >= 0)
|
||||
return content == size;
|
||||
try
|
||||
{
|
||||
return UnpackLegacy(name, offset, size).Length == size;
|
||||
}
|
||||
catch (Exception e) when (e is ZstdException or InvalidDataException or IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool InnerIsZstd(long offset, long size)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var s = new DecompressionStream(new WindowStream(handle, offset, Math.Min(size, 1 << 20)));
|
||||
var four = new byte[4];
|
||||
return s.ReadAtLeast(four, 4, throwOnEndOfStream: false) == 4 && four.AsSpan().SequenceEqual(ZstdMagic);
|
||||
}
|
||||
catch (Exception e) when (e is ZstdException or IOException)
|
||||
{
|
||||
return false; // (made with one of the game's dictionaries: the game's own file)
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A frame of unknown length: decompressed until the file's size is reached (the frame cannot be longer than
|
||||
/// the file plus 64 KB, as nup.py reads it).</summary>
|
||||
byte[] UnpackLegacy(string name, long offset, long size)
|
||||
{
|
||||
using var s = new DecompressionStream(new WindowStream(handle, offset, Math.Min(size + (1 << 16), length - offset)));
|
||||
var output = new byte[size];
|
||||
var got = s.ReadAtLeast(output, output.Length, throwOnEndOfStream: false);
|
||||
if (got != size)
|
||||
throw new InvalidDataException(string.Format("{0}: unpacked to {1} bytes, {2} expected", name, got, size));
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>A read-only stream over part of the package, read by position (safe beside other threads' reads).</summary>
|
||||
sealed class WindowStream(SafeFileHandle handle, long start, long count) : Stream
|
||||
{
|
||||
long position;
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => false;
|
||||
public override bool CanWrite => false;
|
||||
public override long Length => count;
|
||||
public override long Position { get => position; set => throw new NotSupportedException(); }
|
||||
public override int Read(byte[] buffer, int offset, int n) => Read(buffer.AsSpan(offset, n));
|
||||
public override int Read(Span<byte> buffer)
|
||||
{
|
||||
var n = (int)Math.Min(buffer.Length, count - position);
|
||||
if (n <= 0)
|
||||
return 0;
|
||||
n = RandomAccess.Read(handle, buffer[..n], start + position);
|
||||
position += n;
|
||||
return n;
|
||||
}
|
||||
public override void Flush() { }
|
||||
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
public override void Write(byte[] buffer, int offset, int n) => throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
index.Dispose();
|
||||
map.Dispose();
|
||||
file.Dispose();
|
||||
}
|
||||
}
|
||||
149
launcher/Core/GameFiles/Png.cs
Normal file
149
launcher/Core/GameFiles/Png.cs
Normal file
@@ -0,0 +1,149 @@
|
||||
// A minimal PNG writer and reader for 8-bit RGBA images (the reader is only for comparing with reference images and for
|
||||
// tests: it takes the PNGs this writer and common tools make, colour type 6 or 2, 8 bits, not interlaced).
|
||||
using System.Buffers.Binary;
|
||||
using System.IO.Compression;
|
||||
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
public static class Png
|
||||
{
|
||||
static readonly byte[] Signature = { 0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A };
|
||||
|
||||
/// <summary>An RGBA8 image (width * height * 4 bytes, rows top to bottom) as a PNG file's bytes. Each row is filtered
|
||||
/// with "Sub", which keeps the zlib step quick and the file reasonably small.</summary>
|
||||
public static byte[] Encode(ReadOnlySpan<byte> rgba, int width, int height, CompressionLevel level = CompressionLevel.Fastest)
|
||||
{
|
||||
if (rgba.Length < (long)width * height * 4)
|
||||
throw new ArgumentException("the image is smaller than width * height * 4 bytes");
|
||||
var stride = width * 4;
|
||||
var raw = new byte[(stride + 1) * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var row = rgba.Slice(y * stride, stride);
|
||||
var at = y * (stride + 1);
|
||||
raw[at] = 1; // (filter: Sub)
|
||||
row[..4].CopyTo(raw.AsSpan(at + 1));
|
||||
for (var x = 4; x < stride; x++)
|
||||
raw[at + 1 + x] = (byte)(row[x] - row[x - 4]);
|
||||
}
|
||||
using var idat = new MemoryStream();
|
||||
using (var z = new ZLibStream(idat, level, leaveOpen: true))
|
||||
z.Write(raw);
|
||||
|
||||
using var png = new MemoryStream();
|
||||
png.Write(Signature);
|
||||
Span<byte> header = stackalloc byte[13];
|
||||
BinaryPrimitives.WriteInt32BigEndian(header, width);
|
||||
BinaryPrimitives.WriteInt32BigEndian(header[4..], height);
|
||||
header[8] = 8; // bit depth
|
||||
header[9] = 6; // RGBA
|
||||
header[10] = 0; // deflate
|
||||
header[11] = 0; // adaptive filtering
|
||||
header[12] = 0; // not interlaced
|
||||
Chunk(png, "IHDR", header);
|
||||
Chunk(png, "IDAT", idat.GetBuffer().AsSpan(0, (int)idat.Length));
|
||||
Chunk(png, "IEND", ReadOnlySpan<byte>.Empty);
|
||||
return png.ToArray();
|
||||
}
|
||||
|
||||
static void Chunk(Stream s, string type, ReadOnlySpan<byte> payload)
|
||||
{
|
||||
Span<byte> four = stackalloc byte[4];
|
||||
BinaryPrimitives.WriteInt32BigEndian(four, payload.Length);
|
||||
s.Write(four);
|
||||
Span<byte> tag = stackalloc byte[4];
|
||||
for (var i = 0; i < 4; i++)
|
||||
tag[i] = (byte)type[i];
|
||||
s.Write(tag);
|
||||
s.Write(payload);
|
||||
var crc = Crc(Crc(0xFFFFFFFF, tag), payload) ^ 0xFFFFFFFF;
|
||||
BinaryPrimitives.WriteUInt32BigEndian(four, crc);
|
||||
s.Write(four);
|
||||
}
|
||||
|
||||
static readonly uint[] CrcTable = Enumerable.Range(0, 256).Select(n =>
|
||||
{
|
||||
var c = (uint)n;
|
||||
for (var k = 0; k < 8; k++)
|
||||
c = (c & 1) != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1;
|
||||
return c;
|
||||
}).ToArray();
|
||||
|
||||
/// <summary>The CRC-32 PNG chunks carry (zlib's), continued over more bytes.</summary>
|
||||
static uint Crc(uint crc, ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
foreach (var b in bytes)
|
||||
crc = CrcTable[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||||
return crc;
|
||||
}
|
||||
|
||||
/// <summary>A PNG decoded to RGBA8 (8-bit RGBA or RGB, not interlaced).</summary>
|
||||
public static (int Width, int Height, byte[] Rgba) Decode(byte[] png)
|
||||
{
|
||||
if (png.Length < 33 || !png.AsSpan(0, 8).SequenceEqual(Signature))
|
||||
throw new InvalidDataException("not a PNG file");
|
||||
int width = 0, height = 0, channels = 4;
|
||||
using var idat = new MemoryStream();
|
||||
for (var at = 8; at + 8 <= png.Length;)
|
||||
{
|
||||
var n = BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(at));
|
||||
var type = System.Text.Encoding.ASCII.GetString(png, at + 4, 4);
|
||||
var body = png.AsSpan(at + 8, n);
|
||||
if (type == "IHDR")
|
||||
{
|
||||
width = BinaryPrimitives.ReadInt32BigEndian(body);
|
||||
height = BinaryPrimitives.ReadInt32BigEndian(body[4..]);
|
||||
if (body[8] != 8 || (body[9] != 6 && body[9] != 2) || body[12] != 0)
|
||||
throw new NotSupportedException("only 8-bit RGB/RGBA PNGs without interlacing are read");
|
||||
channels = body[9] == 6 ? 4 : 3;
|
||||
}
|
||||
else if (type == "IDAT")
|
||||
idat.Write(body);
|
||||
else if (type == "IEND")
|
||||
break;
|
||||
at += 12 + n;
|
||||
}
|
||||
idat.Position = 0;
|
||||
var stride = width * channels;
|
||||
var raw = new byte[(stride + 1) * height];
|
||||
using (var z = new ZLibStream(idat, CompressionMode.Decompress))
|
||||
z.ReadExactly(raw);
|
||||
|
||||
var pixels = new byte[stride * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
var filter = raw[y * (stride + 1)];
|
||||
var src = raw.AsSpan(y * (stride + 1) + 1, stride);
|
||||
var dst = pixels.AsSpan(y * stride, stride);
|
||||
var up = y > 0 ? pixels.AsSpan((y - 1) * stride, stride) : new byte[stride];
|
||||
for (var x = 0; x < stride; x++)
|
||||
{
|
||||
int a = x >= channels ? dst[x - channels] : 0, b = up[x], c = x >= channels ? up[x - channels] : 0;
|
||||
dst[x] = (byte)(src[x] + filter switch
|
||||
{
|
||||
0 => 0,
|
||||
1 => a,
|
||||
2 => b,
|
||||
3 => (a + b) / 2,
|
||||
4 => Paeth(a, b, c),
|
||||
_ => throw new InvalidDataException("PNG filter " + filter),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (channels == 4)
|
||||
return (width, height, pixels);
|
||||
var rgba = new byte[width * height * 4];
|
||||
for (var i = 0; i < width * height; i++)
|
||||
{
|
||||
pixels.AsSpan(i * 3, 3).CopyTo(rgba.AsSpan(i * 4));
|
||||
rgba[i * 4 + 3] = 255;
|
||||
}
|
||||
return (width, height, rgba);
|
||||
}
|
||||
|
||||
static int Paeth(int a, int b, int c)
|
||||
{
|
||||
int p = a + b - c, pa = Math.Abs(p - a), pb = Math.Abs(p - b), pc = Math.Abs(p - c);
|
||||
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
|
||||
}
|
||||
}
|
||||
123
launcher/Core/GameFiles/Zs.cs
Normal file
123
launcher/Core/GameFiles/Zs.cs
Normal file
@@ -0,0 +1,123 @@
|
||||
// The game's .zs files: zstd frames made with one of three dictionaries that the game keeps in its romfs, in
|
||||
// "Pack/ZsDic.pack.zs" (a zstd frame without a dictionary holding a SARC archive of the dictionaries). Ported from the
|
||||
// lab's research/scratch/t09_common.py (unzs, sarc).
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
using ZstdSharp;
|
||||
|
||||
namespace Triforce.Core.GameFiles;
|
||||
|
||||
/// <summary>Unpacks romfs .zs files with the game's own dictionaries. Thread-safe.</summary>
|
||||
public sealed class Zs
|
||||
{
|
||||
public const string DictionaryPack = "Pack/ZsDic.pack.zs";
|
||||
|
||||
readonly IGameSource source;
|
||||
readonly Lazy<Dictionary<string, byte[]>> dictionaries;
|
||||
|
||||
public Zs(IGameSource source)
|
||||
{
|
||||
this.source = source;
|
||||
dictionaries = new Lazy<Dictionary<string, byte[]>>(() => Sarc(Decompress(source.Read(DictionaryPack), null)));
|
||||
}
|
||||
|
||||
/// <summary>The game's dictionaries by name (zs.zsdic, pack.zsdic, bcett.byml.zsdic).</summary>
|
||||
public IReadOnlyDictionary<string, byte[]> Dictionaries => dictionaries.Value;
|
||||
|
||||
/// <summary>The dictionary the game uses for a file, by its name (t09_common.unzs): bcett files have their own, .pack.zs
|
||||
/// archives theirs, everything else the general one.</summary>
|
||||
public static string DictionaryFor(string romfsPath)
|
||||
{
|
||||
var name = romfsPath[(romfsPath.LastIndexOf('/') + 1)..];
|
||||
return name.Contains("bcett", StringComparison.Ordinal) ? "bcett.byml.zsdic"
|
||||
: name.EndsWith(".pack.zs", StringComparison.Ordinal) ? "pack.zsdic" : "zs.zsdic";
|
||||
}
|
||||
|
||||
/// <summary>A romfs .zs file, read and unpacked.</summary>
|
||||
public byte[] Unpack(string romfsPath) => Unpack(romfsPath, source.Read(romfsPath));
|
||||
|
||||
/// <summary>A .zs file's bytes unpacked. The dictionary is the one the name calls for; when the frame names another
|
||||
/// dictionary by its id, that one is used instead.</summary>
|
||||
public byte[] Unpack(string romfsPath, byte[] data)
|
||||
{
|
||||
var dicts = dictionaries.Value;
|
||||
dicts.TryGetValue(DictionaryFor(romfsPath), out var dict);
|
||||
var wanted = FrameDictionaryId(data);
|
||||
if (wanted != 0 && (dict == null || DictionaryId(dict) != wanted))
|
||||
dict = dicts.Values.FirstOrDefault(d => DictionaryId(d) == wanted) ?? dict;
|
||||
return Decompress(data, dict);
|
||||
}
|
||||
|
||||
/// <summary>One zstd frame unpacked, with a dictionary or none.</summary>
|
||||
public static byte[] Decompress(ReadOnlySpan<byte> data, byte[]? dictionary)
|
||||
{
|
||||
using var z = new Decompressor();
|
||||
if (dictionary != null)
|
||||
z.LoadDictionary(dictionary);
|
||||
var size = Decompressor.GetDecompressedSize(data);
|
||||
if (size > 0 && size <= int.MaxValue)
|
||||
{
|
||||
var output = new byte[size];
|
||||
var n = z.Unwrap(data, output);
|
||||
return n == output.Length ? output : output[..n];
|
||||
}
|
||||
// (a frame that does not say how large it is: unpacked as a stream)
|
||||
using var stream = new DecompressionStream(new MemoryStream(data.ToArray()));
|
||||
if (dictionary != null)
|
||||
stream.LoadDictionary(dictionary);
|
||||
using var into = new MemoryStream();
|
||||
stream.CopyTo(into);
|
||||
return into.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>The dictionary id a zstd frame header names, 0 for none.</summary>
|
||||
static uint FrameDictionaryId(ReadOnlySpan<byte> frame)
|
||||
{
|
||||
if (frame.Length < 6 || BinaryPrimitives.ReadUInt32LittleEndian(frame) != 0xFD2FB528)
|
||||
return 0;
|
||||
var fhd = frame[4];
|
||||
var single = (fhd >> 5) & 1;
|
||||
var idBytes = new[] { 0, 1, 2, 4 }[fhd & 3];
|
||||
var at = 5 + (single != 0 ? 0 : 1);
|
||||
uint id = 0;
|
||||
for (var k = idBytes - 1; k >= 0; k--)
|
||||
id = id << 8 | (at + k < frame.Length ? frame[at + k] : 0u);
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>A zstd dictionary's id (after its magic 0xEC30A437), 0 for raw content.</summary>
|
||||
static uint DictionaryId(byte[] dict) =>
|
||||
dict.Length >= 8 && BinaryPrimitives.ReadUInt32LittleEndian(dict) == 0xEC30A437 ? BinaryPrimitives.ReadUInt32LittleEndian(dict.AsSpan(4)) : 0;
|
||||
|
||||
/// <summary>A SARC archive's files by name (by hash, as 8 hex digits, for one without a name). Little-endian SARC only,
|
||||
/// as this game's are.</summary>
|
||||
public static Dictionary<string, byte[]> Sarc(byte[] b)
|
||||
{
|
||||
if (b.Length < 0x20 || b[0] != 'S' || b[1] != 'A' || b[2] != 'R' || b[3] != 'C')
|
||||
throw new InvalidDataException("not a SARC archive");
|
||||
var dataAt = BinaryPrimitives.ReadInt32LittleEndian(b.AsSpan(0x0C));
|
||||
const int sfat = 0x14;
|
||||
var count = BinaryPrimitives.ReadUInt16LittleEndian(b.AsSpan(sfat + 6));
|
||||
var namesAt = sfat + 12 + 16 * count + 8;
|
||||
var files = new Dictionary<string, byte[]>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var node = b.AsSpan(sfat + 12 + 16 * i);
|
||||
var hash = BinaryPrimitives.ReadUInt32LittleEndian(node);
|
||||
var attr = BinaryPrimitives.ReadUInt32LittleEndian(node[4..]);
|
||||
var start = BinaryPrimitives.ReadInt32LittleEndian(node[8..]);
|
||||
var end = BinaryPrimitives.ReadInt32LittleEndian(node[12..]);
|
||||
string name;
|
||||
if (attr >> 24 != 0)
|
||||
{
|
||||
var at = namesAt + (int)(attr & 0xFFFF) * 4;
|
||||
var zero = Array.IndexOf(b, (byte)0, at);
|
||||
name = Encoding.UTF8.GetString(b, at, (zero < 0 ? b.Length : zero) - at);
|
||||
}
|
||||
else
|
||||
name = hash.ToString("x8");
|
||||
files[name] = b[(dataAt + start)..(dataAt + end)];
|
||||
}
|
||||
return files;
|
||||
}
|
||||
}
|
||||
13
launcher/Core/Triforce.Core.csproj
Normal file
13
launcher/Core/Triforce.Core.csproj
Normal file
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ZstdSharp.Port" Version="0.8.8" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
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 + ".");
|
||||
}
|
||||
}
|
||||
322
launcher/LogicTests/Harness.cs
Normal file
322
launcher/LogicTests/Harness.cs
Normal file
@@ -0,0 +1,322 @@
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Triforce.Logic;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
sealed class TestFailed : Exception { public TestFailed(string m) : base(m) { } }
|
||||
|
||||
static class T
|
||||
{
|
||||
public static void Check(bool ok, string what) { if (!ok) throw new TestFailed(what); }
|
||||
public static void Equal<TV>(TV expected, TV actual, string what)
|
||||
{
|
||||
if (!EqualityComparer<TV>.Default.Equals(expected, actual)) throw new TestFailed(what + ": expected [" + expected + "], got [" + actual + "]");
|
||||
}
|
||||
public static TE Throws<TE>(Action a, string what) where TE : Exception
|
||||
{
|
||||
try { a(); }
|
||||
catch (TE e) { return e; }
|
||||
catch (Exception e) { throw new TestFailed(what + ": threw " + e.GetType().Name + " (" + e.Message + ") instead of " + typeof(TE).Name); }
|
||||
throw new TestFailed(what + ": did not throw " + typeof(TE).Name);
|
||||
}
|
||||
public static async Task<TE> ThrowsAsync<TE>(Func<Task> a, string what) where TE : Exception
|
||||
{
|
||||
try { await a(); }
|
||||
catch (TE e) { return e; }
|
||||
catch (Exception e) { throw new TestFailed(what + ": threw " + e.GetType().Name + " (" + e.Message + ") instead of " + typeof(TE).Name); }
|
||||
throw new TestFailed(what + ": did not throw " + typeof(TE).Name);
|
||||
}
|
||||
|
||||
static readonly string Base = Path.Combine(Path.GetTempPath(), "triforce-logictests-" + Environment.ProcessId);
|
||||
static int n;
|
||||
|
||||
/// <summary>A fresh TRIFORCE_TEST_ROOT folder.</summary>
|
||||
public static string NewRoot(string name)
|
||||
{
|
||||
var root = Path.Combine(Base, Interlocked.Increment(ref n).ToString("00") + "-" + name);
|
||||
Directory.CreateDirectory(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
public static void CleanUp()
|
||||
{
|
||||
try { if (Directory.Exists(Base)) Directory.Delete(Base, true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A context whose test root is root, as if the launcher ran as <root>\Programs\Triforce\TriforceSetup.exe (so
|
||||
/// nothing is written beside the test program itself).</summary>
|
||||
public static TriforceContext Ctx(string root, string? self = null, Dictionary<string, string?>? env = null)
|
||||
{
|
||||
var e = new Dictionary<string, string?>(env ?? new()) { ["TRIFORCE_TEST_ROOT"] = root };
|
||||
return TriforceContext.Create(e, self ?? Path.Combine(root, "Programs", "Triforce", BuildInfo.SetupAsset));
|
||||
}
|
||||
|
||||
/// <summary>This test program's files (its apphost, dlls, runtimeconfig): copied where a fake python or a fake new launcher
|
||||
/// must run; exeName names the copy of the apphost.</summary>
|
||||
public static void CopySelf(string folder, string exeName)
|
||||
{
|
||||
Directory.CreateDirectory(folder);
|
||||
var dir = AppContext.BaseDirectory;
|
||||
File.Copy(Environment.ProcessPath!, Path.Combine(folder, exeName), true);
|
||||
foreach (var f in Directory.GetFiles(dir))
|
||||
{
|
||||
var name = Path.GetFileName(f);
|
||||
if (name.EndsWith(".dll") || name.EndsWith(".runtimeconfig.json") || name.EndsWith(".deps.json"))
|
||||
File.Copy(f, Path.Combine(folder, name), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The bytes of this program's apphost: served as the new TriforceSetup.exe.</summary>
|
||||
public static byte[] SelfBytes => File.ReadAllBytes(Environment.ProcessPath!);
|
||||
}
|
||||
|
||||
/// <summary>A small HTTP/1.1 server on 127.0.0.1 for the release check and the downloads: GET only, a strong ETag, Range
|
||||
/// ("bytes=N-") answered with 206 and If-Range honoured, 404 for anything it does not have. (TcpListener, not HttpListener: no URL
|
||||
/// reservation is needed for a user without admin rights.)</summary>
|
||||
sealed class FakeServer : IDisposable
|
||||
{
|
||||
readonly TcpListener listener;
|
||||
readonly Dictionary<string, (byte[] Body, string Type, int Status)> routes = new();
|
||||
readonly CancellationTokenSource stop = new();
|
||||
public int Requests;
|
||||
public readonly List<string> Seen = new();
|
||||
|
||||
public FakeServer()
|
||||
{
|
||||
listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
_ = Task.Run(Loop);
|
||||
}
|
||||
|
||||
public string Url => "http://127.0.0.1:" + ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
|
||||
public void Add(string path, byte[] body, string type = "application/octet-stream", int status = 200)
|
||||
{
|
||||
lock (routes) routes[path] = (body, type, status);
|
||||
}
|
||||
public void Add(string path, string text, string type = "application/json", int status = 200) => Add(path, Encoding.UTF8.GetBytes(text), type, status);
|
||||
|
||||
async Task Loop()
|
||||
{
|
||||
while (!stop.IsCancellationRequested)
|
||||
{
|
||||
TcpClient c;
|
||||
try { c = await listener.AcceptTcpClientAsync(stop.Token); } catch (Exception) { return; }
|
||||
_ = Task.Run(() => Serve(c));
|
||||
}
|
||||
}
|
||||
|
||||
async Task Serve(TcpClient c)
|
||||
{
|
||||
using (c)
|
||||
try
|
||||
{
|
||||
var s = c.GetStream();
|
||||
var head = new StringBuilder();
|
||||
var buf = new byte[1];
|
||||
while (!head.ToString().EndsWith("\r\n\r\n"))
|
||||
{
|
||||
if (await s.ReadAsync(buf) == 0) return;
|
||||
head.Append((char)buf[0]);
|
||||
}
|
||||
var lines = head.ToString().Split("\r\n");
|
||||
var path = lines[0].Split(' ')[1];
|
||||
Interlocked.Increment(ref Requests);
|
||||
lock (Seen) Seen.Add(path);
|
||||
long from = -1;
|
||||
string? ifRange = null;
|
||||
foreach (var l in lines.Skip(1))
|
||||
{
|
||||
if (l.StartsWith("Range: bytes=", StringComparison.OrdinalIgnoreCase)) from = long.Parse(l.Substring(13).TrimEnd('-'));
|
||||
if (l.StartsWith("If-Range: ", StringComparison.OrdinalIgnoreCase)) ifRange = l.Substring(10);
|
||||
}
|
||||
(byte[] Body, string Type, int Status) r;
|
||||
bool found;
|
||||
lock (routes) found = routes.TryGetValue(path, out r);
|
||||
if (!found) r = (Encoding.UTF8.GetBytes("not found"), "text/plain", 404);
|
||||
var etag = "\"v" + r.Body.Length + "\"";
|
||||
var body = r.Body;
|
||||
var status = r.Status;
|
||||
var extra = "ETag: " + etag + "\r\n";
|
||||
if (from > 0 && status == 200 && (ifRange == null || ifRange == etag))
|
||||
{
|
||||
if (from >= body.Length) { status = 416; body = Array.Empty<byte>(); }
|
||||
else
|
||||
{
|
||||
extra += "Content-Range: bytes " + from + "-" + (r.Body.Length - 1) + "/" + r.Body.Length + "\r\n";
|
||||
body = r.Body.AsSpan((int)from).ToArray();
|
||||
status = 206;
|
||||
}
|
||||
}
|
||||
var text = status switch { 200 => "OK", 206 => "Partial Content", 404 => "Not Found", 416 => "Range Not Satisfiable", _ => "Status" };
|
||||
var header = "HTTP/1.1 " + status + " " + text + "\r\nContent-Type: " + r.Type + "\r\nContent-Length: " + body.Length + "\r\n" + extra + "Connection: close\r\n\r\n";
|
||||
await s.WriteAsync(Encoding.ASCII.GetBytes(header));
|
||||
await s.WriteAsync(body);
|
||||
await s.FlushAsync();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
stop.Cancel();
|
||||
listener.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The fakes this program plays when a test starts it as another program.</summary>
|
||||
static class Fakes
|
||||
{
|
||||
/// <summary>A stand-in game for the benchmark (copied in as Triforce.exe: "image.bin --romfs .. --user .."): the title's fps
|
||||
/// lines, a save that loads after three A presses, "!cheat 1000+n" teleports, and per place fps / 1% low lines; each 5 s
|
||||
/// window of the real game is TRIFORCE_FAKE_WINDOW_MS here (default 400). Frame rates: by place, x1.4 with an upscaler on in
|
||||
/// the options file beside the exe, and the cap there. It writes a save into --user, to show the benchmark's copy takes it.</summary>
|
||||
/// <summary>The stand-in game's benchmark mode: "bench:" progress lines, then the results file (as host/ writes it), then
|
||||
/// it ends. Frame rates by scene, x1.4 with an upscaler on in the options file beside the exe. TRIFORCE_FAKE_WINDOW_MS paces it.</summary>
|
||||
static int FakeBenchmark(string results, string? user)
|
||||
{
|
||||
var ic = System.Globalization.CultureInfo.InvariantCulture;
|
||||
var win = int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_WINDOW_MS"), out var w) ? w : 400;
|
||||
var opts = Triforce.Logic.BenchIni.Read(Path.Combine(AppContext.BaseDirectory, "triforce_options.ini"));
|
||||
var up = opts.TryGetValue("dlss", out var u) && u != 0 ? 1.4 : 1.0;
|
||||
Console.Error.WriteLine("bench: Loading your newest save"); Thread.Sleep(win * 3);
|
||||
if (user != null) { Directory.CreateDirectory(Path.Combine(user, "save")); File.WriteAllText(Path.Combine(user, "save", "written-by-the-game.txt"), "x"); }
|
||||
var scenes = new[] { ("Hyrule Field", 92.0), ("Castle Town Market", 71.0), ("Kokiri Forest", 118.0), ("Lake Hylia", 133.0) };
|
||||
var json = new System.Text.StringBuilder("{\"version\":1,\"stopped\":false,\"gpu\":\"Stand-in GPU\",\"scenes\":[");
|
||||
for (var i = 0; i < scenes.Length; i++)
|
||||
{
|
||||
var (name, fps) = scenes[i];
|
||||
Console.Error.WriteLine($"bench: Going to {name}"); Thread.Sleep(win);
|
||||
Console.Error.WriteLine($"bench: Scene {i + 1} of {scenes.Length} · {name}"); Thread.Sleep(win * 3);
|
||||
var f = fps * up; var ft = Enumerable.Range(0, 120).Select(k => 1000 / f * (1 + 0.08 * Math.Sin(k / 5.0) + (k % 37 == 0 ? 0.6 : 0)));
|
||||
json.Append(string.Create(ic, $"{(i > 0 ? "," : "")}{{\"name\":\"{name}\",\"avg\":{f:0.0},\"low1\":{f * 0.84:0.0},\"low01\":{f * 0.7:0.0},\"frames\":{(int)(f * 15)},\"seconds\":15,\"frametimes_ms\":[{string.Join(",", ft.Select(x => x.ToString("0.00", ic)))}]}}"));
|
||||
}
|
||||
json.Append("]}");
|
||||
File.WriteAllText(results + ".new", json.ToString()); File.Move(results + ".new", results, true);
|
||||
Console.Error.WriteLine("bench: Finished"); Thread.Sleep(win);
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static int FakeGame(string[] a)
|
||||
{
|
||||
string? Arg(string name) { var i = Array.IndexOf(a, name); return i >= 0 && i + 1 < a.Length ? a[i + 1] : null; }
|
||||
if (Environment.GetEnvironmentVariable("HOS_BENCHMARK") is { Length: > 0 } results) return FakeBenchmark(results, Arg("--user"));
|
||||
var input = Environment.GetEnvironmentVariable("HOS_INPUT_LIVE");
|
||||
var win = int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_WINDOW_MS"), out var w) ? w : 400;
|
||||
var ini = Path.Combine(AppContext.BaseDirectory, "triforce_options.ini");
|
||||
var opts = Triforce.Logic.BenchIni.Read(ini);
|
||||
var up = opts.TryGetValue("dlss", out var u) && u != 0 ? 1.4 : 1.0;
|
||||
var capFps = (opts.TryGetValue("frame_rate_cap", out var c) ? c : 0) switch { 0 => 60, 1 => 90, 2 => 120, 3 => 144, 4 => 165, _ => 240 };
|
||||
var place = new Dictionary<int, double> { [1000] = 118, [1001] = 92, [1003] = 71, [1007] = 133 };
|
||||
double baseFps = 80; var presses = 0; var loaded = false; long frames = 0; int readAt = 0;
|
||||
var user = Arg("--user");
|
||||
for (var t = 0; t < 100000; t++)
|
||||
{
|
||||
Thread.Sleep(win);
|
||||
if (input != null && File.Exists(input))
|
||||
{
|
||||
var all = File.ReadAllText(input);
|
||||
foreach (var line in all[readAt..].Split('\n', StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (line.StartsWith("!cheat "))
|
||||
{
|
||||
var id = int.Parse(line[7..].Trim());
|
||||
Console.Error.WriteLine($"cheats: teleport ... to {id} at ...: request sent, result 0x0");
|
||||
if (place.TryGetValue(id, out var f)) baseFps = f;
|
||||
}
|
||||
else presses += line.Split(',').Count(x => x.EndsWith(":A"));
|
||||
}
|
||||
readAt = all.Length;
|
||||
}
|
||||
if (!loaded && presses >= 3) { loaded = true; if (user != null) { Directory.CreateDirectory(Path.Combine(user, "save")); File.WriteAllText(Path.Combine(user, "save", "written-by-the-game.txt"), "x"); } }
|
||||
var fps = Math.Min(capFps, (loaded ? baseFps * up : 60) + Math.Sin(t) * 3);
|
||||
frames += (long)(fps * 5);
|
||||
var ic = System.Globalization.CultureInfo.InvariantCulture;
|
||||
Console.Error.WriteLine(string.Create(ic, $"vi: {frames} frames presented ({fps:0.0} fps over the last 5.0 s, interval 1)"));
|
||||
Console.Error.WriteLine(string.Create(ic, $"vi: 1% low {fps * 0.86:0.0} fps over the last 5.0 s ({(int)(fps * 5)} frames)"));
|
||||
if (loaded) Console.Error.WriteLine(string.Create(ic, $"vk: {frames} presents, {fps:0.0} fps; a frame: 2600 draws"));
|
||||
Console.Error.Flush();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>make_game.py's lines as a build prints them (formats from nx2/make_game.py say(), build.py's @@plan/@@file/@@eta, and
|
||||
/// the game's own "@@stage shaders" from gpu/vk/vk_main.cpp), {OUT} the game folder.</summary>
|
||||
public const string Transcript = """
|
||||
the Windows SDK is here: C:\Program Files (x86)\Windows Kits\10
|
||||
@@stage read Reading your game files
|
||||
@@progress 0.000
|
||||
@@progress 0.500
|
||||
@@progress 1.000
|
||||
@@stage lift Translating the game to PC code
|
||||
lift: 30211 functions
|
||||
@@progress 0.300
|
||||
@@stage compile Compiling
|
||||
@@plan 12 579
|
||||
@@file code_hot_0.c 41.2 new
|
||||
@@file code_1.c 0.0 cached
|
||||
@@file code_2.c 3.5 again
|
||||
@@eta 300
|
||||
@@progress 0.400
|
||||
compiled in 790s
|
||||
@@stage finish Putting the game folder together
|
||||
the build took 0:41:00, compiled in 0:30:00 (the last one 0:45:00)
|
||||
@@times 2460 1800 2700
|
||||
the build's steps: before the game files 0:41, read 1:32, lift 2:10, compile 7:42, finish 1:17
|
||||
@@stage shaders Preparing shaders
|
||||
@@progress 0.500
|
||||
@@progress 1.000
|
||||
@@done {OUT}
|
||||
""";
|
||||
|
||||
/// <summary>"python -I make_game.py ...": --check answers ok; a build plays the transcript and makes the folder (Triforce.exe
|
||||
/// and triforce_version.txt), "@@error" for an --out with FAIL in it, and sits in its first stage for one with SLOW in it.</summary>
|
||||
public static int MakeGame(string[] a)
|
||||
{
|
||||
string? Arg(string name) { var i = Array.IndexOf(a, name); return i >= 0 && i + 1 < a.Length ? a[i + 1] : null; }
|
||||
if (a.Contains("--check"))
|
||||
{
|
||||
Console.WriteLine("@@check ok This is the version Triforce supports (build e0f3ccfa).");
|
||||
return 0;
|
||||
}
|
||||
var outDir = Arg("--out") ?? Arg("--update") ?? "out";
|
||||
File.WriteAllText(Path.Combine(Path.GetDirectoryName(Arg("--work") ?? ".")!, "fake-make-game-args.txt"), string.Join("\n", a));
|
||||
foreach (var raw in Transcript.Split('\n'))
|
||||
{
|
||||
var line = raw.TrimEnd('\r').Replace("{OUT}", outDir);
|
||||
if (line.StartsWith("@@done"))
|
||||
{
|
||||
Directory.CreateDirectory(outDir);
|
||||
File.WriteAllText(Path.Combine(outDir, "Triforce.exe"), "fake game");
|
||||
File.WriteAllText(Path.Combine(outDir, "triforce_version.txt"), "version=v9.9.9\nbuilder=" + Environment.GetEnvironmentVariable("HOOKSHOT_BUILDER_EXE") + "\n");
|
||||
}
|
||||
Console.WriteLine(line);
|
||||
Console.Out.Flush();
|
||||
Thread.Sleep(int.TryParse(Environment.GetEnvironmentVariable("TRIFORCE_FAKE_LINE_MS"), out var ms) ? ms : 15);
|
||||
if (line.StartsWith("@@stage read") && outDir.Contains("SLOW")) { Thread.Sleep(60000); return 9; }
|
||||
if (line.StartsWith("@@stage compile") && outDir.Contains("FAIL"))
|
||||
{
|
||||
Console.Error.WriteLine("clang: error: no space left on device");
|
||||
Console.WriteLine("@@error The disk is full.");
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>A new TriforceSetup.exe started by a self-update: "up" gives the sign its window is up and ends well, "fail" ends with
|
||||
/// an error before it. Its arguments go to <root>\child-args.txt.</summary>
|
||||
public static int NewSetup(string mode, string[] args)
|
||||
{
|
||||
var root = Environment.GetEnvironmentVariable("TRIFORCE_TEST_ROOT")!;
|
||||
File.WriteAllText(Path.Combine(root, "child-args.txt"), string.Join("|", args));
|
||||
if (mode == "fail") return 3;
|
||||
var ctx = TriforceContext.Create();
|
||||
Startup.SignalUp(ctx);
|
||||
Thread.Sleep(300);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
32
launcher/LogicTests/Program.cs
Normal file
32
launcher/LogicTests/Program.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
// Triforce.Logic's tests. Run: dotnet run --project LogicTests (exit code 0 = every test passed). Each test makes its own
|
||||
// TRIFORCE_TEST_ROOT folder under %TEMP%; nothing outside those folders is written.
|
||||
using System.Diagnostics;
|
||||
using Triforce.LogicTests;
|
||||
|
||||
if (args.Length >= 2 && args[0] == "-I" && args[1].EndsWith("make_game.py", StringComparison.Ordinal)) return Fakes.MakeGame(args.Skip(2).ToArray());
|
||||
if (args.Contains("--romfs") && args.Contains("--user")) return Fakes.FakeGame(args);
|
||||
if (Environment.GetEnvironmentVariable("LOGICTESTS_CHILD") is { Length: > 0 } mode && args.Contains("--relaunched")) return Fakes.NewSetup(mode, args);
|
||||
|
||||
var only = args.Length > 0 ? args[0] : null;
|
||||
var tests = Tests.All().Concat(Tests.GameOptionsTests()).Where(t => only == null || t.Name.Contains(only, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
int passed = 0, failed = 0;
|
||||
foreach (var (name, run) in tests)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
try
|
||||
{
|
||||
await run();
|
||||
passed++;
|
||||
Console.WriteLine("PASS " + name + " (" + sw.ElapsedMilliseconds + " ms)");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine("FAIL " + name + ": " + (e is TestFailed ? e.Message : e.ToString()));
|
||||
}
|
||||
}
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(passed + " passed, " + failed + " failed");
|
||||
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
|
||||
if (failed == 0) T.CleanUp();
|
||||
return failed == 0 ? 0 : 1;
|
||||
262
launcher/LogicTests/Tests.Build.cs
Normal file
262
launcher/LogicTests/Tests.Build.cs
Normal file
@@ -0,0 +1,262 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json.Nodes;
|
||||
using Triforce.Logic;
|
||||
using static Triforce.LogicTests.T;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
static partial class Tests
|
||||
{
|
||||
const string TestGame = @"D:\src\triforce-test-game";
|
||||
const string Nup = @"D:\NX2navi-dump\The Legend of Zelda Ocarina of Time [0400486024dec000][v131072].nup";
|
||||
|
||||
static void Protocol()
|
||||
{
|
||||
var t0 = new DateTime(2026, 11, 19, 10, 0, 0, DateTimeKind.Utc);
|
||||
var now = t0;
|
||||
var tr = new BuildTracker(() => now);
|
||||
var changes = new List<string>();
|
||||
tr.StageChanged += (was, to) => changes.Add((was ?? "-") + ">" + to);
|
||||
var events = new List<BuildEvent>();
|
||||
tr.Event += events.Add;
|
||||
foreach (var raw in Fakes.Transcript.Split('\n'))
|
||||
{
|
||||
now = now.AddSeconds(10);
|
||||
tr.Feed(raw.TrimEnd('\r').Replace("{OUT}", @"C:\Games\Triforce"));
|
||||
}
|
||||
tr.End();
|
||||
Equal("->read|read>lift|lift>compile|compile>finish|finish>shaders", string.Join("|", changes), "the stages in order");
|
||||
Equal<(int, int)?>((12, 579), tr.Plan, "@@plan");
|
||||
Equal(2, tr.FilesBuilt, "@@file new + again");
|
||||
Equal(300, events.OfType<BuildEvent.Eta>().Single().Seconds, "@@eta");
|
||||
Equal<int?>(null, tr.EtaSeconds, "the eta cleared when the compile ended");
|
||||
Equal(2460, tr.Times!.TotalSeconds, "@@times total");
|
||||
Equal<int?>(2700, tr.Times.PreviousSeconds, "@@times previous");
|
||||
Equal(@"C:\Games\Triforce", tr.DoneFolder, "@@done");
|
||||
Equal(92.0, tr.ReportedSteps!["read"], "make_game's own step times");
|
||||
Equal(77.0, tr.ReportedSteps["finish"], "finish 1:17");
|
||||
Equal(40.0, tr.StageSeconds["read"], "read: four lines of 10 s");
|
||||
Check(tr.StageSeconds.ContainsKey("shaders"), "the last stage's time at the end");
|
||||
Equal(1.0, tr.StageProgress, "shader progress");
|
||||
Check(events.OfType<BuildEvent.Plain>().Any(p => p.Line.StartsWith("lift: ")), "plain lines are Plain");
|
||||
Equal(new BuildEvent.Check(false, "This is build deadbeef. Triforce supports build e0f3ccfa."),
|
||||
BuildProtocol.Parse("@@check bad This is build deadbeef. Triforce supports build e0f3ccfa."), "@@check bad");
|
||||
Equal(new BuildEvent.Error("The builder stopped on an error it did not expect: x"), BuildProtocol.Parse("@@error The builder stopped on an error it did not expect: x"), "@@error");
|
||||
Equal(new BuildEvent.Times(10, 5, null), BuildProtocol.Parse("@@times 10 5 -1"), "@@times without a previous build");
|
||||
Check(BuildProtocol.Parse("the shaders were not prepared now (\"Prepare shaders now\" is unticked): the game prepares them at its first start") is BuildEvent.NotPrepared, "NOT_PREPARED");
|
||||
Equal(new BuildEvent.Progress(0.25), BuildProtocol.Parse("@@progress 0.250"), "progress, invariant culture");
|
||||
Check(BuildProtocol.Parse("@@progress x") is BuildEvent.Plain, "a bad number is a plain line");
|
||||
Equal(3723.0, BuildProtocol.ParseSteps("compile 1:02:03")["compile"], "h:mm:ss");
|
||||
}
|
||||
|
||||
static void Estimates()
|
||||
{
|
||||
var root = NewRoot("estimates");
|
||||
var none = BuildEstimator.Estimate(BuildHistory.Load(Path.Combine(root, "nothing")), false, 8, GpuVendor.Nvidia);
|
||||
Check(!none.Measured, "no history: a stated range");
|
||||
Equal(TimeSpan.FromSeconds(1890), none.Of("compile")!.Low, "compile's share of the 8-thread range");
|
||||
Check(none.Text.Contains(" to "), "a range in words: " + none.Text);
|
||||
var amd = BuildEstimator.Estimate(BuildHistory.Load(root), false, 16, GpuVendor.Amd);
|
||||
Equal(TimeSpan.FromMinutes(120), amd.Of("shaders")!.High, "AMD's shader step up to 2 hours");
|
||||
File.WriteAllText(Path.Combine(root, "build_times.json"), new JsonObject
|
||||
{
|
||||
["format"] = 1,
|
||||
["builds"] = new JsonArray(new JsonObject { ["when"] = "2026-11-18 21:00:00", ["kind"] = "build", ["modules"] = 579, ["compiled"] = 579, ["compile_seconds"] = 1800.0, ["total_seconds"] = 2400.0 }),
|
||||
["seconds"] = new JsonObject(),
|
||||
}.ToJsonString());
|
||||
var h = BuildHistory.Load(root);
|
||||
Equal(1, h.Builds.Count, "build_times.json read");
|
||||
var est = BuildEstimator.Estimate(h, false, 8, GpuVendor.Nvidia);
|
||||
Check(est.Measured, "measured from build_times.json");
|
||||
Equal(TimeSpan.FromSeconds(1800), est.Of("compile")!.Low, "the compile's own time");
|
||||
Equal(100, (int)Math.Round(est.Of("read")!.Low.TotalSeconds), "the rest split by the stages' weights (600 s * 5/30)");
|
||||
BuildHistory.RecordStages(root, "build", new Dictionary<string, double> { ["read"] = 90, ["lift"] = 130, ["compile"] = 1500, ["finish"] = 70, ["shaders"] = 600 });
|
||||
var est2 = BuildEstimator.Estimate(BuildHistory.Load(root), false, 8, GpuVendor.Nvidia);
|
||||
Equal(TimeSpan.FromSeconds(1500), est2.Of("compile")!.Low, "the stage record wins");
|
||||
Equal(TimeSpan.FromSeconds(600), est2.Of("shaders")!.High, "the shader step measured too");
|
||||
Equal("About 40 minutes", est2.Text, "one time in words");
|
||||
var tr = new BuildTracker();
|
||||
tr.Feed("@@stage compile Compiling");
|
||||
tr.Feed("@@eta 300");
|
||||
var left = BuildClock.Remaining(est2, tr);
|
||||
Equal(TimeSpan.FromSeconds(300 + 70 + 600), left, "time left: the compile's eta, then finish and shaders");
|
||||
Equal("About 16 minutes left", BuildClock.LeftText(left), "in words");
|
||||
Equal("Almost done", BuildClock.LeftText(TimeSpan.FromSeconds(20)), "under a minute");
|
||||
Equal("1 h 5 min", BuildClock.Span(TimeSpan.FromMinutes(65)), "span");
|
||||
}
|
||||
|
||||
/// <summary>A test root with fake tools: tools\nx2\make_game.py, and this program as tools\python\python.exe.</summary>
|
||||
static TriforceContext FakeTools(string root)
|
||||
{
|
||||
var ctx = Ctx(root);
|
||||
Directory.CreateDirectory(Path.Combine(ctx.ToolsFolder, "nx2"));
|
||||
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "nx2", "make_game.py"), "# fake: the test program plays it");
|
||||
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "version.txt"), "v9.9.9\n");
|
||||
CopySelf(Path.Combine(ctx.ToolsFolder, "python"), "python.exe");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
static GameSource FakeSource(string root)
|
||||
{
|
||||
var src = Path.Combine(root, "dump");
|
||||
Directory.CreateDirectory(Path.Combine(src, "romfs"));
|
||||
Directory.CreateDirectory(Path.Combine(src, "exefs"));
|
||||
var main = new byte[0x60];
|
||||
"NSO0"u8.CopyTo(main);
|
||||
Convert.FromHexString("e0f3ccfaf50065ae").CopyTo(main, 0x40);
|
||||
File.WriteAllBytes(Path.Combine(src, "exefs", "main"), main);
|
||||
return GameIntake.Normalize(src)!;
|
||||
}
|
||||
|
||||
static async Task RunnerDone()
|
||||
{
|
||||
var root = NewRoot("runner");
|
||||
var ctx = FakeTools(root);
|
||||
var notes = new List<LauncherNotification>();
|
||||
ctx.Platform.NotificationRequested += (_, n) => notes.Add(n);
|
||||
var src = FakeSource(root);
|
||||
var outDir = Path.Combine(root, "Games", "Triforce");
|
||||
var runner = new BuildRunner(ctx);
|
||||
var stages = new List<string>();
|
||||
runner.StageChanged += (_, to) => stages.Add(to);
|
||||
var lines = 0;
|
||||
runner.Line += _ => Interlocked.Increment(ref lines);
|
||||
var r = await runner.RunAsync(BuildRequest.New(src, outDir, "de"));
|
||||
Check(r.Success, "the build ended well: " + r.Failure + " / " + runner.Details);
|
||||
Equal(outDir, r.Folder, "@@done's folder");
|
||||
Equal("read,lift,compile,finish,shaders", string.Join(",", stages), "stage events");
|
||||
Equal(outDir, ctx.Settings.GameFolder, "GameFolder kept");
|
||||
Equal(outDir + "|", ctx.Settings.ModsBuilt, "the mods marked as built (none)");
|
||||
Check(notes.Count == 1, "a notification for the App");
|
||||
var args = File.ReadAllText(Path.Combine(root, "fake-make-game-args.txt")).Split('\n');
|
||||
Equal("--romfs|" + src.Romfs + "|--exefs|" + src.Exefs + "|--out|" + outDir + "|--language|de|--fsr|--work|" + Path.Combine(root, "build"), string.Join("|", args), "make_game's arguments");
|
||||
Check(File.ReadAllText(Path.Combine(outDir, "triforce_version.txt")).Contains("builder=" + ctx.BuilderExe), "HOOKSHOT_BUILDER_EXE passed");
|
||||
Check(File.ReadAllText(runner.LogFile).Contains("@@progress 0.500"), "the log file keeps every line");
|
||||
Check(!runner.Details.Contains("@@progress"), "the details leave progress out");
|
||||
Check(File.Exists(Path.Combine(ctx.WorkFolder, BuildHistory.StagesFile)), "stage times recorded");
|
||||
Equal(2460, r.Times!.TotalSeconds, "times");
|
||||
Check(lines > 20, "lines came");
|
||||
// (an update of the folder: --update, kind update)
|
||||
var u = await new BuildRunner(ctx).RunAsync(BuildRequest.Update(outDir));
|
||||
Check(u.Success, "the update ended well: " + u.Failure);
|
||||
Equal("--update|" + outDir + "|--fsr|--work|" + Path.Combine(root, "build"), string.Join("|", File.ReadAllText(Path.Combine(root, "fake-make-game-args.txt")).Split('\n')), "update arguments");
|
||||
Check(BuildHistory.Load(ctx.WorkFolder).Stages.Any(s => s.Kind == "update"), "an update's times kept as an update's");
|
||||
// (DLSS chosen: the licence's flags; the update of a folder built with DLSS keeps it)
|
||||
Directory.CreateDirectory(Path.Combine(outDir, "ngx"));
|
||||
File.WriteAllText(Path.Combine(outDir, "ngx", "nvngx_dlss.dll"), "");
|
||||
Check(new Dlss(ctx).ForBuild(outDir) && ctx.Settings.Dlss, "a folder built with DLSS is updated with it, and the choice kept");
|
||||
Check(BuildRunner.Arguments(ctx, BuildRequest.Update(outDir), true).Contains("--accept-nvidia-license"), "the licence flag");
|
||||
}
|
||||
|
||||
static async Task RunnerStop()
|
||||
{
|
||||
var root = NewRoot("runnerstop");
|
||||
var ctx = FakeTools(root);
|
||||
var runner = new BuildRunner(ctx);
|
||||
var reading = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
runner.StageChanged += (_, to) => { if (to == "read") reading.TrySetResult(); };
|
||||
var sw = Stopwatch.StartNew();
|
||||
var run = runner.RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(root, "Games", "SLOW"), "en-US"));
|
||||
await Task.WhenAny(reading.Task, Task.Delay(20000));
|
||||
Check(reading.Task.IsCompleted, "the build reached its first stage");
|
||||
Check(runner.Running, "running");
|
||||
runner.Stop();
|
||||
var r = await run;
|
||||
Check(r.Cancelled && r.Failure == "cancelled" && !r.Success, "stopped: " + r.Failure);
|
||||
Equal("read", r.StoppedAt, "stopped in its first stage");
|
||||
Check(sw.Elapsed < TimeSpan.FromSeconds(30), "stopped at once, not after the fake's minute");
|
||||
var left = Process.GetProcessesByName("python").Where(p => { try { return p.MainModule!.FileName.StartsWith(root, StringComparison.OrdinalIgnoreCase); } catch (Exception) { return false; } });
|
||||
Check(!left.Any(), "no fake make_game left running");
|
||||
}
|
||||
|
||||
static async Task RunnerFail()
|
||||
{
|
||||
var root = NewRoot("runnerfail");
|
||||
var ctx = FakeTools(root);
|
||||
var runner = new BuildRunner(ctx);
|
||||
var r = await runner.RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(root, "Games", "FAIL"), "en-US"));
|
||||
Check(!r.Success && !r.Cancelled, "failed");
|
||||
Equal("The disk is full.", r.Failure, "@@error's text");
|
||||
Equal("compile", r.StoppedAt, "where");
|
||||
Check(runner.Details.Contains("clang: error"), "stderr in the details");
|
||||
var report = Report.ForBuild(ctx, r, runner.Details, "v9.9.9");
|
||||
Check(report.Contains("The build stopped at \"Compiling\"") && report.Contains("---- the build's last lines ----"), "the report");
|
||||
var elsewhere = await new BuildRunner(ctx).RunAsync(BuildRequest.New(FakeSource(root), Path.Combine(Path.GetTempPath(), "not-in-root"), "en-US"));
|
||||
Equal(ctx.TestOnly, elsewhere.Failure, "a test run builds only inside its root");
|
||||
var noTools = await new BuildRunner(Ctx(NewRoot("runner-notools"))).RunAsync(BuildRequest.Update(Path.Combine(root, "x")));
|
||||
Check(noTools.Failure!.Contains("tools"), "no tools: said");
|
||||
}
|
||||
|
||||
static void GameFolder()
|
||||
{
|
||||
var ctx = Ctx(NewRoot("game"));
|
||||
var game = new Game(ctx);
|
||||
Equal(Path.Combine(TestGame, "Triforce.exe"), game.FindExe(TestGame), "Triforce.exe");
|
||||
var info = game.Describe(TestGame);
|
||||
Equal("v0.1.0", info.Version, "triforce_version.txt");
|
||||
Check(info.Kept, "keeps .triforce_exefs and romfs");
|
||||
Check(!info.Dlss, "no DLSS");
|
||||
Check(info.Language == null || Languages.Find(info.Language) != null, "language.txt");
|
||||
Check(!game.IsRunning(TestGame), "not running (test root: only programs inside it count)");
|
||||
Equal(null, game.Play(TestGame), "Play refused outside the test root");
|
||||
Equal(null, game.FindExe(Path.Combine(TestGame, "romfs")), "no game in romfs");
|
||||
}
|
||||
|
||||
static void Intake()
|
||||
{
|
||||
var root = NewRoot("intake");
|
||||
var s = GameIntake.Normalize(TestGame)!;
|
||||
Equal(SourceKind.Folders, s.Kind, "a built game folder is a source");
|
||||
Equal(Path.Combine(TestGame, ".triforce_exefs"), s.Exefs, "its kept exefs");
|
||||
var q = GameIntake.Quick(s);
|
||||
Check(q.Ok && q.BuildId!.StartsWith("e0f3ccfa") && q.Final, "the supported build, read without tools: " + q.Text);
|
||||
var viaRomfs = GameIntake.Normalize(Path.Combine(TestGame, "romfs"))!;
|
||||
Equal(s.Exefs, viaRomfs.Exefs, "the romfs folder finds its exefs");
|
||||
var n = GameIntake.Normalize(Nup)!;
|
||||
Equal(SourceKind.Nup, n.Kind, ".nup");
|
||||
var nq = GameIntake.Quick(n);
|
||||
Check(nq.Ok && nq.Titles!.Any(t => t.Id == "0400486024dec000"), "the .nup's header reads: " + nq.Text);
|
||||
Check(!nq.Final, "a .nup still needs the tools' check");
|
||||
Equal(131072u, nq.Titles![0].Version, "the newest title first (v131072, the file name says)");
|
||||
// (NX2navi's packed romfs)
|
||||
var navi = Path.Combine(root, "navi");
|
||||
Directory.CreateDirectory(Path.Combine(navi, "romfs"));
|
||||
Directory.CreateDirectory(Path.Combine(navi, "exefs"));
|
||||
File.WriteAllText(Path.Combine(navi, "romfs", "romfs.bin"), "packed");
|
||||
File.Copy(Path.Combine(TestGame, ".triforce_exefs", "main"), Path.Combine(navi, "exefs", "main"));
|
||||
Equal(GameIntake.PackedRomfs, GameIntake.Quick(GameIntake.Normalize(navi)!).Text, "packed romfs refused");
|
||||
// (another build)
|
||||
var other = Path.Combine(root, "other");
|
||||
Directory.CreateDirectory(Path.Combine(other, "romfs"));
|
||||
Directory.CreateDirectory(Path.Combine(other, "exefs"));
|
||||
var main = new byte[0x60];
|
||||
"NSO0"u8.CopyTo(main);
|
||||
Convert.FromHexString("deadbeef").CopyTo(main, 0x40);
|
||||
File.WriteAllBytes(Path.Combine(other, "exefs", "main"), main);
|
||||
var oq = GameIntake.Quick(GameIntake.Normalize(other)!);
|
||||
Equal("This is build deadbeef. Triforce supports build e0f3ccfa.", oq.Text, "the wrong version, in make_game's words");
|
||||
Check(GameIntake.IsWrongVersion(oq.Text), "said as the wrong version");
|
||||
var half = GameIntake.Normalize(Path.Combine(other, "romfs"))!;
|
||||
Check(half.Complete, "romfs with its exefs beside it");
|
||||
var lonely = Path.Combine(root, "lonely", "romfs");
|
||||
Directory.CreateDirectory(lonely);
|
||||
var l = GameIntake.Normalize(lonely)!;
|
||||
Equal("exefs", l.Missing, "the exefs is still to be chosen");
|
||||
Equal(null, GameIntake.Normalize(Path.Combine(root, "nothing-here")), "nothing");
|
||||
var notNup = Path.Combine(root, "x.nup");
|
||||
File.WriteAllText(notNup, "not a package at all, longer than the header is......................................................................................................................");
|
||||
Check(!GameIntake.Quick(GameIntake.Normalize(notNup)!).Ok, "a file that is no .nup");
|
||||
var space = new GameIntake(Ctx(root)).Space(root);
|
||||
Check(space.Free > 0 && space.Text.StartsWith("Takes 60 GB while building, about 24 GB after."), space.Text);
|
||||
}
|
||||
|
||||
static async Task IntakeCheck()
|
||||
{
|
||||
var root = NewRoot("intakecheck");
|
||||
var noTools = await new GameIntake(Ctx(NewRoot("intake-notools"))).CheckAsync(GameIntake.Normalize(TestGame)!);
|
||||
Check(noTools.ToolsMissing && !noTools.Ok, "no tools: said so");
|
||||
var ctx = FakeTools(root);
|
||||
var r = await new GameIntake(ctx).CheckAsync(GameIntake.Normalize(TestGame)!);
|
||||
Check(r.Ok && r.BuildId == "e0f3ccfa", "make_game --check's @@check ok: " + r.Text);
|
||||
}
|
||||
}
|
||||
246
launcher/LogicTests/Tests.Core.cs
Normal file
246
launcher/LogicTests/Tests.Core.cs
Normal file
@@ -0,0 +1,246 @@
|
||||
using System.Text;
|
||||
using Triforce.Logic;
|
||||
using static Triforce.LogicTests.T;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
static partial class Tests
|
||||
{
|
||||
public static IEnumerable<(string Name, Func<Task> Run)> All()
|
||||
{
|
||||
(string, Func<Task>) Sync(string n, Action a) => (n, () => { a(); return Task.CompletedTask; });
|
||||
yield return Sync("settings: registry.txt round trip", SettingsTestRoot);
|
||||
yield return Sync("settings: builder.ini round trip (Linux store)", SettingsIni);
|
||||
yield return Sync("startup: argument parsing", StartArgsParsing);
|
||||
yield return Sync("startup: lock name algorithm", LockName);
|
||||
yield return Sync("startup: installed run, old exe removed, second start defers", StartupInstalled);
|
||||
yield return Sync("startup: not installed shows Install; uninstall refused while open", StartupNotInstalled);
|
||||
yield return Sync("install + uninstall in a test root", InstallUninstall);
|
||||
yield return ("release: check, parse, notes against a fake server", ReleaseCheck);
|
||||
yield return ("release: download with size check and resume", DownloadResume);
|
||||
yield return ("release: self-swap, new launcher up", SelfSwapUp);
|
||||
yield return ("release: self-swap, new launcher fails, rolled back", SelfSwapFails);
|
||||
yield return Sync("release: decide what the start does", Decide);
|
||||
yield return Sync("tools: unpack the whole zip, refuse unsafe names", ToolsUnpack);
|
||||
yield return Sync("tools: base list and parts", ToolsParts);
|
||||
yield return ("tools: update from the fake server with progress", ToolsUpdate);
|
||||
yield return Sync("build: @@ protocol from a recorded transcript", Protocol);
|
||||
yield return Sync("build: estimates from history and without", Estimates);
|
||||
yield return ("build: runner with a fake make_game (done, args, log, times)", RunnerDone);
|
||||
yield return ("build: runner stop kills the tree", RunnerStop);
|
||||
yield return ("build: runner failure and test-root refusal", RunnerFail);
|
||||
yield return Sync("game: the built test game folder", GameFolder);
|
||||
yield return Sync("intake: folders, .nup header, packed romfs, space", Intake);
|
||||
yield return ("intake: make_game --check (fake)", IntakeCheck);
|
||||
yield return Sync("saves: slots of lab-game-merge98 (read only)", SavesListing);
|
||||
yield return ("saves: find, import, export with backups", SavesCopy);
|
||||
yield return Sync("mods: list, order, on/off, remove, rebuild mark", ModsFolder);
|
||||
yield return Sync("mods: add archives and their safety checks", ModsArchives);
|
||||
yield return ("mods: GameBanana install into the mods folder (fake server)", GameBananaInstall);
|
||||
yield return ("mods: GameBanana live list (read only)", GameBananaLive);
|
||||
yield return Sync("mods: GameBanana page parsing and plain text", GameBananaParse);
|
||||
yield return Sync("linux: release keys, modes, parts list", LinuxLogic);
|
||||
yield return Sync("steam: add, set, remove in a fake Steam folder", SteamShortcut);
|
||||
yield return Sync("report: names out", ReportNames);
|
||||
yield return Sync("languages", LanguagesTest);
|
||||
}
|
||||
|
||||
// ---- settings ----
|
||||
|
||||
static void SettingsTestRoot()
|
||||
{
|
||||
var root = NewRoot("settings");
|
||||
var ctx = Ctx(root);
|
||||
ctx.Settings.GameFolder = @"D:\Games\Triforce";
|
||||
ctx.Settings.Language = "de";
|
||||
ctx.Settings.Dlss = true;
|
||||
ctx.Settings.Set("Language", "fr");
|
||||
ctx.Platform.Settings.SetUninstall("InstallLocation", root);
|
||||
ctx.Platform.Settings.SetUninstallNumber("NoModify", 1);
|
||||
var again = Ctx(root);
|
||||
Equal(@"D:\Games\Triforce", again.Settings.GameFolder, "GameFolder read back");
|
||||
Equal("fr", again.Settings.Language, "the last value for a name wins");
|
||||
Check(again.Settings.Dlss, "Dlss read back");
|
||||
Equal(40, again.Settings.MusicVolume, "music volume default");
|
||||
again.Settings.MusicVolume = 250;
|
||||
Equal(100, Ctx(root).Settings.MusicVolume, "volume clamped");
|
||||
var lines = File.ReadAllLines(Path.Combine(root, "registry.txt"));
|
||||
Check(lines.Contains(@"Software\Triforce\GameFolder=D:\Games\Triforce"), "the old Setup's line format: " + string.Join(" / ", lines));
|
||||
Check(lines.Contains(@"Software\Microsoft\Windows\CurrentVersion\Uninstall\Triforce\NoModify=1"), "uninstall entry lines");
|
||||
Equal(1, lines.Count(l => l.StartsWith(@"Software\Triforce\Language=")), "one line per name after a write");
|
||||
again.Platform.Settings.RemoveAll();
|
||||
Equal(null, Ctx(root).Settings.Language, "settings removed");
|
||||
Equal(root, Ctx(root).Platform.Settings.GetUninstall("InstallLocation"), "uninstall entry kept until removed");
|
||||
var snap = Ctx(root);
|
||||
snap.NoWrites = true;
|
||||
snap.Settings.Language = "ja";
|
||||
Equal(null, Ctx(root).Settings.Language, "NoWrites writes nothing");
|
||||
}
|
||||
|
||||
static void SettingsIni()
|
||||
{
|
||||
var root = NewRoot("ini");
|
||||
var file = Path.Combine(root, "triforce", "builder.ini");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
File.WriteAllText(file, "kind=nup\nnup=/home/a/oot.nup\nout=/home/a/Games/Old\nlanguage=en-US\nprepare=1\nout=/home/a/Games/Triforce\n");
|
||||
var s = new IniSettingsStore(file);
|
||||
Equal("/home/a/Games/Triforce", s.Get(SettingNames.GameFolder), "GameFolder is the last out= line (hookshot-launch)");
|
||||
s.Set(SettingNames.Language, "ja");
|
||||
s.Set(SettingNames.Dlss, "1");
|
||||
s.Set(SettingNames.SetupSkip, "v0.5.2");
|
||||
var text = File.ReadAllText(file);
|
||||
Check(text.Contains("kind=nup\n") && text.Contains("prepare=1\n") && text.Contains("nup=/home/a/oot.nup\n"), "the Tk builder's keys kept: " + text);
|
||||
Check(text.Contains("language=ja\n") && text.Contains("dlss=1\n") && text.Contains("SetupSkip=v0.5.2\n"), "written under the shared names: " + text);
|
||||
Equal(1, text.Split('\n').Count(l => l.StartsWith("out=")), "one out= line after a rewrite");
|
||||
Throws<ArgumentException>(() => s.Set("x", "a\nb"), "a line break is refused");
|
||||
}
|
||||
|
||||
// ---- startup ----
|
||||
|
||||
static void StartArgsParsing()
|
||||
{
|
||||
var a = StartArgs.Parse(new[] { "--relaunched", "--merge" });
|
||||
Check(a.Relaunched && a.Merge && a.UpdateFolder == null, "--relaunched --merge");
|
||||
a = StartArgs.Parse(new[] { "--update", @"C:\Games\Triforce", "--relaunched" });
|
||||
Check(a.UpdateFolder == @"C:\Games\Triforce" && a.Merge && a.Relaunched, "--update sets merge");
|
||||
a = StartArgs.Parse(new[] { "--update", @"C:\Games\Triforce", "--tag", "v0.5.2" });
|
||||
Equal("v0.5.2", a.Tag, "--tag from the game");
|
||||
// (a folder ending in a backslash, quoted on a command line: \" escapes the quote)
|
||||
a = StartArgs.Parse(new[] { "--update", "C:\\Games\\Triforce\" --tag v0.5.2" });
|
||||
Equal(@"C:\Games\Triforce\", a.UpdateFolder, "the folder repaired");
|
||||
Equal("v0.5.2", a.Tag, "and the tag after it");
|
||||
a = StartArgs.Parse(new[] { "--uninstall", "--quiet", "--something-new", "x" });
|
||||
Check(a.Uninstall && a.Quiet && a.Unknown.Contains("--something-new"), "unknown arguments kept aside, not fatal");
|
||||
a = StartArgs.Parse(new[] { "--launch", "/home/a/Games/Triforce" });
|
||||
Equal("/home/a/Games/Triforce", a.LaunchFolder, "Linux --launch");
|
||||
a = StartArgs.Parse(new[] { "--update", "/g", "--tag", "v1", "--fetched" });
|
||||
Check(a.Fetched && a.UpdateFolder == "/g" && a.Tag == "v1", "Linux --update --tag --fetched");
|
||||
a = StartArgs.Parse(new[] { "--install-to", @"D:\T", "--no-desktop" });
|
||||
Check(a.InstallTo == @"D:\T" && a.NoDesktop && !a.NoStartMenu, "--install-to");
|
||||
Equal("--relaunched|--merge", string.Join("|", new StartArgs { Merge = true }.PassOn(true)), "self-update passes --relaunched --merge");
|
||||
Equal("--update|C:\\G|--relaunched", string.Join("|", new StartArgs { Merge = true, UpdateFolder = @"C:\G" }.PassOn(true)), "with the game's folder");
|
||||
Equal("--merge", string.Join("|", new StartArgs { Merge = true }.PassOn(false)), "install relaunch");
|
||||
}
|
||||
|
||||
static void LockName()
|
||||
{
|
||||
var a = @"C:\Users\you\AppData\Local\Programs\Triforce";
|
||||
var name = InstanceLock.Name(a, null);
|
||||
Equal(@"Local\TriforceSetup-8f6ec578ae853054-C--USERS-YOU-APPDATA-LOCAL-PROGRAMS-TRIFORCE", name, "FNV-1a 64 + tail, as the old Setup (PowerShell reference)");
|
||||
Equal(name, InstanceLock.Name(a.ToLowerInvariant() + @"\", null), "case and a trailing slash");
|
||||
Equal(name, InstanceLock.Name(@"C:\Users\you\AppData\Local\Programs\Other\..\Triforce", null), "another way to the same folder");
|
||||
Check(name != InstanceLock.Name(a, @"E:\scratch\root"), "a test root names another lock");
|
||||
Equal(name + "-up", InstanceLock.UpName(a, null), "the handover sign");
|
||||
var tail = InstanceLock.Name(@"C:\" + new string('x', 400), null);
|
||||
Check(tail.Length < 200 && tail.EndsWith(new string('X', 60)), "the tail is the last 60 characters");
|
||||
}
|
||||
|
||||
static void StartupInstalled()
|
||||
{
|
||||
var root = NewRoot("startup");
|
||||
var dir = Path.Combine(root, "Programs", "Triforce");
|
||||
Directory.CreateDirectory(dir);
|
||||
var exe = Path.Combine(dir, BuildInfo.SetupAsset);
|
||||
File.WriteAllText(exe, "installed");
|
||||
File.WriteAllText(Path.Combine(dir, "TriforceSetup.old.exe"), "replaced one");
|
||||
var ctx = Ctx(root, exe);
|
||||
ctx.Platform.Settings.SetUninstall("InstallLocation", dir);
|
||||
Check(ctx.RunningInstalled, "running installed");
|
||||
var r = Startup.Run(ctx, new[] { "--relaunched", "--merge" });
|
||||
try
|
||||
{
|
||||
Equal(StartScreen.Check, r.Screen, "an installed run checks for updates");
|
||||
Check(r.Args.Merge && r.SignalUpWhenShown, "merge carried, up sign asked");
|
||||
Check(!File.Exists(Path.Combine(dir, "TriforceSetup.old.exe")), "TriforceSetup.old.exe removed");
|
||||
Check(r.Lock is { Held: true }, "the lock held");
|
||||
var second = Startup.Run(Ctx(root, exe), Array.Empty<string>());
|
||||
Equal(StartScreen.Exit, second.Screen, "a second start ends");
|
||||
Equal(0, second.ExitCode, "after asking the first to the front");
|
||||
var un = Startup.Run(Ctx(root, exe), new[] { "--uninstall", "--quiet" });
|
||||
Check(un.Screen == StartScreen.Exit && un.ExitCode == 1 && un.Message == null, "uninstall refused while open, quietly");
|
||||
}
|
||||
finally { r.Lock?.Dispose(); }
|
||||
var after = Startup.Run(Ctx(root, exe), Array.Empty<string>());
|
||||
try { Equal(StartScreen.Check, after.Screen, "the lock is free again after Release"); }
|
||||
finally { after.Lock?.Dispose(); }
|
||||
}
|
||||
|
||||
static void StartupNotInstalled()
|
||||
{
|
||||
var root = NewRoot("notinstalled");
|
||||
var ctx = Ctx(root, Path.Combine(root, "Downloads", BuildInfo.SetupAsset));
|
||||
var r = Startup.Run(ctx, Array.Empty<string>());
|
||||
try { Equal(StartScreen.Install, r.Screen, "a download that is not installed shows Install"); }
|
||||
finally { r.Lock?.Dispose(); }
|
||||
var u = Startup.Run(ctx, new[] { "--uninstall" });
|
||||
try { Equal(StartScreen.Uninstall, u.Screen, "uninstall goes on when nothing is open"); }
|
||||
finally { u.Lock?.Dispose(); }
|
||||
// (installed elsewhere, started from a download: the download becomes the installed launcher; here that copy cannot start,
|
||||
// so this one carries on)
|
||||
var dir = Path.Combine(root, "Programs", "Triforce");
|
||||
var self = Path.Combine(root, "Downloads", BuildInfo.SetupAsset);
|
||||
Directory.CreateDirectory(dir);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(self)!);
|
||||
File.WriteAllText(self, "downloaded copy, no program");
|
||||
File.WriteAllText(Path.Combine(dir, BuildInfo.SetupAsset), "installed copy");
|
||||
var c2 = Ctx(root, self);
|
||||
c2.Platform.Settings.SetUninstall("InstallLocation", dir);
|
||||
var r2 = Startup.Run(c2, new[] { "--merge" });
|
||||
try
|
||||
{
|
||||
Equal("downloaded copy, no program", File.ReadAllText(Path.Combine(dir, BuildInfo.SetupAsset)), "the download was copied over the installed copy");
|
||||
Equal(StartScreen.Check, r2.Screen, "and, the installed copy not starting, this one carries on");
|
||||
}
|
||||
finally { r2.Lock?.Dispose(); }
|
||||
}
|
||||
|
||||
static void InstallUninstall()
|
||||
{
|
||||
var root = NewRoot("install");
|
||||
var self = Path.Combine(root, "Downloads", BuildInfo.SetupAsset);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(self)!);
|
||||
File.WriteAllText(self, "launcher bytes");
|
||||
var ctx = Ctx(root, self);
|
||||
var inst = new Installer(ctx);
|
||||
Equal(Path.Combine(root, "Programs", "Triforce"), inst.DefaultDir, "default install folder under the test root's LocalAppData");
|
||||
var exe = inst.Run(inst.DefaultDir, desktop: true, startMenu: true);
|
||||
Equal("launcher bytes", File.ReadAllText(exe), "copied");
|
||||
Equal(inst.DefaultDir, ctx.InstalledDir, "registered (InstallLocation)");
|
||||
Equal("\"" + exe + "\" --uninstall --quiet", ctx.Platform.Settings.GetUninstall("QuietUninstallString"), "quiet uninstall string");
|
||||
Check(File.Exists(Path.Combine(root, "Desktop", "Triforce.lnk")), "desktop shortcut in the test root");
|
||||
Check(File.Exists(Path.Combine(root, "Start Menu", "Triforce", "Triforce.lnk")), "start menu shortcut in the test root");
|
||||
Throws<InvalidOperationException>(() => inst.Run(Path.Combine(Path.GetTempPath(), "elsewhere-" + Guid.NewGuid().ToString("N")), false, false), "outside the test root refused");
|
||||
Directory.CreateDirectory(Path.Combine(root, "build", "objcache"));
|
||||
ctx.Settings.GameFolder = Path.Combine(root, "Games", "Triforce");
|
||||
var plan = new Uninstaller(ctx).Describe();
|
||||
Check(plan.Keeps.Any(k => k.Contains("saves")) && plan.Removes.Count >= 3, "the plan says what goes and stays");
|
||||
new Uninstaller(ctx).Run();
|
||||
Check(!File.Exists(Path.Combine(root, "Desktop", "Triforce.lnk")) && !Directory.Exists(Path.Combine(root, "Start Menu", "Triforce")), "shortcuts gone");
|
||||
Check(!Directory.Exists(Path.Combine(root, "build")), "work folder gone");
|
||||
Equal(null, Ctx(root, self).Platform.Settings.GetUninstall("InstallLocation"), "uninstall entry gone");
|
||||
Equal(null, Ctx(root, self).Settings.GameFolder, "settings gone");
|
||||
}
|
||||
|
||||
// ---- report, languages ----
|
||||
|
||||
static void ReportNames()
|
||||
{
|
||||
var text = @"C:\Users\Ann\AppData\x and c:/users/ann//Games and C:\Users\Anna\y and C:\Users\ANN~1\Temp";
|
||||
var o = Report.NoName(text, @"C:\Users\Ann", @"C:\Users\ANN~1");
|
||||
Equal(@"%USERPROFILE%\AppData\x and %USERPROFILE%//Games and C:\Users\Anna\y and %USERPROFILE%\Temp", o, "the account's folder read as %USERPROFILE%");
|
||||
Equal("b\nc", Report.Tail("a\nb\nc\n\n", 2).Replace("\r", ""), "tail");
|
||||
}
|
||||
|
||||
static void LanguagesTest()
|
||||
{
|
||||
Equal(16, Languages.All.Count, "16 codes");
|
||||
Equal("zh-Hant", Languages.Default("zh-TW").Code, "zh-TW");
|
||||
Equal("zh-Hans", Languages.Default("zh-CN").Code, "zh-CN");
|
||||
Equal("es-419", Languages.Default("es-MX").Code, "es-MX");
|
||||
Equal("es", Languages.Default("es-ES").Code, "es-ES");
|
||||
Equal("pt-BR", Languages.Default("pt-PT").Code, "pt-PT");
|
||||
Equal("de", Languages.Default("de-AT").Code, "de-AT");
|
||||
Equal("en-US", Languages.Default("xx-YY").Code, "unknown");
|
||||
Equal("fr-CA", Languages.Default("fr-CA").Code, "exact");
|
||||
}
|
||||
}
|
||||
386
launcher/LogicTests/Tests.Data.cs
Normal file
386
launcher/LogicTests/Tests.Data.cs
Normal file
@@ -0,0 +1,386 @@
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using Triforce.Logic;
|
||||
using static Triforce.LogicTests.T;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
static partial class Tests
|
||||
{
|
||||
const string LabGame = @"D:\src\lab-game-merge98";
|
||||
|
||||
// ---- saves ----
|
||||
|
||||
static void SavesListing()
|
||||
{
|
||||
// (READ ONLY: lab-game-merge98 holds real slots. Nothing here copies, locks or writes there)
|
||||
var saves = new Saves(Ctx(NewRoot("saves-list")));
|
||||
Equal(Path.Combine(LabGame, "user", "save", Saves.TriforceUid), saves.TriforceFolder(LabGame), "Triforce's save folder");
|
||||
var slots = saves.Slots(LabGame);
|
||||
Equal(6, slots.Count, "six files");
|
||||
Check(slots.Count(s => s.Used) >= 1, "slots in use");
|
||||
foreach (var s in slots.Where(s => s.Used))
|
||||
{
|
||||
Check(s.Caption != null && File.Exists(s.Caption), "File " + s.FileNumber + " has its caption.sav");
|
||||
var bytes = File.ReadAllBytes(s.Caption!);
|
||||
var jpeg = bytes.AsSpan().IndexOf(new byte[] { 0xFF, 0xD8, 0xFF });
|
||||
Check(jpeg > 0, "File " + s.FileNumber + "'s caption holds a JPEG (at " + jpeg + ")");
|
||||
Check(s.Written != null, "written time");
|
||||
}
|
||||
var newest = saves.Newest(LabGame)!;
|
||||
Check(slots.Where(s => s.Used).All(s => File.GetLastWriteTime(s.Caption!) <= File.GetLastWriteTime(newest.Caption!)), "the newest is the caption written last");
|
||||
var set = Saves.Describe("Triforce", saves.TriforceNewest(LabGame));
|
||||
Check(!set.Empty && set.Slots == slots.Count(s => s.Used), "described: " + set.Slots + " slots");
|
||||
}
|
||||
|
||||
static void MakeSave(string dir, string marker, int slots = 2)
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
File.WriteAllText(Path.Combine(dir, "option.sav"), marker);
|
||||
File.WriteAllText(Path.Combine(dir, "account.sav"), marker);
|
||||
for (var i = 0; i < slots; i++)
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(dir, "slot_0" + i));
|
||||
File.WriteAllText(Path.Combine(dir, "slot_0" + i, "progress.sav"), marker + i);
|
||||
File.WriteAllText(Path.Combine(dir, "slot_0" + i, "caption.sav"), marker + i);
|
||||
}
|
||||
}
|
||||
|
||||
static async Task SavesCopy()
|
||||
{
|
||||
var root = NewRoot("saves-copy");
|
||||
var ctx = Ctx(root);
|
||||
var saves = new Saves(ctx);
|
||||
var eden = Path.Combine(root, "Roaming", "eden", "nand", "user", "save", "0000000000000000", "ABCDEF0123456789ABCDEF0123456789", Saves.TitleId);
|
||||
MakeSave(eden, "eden", 3);
|
||||
var ryu = Path.Combine(root, "Roaming", "Ryujinx", "bis", "user", "save", "0000000000000001", "0");
|
||||
MakeSave(ryu, "ryujinx", 1);
|
||||
var navi = Path.Combine(root, "Local", "Programs", "NX2navi", "game", "profile", "save", "0123456789abcdef0123456789abcdef");
|
||||
MakeSave(navi, "navi", 1);
|
||||
var found = saves.FindEmulatorSaves();
|
||||
Check(found.Any(f => f.Name == "Eden" && f.Slots == 3), "Eden found: " + string.Join(", ", found.Select(f => f.Name)));
|
||||
Check(found.Any(f => f.Name == "Ryujinx") && found.Any(f => f.Name == "NX2navi"), "Ryujinx and NX2navi found");
|
||||
Equal(null, saves.RunningGame(), "nothing runs inside the test root");
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
MakeSave(saves.TriforceFolder(game), "triforce", 1);
|
||||
Directory.CreateDirectory(Path.Combine(game, "user", "save-tx", Saves.TriforceUid, "work"));
|
||||
var backup = await saves.ImportAsync(found.First(f => f.Name == "Eden"), game);
|
||||
Check(backup != null && File.ReadAllText(Path.Combine(backup, "option.sav")) == "triforce", "Triforce's saves backed up first");
|
||||
Check(backup!.StartsWith(ctx.SaveBackupsFolder) && backup.EndsWith("_Triforce-before-Eden"), "the backup's name: " + backup);
|
||||
Equal("eden", File.ReadAllText(Path.Combine(saves.TriforceFolder(game), "option.sav")), "Eden's saves in Triforce");
|
||||
Equal(3, saves.Slots(game).Count(s => s.Used), "three files now");
|
||||
Check(!Directory.Exists(Path.Combine(game, "user", "save-tx", Saves.TriforceUid)), "the old save's transaction removed");
|
||||
Check(File.Exists(Path.Combine(game, "user", "save.lock")), "the game's lock was taken across the copy");
|
||||
Check(!Directory.Exists(saves.TriforceFolder(game) + ".partial") && !Directory.Exists(saves.TriforceFolder(game) + ".old"), "no partial left");
|
||||
// (out: a waiting commit is the newest save)
|
||||
var ready = Path.Combine(game, "user", "save-tx", Saves.TriforceUid, "ready-2");
|
||||
MakeSave(ready, "ready", 2);
|
||||
Equal(ready, saves.TriforceNewest(game), "the waiting commit");
|
||||
var target = Saves.Describe("Ryujinx", ryu);
|
||||
var b2 = await saves.ExportAsync(game, target);
|
||||
Equal("ready", File.ReadAllText(Path.Combine(ryu, "option.sav")), "Triforce's newest out to Ryujinx");
|
||||
Check(b2 != null && File.ReadAllText(Path.Combine(b2, "option.sav")) == "ryujinx", "Ryujinx's backed up");
|
||||
Equal(Path.Combine(game, "user", "save.lock"), SaveLock.PathOf(ready), "a commit's lock is its user folder's");
|
||||
Equal(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(navi))!, "instance.lock"), SaveLock.PathOf(navi), "NX2navi's lock");
|
||||
// (only inside the test root)
|
||||
await ThrowsAsync<InvalidOperationException>(() => saves.ExportAsync(game, Saves.Describe("lab", Path.Combine(LabGame, "user", "save", Saves.TriforceUid))), "a test run writes no save outside its root");
|
||||
Equal(navi, Saves.FindIn(Path.Combine(root, "Local", "Programs", "NX2navi", "game")), "a chosen NX2navi game folder");
|
||||
Equal(eden, Saves.FindIn(Path.Combine(root, "Roaming", "eden")), "a chosen emulator folder, searched down");
|
||||
}
|
||||
|
||||
// ---- mods ----
|
||||
|
||||
static string MakeMod(string mods, string folder, params (string Rel, string Text)[] files)
|
||||
{
|
||||
var dir = Path.Combine(mods, folder);
|
||||
foreach (var (rel, text) in files)
|
||||
{
|
||||
var p = Path.Combine(dir, rel.Replace('/', Path.DirectorySeparatorChar));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(p)!);
|
||||
File.WriteAllText(p, text);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
static void ModsFolder()
|
||||
{
|
||||
var root = NewRoot("mods");
|
||||
var ctx = Ctx(root);
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
var mods = Mods.FolderOf(game);
|
||||
var mm = new ModManager(ctx) { GameRuns = _ => false };
|
||||
MakeMod(mods, "Tall grass", ("romfs/Model/Grass.bfres", "a"), ("romfs/UI/x.bntx", "b"));
|
||||
MakeMod(mods, "Better HUD", ("romfs/UI/X.bntx", "c"));
|
||||
MakeMod(mods, "-Off one", ("romfs/Sound/a.bwav", "d"));
|
||||
MakeMod(mods, "_pack/Inner", ("romfs/Event/e.bin", "e"));
|
||||
MakeMod(mods, "Code mod", ("exefs/main.ips", "PATCH"), ("cheats/c.txt", "cheat"));
|
||||
MakeMod(mods, ".hidden", ("romfs/a", "x"));
|
||||
var list = mm.List(mods);
|
||||
Equal("Better HUD,Code mod,Off one,Inner,Tall grass", string.Join(",", list.Select(m => m.Name)), "the game's order, switches ignored, dot folders left out");
|
||||
Check(!list.First(m => m.Name == "Off one").On && list.First(m => m.Name == "Inner").OffAbove == "_pack", "off, and off by its folder");
|
||||
var conflicts = Mods.Conflicts(list);
|
||||
Equal(1, conflicts.Count, "one shared file");
|
||||
Equal("ui/x.bntx", conflicts[0].File, "keyed in lower case with /");
|
||||
Equal("Tall grass", conflicts[0].Winner.Name, "the last one wins");
|
||||
Equal("2 game files", Mods.Carries(list.First(m => m.Name == "Tall grass")), "carries");
|
||||
Equal("1 code patch file, 1 cheat file", Mods.Carries(list.First(m => m.Name == "Code mod")), "code");
|
||||
// (the build mark)
|
||||
Check(mm.NeedsRebuild(game), "code patches never built: build again");
|
||||
mm.MarkBuilt(game);
|
||||
Check(!mm.NeedsRebuild(game), "marked");
|
||||
var state = Mods.CodeState(list);
|
||||
Equal(16, state.Length, "16 hex digits");
|
||||
// (on/off, order, remove)
|
||||
var hud = list.First(m => m.Name == "Better HUD");
|
||||
var off = mm.SetOn(mods, hud, false);
|
||||
Equal(Path.Combine(mods, "-Better HUD"), off, "off is a - in front");
|
||||
Throws<ModsException>(() => mm.SetOn(mods, mm.List(mods).First(m => m.Name == "Inner"), true), "a folder above switches it off");
|
||||
var code = mm.List(mods).First(m => m.Name == "Code mod");
|
||||
mm.SetOn(mods, code, false);
|
||||
Check(mm.NeedsRebuild(game), "a code mod switched off: build again");
|
||||
Check(mm.Move(mods, mm.List(mods).First(m => m.Name == "Tall grass"), later: false), "moved earlier");
|
||||
var tops = Mods.Tops(mm.List(mods));
|
||||
Check(tops.All(t => Mods.Parse(t).Number != null), "every folder numbered: " + string.Join(",", tops));
|
||||
Check(tops.Contains("-01-Better HUD") || tops.Any(t => t.StartsWith("-0") && t.EndsWith("Better HUD")), "the switch kept in front of the number: " + string.Join(",", tops));
|
||||
var order = mm.List(mods).Select(m => m.Name).ToList();
|
||||
Check(order.IndexOf("Tall grass") < order.IndexOf("Inner"), "Tall grass passed Inner: " + string.Join(",", order));
|
||||
Check(!mm.Move(mods, mm.List(mods)[0], later: false), "the first cannot go earlier");
|
||||
var removed = mm.Remove(mods, mm.List(mods).First(m => m.Name == "Tall grass"));
|
||||
Check(removed.StartsWith(Path.Combine(mods, Mods.Removed)) && Directory.Exists(removed), "removed to .removed, nothing deleted");
|
||||
Check(mm.List(mods).All(m => m.Name != "Tall grass"), "out of the list");
|
||||
var busy = new ModManager(ctx) { GameRuns = _ => true };
|
||||
Equal("Close the game first. Mods are added, switched, ordered and removed only while it is not running.",
|
||||
Throws<ModsException>(() => busy.Remove(mods, busy.List(mods)[0]), "refused while the game runs").Message, "said so");
|
||||
// (the romfs file the game reads)
|
||||
MakeMod(mods, "99-Sound", ("romfs/Sound/Resource/Stream/SE_Sys_Do00.bwav", "mod's"));
|
||||
Directory.CreateDirectory(Path.Combine(game, "romfs", "Sound", "Resource", "Stream"));
|
||||
File.WriteAllText(Path.Combine(game, "romfs", "Sound", "Resource", "Stream", "SE_Sys_Cancel00.bwav"), "game's");
|
||||
Equal("mod's", File.ReadAllText(mm.RomfsFile(game, "Sound/Resource/Stream/SE_Sys_Do00.bwav")!), "a mod's file wins");
|
||||
Equal("game's", File.ReadAllText(mm.RomfsFile(game, "Sound/Resource/Stream/SE_Sys_Cancel00.bwav")!), "else the game's");
|
||||
Equal(null, mm.RomfsFile(game, "../secret"), "no way out");
|
||||
Equal<(bool, int?, string)>((true, 2, "Grass"), Mods.Parse("-02-Grass"), "parse");
|
||||
Equal((false, (int?)null, "4K-grass"), Mods.Parse("4K-grass"), "4K- is a name");
|
||||
Check(Mods.Compare("a", "B") < 0 && Mods.Compare("_", "a") < 0, "_stricmp order");
|
||||
}
|
||||
|
||||
static byte[] ZipBytes(Action<ZipArchive> fill)
|
||||
{
|
||||
using var m = new MemoryStream();
|
||||
using (var z = new ZipArchive(m, ZipArchiveMode.Create, true)) fill(z);
|
||||
return m.ToArray();
|
||||
}
|
||||
|
||||
static void Put(ZipArchive z, string name, string text)
|
||||
{
|
||||
using var w = new StreamWriter(z.CreateEntry(name).Open());
|
||||
w.Write(text);
|
||||
}
|
||||
|
||||
static void ModsArchives()
|
||||
{
|
||||
var root = NewRoot("modzip");
|
||||
var ctx = Ctx(root);
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
var mods = Mods.FolderOf(game);
|
||||
var mm = new ModManager(ctx) { GameRuns = _ => false };
|
||||
var good = Path.Combine(root, "Cool Link.zip");
|
||||
File.WriteAllBytes(good, ZipBytes(z => { Put(z, "contents/0400486024DEC000/romfs/Model/Link.bfres", "link"); Put(z, "readme.txt", "hi"); }));
|
||||
var m = mm.Add(mods, good);
|
||||
Equal("Cool Link", m.Name, "named after the archive when its folder is generic");
|
||||
Equal("model/link.bfres", m.Files.Single(), "its file");
|
||||
Check(!Directory.EnumerateDirectories(mods, ".adding-*").Any(), "the temporary folder removed");
|
||||
File.WriteAllBytes(good, ZipBytes(z => Put(z, "Hat/romfs/UI/hat.bntx", "hat")));
|
||||
Equal("Hat", mm.Add(mods, good).Name, "named after its own folder");
|
||||
void Refused(string name, Action<ZipArchive> fill, string words)
|
||||
{
|
||||
var f = Path.Combine(root, name);
|
||||
File.WriteAllBytes(f, ZipBytes(fill));
|
||||
var e = Throws<ModsException>(() => mm.Add(mods, f), name);
|
||||
Check(e.Message.Contains(words), name + ": " + e.Message);
|
||||
}
|
||||
Refused("escape.zip", z => Put(z, "../../evil/romfs/x", "x"), "leaves its own folder");
|
||||
Refused("device.zip", z => Put(z, "m/romfs/CON.txt", "x"), "device");
|
||||
Refused("two.zip", z => { Put(z, "a/romfs/x", "x"); Put(z, "b/romfs/y", "y"); }, "versions to choose from");
|
||||
Refused("none.zip", z => Put(z, "just/a/file.txt", "x"), "no romfs, exefs or cheats");
|
||||
Refused("other.zip", z => Put(z, "contents/0100000000010000/romfs/x", "x"), "another game");
|
||||
Refused("link.zip", z => { var e = z.CreateEntry("m/romfs/link"); e.ExternalAttributes = unchecked((int)(0xA1FFu << 16)); using var w = new StreamWriter(e.Open()); w.Write("/etc/passwd"); }, "link");
|
||||
Refused("dup.zip", z => { Put(z, "m/romfs/a", "1"); Put(z, "m/romfs/a", "2"); }, "two files of one name");
|
||||
var big = new ModManager(ctx) { GameRuns = _ => false, MaxBytes = 10 };
|
||||
File.WriteAllBytes(good, ZipBytes(z => Put(z, "m/romfs/big", new string('x', 100))));
|
||||
Check(Throws<ModsException>(() => big.Add(mods, good), "too big").Message.Contains("more than"), "the size bound");
|
||||
Throws<ModsException>(() => mm.Add(mods, Path.Combine(root, "x.txt")), "not an archive");
|
||||
Equal("Mod", Mods.Clean("..."), "clean: nothing left");
|
||||
Equal("Mod", Mods.Clean("NUL"), "clean: a device");
|
||||
Equal("Tall grass", Mods.Clean("-_Tall grass. "), "clean: switches and dots");
|
||||
Equal(2, mm.List(mods).Count, "only the two good ones added");
|
||||
}
|
||||
|
||||
// ---- GameBanana ----
|
||||
|
||||
const string PageJson = """
|
||||
{"_aMetadata":{"_nRecordCount":3,"_bIsComplete":true},"_aRecords":[
|
||||
{"_idRow":101,"_sModelName":"Mod","_sName":"Hat","_sProfileUrl":"https://gamebanana.com/mods/101","_nLikeCount":5,"_nViewCount":50,
|
||||
"_tsDateModified":1700000000,"_aSubmitter":{"_sName":"ann"},"_aRootCategory":{"_sName":"Models"},"_aGame":{"_idRow":26242},
|
||||
"_aPreviewMedia":{"_aImages":[{"_sBaseUrl":"https://images.gamebanana.com/img/ss/mods","_sFile":"a.jpg","_sFile530":"530-90_a.jpg"}]}},
|
||||
{"_idRow":105323,"_sModelName":"Wip","_sName":"Squadala!","_bHasFiles":true,"_aSubmitter":{"_sName":"daurosk"},"_aRootCategory":{"_sName":"Other"}},
|
||||
{"_idRow":7,"_sModelName":"Wip","_sName":"Showcase","_bHasFiles":false},
|
||||
{"_idRow":8,"_sModelName":"Request","_sName":"Please"},
|
||||
{"_idRow":9,"_sModelName":"Mod","_sName":"Other game","_aGame":{"_idRow":1}}
|
||||
]}
|
||||
""";
|
||||
|
||||
static void GameBananaParse()
|
||||
{
|
||||
var p = GameBanana.ParsePage(PageJson, null, 1, false);
|
||||
Equal(2, p.Mods.Count, "a mod and a WiP with files; no showcase, request or other game");
|
||||
Equal("https://images.gamebanana.com/img/ss/mods/530-90_a.jpg", p.Mods[0].ThumbUrl, "the 530 picture");
|
||||
Check(p.Mods[1].IsKit && p.Mods[1].Wip, "Squadala is the kit");
|
||||
Check(p.Complete && p.Total == 3, "metadata");
|
||||
Equal("https://gamebanana.com/apiv11/Game/26242/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=2", GameBanana.ListUrl(2), "the section's URL");
|
||||
Equal("https://gamebanana.com/apiv11/Util/Search/Results?_sModelName=Wip&_idGameRow=26242&_sOrder=best_match&_nPage=1&_sSearchString=link%20%26%20zelda%C3%A9",
|
||||
GameBanana.SearchUrl(true, 1, "link & zeldaé"), "search URL, UTF-8 escaped");
|
||||
// (as the game's own: </p> and <br> each a line, at most one blank line; <li> opens "- " where it stands)
|
||||
Equal("Line one\n\nLine two- item\nA & B", GameBanana.Plain("<p>Line one</p><br>Line two<ul><li>item</li></ul>A & B"), "plain text");
|
||||
using var d = System.Text.Json.JsonDocument.Parse("""{"_sText":"<b>Hi</b>","_nDownloadCount":12,"_aFiles":[{"_idRow":1,"_sFile":"x-linux.zip","_sDownloadUrl":"https://gamebanana.com/dl/1","_nFilesize":10,"_tsDateAdded":5},{"_idRow":2,"_sFile":"x-windows.zip","_sDownloadUrl":"https://gamebanana.com/dl/2","_nFilesize":11,"_tsDateAdded":6},{"_idRow":3,"_sFile":"nolink"}]}""");
|
||||
var det = GameBanana.ParseDetails(d.RootElement, 105323, true);
|
||||
Equal(2, det.Files.Count, "files with a link");
|
||||
Equal(1, det.DefaultFile(true), "a kit's Windows file first");
|
||||
Equal("Hi", det.Text, "description");
|
||||
}
|
||||
|
||||
static async Task GameBananaLive()
|
||||
{
|
||||
// (one read-only list call to the real API)
|
||||
var gb = new GameBanana();
|
||||
var page = await gb.ListAsync(1);
|
||||
Check(page.Mods.Count > 0 && page.Total > 0, "the section lists mods: " + page.Mods.Count + " of " + page.Total);
|
||||
Check(page.Mods.All(m => m.Id > 0 && m.Name.Length > 0), "cards have ids and names");
|
||||
}
|
||||
|
||||
static async Task GameBananaInstall()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var root = NewRoot("gbinstall");
|
||||
var ctx = Ctx(root);
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
var mods = Mods.FolderOf(game);
|
||||
MakeMod(mods, "01-Old one", ("romfs/a", "a"));
|
||||
var mm = new ModManager(ctx) { GameRuns = _ => false };
|
||||
var inst = new GameBananaInstaller(ctx, mm);
|
||||
s.Add("/dl/1", ZipBytes(z => { Put(z, "Fancy Hat v2/romfs/UI/hat.bntx", "hat"); Put(z, "readme.txt", "r"); }));
|
||||
var mod = new GbMod(101, false, "Fancy Hat", "ann", "Models", "https://gamebanana.com/mods/101", 1, 1, 1, null);
|
||||
var file = new GbFile(1, "hat.zip", "", s.Url + "/dl/1", 0, 1700000000);
|
||||
using var http = Downloader.CreateHttp();
|
||||
var msg = await inst.InstallAsync(http, mod, file, game, null, CancellationToken.None);
|
||||
Check(msg.Contains("02-Fancy Hat"), "installed after the highest number: " + msg);
|
||||
var info = ModManager.ReadInfo(Path.Combine(mods, "02-Fancy Hat"))!;
|
||||
Check(info.GameBananaId == 101 && info.Author == "ann" && info.FileDate == 1700000000, "triforce_mod.json");
|
||||
Check(inst.Installed(game).Any(i => i.Id == 101), "listed as installed");
|
||||
Check(!Directory.Exists(Path.Combine(mods, ".triforce-download")), "the download folder removed");
|
||||
// (switched off, then updated: the new one takes its place and its switch)
|
||||
mm.SetOn(mods, mm.List(mods).First(m => m.Name == "Fancy Hat"), false);
|
||||
s.Add("/dl/2", ZipBytes(z => Put(z, "romfs/UI/hat2.bntx", "hat2")));
|
||||
await inst.InstallAsync(http, mod, file with { Url = s.Url + "/dl/2", Added = 1800000000 }, game, null, CancellationToken.None);
|
||||
var now = mm.List(mods).Where(m => m.Info?.GameBananaId == 101).ToList();
|
||||
Equal(1, now.Count, "one folder for the mod after its update");
|
||||
Check(now[0].Folder.StartsWith("_02-") && !now[0].On, "its place and its off kept: " + now[0].Folder);
|
||||
Equal("ui/hat2.bntx", now[0].Files.Single(), "the new files");
|
||||
s.Add("/dl/3", ZipBytes(z => Put(z, "docs/readme.txt", "x")));
|
||||
await ThrowsAsync<ModsException>(() => inst.InstallAsync(http, mod with { Id = 5 }, file with { Url = s.Url + "/dl/3" }, game, null, CancellationToken.None), "no romfs: refused");
|
||||
// (bare game folders, no romfs above them: wrapped)
|
||||
s.Add("/dl/4", ZipBytes(z => Put(z, "MyPack/Model/x.bfres", "m")));
|
||||
await inst.InstallAsync(http, mod with { Id = 6, Name = "Bare" }, file with { Url = s.Url + "/dl/4" }, game, null, CancellationToken.None);
|
||||
Check(mm.List(mods).Any(m => m.Name == "Bare" && m.Files.Contains("model/x.bfres")), "wrapped in a romfs");
|
||||
}
|
||||
|
||||
// ---- Linux update logic (tests/test_linux_update.py's cases) ----
|
||||
|
||||
static void LinuxLogic()
|
||||
{
|
||||
string M(string? g, string t, string? l, bool p, bool k) => LinuxUpdate.ChooseMode(g, t, l, p, k);
|
||||
Equal("update-game", M("v1", "v2", "v2", false, true), "1");
|
||||
Equal("up-to-date", M("v2", "v2", "v2", false, true), "2");
|
||||
Equal("up-to-date", M("v1", "v1", null, false, true), "3");
|
||||
Equal("update-game", M("v1", "v1", "v2", false, true), "4");
|
||||
Equal("update-builder", M(null, "v1", "v2", false, false), "5");
|
||||
Equal("build", M(null, "v2", "v2", false, false), "6");
|
||||
Equal("build", M("v2", "v2", "v2", true, true), "7");
|
||||
var ci = "v2.0.5-3-g1a2b3c4";
|
||||
Equal("build", M(null, ci, "v2.0.5", false, false), "an Actions build is not taken back");
|
||||
Equal("build", M(null, "1a2b3c4", "v2.0.5", false, false), "a bare commit");
|
||||
Equal("build", M(null, "dev", "v2.0.5", false, false), "dev");
|
||||
Equal("build", M(null, "v2.0.6", "v2.0.5", false, false), "newer");
|
||||
Equal("build", M(null, "v2.1.0-rc.1", "v2.0.5", false, false), "an rc after");
|
||||
Equal("up-to-date", M(ci, ci, "v2.0.5", false, true), "its own game");
|
||||
Equal("update-game", M("v2.0.4", ci, "v2.0.5", false, true), "an older game");
|
||||
Equal(ci, LinuxUpdate.UpdateTarget("v2.0.5", ci), "target stays");
|
||||
Equal("update-game", M("v2.0.5", ci, "v2.0.5", false, true), "the release's game is older than this builder");
|
||||
Equal("update-builder", M(null, "v2.0.4", "v2.0.5", false, false), "an older release");
|
||||
Equal("update-builder", M(null, "v2.1.0-rc.1", "v2.1.0", false, false), "rc before its release");
|
||||
Equal("build", M(null, "v2.0.10", "v2.0.9", false, false), "numbers, not text");
|
||||
Equal("update-builder", M(null, "v2.0.4-3-g1a2b3c4", "v2.0.5", false, false), "after an older release");
|
||||
Equal("build", M(null, "v2.0.5-3-g1a2b3c4-dirty", "v2.0.5", false, false), "dirty after");
|
||||
Equal("update-builder", M(null, "v2.1.0-rc.1-2-gabc1234", "v2.1.0", false, false), "rc commits before the release");
|
||||
var sha = new string('a', 64);
|
||||
var list = LinuxUpdate.ParseList("# x\ntag v0.5.2\npart " + sha + " 10 usr/share/hookshot https://x/a.zip\ntree\npart " + sha + " 5 usr/lib/hookshot https://x/b.zip\nfile hookshot_vk.so\nfile libSDL2-2.0.so.0\n", local: false);
|
||||
Equal("v0.5.2", list.Tag, "tag");
|
||||
Check(list.Parts[0].Files == null && list.Parts[1].Files!.Count == 2, "tree and files");
|
||||
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\npart " + sha + " 1 a file:///x\ntree\n", local: false), "file:// only in a local list");
|
||||
Throws<FormatException>(() => LinuxUpdate.ParseList("tag ../x\npart " + sha + " 1 a https://x\ntree\n"), "a tag that is a path");
|
||||
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\npart " + sha + " 1 ../a https://x\ntree\n"), "a part out of its folder");
|
||||
Throws<FormatException>(() => LinuxUpdate.ParseList("tag v1\nwhat\n"), "unknown line");
|
||||
Equal("\"/home/a/100%% Games/\\\\\\\\x\\\\$y\"", LinuxPlatform.DesktopExec("/home/a/100% Games/\\x$y"), "desktop Exec escaping");
|
||||
}
|
||||
|
||||
// ---- Steam ----
|
||||
|
||||
static void SteamShortcut()
|
||||
{
|
||||
var root = NewRoot("steam");
|
||||
var ctx = Ctx(root);
|
||||
var steamRoot = Path.Combine(root, "Steam");
|
||||
Directory.CreateDirectory(Path.Combine(steamRoot, "userdata", "1001", "config"));
|
||||
Directory.CreateDirectory(Path.Combine(steamRoot, "userdata", "2002", "config"));
|
||||
Directory.CreateDirectory(Path.Combine(steamRoot, "config"));
|
||||
File.WriteAllText(Path.Combine(steamRoot, "config", "loginusers.vdf"),
|
||||
"\"users\"\n{\n\t\"" + (76561197960265728L + 2002) + "\"\n\t{\n\t\t\"PersonaName\"\t\t\"Link\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n");
|
||||
var lib = new SteamLibrary(ctx) { Running = _ => false };
|
||||
Equal(steamRoot, lib.Root(), "the test root's Steam only");
|
||||
var user = lib.User()!;
|
||||
Check(user.Id == "2002" && user.Name == "Link", "the most recent account");
|
||||
// (another shortcut there first, kept byte for byte)
|
||||
var other = SteamVdf.With(Array.Empty<byte>(), "\"C:\\Other\\other.exe\"", "\"C:\\Other\"", "", out _, out _);
|
||||
var otherBytes = other.ToArray();
|
||||
// (named Triforce but not ours: its program is no game exe, and its number is another)
|
||||
File.WriteAllBytes(user.Shortcuts, otherBytes);
|
||||
var before = File.ReadAllBytes(user.Shortcuts);
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
Directory.CreateDirectory(game);
|
||||
var exe = Path.Combine(game, "Triforce.exe");
|
||||
File.WriteAllText(exe, "");
|
||||
var pics = SteamVdf.Pictures.ToDictionary(p => p.Kind, p => new byte[] { 0x89, (byte)'P', (byte)'N', (byte)'G' });
|
||||
Check(lib.Add(user, exe, pics), "added");
|
||||
Check(lib.Added(user, exe), "there");
|
||||
Equal(exe, lib.Where(user, exe), "it starts the game");
|
||||
var id = SteamVdf.Id("\"" + exe + "\"", "Triforce");
|
||||
Check(id >= 0x80000000u, "the top bit set");
|
||||
Check(File.Exists(Path.Combine(user.Grid, id + "p.png")) && File.Exists(Path.Combine(user.Grid, id + "_icon.png")), "pictures under the id");
|
||||
Check(File.ReadAllBytes(user.Shortcuts + SteamLibrary.First).SequenceEqual(before), "the file before the first change kept");
|
||||
// (the game folder moved: the shortcut set to it, its pictures moved along)
|
||||
var moved = Path.Combine(root, "Games", "Moved");
|
||||
Directory.CreateDirectory(moved);
|
||||
var exe2 = Path.Combine(moved, "Triforce.exe");
|
||||
File.WriteAllText(exe2, "");
|
||||
Equal(exe, lib.Where(user, exe2), "the old shortcut found by its name and program");
|
||||
Check(!lib.Add(user, exe2, pics), "set, not added");
|
||||
var id2 = SteamVdf.Id("\"" + exe2 + "\"", "Triforce");
|
||||
Check(File.Exists(Path.Combine(user.Grid, id2 + "p.png")) && !File.Exists(Path.Combine(user.Grid, id + "p.png")), "pictures moved to the new id");
|
||||
var busy = new SteamLibrary(ctx) { Running = _ => true };
|
||||
Equal(SteamLibrary.CloseFirst, Throws<SteamException>(() => busy.Remove(user, exe2), "Steam running").Message, "close Steam first");
|
||||
Check(lib.Remove(user, exe2), "removed");
|
||||
Check(!lib.Added(user, exe2), "gone");
|
||||
Check(File.ReadAllBytes(user.Shortcuts).SequenceEqual(before), "the file as it was before");
|
||||
File.WriteAllBytes(user.Shortcuts, new byte[] { 0, 1, 2 });
|
||||
Check(Throws<SteamException>(() => lib.Add(user, exe, pics), "a broken file").Message.Contains("left it alone"), "left alone");
|
||||
}
|
||||
}
|
||||
515
launcher/LogicTests/Tests.GameOptions.cs
Normal file
515
launcher/LogicTests/Tests.GameOptions.cs
Normal file
@@ -0,0 +1,515 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Triforce.Logic;
|
||||
using static Triforce.LogicTests.T;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
static partial class Tests
|
||||
{
|
||||
// (READ ONLY: the owner's own game folder. Nothing here writes there; the tests that write work on a copy in a test root)
|
||||
const string RealGame = @"D:\src\triforce-game";
|
||||
|
||||
public static IEnumerable<(string Name, Func<Task> Run)> GameOptionsTests()
|
||||
{
|
||||
(string, Func<Task>) Sync(string n, Action a) => (n, () => { a(); return Task.CompletedTask; });
|
||||
yield return Sync("game options: schema matches vk_menu.cpp's table", GameOptionsMatchMenu);
|
||||
yield return Sync("game options: keys, labels, choices, no Hookshot", GameOptionsLabels);
|
||||
yield return Sync("game options: the real triforce_options.ini (read only)", GameOptionsRealFile);
|
||||
yield return Sync("game options: round trip, merge, atomic write (a copy)", GameOptionsWrite);
|
||||
yield return Sync("game options: Set's rules, Quality preset, Apply", GameOptionsSetRules);
|
||||
yield return Sync("game options: an older options_version, a new file", GameOptionsOldVersion);
|
||||
}
|
||||
|
||||
// ---- the schema against the game's source ----
|
||||
|
||||
/// <summary>gpu/vk of this source tree (the launcher's own repository), found from this file's folder up, else from the test
|
||||
/// program's.</summary>
|
||||
static string? MenuSource([System.Runtime.CompilerServices.CallerFilePath] string here = "")
|
||||
{
|
||||
foreach (var start in new[] { Path.GetDirectoryName(here), AppContext.BaseDirectory })
|
||||
for (var d = start is { Length: > 0 } ? new DirectoryInfo(start) : null; d != null; d = d.Parent)
|
||||
if (File.Exists(Path.Combine(d.FullName, "gpu", "vk", "vk_menu.cpp"))) return Path.Combine(d.FullName, "gpu", "vk");
|
||||
return null;
|
||||
}
|
||||
|
||||
sealed record MenuRow(string Tab, string Name, string Value, string Lo, string Hi, string Step, string Text, string? Help, bool Restart, bool Exempt, bool Heading);
|
||||
|
||||
/// <summary>vk_menu.cpp's rows[] table, each entry's fields (comments out, adjacent string literals joined).</summary>
|
||||
static List<MenuRow> ReadMenuTable(string cpp)
|
||||
{
|
||||
var body = cpp[cpp.IndexOf("Row rows[] = {", StringComparison.Ordinal)..cpp.IndexOf("constexpr int kRowsEnd", StringComparison.Ordinal)];
|
||||
var sb = new StringBuilder();
|
||||
for (int i = 0, inStr = 0; i < body.Length; i++)
|
||||
{
|
||||
var c = body[i];
|
||||
if (inStr == 1)
|
||||
{
|
||||
sb.Append(c);
|
||||
if (c == '\\') { sb.Append(body[++i]); continue; }
|
||||
if (c == '"') inStr = 0;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') { inStr = 1; sb.Append(c); continue; }
|
||||
if (c == '/' && i + 1 < body.Length && body[i + 1] == '/') { while (i < body.Length && body[i] != '\n') i++; sb.Append('\n'); continue; }
|
||||
sb.Append(c);
|
||||
}
|
||||
body = sb.ToString();
|
||||
var rows = new List<MenuRow>();
|
||||
foreach (Match m in Regex.Matches(body, @"\{(TAB_[A-Z]+),"))
|
||||
{
|
||||
int k = m.Index + m.Length, depth = 1;
|
||||
var inS = false;
|
||||
var fields = new List<string>();
|
||||
var cur = new StringBuilder();
|
||||
for (; depth > 0; k++)
|
||||
{
|
||||
var c = body[k];
|
||||
if (inS)
|
||||
{
|
||||
cur.Append(c);
|
||||
if (c == '\\') { cur.Append(body[++k]); continue; }
|
||||
if (c == '"') inS = false;
|
||||
continue;
|
||||
}
|
||||
if (c == '"') { inS = true; cur.Append(c); }
|
||||
else if (c == '{') { depth++; cur.Append(c); }
|
||||
else if (c == '}') { if (--depth > 0) cur.Append(c); }
|
||||
else if (c == ',') { fields.Add(cur.ToString().Trim()); cur.Clear(); }
|
||||
else cur.Append(c);
|
||||
}
|
||||
if (cur.ToString().Trim().Length > 0) fields.Add(cur.ToString().Trim());
|
||||
string? Lit(int i) => i < fields.Count && fields[i].StartsWith('"')
|
||||
? string.Concat(Regex.Matches(fields[i], "\"((?:[^\"\\\\]|\\\\.)*)\"").Select(x => x.Groups[1].Value)).Replace("\\\"", "\"").Replace("\\\\", "\\")
|
||||
: null;
|
||||
string F(int i, string dflt) => i < fields.Count ? fields[i] : dflt;
|
||||
rows.Add(new MenuRow(m.Groups[1].Value, Lit(0) ?? fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], Lit(6),
|
||||
F(8, "false") == "true", F(9, "false") == "true", F(11, "false") == "true"));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// <summary>vk_menu.h's Options defaults, by field.</summary>
|
||||
static Dictionary<string, int> ReadOptionDefaults(string h)
|
||||
{
|
||||
var s = h[h.IndexOf("struct Options {", StringComparison.Ordinal)..h.IndexOf("extern Options opts;", StringComparison.Ordinal)];
|
||||
var d = new Dictionary<string, int>();
|
||||
foreach (var line in s.Split('\n'))
|
||||
{
|
||||
var code = line.Split("//")[0];
|
||||
var m = Regex.Match(code, @"^\s*int\s+(.*);");
|
||||
if (!m.Success) continue;
|
||||
foreach (var part in m.Groups[1].Value.Split(','))
|
||||
{
|
||||
var kv = part.Split('=');
|
||||
d[kv[0].Trim()] = int.Parse(kv[1].Trim());
|
||||
}
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static void GameOptionsMatchMenu()
|
||||
{
|
||||
var dir = MenuSource();
|
||||
Check(dir != null, "gpu/vk/vk_menu.cpp is found above the test program");
|
||||
var table = ReadMenuTable(File.ReadAllText(Path.Combine(dir!, "vk_menu.cpp")));
|
||||
var defaults = ReadOptionDefaults(File.ReadAllText(Path.Combine(dir!, "vk_menu.h")));
|
||||
Check(table.Count > 100, "the table read: " + table.Count + " entries");
|
||||
var symbols = new Dictionary<string, int>
|
||||
{
|
||||
["kLastOutput"] = 6, ["ur::kValues - 1"] = 6, ["ur::kUpscalers - 1"] = 6, ["ur::kModels - 1"] = 3, ["aa_rows::kValues - 1"] = 3,
|
||||
["2 + kMaxMics"] = 18, ["HOS_PROMPT_N"] = 6,
|
||||
};
|
||||
int Num(string s, string what) => int.TryParse(s, out var v) ? v : symbols.TryGetValue(s, out v) ? v : throw new TestFailed(what + ": a symbol the test does not know, " + s);
|
||||
var tabs = new Dictionary<string, GameOptionTab>
|
||||
{
|
||||
["TAB_DISPLAY"] = GameOptionTab.Display, ["TAB_GRAPHICS"] = GameOptionTab.Graphics, ["TAB_AUDIO"] = GameOptionTab.Audio,
|
||||
["TAB_CONTROLS"] = GameOptionTab.Controls, ["TAB_SYSTEM"] = GameOptionTab.System, ["TAB_MOTION"] = GameOptionTab.Controls,
|
||||
["TAB_PAGE"] = GameOptionTab.Controls,
|
||||
};
|
||||
var left = new[] { "&opts.language", "&opts.pad_layout" }; // (Game language: language.txt's; Layout preset: KeptKeys)
|
||||
var sections = new Dictionary<string, string>();
|
||||
var names = new List<string>();
|
||||
foreach (var r in table)
|
||||
{
|
||||
if (r.Heading) { sections[r.Tab] = r.Name; continue; }
|
||||
if (r.Value == "nullptr" || r.Tab == "TAB_DEBUG" || left.Contains(r.Value)) continue;
|
||||
var row = GameOptionsSchema.ByName(r.Name);
|
||||
Check(row != null, "the menu's row \"" + r.Name + "\" is in the schema");
|
||||
names.Add(r.Name);
|
||||
Equal(tabs[r.Tab], row!.Tab, r.Name + ": tab");
|
||||
var section = r.Tab == "TAB_MOTION" ? "Motion" : r.Tab == "TAB_PAGE" ? "Controls" : sections.GetValueOrDefault(r.Tab);
|
||||
Equal(section, row.Section, r.Name + ": section");
|
||||
Equal(Num(r.Lo, r.Name), row.Lo, r.Name + ": lo");
|
||||
Equal(Num(r.Hi, r.Name), row.Hi, r.Name + ": hi");
|
||||
Equal(Num(r.Step, r.Name), row.Step, r.Name + ": step");
|
||||
Equal(r.Help, row.Help, r.Name + ": help");
|
||||
Equal(r.Restart, row.Restart, r.Name + ": restart");
|
||||
Equal(r.Exempt, row.PresetExempt, r.Name + ": preset exempt");
|
||||
Equal(defaults[r.Value["&opts.".Length..]], row.Default, r.Name + ": default");
|
||||
}
|
||||
Equal(string.Join("|", names), string.Join("|", GameOptionsSchema.All.Select(r => r.Name)), "the rows, in the menu's order");
|
||||
// (the Debug tab's keys, and the Layout preset's, are the KeptKeys: each with its reason)
|
||||
foreach (var r in table.Where(r => r.Value != "nullptr" && !r.Heading && (r.Tab == "TAB_DEBUG" || r.Value == "&opts.pad_layout")))
|
||||
Check(GameOptionsSchema.KeptKeys.ContainsKey(GameOptionsSchema.IniKey(r.Name)), r.Name + "'s key " + GameOptionsSchema.IniKey(r.Name) + " is a kept key");
|
||||
}
|
||||
|
||||
// ---- keys and labels ----
|
||||
|
||||
static void GameOptionsLabels()
|
||||
{
|
||||
var all = GameOptionsSchema.All;
|
||||
Equal(all.Count, all.Select(r => r.Key).Distinct().Count(), "keys are unique");
|
||||
Check(all.All(r => r.Key.Length <= 31 && !r.Key.Contains(' ')), "keys as ini_key makes them");
|
||||
Equal("frame_rate_cap", GameOptionsSchema.Get("frame_rate_cap").Key, "renamed row keeps its key");
|
||||
Equal("Game frame rate cap", GameOptionsSchema.Get("frame_rate_cap").Name, "by key");
|
||||
Equal("amd_anti-lag_2", GameOptionsSchema.ByName("AMD Anti-Lag 2")!.Key, "AMD Anti-Lag 2's key");
|
||||
Equal("upscaling", GameOptionsSchema.ByName("Window scaling filter")!.Key, "Window scaling filter's key");
|
||||
Equal("tail_early", GameOptionsSchema.IniKey("Start next frame early"), "Start next frame early's key");
|
||||
Equal("export_save_for_a_bug_report", GameOptionsSchema.IniKey("Export save for a bug report"), "a long name: 28 letters");
|
||||
Equal("abcdefghijklmnopqrstuvwxyzabcde", GameOptionsSchema.IniKey("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGH"), "cut at 31");
|
||||
Equal(null, GameOptionsSchema.ByKey("Fullscreen"), "keys are exact");
|
||||
Throws<KeyNotFoundException>(() => GameOptionsSchema.Get("nope"), "an unknown key");
|
||||
|
||||
foreach (var r in all)
|
||||
{
|
||||
foreach (var text in new[] { r.Name, r.Help }.Concat(r.Choices.Select(c => c.Label)).Concat(new[] { r.Label(r.Lo), r.Label(r.Hi), r.Label(r.Default) }))
|
||||
Check(!text.Contains("hookshot", StringComparison.OrdinalIgnoreCase), r.Name + ": no Hookshot in \"" + text + "\"");
|
||||
Check(r.Help.Length > 10, r.Name + ": has its help");
|
||||
Check(r.Default >= r.Lo && r.Default <= r.Hi, r.Name + ": default in range");
|
||||
Equal(r.Default, r.Clamp(r.Default), r.Name + ": default on its steps");
|
||||
if (r.Kind == GameOptionKind.Choice)
|
||||
{
|
||||
Check(r.Key == GameOptionsSchema.GpuKey || r.Choices.Count >= 2, r.Name + ": choices");
|
||||
Check(r.Key == GameOptionsSchema.GpuKey || r.Choices.Any(c => c.Value == r.Default), r.Name + ": its default is a choice");
|
||||
Equal(r.Choices.Count, r.Choices.Select(c => c.Label).Distinct().Count(), r.Name + ": labels differ");
|
||||
}
|
||||
else Equal(0, r.Choices.Count, r.Name + ": a slider has no choice list");
|
||||
}
|
||||
Equal(1, all.Count(r => r.Tab == GameOptionTab.Graphics && r.Key == GameOptionsSchema.PresetKey), "the preset row");
|
||||
Equal("Screen,Widescreen,Frame rate,High dynamic range,RenoDX", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Display)), "Display's sections");
|
||||
Equal("Quality,Upscaling and edges,Smoothness,Latency,Advanced", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Graphics)), "Graphics' sections");
|
||||
Equal("Camera,Sticks,Movement,Vibration,Other,Motion,Controls", string.Join(",", GameOptionsSchema.Sections(GameOptionTab.Controls)), "Controls' sections");
|
||||
Equal(0, GameOptionsSchema.Sections(GameOptionTab.Audio).Count, "Audio has none");
|
||||
|
||||
string L(string key, int v) => GameOptionsSchema.Get(key).Label(v);
|
||||
string Cs(string key) => string.Join("|", GameOptionsSchema.Get(key).Choices.Select(c => c.Value + "=" + c.Label));
|
||||
Equal("-3=30|-2=40|-1=45|0=60 (the console's)|1=90|2=120|3=144|4=165|5=240|6=Monitor's rate", Cs("frame_rate_cap"), "fps cap");
|
||||
Equal("3=1920x1080|0=2048x1152|1=2560x1440|2=3840x2160|4=5120x1440|6=5120x2160|5=5120x2880", Cs("output_res"), "output sizes, smallest first");
|
||||
Equal("0=Game|1=NVIDIA DLSS|2=NVIDIA DLAA|3=AMD FSR 3.1|6=AMD FSR 3.1 Native AA|4=AMD FSR 4|5=AMD FSR 4 Native AA", Cs("dlss"), "upscalers in the menu's order");
|
||||
Equal("0=Auto (dynamic)|1=100% (2048x1152)|2=75% (1536x864)|3=67% (1366x768)|4=50% (1024x576)", Cs("resolution"), "render resolution, the game's own");
|
||||
Equal("0=Custom|1=Minimum (6GB)|2=Low (8GB)|3=Balanced (12GB)|4=High (16GB)|5=Ultra (20GB+)", Cs("quality_preset"), "presets");
|
||||
Equal("0=Off|1=Default", Cs("microphone"), "microphone without devices");
|
||||
Equal("0=Game SMAA|1=Off|2=FXAA|3=SMAA Ultra", Cs("anti-aliasing"), "anti-aliasing");
|
||||
Equal("0=Off|1=Auto|2=2x|3=3x|4=4x|5=5x|6=6x|7=7x|8=8x|9=AMD FSR 4", Cs("frame_generation"), "frame generation");
|
||||
Equal("0=Auto|1=Switch|2=Xbox|3=PlayStation 4|4=PlayStation 5|5=Steam Deck|6=Keyboard & mouse", Cs("button_prompts"), "prompts");
|
||||
Equal("0=Auto|1=Off|2=On", Cs("robust_buffers"), "robust");
|
||||
Equal("0=Insert or F1|1=F1 only", Cs("menu_shortcut"), "menu shortcut");
|
||||
Equal("1.25", L("mouse_sensitivity", 125), "sensitivity");
|
||||
Equal("0.51", L("walk_scale", 51), "walk scale");
|
||||
Equal("10000 nits", L("hdr_peak_brightness", 10000), "nits");
|
||||
Equal("Muted", L("master_volume", 0), "volume 0");
|
||||
Equal("85%", L("master_volume", 85), "volume");
|
||||
Equal("Off", L("menu_sounds", 0), "menu sounds 0");
|
||||
Equal("Off", L("rumble_strength", 0), "rumble 0");
|
||||
Equal("As Stick dead zone", L("left_stick_dead_zone", -1), "own dead zone");
|
||||
Equal("0%", L("right_stick_dead_zone", 0), "own dead zone 0");
|
||||
Equal("50", L("renodx_bloom", 50), "grade");
|
||||
Equal("Default (24%)", L("stick_dead_zone", 0), "stick dead zone");
|
||||
Equal("Off", L("upscaling", 7), "past the row: its first");
|
||||
Equal("16:9", L("ultrawide", 0), "ultrawide");
|
||||
|
||||
// (the GPU device row: the names the launcher gives it)
|
||||
var before = GameOptionsSchema.GpuNames;
|
||||
try
|
||||
{
|
||||
GameOptionsSchema.GpuNames = null;
|
||||
Equal("Auto", L("gpu_device", 0), "gpu 0");
|
||||
Equal("1: Device 1", L("gpu_device", 2), "gpu without names");
|
||||
Equal("0=Auto", Cs("gpu_device"), "gpu choices without names");
|
||||
GameOptionsSchema.GpuNames = () => new[] { "NVIDIA GeForce RTX 4070", "AMD Radeon(TM) Graphics" };
|
||||
Equal("0=Auto|1=0: NVIDIA GeForce RTX 4070|2=1: AMD Radeon(TM) Graphics", Cs("gpu_device"), "gpu choices");
|
||||
Equal("0: NVIDIA GeForce RTX 4070", L("gpu_device", 1), "gpu 1");
|
||||
GameOptionsSchema.UseSystemGpus(); // (not asked here: the tests do not read this PC's registry)
|
||||
Check(GameOptionsSchema.GpuNames != null, "the hook is set");
|
||||
}
|
||||
finally { GameOptionsSchema.GpuNames = before; }
|
||||
|
||||
Equal(6, GameOptionsSchema.PresetSummaries.Count, "a summary for each preset");
|
||||
Equal(0, GameOptionsSchema.PresetValues(0).Count, "Custom sets nothing");
|
||||
}
|
||||
|
||||
// ---- the real file ----
|
||||
|
||||
static void GameOptionsRealFile()
|
||||
{
|
||||
var path = Path.Combine(RealGame, GameOptionsSchema.FileName);
|
||||
Check(File.Exists(path), "the real options file is there: " + path);
|
||||
var info = new FileInfo(path);
|
||||
var (len, time) = (info.Length, info.LastWriteTimeUtc);
|
||||
var f = GameOptionsFile.Load(RealGame);
|
||||
Check(f.Exists && f.Version == GameOptionsSchema.CurrentVersion, "read, version " + f.Version);
|
||||
// (every key is a row or a kept one: these, knowingly. options_version: the format; menu_size: the old Menu size row;
|
||||
// layout_preset: rebinds the pad_ lines in the game; the Debug tab's; pad_* and key_*: the Controls page's bindings)
|
||||
Equal("", string.Join(",", f.UnknownKeys), "no key nobody knows");
|
||||
var kept = f.OtherLines.Select(o => o.Key).Where(k => !k.StartsWith("pad_") && !k.StartsWith("key_")).ToList();
|
||||
foreach (var k in kept) Check(GameOptionsSchema.KeptKeys.ContainsKey(k), k + " is a kept key");
|
||||
Check(f.OtherLines.Any(o => o.Key.StartsWith("key_")), "the bindings are other lines");
|
||||
foreach (var r in GameOptionsSchema.All)
|
||||
{
|
||||
var v = f.Get(r.Key);
|
||||
var label = f.Label(r.Key);
|
||||
Check(label.Length > 0 && !label.Contains("Device"), r.Name + ": label \"" + label + "\"");
|
||||
if (r.Kind == GameOptionKind.Choice)
|
||||
Check(f.ChoicesOf(r.Key).Any(c => c.Value == v && c.Label == label), r.Name + ": " + v + " = \"" + label + "\" is one of its choices");
|
||||
else
|
||||
Check(Regex.IsMatch(label, @"^(-?\d+( nits|%)?|\d\.\d\d|Off|Muted|As Stick dead zone)$"), r.Name + ": a slider's label \"" + label + "\"");
|
||||
Check(f.Raw(r.Key) == null || v == r.AsRead(GameOptionsFile.Atoi(f.Raw(r.Key)!)), r.Name + ": the file's value as the game reads it");
|
||||
}
|
||||
info.Refresh();
|
||||
Equal(len, info.Length, "the real file is not written");
|
||||
Equal(time, info.LastWriteTimeUtc, "the real file's time is the same");
|
||||
Check(!File.Exists(path + ".new"), "nothing beside it");
|
||||
}
|
||||
|
||||
/// <summary>The real file's lines as of 11-19 (version 7, CRLF), for the exact checks: the real one changes as he plays.</summary>
|
||||
const string OptionsFixture = "fullscreen=0\r\noutput_res=1\r\ngpu_device=0\r\nultrawide=0\r\nultrawide_hud=0\r\nultrawide_menus=1\r\nframe_rate_cap=0\r\n" +
|
||||
"fps_counter=1\r\nhdr=0\r\nhdr_paper_white=400\r\nhdr_peak_brightness=4000\r\nrenodx_midgray=2\r\nrenodx_color_space=2\r\nquality_preset=0\r\n" +
|
||||
"resolution=1\r\ntexture_detail=1\r\ndlss=0\r\ndlss_model=1\r\nanti-aliasing=1\r\nsharpness=50\r\nupscaling=2\r\nframe_pacing=1\r\nnvidia_reflex=0\r\n" +
|
||||
"robust_buffers=1\r\nmicrophone=1\r\nmouse_sensitivity=125\r\ncontroller_in_background=1\r\nlayout_preset=1\r\nbutton_prompts=2\r\ndebug_tools=0\r\n" +
|
||||
"replay_helper_threads=0\r\ntail_early=1\r\noptions_version=7\r\nmenu_size=1\r\npad_a=0\r\nkey_a=69,0\r\nkey_cam_right=39,76\r\n";
|
||||
|
||||
static string NewGameFolder(string name, string content)
|
||||
{
|
||||
var game = Path.Combine(NewRoot(name), "game");
|
||||
Directory.CreateDirectory(game);
|
||||
File.WriteAllText(Path.Combine(game, GameOptionsSchema.FileName), content, Encoding.Latin1);
|
||||
return game;
|
||||
}
|
||||
|
||||
static void GameOptionsWrite()
|
||||
{
|
||||
// (a copy of the real file, in a test root)
|
||||
var root = NewRoot("game-options");
|
||||
var game = Path.Combine(root, "game");
|
||||
Directory.CreateDirectory(game);
|
||||
var path = Path.Combine(game, GameOptionsSchema.FileName);
|
||||
File.Copy(Path.Combine(RealGame, GameOptionsSchema.FileName), path);
|
||||
var original = File.ReadAllBytes(path);
|
||||
var f = GameOptionsFile.Load(game);
|
||||
f.Save();
|
||||
Check(File.ReadAllBytes(path).SequenceEqual(original), "nothing changed: nothing written");
|
||||
f.Set("hdr", f.Get("hdr"));
|
||||
Equal(0, f.Changes.Count, "set to what it is: no change");
|
||||
f.Save();
|
||||
Check(File.ReadAllBytes(path).SequenceEqual(original), "still the same bytes");
|
||||
|
||||
// (one row changed: that line alone)
|
||||
var sens = f.Get("mouse_sensitivity") == 200 ? 300 : 200;
|
||||
f.Set("mouse_sensitivity", sens);
|
||||
f.Save();
|
||||
var before = Encoding.Latin1.GetString(original).Split("\r\n");
|
||||
var after = File.ReadAllText(path, Encoding.Latin1).Split("\r\n");
|
||||
Equal(before.Length, after.Length, "as many lines, CRLF kept");
|
||||
for (var i = 0; i < before.Length; i++)
|
||||
Equal(before[i].StartsWith("mouse_sensitivity=") ? "mouse_sensitivity=" + sens : before[i], after[i], "line " + i);
|
||||
Equal(sens, GameOptionsFile.Load(game).Get("mouse_sensitivity"), "read back");
|
||||
Check(!File.Exists(path + ".new"), "no .new left");
|
||||
|
||||
// (exact labels on the fixture)
|
||||
var fx = GameOptionsFile.Load(NewGameFolder("game-options-fixture", OptionsFixture));
|
||||
string Lb(string k) => fx.Label(k);
|
||||
Equal("2560x1440", Lb("output_res"), "output");
|
||||
Equal("100% (2560x1440)", Lb("resolution"), "render resolution at 2560x1440");
|
||||
Equal("1.25", Lb("mouse_sensitivity"), "mouse sensitivity 125");
|
||||
Equal("4000 nits", Lb("hdr_peak_brightness"), "peak");
|
||||
Equal("400 nits", Lb("hdr_paper_white"), "paper white");
|
||||
Equal("Off", Lb("anti-aliasing"), "aa");
|
||||
Equal("Xbox", Lb("button_prompts"), "prompts");
|
||||
Equal("On", Lb("fps_counter"), "fps counter");
|
||||
Equal("DCI-P3", Lb("renodx_color_space"), "colour space");
|
||||
Equal("Eye adaptation", Lb("renodx_midgray"), "midgray");
|
||||
Equal("Transformer 2 (M)", Lb("dlss_model"), "dlss model");
|
||||
Equal("Lanczos", Lb("upscaling"), "filter");
|
||||
Equal("50%", Lb("sharpness"), "sharpness");
|
||||
Equal("Off", Lb("robust_buffers"), "robust 1");
|
||||
Equal("Default", Lb("microphone"), "microphone");
|
||||
Equal("Full", Lb("texture_detail"), "texture detail");
|
||||
Equal("Off", Lb("nvidia_reflex"), "reflex 0");
|
||||
Equal("Per frame", GameOptionsSchema.Get("game_speed").Label(0), "game speed 0");
|
||||
Equal("Real time", Lb("game_speed"), "game speed: its default without a line");
|
||||
Equal("80%", Lb("menu_sounds"), "menu sounds' default");
|
||||
Equal("Middle", Lb("ultrawide_hud"), "wide HUD");
|
||||
Equal("Centred, blurred sides", Lb("ultrawide_menus"), "wide menus");
|
||||
Equal("layout_preset,debug_tools,replay_helper_threads,tail_early,options_version,menu_size,pad_a,key_a,key_cam_right",
|
||||
string.Join(",", fx.OtherLines.Select(o => o.Key)), "other lines in the file's order");
|
||||
Equal("69,0", fx.OtherLines.Single(o => o.Key == "key_a").Value, "a binding's value as it is");
|
||||
fx.Set("dlss", 1);
|
||||
Equal("Quality (67%)", fx.Label("resolution"), "with DLSS: its mode (100% moved to Quality)");
|
||||
Equal("DLSS's own", fx.Label("anti-aliasing"), "aa with DLSS");
|
||||
Equal("0,3,5,4,6", string.Join(",", fx.ChoicesOf("resolution").Select(c => c.Value)), "DLSS's steps");
|
||||
fx.Set("dlss", 2);
|
||||
Equal("Native (DLAA)", fx.Label("resolution"), "DLAA");
|
||||
fx.Set("dlss", 3);
|
||||
Equal("FSR's own", fx.Label("anti-aliasing"), "aa with FSR");
|
||||
fx.Set("dlss", 0);
|
||||
fx.Set("handheld_profile", 1);
|
||||
Equal("67% (1024x576)", fx.Label("resolution"), "handheld profile's size (100% went to DLSS's Quality, which stays with the game's own)");
|
||||
|
||||
// (the merge: a line changed outside since Load stays; the launcher's own change goes in; an unknown line stays in place)
|
||||
var m = NewGameFolder("game-options-merge", OptionsFixture);
|
||||
var mp = Path.Combine(m, GameOptionsSchema.FileName);
|
||||
var a = GameOptionsFile.Load(m);
|
||||
a.Set("fullscreen", 1);
|
||||
a.Set("sharpness", 70);
|
||||
var outside = File.ReadAllText(mp, Encoding.Latin1).Replace("hdr=0\r\n", "hdr=2\r\nzz_tool_line=5\r\n").Replace("sharpness=50", "sharpness=20");
|
||||
File.WriteAllText(mp, outside, Encoding.Latin1);
|
||||
a.Save();
|
||||
var merged = File.ReadAllText(mp, Encoding.Latin1);
|
||||
Check(merged.Contains("\r\nhdr=2\r\nzz_tool_line=5\r\n"), "the outside change and its new line kept in place");
|
||||
Check(merged.StartsWith("fullscreen=1\r\n"), "the launcher's change in its line");
|
||||
Check(merged.Contains("\r\nsharpness=70\r\n"), "a row changed on both sides: the launcher's (the later writer)");
|
||||
Equal(outside.Replace("fullscreen=0", "fullscreen=1").Replace("sharpness=20", "sharpness=70"), merged, "every other line as the file had it");
|
||||
Equal("zz_tool_line", a.UnknownKeys.Single(), "an unknown key, kept");
|
||||
Equal(2, a.Get("hdr"), "this object holds the file as written");
|
||||
|
||||
// (a row with no line goes in before options_version; duplicates all take the value)
|
||||
var d = NewGameFolder("game-options-dup", "sharpness=10\nsharpness=20\n#note\noptions_version=7\nmenu_size=1\n");
|
||||
var df = GameOptionsFile.Load(d);
|
||||
Equal(20, df.Get("sharpness"), "the last line wins, as the game reads it");
|
||||
df.Set("sharpness", 30);
|
||||
df.Set("vsync", 0);
|
||||
df.Save();
|
||||
Equal("sharpness=30\nsharpness=30\n#note\nvsync=0\noptions_version=7\nmenu_size=1\n", File.ReadAllText(Path.Combine(d, GameOptionsSchema.FileName)), "LF kept, line added, comment kept");
|
||||
|
||||
// (a device's name in UTF-8: its bytes as they were, its label as text)
|
||||
var mic = "microphone_device=Mikrofon (Ä USB)";
|
||||
var micBytes = Encoding.UTF8.GetBytes("microphone=2\r\n" + mic + "\r\noptions_version=7\r\n");
|
||||
var mg = Path.Combine(NewRoot("game-options-mic"), "game");
|
||||
Directory.CreateDirectory(mg);
|
||||
File.WriteAllBytes(Path.Combine(mg, GameOptionsSchema.FileName), micBytes);
|
||||
var mf = GameOptionsFile.Load(mg);
|
||||
Equal("Mikrofon (Ä USB)", mf.Label("microphone"), "the device's name");
|
||||
Equal("0=Off|1=Default|2=Mikrofon (Ä USB)", string.Join("|", mf.ChoicesOf("microphone").Select(c => c.Value + "=" + c.Label)), "its choices");
|
||||
mf.Set("fullscreen", 1);
|
||||
mf.Save();
|
||||
var micAfter = File.ReadAllBytes(Path.Combine(mg, GameOptionsSchema.FileName));
|
||||
Check(micAfter.AsSpan().IndexOf(Encoding.UTF8.GetBytes(mic)) >= 0, "the name's UTF-8 bytes kept");
|
||||
|
||||
// (atomic: the .new cannot be made, the file is as it was and the error is the caller's)
|
||||
var w = NewGameFolder("game-options-atomic", OptionsFixture);
|
||||
var wp = Path.Combine(w, GameOptionsSchema.FileName);
|
||||
Directory.CreateDirectory(wp + ".new");
|
||||
var wf = GameOptionsFile.Load(w);
|
||||
wf.Set("vsync", 0);
|
||||
Throws<Exception>(() => wf.Save(), "a failed write throws");
|
||||
Equal(OptionsFixture, File.ReadAllText(wp, Encoding.Latin1), "the old file whole");
|
||||
Equal(1, wf.Changes.Count, "the change is still to be saved");
|
||||
Directory.Delete(wp + ".new");
|
||||
wf.Save();
|
||||
Equal(0, GameOptionsFile.Load(w).Get("vsync"), "saved once it can be");
|
||||
Check(!File.Exists(wp + ".new") && !Directory.Exists(wp + ".new"), "nothing left beside it");
|
||||
}
|
||||
|
||||
static void GameOptionsSetRules()
|
||||
{
|
||||
var f = GameOptionsFile.Load(NewGameFolder("game-options-set", OptionsFixture));
|
||||
Equal(10000, f.Set("hdr_peak_brightness", 12345), "past the end: the end");
|
||||
Equal(130, f.Set("mouse_sensitivity", 125), "onto the steps: the nearest, the larger on a tie");
|
||||
Equal(50, f.Set("rumble_strength", 60), "rumble on 25s");
|
||||
Equal(0, f.Set("output_res", 9), "an output past the list: the first");
|
||||
Equal(-1, f.Set("left_stick_dead_zone", -7), "a range below 0");
|
||||
Equal(-3, f.Set("frame_rate_cap", -3), "the cap's 30");
|
||||
|
||||
// (the preset sets its rows; a row not exempt changed by hand makes it Custom, an exempt one does not)
|
||||
f.Set("quality_preset", 4);
|
||||
foreach (var (k, v) in new Dictionary<string, int> { ["resolution"] = 1, ["upscaling"] = 2, ["sharpness"] = 40, ["frame_pacing"] = 1, ["game_speed"] = 1, ["handheld_profile"] = 0, ["texture_detail"] = 1 })
|
||||
Equal(v, f.Get(k), "High sets " + k);
|
||||
Equal("High (16GB)", f.Label("quality_preset"), "the preset's label");
|
||||
f.Set("fullscreen", 1);
|
||||
Equal(4, f.Get("quality_preset"), "an exempt row leaves the preset");
|
||||
f.Set("sharpness", 40);
|
||||
Equal(4, f.Get("quality_preset"), "the same value is no change");
|
||||
f.Set("sharpness", 60);
|
||||
Equal(0, f.Get("quality_preset"), "a scaling row by hand: Custom");
|
||||
// (with DLSS the preset's resolution is its nearest mode)
|
||||
f.Set("dlss", 1);
|
||||
f.Set("quality_preset", 2);
|
||||
Equal(3, f.Get("resolution"), "Low's 75% with DLSS: Quality (67%)");
|
||||
Equal(2, f.Get("texture_detail"), "Low: Reduced textures");
|
||||
f.Set("quality_preset", 1);
|
||||
Equal(4, f.Get("resolution"), "Minimum's 50% is DLSS's Performance");
|
||||
Equal(3, f.Get("texture_detail"), "Minimum: Low textures");
|
||||
Equal(1, f.Get("handheld_profile"), "Minimum: handheld profile");
|
||||
// (another Upscaler moves the resolution onto its steps)
|
||||
f.Set("dlss", 0);
|
||||
f.Set("resolution", 2);
|
||||
f.Set("dlss", 3);
|
||||
Equal(3, f.Get("resolution"), "75% with FSR 3.1: 67%");
|
||||
Equal(0, f.Get("quality_preset"), "the Upscaler is not exempt");
|
||||
|
||||
// (Apply: the preset first, then the rest by the same rules)
|
||||
var b = GameOptionsFile.Load(NewGameFolder("game-options-apply", OptionsFixture));
|
||||
var got = b.Apply(new Dictionary<string, int> { ["frame_generation"] = 2, ["quality_preset"] = 3, ["sharpness"] = 30 });
|
||||
Equal(3, got["quality_preset"], "a preset row at the preset's own value keeps the preset");
|
||||
Equal(2, got["frame_generation"], "frame generation set");
|
||||
Equal(1, b.Get("upscaling"), "Balanced: Catmull-Rom");
|
||||
var c = b.Apply(new Dictionary<string, int> { ["quality_preset"] = 5, ["sharpness"] = 80 });
|
||||
Equal(0, c["quality_preset"], "a preset row changed after it: Custom, as in the game");
|
||||
Equal(80, c["sharpness"], "and its value");
|
||||
var changes = b.Changes.Count;
|
||||
Throws<KeyNotFoundException>(() => b.Apply(new Dictionary<string, int> { ["vsync"] = 0, ["descriptor_reuse"] = 0 }), "a key that is no row");
|
||||
Equal(changes, b.Changes.Count, "nothing set then");
|
||||
Equal(1, b.Get("vsync"), "vsync untouched");
|
||||
b.Save();
|
||||
var back = GameOptionsFile.Load(Path.GetDirectoryName(b.Path)!);
|
||||
Equal(80, back.Get("sharpness"), "saved");
|
||||
Equal(2, back.Get("frame_generation"), "saved");
|
||||
Equal(0, back.Changes.Count, "a fresh read has no changes");
|
||||
}
|
||||
|
||||
static void GameOptionsOldVersion()
|
||||
{
|
||||
// (options_version 5: Frame pacing's and Start next frame early's old off defaults, Ultrawide's 1 the monitor's shape)
|
||||
var g = NewGameFolder("game-options-v5", "frame_pacing=0\r\nultrawide=1\r\nnvidia_reflex=0\r\nsharpness=20\r\noptions_version=5\r\npad_a=0\r\n");
|
||||
var f = GameOptionsFile.Load(g, (2560, 1080));
|
||||
Equal(5, f.Version, "version");
|
||||
Equal(1, f.Get("frame_pacing"), "pacing on, as the game reads a file before 7");
|
||||
Equal(2, f.Get("ultrawide"), "the monitor's shape at 2560x1080: 21:9");
|
||||
Equal(0, f.Get("nvidia_reflex"), "Reflex as saved from 5 on");
|
||||
Equal(0, GameOptionsFile.Load(g).Get("ultrawide"), "without the screen: 16:9, as the game where it cannot ask");
|
||||
f.Set("sharpness", 30);
|
||||
f.Save();
|
||||
Equal("frame_pacing=1\r\nultrawide=2\r\nnvidia_reflex=0\r\nsharpness=30\r\noptions_version=7\r\npad_a=0\r\n",
|
||||
File.ReadAllText(Path.Combine(g, GameOptionsSchema.FileName)).Replace("tail_early=1\r\n", ""), "brought up to 7 as the game would read it");
|
||||
Check(File.ReadAllText(Path.Combine(g, GameOptionsSchema.FileName)).Contains("tail_early=1\r\noptions_version=7"), "the Debug tab's tail_early too, before the version");
|
||||
var again = GameOptionsFile.Load(g);
|
||||
Equal(7, again.Version, "now 7");
|
||||
again.Set("frame_pacing", 0);
|
||||
again.Save();
|
||||
Equal(0, GameOptionsFile.Load(g).Get("frame_pacing"), "and from 7 on the choice is read as it is");
|
||||
|
||||
// (no options_version line: Game speed real time; no resolution line but the old dynamic_resolution)
|
||||
var o = NewGameFolder("game-options-v0", "game_speed=0\ndynamic_resolution=0\n");
|
||||
var of = GameOptionsFile.Load(o);
|
||||
Equal(1, of.Get("game_speed"), "the old default real time");
|
||||
Equal(1, of.Get("resolution"), "dynamic_resolution 0: 100%");
|
||||
Equal(2, of.Get("nvidia_reflex"), "Reflex On + Boost before 5");
|
||||
|
||||
// (no file: the defaults; a Save makes it with the changed rows and the version)
|
||||
var n = Path.Combine(NewRoot("game-options-new"), "game");
|
||||
Directory.CreateDirectory(n);
|
||||
var nf = GameOptionsFile.Load(n);
|
||||
Check(!nf.Exists, "no file");
|
||||
Equal(1, nf.Get("vsync"), "default");
|
||||
Equal("Off", nf.Label("fullscreen"), "default label");
|
||||
nf.Save();
|
||||
Check(!File.Exists(nf.Path), "nothing to write: no file made");
|
||||
nf.Set("vsync", 0);
|
||||
nf.Set("master_volume", 83);
|
||||
nf.Save();
|
||||
var nl = OperatingSystem.IsWindows() ? "\r\n" : "\n";
|
||||
Equal("vsync=0" + nl + "master_volume=85" + nl + "options_version=7" + nl, File.ReadAllText(nf.Path), "a new file: the rows in the menu's order, then the version");
|
||||
Check(nf.Exists, "now there");
|
||||
}
|
||||
}
|
||||
303
launcher/LogicTests/Tests.Release.cs
Normal file
303
launcher/LogicTests/Tests.Release.cs
Normal file
@@ -0,0 +1,303 @@
|
||||
using System.IO.Compression;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Triforce.Logic;
|
||||
using static Triforce.LogicTests.T;
|
||||
|
||||
namespace Triforce.LogicTests;
|
||||
|
||||
static partial class Tests
|
||||
{
|
||||
const string Notes = "Triforce v0.5.2 brings these:\n\n**Faster updates.** The tools come in two parts now.\n* **Mods page.** GameBanana's mods in the launcher, with `kits`.\n" +
|
||||
"**A new look.** The launcher is [rebuilt](https://example.invalid).\n**A fourth one.** Not shown.\n\n## Fixes\n* one\n";
|
||||
|
||||
/// <summary>A Forgejo answer: a list of one release whose assets each carry a nested uploader object.</summary>
|
||||
static string ReleaseJson(string server, string tag, IEnumerable<(string Name, long Size)> assets, string body = Notes)
|
||||
{
|
||||
var list = string.Join(",", assets.Select((a, i) =>
|
||||
"{\"id\":" + (100 + i) + ",\"name\":\"" + a.Name + "\",\"size\":" + a.Size + ",\"download_count\":3,\"uploader\":{\"id\":1,\"login\":\"triforce\",\"assets\":[]}," +
|
||||
"\"browser_download_url\":\"" + server + "/assets/" + a.Name + "\"}"));
|
||||
return "[{\"id\":17,\"tag_name\":\"" + tag + "\",\"name\":\"Triforce " + tag + "\",\"prerelease\":true,\"html_url\":\"" + server + "/release\",\"published_at\":\"2026-11-19T10:00:00Z\"," +
|
||||
"\"body\":" + System.Text.Json.JsonSerializer.Serialize(body) + ",\"assets\":[" + list + "]}]";
|
||||
}
|
||||
|
||||
static async Task ReleaseCheck()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var root = NewRoot("release");
|
||||
var setup = Encoding.ASCII.GetBytes("new setup");
|
||||
s.Add("/api/releases", ReleaseJson(s.Url, "v0.5.2", new[] { ("TriforceSetup.exe", (long)setup.Length), ("triforce-tools.ZIP", 1234L), ("Triforce-Tools-code.zip", 12L),
|
||||
("Triforce-Tools-base.zip", 34L), ("Triforce-v0.5.2-linux-test-x86_64.AppImage", 99L), ("other.txt", 1L) }));
|
||||
var ctx = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/api/releases" });
|
||||
using var http = Downloader.CreateHttp();
|
||||
var r = await new Updater(ctx).CheckAsync(http, CancellationToken.None);
|
||||
Equal("v0.5.2", r.Tag, "tag");
|
||||
Equal(s.Url + "/assets/TriforceSetup.exe", r.SetupUrl, "setup url");
|
||||
Equal((long)setup.Length, r.SetupSize, "setup size");
|
||||
Equal(1234L, r.ToolsSize, "tools matched without case");
|
||||
Check(r.ToolsCodeUrl != null && r.ToolsBaseSize == 34, "parts");
|
||||
Check(r.LinuxAppImageUrl != null && r.LinuxListUrl == null, "the AppImage; no linux list (none published)");
|
||||
Check(r.Prerelease && r.PageUrl == s.Url + "/release", "page and prerelease");
|
||||
var newIn = r.NewIn;
|
||||
Equal(3, newIn.Count, "three New in items");
|
||||
Equal("Faster updates", newIn[0].Title, "title without its dot");
|
||||
Equal("The tools come in two parts now.", newIn[0].Text, "its line");
|
||||
Equal("GameBanana's mods in the launcher, with kits.", newIn[1].Text, "markdown out");
|
||||
Equal("The launcher is rebuilt.", newIn[2].Text, "link text kept");
|
||||
var bullets = ReleaseNotes.NewIn("Intro\n\n* First fix\n* **Second.** two\n- third\n- fourth");
|
||||
Equal("First fix|Second|third", string.Join("|", bullets.Select(b => b.Title)), "fallback: the first bullets");
|
||||
// (404: no release yet)
|
||||
var none = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/missing" });
|
||||
await ThrowsAsync<NoReleaseException>(() => Release.LatestAsync(none, http, CancellationToken.None), "404");
|
||||
s.Add("/empty", "[]");
|
||||
var empty = Ctx(root, env: new() { ["TRIFORCE_RELEASE_API"] = s.Url + "/empty" });
|
||||
await ThrowsAsync<NoReleaseException>(() => Release.LatestAsync(empty, http, CancellationToken.None), "an empty list");
|
||||
var single = Release.Parse("{\"tag_name\":\"v1\",\"assets\":[]}");
|
||||
Equal("v1", single.Tag, "a single release object");
|
||||
}
|
||||
|
||||
static async Task DownloadResume()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var root = NewRoot("download");
|
||||
var ctx = Ctx(root);
|
||||
var data = RandomNumberGenerator.GetBytes(3_000_000);
|
||||
s.Add("/assets/big.bin", data);
|
||||
using var http = Downloader.CreateHttp();
|
||||
var file = Path.Combine(root, "downloads", "big.bin");
|
||||
var seen = new List<DownloadProgress>();
|
||||
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", file, data.Length, p => seen.Add(p), CancellationToken.None);
|
||||
Check(File.ReadAllBytes(file).SequenceEqual(data), "the file whole");
|
||||
Check(seen.Count > 0 && seen[^1].Fraction == 1, "progress to 1");
|
||||
Check(!File.Exists(file + ".part") && !File.Exists(file + ".part.of"), "no part left");
|
||||
// (the size the release lists is not what the server sends: refused before a byte is kept)
|
||||
var bad = Path.Combine(root, "downloads", "bad.bin");
|
||||
await ThrowsAsync<IOException>(() => new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", bad, data.Length + 5, null, CancellationToken.None), "a size that contradicts the release");
|
||||
Check(!File.Exists(bad), "nothing kept");
|
||||
// (a part from a cut download goes on from where it stopped: Range + If-Range)
|
||||
var resumed = Path.Combine(root, "downloads", "resumed.bin");
|
||||
File.WriteAllBytes(resumed + ".part", data.AsSpan(0, 1_000_000).ToArray());
|
||||
File.WriteAllLines(resumed + ".part.of", new[] { s.Url + "/assets/big.bin", data.Length.ToString(), "\"v" + data.Length + "\"" });
|
||||
long first = -1;
|
||||
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", resumed, data.Length, p => { if (first < 0) first = p.Bytes; }, CancellationToken.None);
|
||||
Check(File.ReadAllBytes(resumed).SequenceEqual(data), "resumed file whole");
|
||||
Equal(1_000_000L, first, "it went on from the part");
|
||||
// (a part whose note names another address is fetched anew)
|
||||
var other = Path.Combine(root, "downloads", "other.bin");
|
||||
File.WriteAllBytes(other + ".part", new byte[] { 1, 2, 3 });
|
||||
File.WriteAllLines(other + ".part.of", new[] { "https://elsewhere.invalid/x", data.Length.ToString(), "\"x\"" });
|
||||
await new Downloader(ctx).ToFileAsync(http, s.Url + "/assets/big.bin", other, data.Length, null, CancellationToken.None);
|
||||
Check(File.ReadAllBytes(other).SequenceEqual(data), "a foreign part was not joined on");
|
||||
}
|
||||
|
||||
/// <summary>An installed launcher in a test root that can run: this program's files beside a TriforceSetup.exe that says "OLD".</summary>
|
||||
static (TriforceContext Ctx, string Dir, string Root) InstalledRoot(string name)
|
||||
{
|
||||
var root = NewRoot(name);
|
||||
var dir = Path.Combine(root, "Programs", "Triforce");
|
||||
CopySelf(dir, "copy-of-tests.exe");
|
||||
File.WriteAllText(Path.Combine(dir, BuildInfo.SetupAsset), "OLD");
|
||||
var ctx = Ctx(root, Path.Combine(dir, BuildInfo.SetupAsset));
|
||||
ctx.Platform.Settings.SetUninstall("InstallLocation", dir);
|
||||
return (ctx, dir, root);
|
||||
}
|
||||
|
||||
static async Task<Release> ServeNewSetup(FakeServer s, string tag)
|
||||
{
|
||||
var bytes = SelfBytes;
|
||||
s.Add("/assets/TriforceSetup.exe", bytes);
|
||||
s.Add("/api", ReleaseJson(s.Url, tag, new[] { ("TriforceSetup.exe", (long)bytes.Length) }));
|
||||
await Task.CompletedTask;
|
||||
return Release.Parse(ReleaseJson(s.Url, tag, new[] { ("TriforceSetup.exe", (long)bytes.Length) }));
|
||||
}
|
||||
|
||||
static async Task SelfSwapUp()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var (ctx, dir, root) = InstalledRoot("selfswap-up");
|
||||
var r = await ServeNewSetup(s, "v9.0.0");
|
||||
var held = InstanceLock.TryTake(dir, root)!;
|
||||
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", root);
|
||||
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", "up");
|
||||
var hidden = false;
|
||||
try
|
||||
{
|
||||
using var http = Downloader.CreateHttp();
|
||||
var u = new Updater(ctx) { HandoverLimit = TimeSpan.FromSeconds(20) };
|
||||
var result = await u.SelfUpdateAsync(http, r, new StartArgs(), held, null, () => hidden = true, CancellationToken.None);
|
||||
Equal(SelfUpdateResult.CloseNow, result, "the old one closes");
|
||||
Check(hidden, "the window was hidden while it waited");
|
||||
Check(File.ReadAllBytes(Path.Combine(dir, BuildInfo.SetupAsset)).SequenceEqual(SelfBytes), "the new exe under the name");
|
||||
Equal("OLD", File.ReadAllText(Path.Combine(dir, "TriforceSetup.old.exe")), "the running one stepped aside");
|
||||
Check(!File.Exists(Path.Combine(dir, "TriforceSetup.new.exe")), "no .new left");
|
||||
Equal("--relaunched|--merge", File.ReadAllText(Path.Combine(root, "child-args.txt")), "started as an old Setup starts it");
|
||||
Check(ctx.Log.ReadAll().Contains("its window is up"), "it gave its sign: " + ctx.Log.ReadAll());
|
||||
Equal(null, ctx.Settings.SetupSkip, "nothing skipped");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
|
||||
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", null);
|
||||
held.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static async Task SelfSwapFails()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var (ctx, dir, root) = InstalledRoot("selfswap-fail");
|
||||
var r = await ServeNewSetup(s, "v9.0.1");
|
||||
var held = InstanceLock.TryTake(dir, root)!;
|
||||
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", root);
|
||||
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", "fail");
|
||||
try
|
||||
{
|
||||
using var http = Downloader.CreateHttp();
|
||||
var u = new Updater(ctx) { HandoverLimit = TimeSpan.FromSeconds(20) };
|
||||
var e = await ThrowsAsync<NotStartedException>(() => u.SelfUpdateAsync(http, r, new StartArgs { UpdateFolder = @"C:\G", Merge = true }, held, null, null, CancellationToken.None), "a new launcher that fails");
|
||||
Check(e.Message.Contains("is back in its place"), e.Message);
|
||||
Equal("OLD", File.ReadAllText(Path.Combine(dir, BuildInfo.SetupAsset)), "the old exe back under the name");
|
||||
Equal("v9.0.1", ctx.Settings.SetupSkip, "that tag is skipped from now on");
|
||||
Check(held.Held, "the lock taken again");
|
||||
Equal("--update|C:\\G|--relaunched", File.ReadAllText(Path.Combine(root, "child-args.txt")), "the game's folder passed on");
|
||||
Check(!new Updater(ctx).LauncherNewer(r), "a skipped (or dev) launcher is not newer");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Environment.SetEnvironmentVariable("LOGICTESTS_CHILD", null);
|
||||
Environment.SetEnvironmentVariable("TRIFORCE_TEST_ROOT", null);
|
||||
held.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
static void Decide()
|
||||
{
|
||||
var root = NewRoot("decide");
|
||||
var ctx = Ctx(root);
|
||||
var u = new Updater(ctx);
|
||||
var r = new Release { Tag = "v0.5.2", SetupUrl = "x", ToolsUrl = "y" };
|
||||
Equal(CheckOutcome.Merge, u.Decide(new StartArgs(), r, null).Outcome, "first start, nothing here: the tools come at once");
|
||||
Equal(CheckOutcome.Failed, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Outcome, "offline with nothing");
|
||||
Equal(FailureKind.Offline, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Failure!.Kind, "said as offline");
|
||||
Equal(FailureKind.Cancelled, u.Decide(new StartArgs(), null, new OperationCanceledException(), cancelled: true).Failure!.Kind, "cancelled");
|
||||
// (tools here)
|
||||
Directory.CreateDirectory(Path.Combine(ctx.ToolsFolder, "nx2"));
|
||||
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "nx2", "make_game.py"), "");
|
||||
File.WriteAllText(Path.Combine(ctx.ToolsFolder, "version.txt"), "v0.5.1\n");
|
||||
Equal(CheckOutcome.Home, u.Decide(new StartArgs(), r, null).Outcome, "with tools: Home");
|
||||
Equal(CheckOutcome.Merge, u.Decide(new StartArgs { Merge = true }, r, null).Outcome, "--merge: carries on");
|
||||
Equal(CheckOutcome.HomeOffline, u.Decide(new StartArgs(), null, new HttpRequestException("x")).Outcome, "offline with tools: Home");
|
||||
Check(u.ToolsNewer(r), "tools v0.5.1 behind v0.5.2");
|
||||
var game = Path.Combine(root, "Games", "Triforce");
|
||||
Directory.CreateDirectory(game);
|
||||
File.WriteAllText(Path.Combine(game, "Triforce.exe"), "");
|
||||
File.WriteAllText(Path.Combine(game, "triforce_version.txt"), "version=v0.5.0\n");
|
||||
ctx.Settings.GameFolder = game;
|
||||
var st = u.State(r);
|
||||
Check(st.ToolsNewer && st.GameBehind && !st.LauncherNewer && st.Any, "home's update state (a dev launcher never replaces itself)");
|
||||
var plan = u.Plan(new StartArgs { Merge = true }, r);
|
||||
Check(plan.Tools && plan.RebuildFolder == game && !plan.SelfUpdate, "merge plan: tools, then the game rebuilt");
|
||||
}
|
||||
|
||||
// ---- tools ----
|
||||
|
||||
static byte[] Zip(params (string Name, string Text)[] files)
|
||||
{
|
||||
using var m = new MemoryStream();
|
||||
using (var z = new ZipArchive(m, ZipArchiveMode.Create, true))
|
||||
foreach (var (name, text) in files)
|
||||
{
|
||||
var e = z.CreateEntry(name);
|
||||
if (!name.EndsWith('/')) using (var w = new StreamWriter(e.Open())) w.Write(text);
|
||||
}
|
||||
return m.ToArray();
|
||||
}
|
||||
|
||||
static string Sha(string text) => Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
|
||||
|
||||
static string BaseList(params (string Path, string Text)[] files) =>
|
||||
"triforce-tools-base\t1\nid\t" + Sha("base") + "\ndir\tpython\n" + string.Concat(files.Select(f => "file\t" + Encoding.UTF8.GetByteCount(f.Text) + "\t" + Sha(f.Text) + "\t" + f.Path + "\n"));
|
||||
|
||||
static void ToolsUnpack()
|
||||
{
|
||||
var root = NewRoot("tools");
|
||||
var ctx = Ctx(root);
|
||||
var tools = new Tools(ctx);
|
||||
var zip = Path.Combine(root, "t.zip");
|
||||
File.WriteAllBytes(zip, Zip(("tools/nx2/make_game.py", "print('x')"), ("tools/python/python.exe", "py"), ("tools/scripts/", ""),
|
||||
("tools/base.list", BaseList(("python/python.exe", "py")))));
|
||||
Directory.CreateDirectory(tools.Folder + ".part"); // (left by a cut-off unpacking)
|
||||
tools.Sweep();
|
||||
Check(!Directory.Exists(tools.Folder + ".part"), "sweep");
|
||||
double last = -1;
|
||||
tools.Unpack(zip, "v0.5.2", f => last = f);
|
||||
Equal("v0.5.2", tools.InstalledVersion, "version.txt written");
|
||||
Equal(1.0, last, "progress to 1");
|
||||
Check(File.Exists(Path.Combine(tools.Folder, "nx2", "make_game.py")) && Directory.Exists(Path.Combine(tools.Folder, "scripts")), "the prefix tools/ stripped");
|
||||
Equal(Sha("base"), File.ReadAllText(Path.Combine(tools.Folder, Tools.BaseHave)).Trim(), "base.have from the whole zip's list");
|
||||
var found = tools.Find()!;
|
||||
Equal(Path.Combine(tools.Folder, "python", "python.exe"), found.Python, "its own python");
|
||||
// (unsafe names: the whole zip refused, the tools there kept)
|
||||
foreach (var bad in new[] { "tools/../evil.txt", "tools/CON.txt", "tools/a:b", "tools/name. " })
|
||||
{
|
||||
File.WriteAllBytes(zip, Zip(("tools/nx2/make_game.py", "x"), (bad, "x")));
|
||||
Throws<InvalidDataException>(() => tools.Unpack(zip, "v9", null), "refused: " + bad);
|
||||
Equal("v0.5.2", tools.InstalledVersion, "the tools there kept after " + bad);
|
||||
}
|
||||
// (no tools in a test root without its own: never the development checkout above the test program)
|
||||
Equal(null, new Tools(Ctx(NewRoot("notools"))).Find(), "no dev-checkout fallback in a test run");
|
||||
}
|
||||
|
||||
static void ToolsParts()
|
||||
{
|
||||
Equal(null, Tools.ParseBaseList("triforce-tools-base\t1\nid\tabc\n"), "a short id is no list");
|
||||
Equal(null, Tools.ParseBaseList("triforce-tools-base\t1\nid\t" + Sha("x") + "\ndir\tpython\nfile\t1\t" + Sha("a") + "\ta\nwhat\tnow\n"), "an unknown line");
|
||||
var root = NewRoot("parts");
|
||||
var ctx = Ctx(root);
|
||||
var tools = new Tools(ctx);
|
||||
var list = BaseList(("python/python.exe", "py"), ("python/lib.txt", "library"));
|
||||
var b = Tools.ParseBaseList(list)!;
|
||||
Equal(2, b.Files.Count, "two base files");
|
||||
// (tools here with that base)
|
||||
Directory.CreateDirectory(Path.Combine(tools.Folder, "python"));
|
||||
Directory.CreateDirectory(Path.Combine(tools.Folder, "nx2"));
|
||||
File.WriteAllText(Path.Combine(tools.Folder, "python", "python.exe"), "py");
|
||||
File.WriteAllText(Path.Combine(tools.Folder, "python", "lib.txt"), "library");
|
||||
File.WriteAllText(Path.Combine(tools.Folder, "nx2", "make_game.py"), "old");
|
||||
File.WriteAllText(Path.Combine(tools.Folder, "version.txt"), "v0.5.1");
|
||||
Check(Tools.HasBase(b, tools.Folder, null), "the base is here (sha read)");
|
||||
Equal(b.Id, File.ReadAllText(Path.Combine(tools.Folder, Tools.BaseHave)).Trim(), "base.have remembered");
|
||||
var code = Path.Combine(root, "code.zip");
|
||||
File.WriteAllBytes(code, Zip(("tools/nx2/make_game.py", "new"), ("tools/base.list", list)));
|
||||
Equal(b.Id, Tools.BaseListIn(code)!.Id, "the code zip's list");
|
||||
tools.UnpackParts(code, null, b, "v0.5.2", null);
|
||||
Equal("v0.5.2", tools.InstalledVersion, "new version");
|
||||
Equal("new", File.ReadAllText(Path.Combine(tools.Folder, "nx2", "make_game.py")), "new code");
|
||||
Equal("library", File.ReadAllText(Path.Combine(tools.Folder, "python", "lib.txt")), "the base moved over");
|
||||
File.WriteAllText(Path.Combine(tools.Folder, "python", "lib.txt"), "changed!");
|
||||
Check(!Tools.HasBase(b, tools.Folder, null), "a changed base file (other size) is not the base");
|
||||
}
|
||||
|
||||
static async Task ToolsUpdate()
|
||||
{
|
||||
using var s = new FakeServer();
|
||||
var root = NewRoot("toolsupdate");
|
||||
var zip = Zip(("tools/nx2/make_game.py", "print('x')"), ("tools/python/python.exe", "py"));
|
||||
s.Add("/assets/Triforce-Tools.zip", zip);
|
||||
var r = Release.Parse(ReleaseJson(s.Url, "v0.5.2", new[] { ("Triforce-Tools.zip", (long)zip.Length) }));
|
||||
var ctx = Ctx(root);
|
||||
var inst = new ToolsInstaller(ctx);
|
||||
var steps = new List<ToolsStep>();
|
||||
inst.Progress += p => steps.Add(p.Step);
|
||||
Check(inst.Needed(r), "no tools: needed");
|
||||
using var http = Downloader.CreateHttp();
|
||||
await inst.UpdateAsync(http, r, CancellationToken.None);
|
||||
Equal("v0.5.2", new Tools(ctx).InstalledVersion, "tools installed");
|
||||
Check(steps.Contains(ToolsStep.Download) && steps.Contains(ToolsStep.Unpack) && steps[^1] == ToolsStep.Done, "progress steps: " + string.Join(",", steps));
|
||||
Check(Directory.GetFiles(ctx.DownloadsFolder).Length == 0, "the download cache emptied");
|
||||
Check(!inst.Needed(r), "up to date now");
|
||||
var n = s.Requests;
|
||||
await inst.UpdateAsync(http, r, CancellationToken.None);
|
||||
Equal(n, s.Requests, "nothing fetched when up to date");
|
||||
}
|
||||
}
|
||||
22
launcher/LogicTests/Triforce.LogicTests.csproj
Normal file
22
launcher/LogicTests/Triforce.LogicTests.csproj
Normal file
@@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!-- Triforce.Logic's own tests: a console program (exit 0 = all passed). Everything runs inside TRIFORCE_TEST_ROOT temp folders and
|
||||
a fake release server on 127.0.0.1; it never starts a real build or the real game, never touches the registry, the real
|
||||
shortcuts or Steam, and only reads D:\src\lab-game-merge98, D:\src\triforce-test-game and the NX2navi .nup.
|
||||
The exe doubles as the fakes it needs (Program.cs Fakes): a "python" that plays make_game.py's lines, and a new
|
||||
"TriforceSetup.exe" for the self-update. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>Triforce.LogicTests</AssemblyName>
|
||||
<RootNamespace>Triforce.LogicTests</RootNamespace>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Logic\Triforce.Logic.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
212
launcher/Tests/Program.cs
Normal file
212
launcher/Tests/Program.cs
Normal file
@@ -0,0 +1,212 @@
|
||||
// The launcher's test commands. One command per case below; others add theirs to the switch.
|
||||
//
|
||||
// gamefiles <nup-or-folder> <outdir> decode the title art and the sounds from a player's game, time it, and compare
|
||||
// with the reference files the lab's tools made
|
||||
// caption <caption.sav> <out.jpg> the JPEG of a save slot's caption.sav
|
||||
//
|
||||
// Output made from the game goes only where it is told to (the lab's scratch folder), never into the repository.
|
||||
using System.Diagnostics;
|
||||
using Triforce.Core.GameFiles;
|
||||
|
||||
if (args.Length == 0)
|
||||
{
|
||||
Console.WriteLine("usage: Triforce.Tests <command> ... (commands: gamefiles, caption)");
|
||||
return 2;
|
||||
}
|
||||
|
||||
switch (args[0])
|
||||
{
|
||||
case "gamefiles":
|
||||
return args.Length == 3 ? GameFilesTest.Run(args[1], args[2]) : Usage("gamefiles <nup-or-folder> <outdir>");
|
||||
case "caption":
|
||||
return args.Length == 3 ? GameFilesTest.CaptionTest(args[1], args[2]) : Usage("caption <caption.sav> <out.jpg>");
|
||||
default:
|
||||
Console.WriteLine("unknown command " + args[0]);
|
||||
return 2;
|
||||
}
|
||||
|
||||
static int Usage(string text)
|
||||
{
|
||||
Console.WriteLine("usage: Triforce.Tests " + text);
|
||||
return 2;
|
||||
}
|
||||
|
||||
static class GameFilesTest
|
||||
{
|
||||
const string ReferenceImages = @"D:\src\lab\hookshot\ui\launcher-rebuild\mockups\img\game";
|
||||
const string ReferenceAudio = @"D:\src\lab\hookshot\ui\launcher-rebuild\prototype\audio";
|
||||
|
||||
static double Ms(Stopwatch w) => w.Elapsed.TotalMilliseconds;
|
||||
|
||||
public static int Run(string game, string outDir)
|
||||
{
|
||||
Directory.CreateDirectory(outDir);
|
||||
var cache = Path.Combine(outDir, "cache");
|
||||
if (Directory.Exists(cache))
|
||||
Directory.Delete(cache, true);
|
||||
var failures = 0;
|
||||
|
||||
// ---- open ----
|
||||
var w = Stopwatch.StartNew();
|
||||
using var source = GameSource.Open(game);
|
||||
Console.WriteLine("open: {0:0.0} ms {1}", Ms(w), source.Describe);
|
||||
if (source is NupSource nup)
|
||||
foreach (var t in nup.Titles)
|
||||
Console.WriteLine(" title {0} v{1}", t.IdHex, t.Version);
|
||||
w.Restart();
|
||||
var exists = source.Exists(GameMedia.TitleArchive);
|
||||
Console.WriteLine("first lookup: {0:0.0} ms (title archive {1})", Ms(w), exists ? "found" : "MISSING");
|
||||
w.Restart();
|
||||
var streams = source.List("Sound/Resource/Stream").Count();
|
||||
Console.WriteLine("list Sound/Resource/Stream: {0} entries in {1:0.0} ms", streams, Ms(w));
|
||||
|
||||
// ---- cold: what a player waits for on the first start ----
|
||||
var media = new GameMedia(source, cache);
|
||||
w.Restart();
|
||||
foreach (var name in GameMedia.LogoSet)
|
||||
{
|
||||
var one = Stopwatch.StartNew();
|
||||
media.PngFile(name);
|
||||
Console.WriteLine(" {0,-20} {1,7:0.0} ms", name, Ms(one));
|
||||
}
|
||||
Console.WriteLine("cold: logo set (4 PNGs) {0:0.0} ms", Ms(w));
|
||||
w.Restart();
|
||||
media.WavFile("saria");
|
||||
Console.WriteLine("cold: Saria's Song (8 layers mixed) {0:0.0} ms", Ms(w));
|
||||
w.Restart();
|
||||
foreach (var id in GameMedia.Sounds.Keys.Where(k => k != "saria"))
|
||||
media.WavFile(id);
|
||||
Console.WriteLine("cold: the other 13 sounds {0:0.0} ms", Ms(w));
|
||||
|
||||
// ---- warm: a second start (a new instance, same cache) ----
|
||||
var again = new GameMedia(source, cache);
|
||||
w.Restart();
|
||||
foreach (var name in GameMedia.LogoSet)
|
||||
again.Png(name);
|
||||
Console.WriteLine("warm: logo set {0:0.0} ms", Ms(w));
|
||||
w.Restart();
|
||||
again.Wav("saria");
|
||||
Console.WriteLine("warm: Saria's Song {0:0.0} ms", Ms(w));
|
||||
|
||||
// ---- where the logo's time goes (decoded again, outside the cache) ----
|
||||
w.Restart();
|
||||
var zs = new Zs(source);
|
||||
_ = zs.Dictionaries.Count;
|
||||
Console.WriteLine(" breakdown: dictionaries {0:0.0} ms", Ms(w));
|
||||
w.Restart();
|
||||
var archive = new Bntx(zs.Unpack(GameMedia.TitleArchive));
|
||||
Console.WriteLine(" breakdown: title archive read + unpacked + parsed {0:0.0} ms", Ms(w));
|
||||
var logo = archive.Find("Logo_USEU_00")!;
|
||||
w.Restart();
|
||||
var rgba = archive.DecodeRgba(logo);
|
||||
Console.WriteLine(" breakdown: Logo_USEU_00 deswizzle + ASTC {0:0.0} ms", Ms(w));
|
||||
w.Restart();
|
||||
Png.Encode(rgba, logo.Width, logo.Height);
|
||||
Console.WriteLine(" breakdown: Logo_USEU_00 PNG {0:0.0} ms", Ms(w));
|
||||
|
||||
// ---- everything at once from several threads, into a fresh cache (a page asking for all of it) ----
|
||||
var cache2 = Path.Combine(outDir, "cache-parallel");
|
||||
if (Directory.Exists(cache2))
|
||||
Directory.Delete(cache2, true);
|
||||
var together = new GameMedia(source, cache2);
|
||||
var jobs = GameMedia.LogoSet.Select(n => (Action)(() => together.Png(n)))
|
||||
.Concat(GameMedia.Sounds.Keys.Select(id => (Action)(() => together.Wav(id))))
|
||||
.ToList();
|
||||
jobs.AddRange(jobs.ToList()); // (each item asked for twice at the same time)
|
||||
w.Restart();
|
||||
Parallel.Invoke(jobs.ToArray());
|
||||
var made = Directory.GetFiles(cache2).Length;
|
||||
Console.WriteLine("cold, all at once from {0} threads: {1:0.0} ms, {2} cache files (18 expected)", jobs.Count, Ms(w), made);
|
||||
if (made != 18)
|
||||
failures++;
|
||||
|
||||
// ---- the texture list (formats in the title archive) ----
|
||||
var formats = media.Textures().GroupBy(t => t.FormatName).Select(g => g.Key + " x" + g.Count());
|
||||
Console.WriteLine("title archive formats: " + string.Join(", ", formats));
|
||||
|
||||
// ---- write and compare ----
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("images (against {0}):", ReferenceImages);
|
||||
foreach (var name in GameMedia.LogoSet)
|
||||
{
|
||||
var png = media.Png(name);
|
||||
File.WriteAllBytes(Path.Combine(outDir, name + ".png"), png);
|
||||
var mine = Png.Decode(png);
|
||||
var refPath = Path.Combine(ReferenceImages, name + ".png");
|
||||
if (!File.Exists(refPath))
|
||||
{
|
||||
Console.WriteLine(" {0,-20} {1}x{2} (no reference)", name, mine.Width, mine.Height);
|
||||
continue;
|
||||
}
|
||||
var reference = Png.Decode(File.ReadAllBytes(refPath));
|
||||
if (reference.Width != mine.Width || reference.Height != mine.Height)
|
||||
{
|
||||
Console.WriteLine(" {0,-20} SIZE DIFFERS: {1}x{2}, reference {3}x{4}", name, mine.Width, mine.Height, reference.Width, reference.Height);
|
||||
failures++;
|
||||
continue;
|
||||
}
|
||||
int maxDiff = 0, pixelsDiffering = 0;
|
||||
for (var i = 0; i < mine.Rgba.Length; i += 4)
|
||||
{
|
||||
var d = 0;
|
||||
for (var c = 0; c < 4; c++)
|
||||
d = Math.Max(d, Math.Abs(mine.Rgba[i + c] - reference.Rgba[i + c]));
|
||||
if (d > 0)
|
||||
pixelsDiffering++;
|
||||
maxDiff = Math.Max(maxDiff, d);
|
||||
}
|
||||
Console.WriteLine(" {0,-20} {1}x{2} max channel difference {3}, {4} of {5} pixels differ ({6} KB)", name, mine.Width,
|
||||
mine.Height, maxDiff, pixelsDiffering, mine.Width * mine.Height, png.Length / 1024);
|
||||
if (maxDiff > 1)
|
||||
failures++;
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("sounds (against {0}):", ReferenceAudio);
|
||||
foreach (var id in GameMedia.Sounds.Keys)
|
||||
{
|
||||
var wav = media.Wav(id);
|
||||
File.WriteAllBytes(Path.Combine(outDir, id + ".wav"), wav);
|
||||
var mine = Bwav.FromWav(wav);
|
||||
var refPath = Path.Combine(ReferenceAudio, id + ".wav");
|
||||
if (!File.Exists(refPath))
|
||||
{
|
||||
Console.WriteLine(" {0,-9} {1} frames (no reference)", id, mine.Frames);
|
||||
continue;
|
||||
}
|
||||
var reference = Bwav.FromWav(File.ReadAllBytes(refPath));
|
||||
int maxDiff = 0, differing = 0;
|
||||
var n = Math.Min(mine.Samples.Length, reference.Samples.Length);
|
||||
for (var i = 0; i < n; i++)
|
||||
{
|
||||
var d = Math.Abs(mine.Samples[i] - reference.Samples[i]);
|
||||
if (d > 0)
|
||||
differing++;
|
||||
maxDiff = Math.Max(maxDiff, d);
|
||||
}
|
||||
var lengthOk = mine.Frames == reference.Frames && mine.Rate == reference.Rate;
|
||||
Console.WriteLine(" {0,-9} {1,8} frames {2,6:0.00} s reference {3,8} frames{4} peak {5}/{6} max sample difference {7}, {8} samples differ",
|
||||
id, mine.Frames, mine.Seconds, reference.Frames, lengthOk ? "" : " LENGTH DIFFERS", mine.Peak, reference.Peak, maxDiff, differing);
|
||||
if (!lengthOk || maxDiff > 1)
|
||||
failures++;
|
||||
}
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine(failures == 0 ? "all match" : failures + " item(s) differ");
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
public static int CaptionTest(string captionSav, string outJpg)
|
||||
{
|
||||
var jpeg = Caption.JpegFromFile(captionSav);
|
||||
if (jpeg == null)
|
||||
{
|
||||
Console.WriteLine("no JPEG in " + captionSav);
|
||||
return 1;
|
||||
}
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outJpg))!);
|
||||
File.WriteAllBytes(outJpg, jpeg);
|
||||
Console.WriteLine("{0}: JPEG of {1} bytes -> {2}", captionSav, jpeg.Length, outJpg);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
14
launcher/Tests/Triforce.Tests.csproj
Normal file
14
launcher/Tests/Triforce.Tests.csproj
Normal file
@@ -0,0 +1,14 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Core\Triforce.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
107
launcher/Triforce.Launcher.sln
Normal file
107
launcher/Triforce.Launcher.sln
Normal file
@@ -0,0 +1,107 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.31903.59
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{FBF56CC3-7AE6-AD2D-3F14-7F97FD322CD6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triforce.Core", "Core\Triforce.Core.csproj", "{F2AEC94A-D8D3-49A1-924C-E321B04521E4}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "App", "App", "{F95F473B-E98A-ACD6-1986-755F447BE36F}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triforce.Launcher", "App\Triforce.Launcher.csproj", "{0FF12479-60D5-4DA9-894A-347A091A189B}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triforce.Tests", "Tests\Triforce.Tests.csproj", "{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Logic", "Logic", "{B68C8C56-9D20-6463-44D5-977C364AEFA8}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triforce.Logic", "Logic\Triforce.Logic.csproj", "{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "LogicTests", "LogicTests", "{C3750C64-1198-3C82-7F6F-1BC757EB312B}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Triforce.LogicTests", "LogicTests\Triforce.LogicTests.csproj", "{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4}.Release|x86.Build.0 = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B}.Release|x86.Build.0 = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|x64.Build.0 = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9}.Release|x86.Build.0 = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|x64.Build.0 = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110}.Release|x86.Build.0 = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{F2AEC94A-D8D3-49A1-924C-E321B04521E4} = {FBF56CC3-7AE6-AD2D-3F14-7F97FD322CD6}
|
||||
{0FF12479-60D5-4DA9-894A-347A091A189B} = {F95F473B-E98A-ACD6-1986-755F447BE36F}
|
||||
{077DCD0E-E420-4AB9-9D96-D490D1FE6DA9} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{2DFF2E8F-EABF-4A9D-9B7A-95AB9663B110} = {B68C8C56-9D20-6463-44D5-977C364AEFA8}
|
||||
{32A0740A-8108-4B1D-8D5E-EFCB6CB2D0BC} = {C3750C64-1198-3C82-7F6F-1BC757EB312B}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
44
launcher/build.ps1
Normal file
44
launcher/build.ps1
Normal file
@@ -0,0 +1,44 @@
|
||||
# Builds the Triforce launcher: one self-contained file per system.
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File launcher\build.ps1 -Version v0.6.0 [-Rid win-x64|linux-x64|all]
|
||||
# Output: launcher\out\TriforceSetup.exe (Windows; the release asset old installs update onto) and launcher\out\triforce-launcher (Linux).
|
||||
param([string]$Version = 'dev', [string]$Rid = 'all', [string]$Dotnet = 'D:\src\tools\dotnet\dotnet.exe')
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path; $repo = Split-Path -Parent $here
|
||||
$gen = Join-Path $here 'App\obj\gen'; New-Item -ItemType Directory -Force $gen | Out-Null
|
||||
$env:DOTNET_CLI_TELEMETRY_OPTOUT = '1'; $env:DOTNET_NOLOGO = '1'
|
||||
|
||||
# ---- the icon: our crest (assets\triforce.png) centred in a square, PNG entries 16..256 (as setup\build.ps1) ----
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
function Square([System.Drawing.Image]$src, [int]$s) {
|
||||
$b = New-Object System.Drawing.Bitmap $s, $s, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [System.Drawing.Graphics]::FromImage($b); $g.InterpolationMode = 'HighQualityBicubic'; $g.PixelOffsetMode = 'HighQuality'
|
||||
$k = [math]::Min($s / $src.Width, $s / $src.Height); $w = $src.Width * $k; $h = $src.Height * $k
|
||||
$g.DrawImage($src, [single](($s - $w) / 2), [single](($s - $h) / 2), [single]$w, [single]$h); $g.Dispose(); return $b
|
||||
}
|
||||
$crest = [System.Drawing.Image]::FromFile((Join-Path $repo 'assets\triforce.png'))
|
||||
$sizes = 16, 20, 24, 32, 40, 48, 64, 96, 128, 256
|
||||
$pngs = foreach ($s in $sizes) { $ms = New-Object IO.MemoryStream; (Square $crest $s).Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); , $ms.ToArray() }
|
||||
(Square $crest 256).Save((Join-Path $gen 'triforce.png'), [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$ico = New-Object IO.MemoryStream; $bw = New-Object IO.BinaryWriter $ico
|
||||
$bw.Write([uint16]0); $bw.Write([uint16]1); $bw.Write([uint16]$sizes.Count); $off = 6 + 16 * $sizes.Count
|
||||
for ($i = 0; $i -lt $sizes.Count; $i++) { $s = $sizes[$i]; $d = if ($s -ge 256) { 0 } else { $s }
|
||||
$bw.Write([byte]$d); $bw.Write([byte]$d); $bw.Write([byte]0); $bw.Write([byte]0); $bw.Write([uint16]1); $bw.Write([uint16]32)
|
||||
$bw.Write([uint32]$pngs[$i].Length); $bw.Write([uint32]$off); $off += $pngs[$i].Length }
|
||||
foreach ($p in $pngs) { $bw.Write($p) }; $bw.Flush(); [IO.File]::WriteAllBytes((Join-Path $gen 'triforce.ico'), $ico.ToArray()); $crest.Dispose()
|
||||
|
||||
# ---- publish ----
|
||||
$out = Join-Path $here 'out'; New-Item -ItemType Directory -Force $out | Out-Null
|
||||
$numeric = if ($Version -match '(\d+)\.(\d+)\.(\d+)') { "$($Matches[1]).$($Matches[2]).$($Matches[3])" } else { '0.0.0' }
|
||||
$common = @('-c', 'Release', "-p:Version=$numeric", "-p:InformationalVersion=$Version", "-p:TriforceVersion=$Version", '-nowarn:MSB3277', '-v', 'q')
|
||||
if ($Rid -in 'all', 'win-x64') {
|
||||
& $Dotnet publish (Join-Path $here 'App\Triforce.Launcher.csproj') -f net10.0-windows -r win-x64 -o (Join-Path $out 'win') @common
|
||||
if ($LASTEXITCODE) { throw 'windows publish failed' }
|
||||
Copy-Item (Join-Path $out 'win\TriforceSetup.exe') $out -Force
|
||||
}
|
||||
if ($Rid -in 'all', 'linux-x64') {
|
||||
& $Dotnet publish (Join-Path $here 'App\Triforce.Launcher.csproj') -f net10.0 -r linux-x64 -o (Join-Path $out 'linux') @common
|
||||
if ($LASTEXITCODE) { throw 'linux publish failed' }
|
||||
Copy-Item (Join-Path $out 'linux\triforce-launcher') $out -Force
|
||||
Copy-Item (Join-Path $gen 'triforce.png') (Join-Path $out 'triforce.png') -Force
|
||||
}
|
||||
Get-ChildItem $out -File | ForEach-Object { '{0,-24} {1,8:N1} MB' -f $_.Name, ($_.Length / 1MB) }
|
||||
129
launcher/ui/app.css
Normal file
129
launcher/ui/app.css
Normal file
@@ -0,0 +1,129 @@
|
||||
/* The launcher's own additions on top of the approved look (v3.css) and the prototype's interaction styles (proto.css). */
|
||||
|
||||
/* no game read yet: no game art anywhere (the crest stands in on the working screens) */
|
||||
.noart .gamelogo, .noart .rlogo .aura, .noart .rlogo .glowl, .noart .mini .aura, .noart .logo .aura { display: none; }
|
||||
.noart .mini { background: url(img/crest.png) center / 92px no-repeat; }
|
||||
.gamelogo[src=""] { visibility: hidden; }
|
||||
|
||||
/* the bar with nothing to show (benchmark run) */
|
||||
.bar.bare { display: none; }
|
||||
|
||||
/* off buttons: visible, quiet, and they say why when pressed (the launcher sends a toast) */
|
||||
.play.off { filter: grayscale(.85) brightness(.6); cursor: not-allowed; }
|
||||
.row-set.off { opacity: .5; }
|
||||
.row-set.danger b, .row-set.danger em { color: #ff8a92; }
|
||||
|
||||
/* the reveal's choice rows can be 2 or 3 (NVIDIA: DLSS) */
|
||||
.choices { display: grid; gap: 0 40px; }
|
||||
.choices > div.bad b, .choices > div.bad small { color: #ff8a92; }
|
||||
|
||||
/* the working screen */
|
||||
.workfoot { position: absolute; left: 64px; bottom: 26px; font-size: 13.5px; color: var(--text3); }
|
||||
.workfoot .lnk { color: var(--gold); }
|
||||
.workerr { position: absolute; left: 230px; width: 820px; top: 470px; text-align: center; }
|
||||
.workerr p { margin-top: 18px; font-size: 14px; color: var(--text3); } .workerr .lnk { color: var(--gold); }
|
||||
#s-work.failed .center h1 { color: #ffd6d9; }
|
||||
#s-work.failed .nowmusic, #s-work.failed .workfoot { display: none; }
|
||||
.drawer { position: absolute; left: 0; right: 0; bottom: 0; height: 0; overflow: hidden; z-index: 12; background: rgba(8, 7, 6, .97);
|
||||
border-top: 1px solid rgba(224, 178, 62, .4); transition: height .25s ease; }
|
||||
.drawer.open { height: 330px; }
|
||||
.drawer .dhead { display: flex; gap: 22px; align-items: baseline; padding: 14px 64px 8px; font-size: 14px; }
|
||||
.drawer .dhead b { flex: 1; font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-size: 19px; color: var(--gold-hi); }
|
||||
.drawer .dhead .lnk { color: var(--gold); cursor: pointer; }
|
||||
.drawer pre { margin: 0 64px; height: 270px; overflow: auto; font: 12.5px/1.45 'Cascadia Mono', Consolas, 'DejaVu Sans Mono', monospace; color: var(--text2); white-space: pre-wrap; }
|
||||
|
||||
/* sheets: lists to choose from and questions */
|
||||
.opts.many { display: grid; grid-template-columns: 1fr 1fr; gap: 0 10px; max-height: 420px; overflow: auto; }
|
||||
.opts.many .opt:first-of-type, .opts.many .opt:nth-of-type(2) { margin-top: 18px; }
|
||||
.opt.sel > span:last-child::before { content: '\25C6'; color: var(--gold-hi); }
|
||||
.asktext { margin-top: 12px; max-height: 360px; overflow: auto; font-size: 14px; color: var(--text2); line-height: 1.5; }
|
||||
.asktext p + p { margin-top: 8px; }
|
||||
.sheet { width: 600px; }
|
||||
|
||||
/* saves */
|
||||
.sc.empty .p { display: grid; place-items: center; background: rgba(10, 9, 8, .45); }
|
||||
.sc.empty .p span { font-family: 'Cormorant Garamond', Georgia, serif; font-style: italic; font-size: 18px; color: var(--text3); }
|
||||
|
||||
/* mods */
|
||||
.modtabs { position: absolute; left: 64px; top: 170px; display: flex; gap: 26px; font-size: 15px; color: var(--text3); }
|
||||
.modtabs span { padding-bottom: 6px; cursor: pointer; } .modtabs span.on { color: var(--gold-hi); font-weight: 600; box-shadow: inset 0 -2px 0 var(--gold); }
|
||||
.search { left: auto !important; right: 64px; top: 160px !important; width: 360px !important; padding: 0 !important; }
|
||||
.search input { width: 100%; height: 100%; padding: 0 14px; border: 0; outline: 0; background: transparent; color: var(--text); font: inherit; font-size: 14.5px; }
|
||||
.search input::placeholder { color: var(--text3); }
|
||||
.mods { top: 222px !important; max-height: 500px; overflow-y: auto; align-content: start; }
|
||||
.mods::-webkit-scrollbar { width: 6px; } .mods::-webkit-scrollbar-thumb { background: rgba(224, 178, 62, .35); }
|
||||
.mod { grid-template-columns: 64px 1fr auto !important; gap: 14px; }
|
||||
.mod .mi { width: 64px; height: 40px; background-size: cover; background-position: center; outline: 1px solid rgba(224, 178, 62, .3); }
|
||||
.mod .mi.none { background: rgba(255, 255, 255, .04); }
|
||||
.mod em.offm { color: var(--text3); }
|
||||
.mod.more b { color: var(--gold); }
|
||||
.modnote { position: absolute; left: 64px; right: 64px; bottom: 26px; font-size: 13.5px; color: var(--text2); }
|
||||
.modnote b { color: var(--gold-hi); }
|
||||
|
||||
/* home with no save yet: no picture, the title alone */
|
||||
#s-home.nopic .frame, #s-home.nopic .glow { display: none; }
|
||||
|
||||
/* in the real window: the bar is the title bar */
|
||||
.bar { app-region: drag; -webkit-app-region: drag; }
|
||||
.bar .nav a, .bar .state, .bar .spk, .bar .wc span { app-region: no-drag; -webkit-app-region: no-drag; }
|
||||
.nochrome .wc { display: none; }
|
||||
.hosted #protonote, .hosted #jump { display: none; }
|
||||
.choices > div > div { min-width: 0; flex: 1; }
|
||||
.choices b { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.choices small { display: block; margin: 2px 0 0 !important; }
|
||||
.choices .ch { flex: none; margin-left: 18px; }
|
||||
.found4 { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 1100px; left: 90px; right: 90px; }
|
||||
.choices label { white-space: nowrap; }
|
||||
.choices > div { padding: 16px 22px; }
|
||||
|
||||
/* settings: a long value (a folder) keeps to its column */
|
||||
.row-set > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
/* mods: a description keeps its paragraphs */
|
||||
.asktext.modesc { white-space: pre-line; }
|
||||
.whatsnew h4 .lnk { font-family: Commissioner, sans-serif; font-style: normal; font-size: 13px; color: var(--gold); margin-left: 4px; }
|
||||
.sheet:has(.opts.many) { width: 720px; }
|
||||
.opts.many .opt { padding: 12px 14px; }
|
||||
.opt > div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
/* a long text in a sheet scrolls with the launcher's own thin bar, not the system's */
|
||||
.asktext::-webkit-scrollbar { width: 6px; } .asktext::-webkit-scrollbar-thumb { background: rgba(224, 178, 62, .35); }
|
||||
.asktext::-webkit-scrollbar-button { display: none; } .asktext { padding-right: 10px; }
|
||||
/* settings: the list scrolls inside the page (it is longer than the window) */
|
||||
.set { max-height: 572px; overflow-y: auto; padding-right: 14px; }
|
||||
.set::-webkit-scrollbar { width: 6px; } .set::-webkit-scrollbar-thumb { background: rgba(224, 178, 62, .35); }
|
||||
.opts.grid::-webkit-scrollbar { width: 6px; } .opts.grid::-webkit-scrollbar-thumb { background: rgba(224, 178, 62, .35); }
|
||||
/* (Cormorant's old-style figures read "1" as "ı": lining figures everywhere) */
|
||||
body { font-variant-numeric: lining-nums; }
|
||||
/* Mods: the tabs under the title, not over it */
|
||||
.modtabs { top: 216px !important; }
|
||||
.search { top: 206px !important; }
|
||||
.mods { top: 268px !important; max-height: 470px !important; }
|
||||
.whatsnew p { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 440px; }
|
||||
/* benchmark places without a picture of their own: the hall's warm dark, the name carries it */
|
||||
.place.noimg { background: radial-gradient(120% 140% at 30% 0%, #2a2112 0%, #15110b 60%, #0a0908 100%); }
|
||||
.place.noimg::after { background: none; }
|
||||
/* Settings: Launcher and the game's own tabs */
|
||||
.settabs { position: absolute; left: 64px; top: 196px; display: flex; gap: 26px; font-size: 15px; color: var(--text3); }
|
||||
.settabs span { padding-bottom: 6px; cursor: pointer; } .settabs span.on { color: var(--gold-hi); font-weight: 600; box-shadow: inset 0 -2px 0 var(--gold); }
|
||||
#s-settings .set { top: 246px !important; max-height: 520px !important; overflow-y: auto; padding-right: 12px; }
|
||||
.gnote { font-size: 13px; color: var(--text3); margin: 0 0 4px; }
|
||||
.row-set.gs .slider { width: 260px; }
|
||||
.row-set .gval { min-width: 110px; display: inline-block; }
|
||||
#s-settings .benchcard { top: 246px; }
|
||||
.dot.grey { background: #8a8578; box-shadow: none; }
|
||||
/* benchmark: running, and the results' frame-time lines */
|
||||
.brun .bline { margin-top: 10px; font-size: 18px; color: var(--text); }
|
||||
.brun .bhint { margin-top: 8px; font-size: 14px; color: var(--text2); max-width: 720px; }
|
||||
.place .pg { position: absolute; left: 14px; right: 14px; top: 12px; height: 46px; z-index: 1; }
|
||||
.spark { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
|
||||
.spark polyline { fill: none; stroke: var(--gold); stroke-width: 1.6; vector-effect: non-scaling-stroke; }
|
||||
.spark.b polyline { stroke: var(--emerald); }
|
||||
.spark .l60 { stroke: rgba(243, 234, 213, .25); stroke-dasharray: 4 4; vector-effect: non-scaling-stroke; }
|
||||
.place .vs { font-style: normal; color: var(--emerald); } .place .vs strong { color: var(--emerald); }
|
||||
.place.two { height: 150px; }
|
||||
.place > div.two { display: grid; grid-template-columns: 1fr; gap: 2px; align-items: end; }
|
||||
.place > div.two b { margin-bottom: 4px; }
|
||||
.place > div.two span { display: flex; align-items: baseline; gap: 6px; }
|
||||
.place > div.two span i { font-style: normal; font-size: 12.5px; color: var(--text3); min-width: 96px; }
|
||||
.place.two .pg { height: 40px; }
|
||||
.recs .compare { margin-top: 14px; width: 100%; }
|
||||
.recs .act .qlink { white-space: nowrap; }
|
||||
562
launcher/ui/app.js
Normal file
562
launcher/ui/app.js
Normal file
@@ -0,0 +1,562 @@
|
||||
/* Triforce launcher: the page. It draws, plays the sounds and takes the mouse, keyboard and controller; everything real
|
||||
(reading the game, building, updating, saves, mods, settings) is the launcher's, behind messages:
|
||||
|
||||
page -> launcher {t:'ready'} {t:'win', a:'min'|'max'|'close'} {t:'pick', kind:'file'|'folder'} {t:'drop', files:[file:// on Linux]}
|
||||
{t:'cmd', c:<name>, ...args} (build, stop, retry, play, update, playold, showgame, open, lang, folder, setting,
|
||||
saves.import, saves.export, saves.open, mods.*, bench, benchstop, benchapply,
|
||||
report, sound, workback, ...)
|
||||
launcher -> page {t:'hello', chrome, os} {t:'state', ...parts} {t:'go', s} {t:'check', st, name, msg}
|
||||
{t:'work', ...} {t:'log', lines} {t:'toast', html} {t:'sfx', id} {t:'bench', ...} {t:'max', on}
|
||||
|
||||
Without a launcher (a plain browser) demo.js answers instead, so the design can be looked at anywhere. */
|
||||
'use strict';
|
||||
const $ = (s, r = document) => r.querySelector(s), $$ = (s, r = document) => [...r.querySelectorAll(s)];
|
||||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
|
||||
/* ---------------- the window this page lives in ---------------- */
|
||||
const HOST = window.chrome && window.chrome.webview ? 'win' : (window.external && typeof window.external.sendMessage === 'function' ? 'linux' : null);
|
||||
const hostHandlers = [];
|
||||
function onHost(fn) { hostHandlers.push(fn); }
|
||||
function fromHost(s) { let m; try { m = typeof s === 'string' ? JSON.parse(s) : s; } catch { return; } hostHandlers.forEach(f => { try { f(m); } catch (e) { console.error(e); } }); }
|
||||
function send(o) {
|
||||
const s = JSON.stringify(o);
|
||||
if (HOST === 'win') window.chrome.webview.postMessage(s);
|
||||
else if (HOST === 'linux') window.external.sendMessage(s);
|
||||
else if (window.DEMO) window.DEMO.receive(o, fromHost);
|
||||
}
|
||||
function cmd(c, args) { send(Object.assign({ t: 'cmd', c }, args || {})); }
|
||||
if (HOST === 'win') window.chrome.webview.addEventListener('message', e => fromHost(e.data));
|
||||
else if (HOST === 'linux') window.external.receiveMessage(fromHost);
|
||||
document.documentElement.classList.add(HOST ? 'hosted' : 'browser', 'noart'); // (no game art until the launcher says there is)
|
||||
if (HOST) document.documentElement.classList.add('host-' + HOST);
|
||||
window.addEventListener('error', e => send({ t: 'log', s: 'page error: ' + e.message + ' @' + e.lineno }));
|
||||
|
||||
/* ---------------- fit the 1280x800 design into the window ---------------- */
|
||||
function fit() { const k = Math.min(innerWidth / 1280, innerHeight / 800); $('#fit').style.transform = `translate(-50%,-50%) scale(${k})`; }
|
||||
addEventListener('resize', fit); fit();
|
||||
|
||||
/* ---------------- the launcher's state, as last sent ---------------- */
|
||||
const S = { media: { art: false, music: false, sfx: false }, sound: { music: .4, sfx: .7, muted: false }, files: [], settings: [], mods: { tab: 'browse', items: [] } };
|
||||
|
||||
/* ---------------- sound: the game's own music and menu sounds (only once a game is known) ---------------- */
|
||||
const TRACKS = { saria: "Saria's Song", fairy: 'Fairy Fountain', temple: 'Temple of Time', itemget: 'Item get' };
|
||||
const live = []; // music being played: { el, k, target, rate, name }
|
||||
let curTrack = null, unlocked = !!HOST;
|
||||
addEventListener('pointerdown', () => unlocked = true, true); addEventListener('keydown', () => unlocked = true, true);
|
||||
function music(name, loop = true, fade = 1.4) {
|
||||
if (name && !S.media.music) name = null;
|
||||
if (curTrack === name) return;
|
||||
curTrack = name;
|
||||
for (const m of live) { m.target = 0; m.rate = 1 / fade; }
|
||||
if (name) {
|
||||
const el = new Audio('audio/' + name + '.wav'); el.loop = loop; el.volume = 0;
|
||||
const m = { el, k: 0, target: 1, rate: 1 / fade, name };
|
||||
el.play().catch(() => { m.blocked = true; });
|
||||
if (!loop) el.onended = () => { m.target = 0; m.k = 0; if (curTrack === name) { curTrack = null; afterOneShot(name); } };
|
||||
live.push(m);
|
||||
}
|
||||
nowPlaying();
|
||||
}
|
||||
let lastT = performance.now();
|
||||
function audioTick(t) {
|
||||
const dt = Math.min(.1, (t - lastT) / 1000); lastT = t;
|
||||
const mv = S.sound.muted ? 0 : S.sound.music;
|
||||
for (let i = live.length - 1; i >= 0; i--) {
|
||||
const m = live[i];
|
||||
m.k += Math.sign(m.target - m.k) * Math.min(Math.abs(m.target - m.k), m.rate * dt);
|
||||
m.el.volume = Math.max(0, Math.min(1, m.k * m.k * mv));
|
||||
if (m.k <= 0 && m.target === 0) { m.el.pause(); m.el.removeAttribute('src'); live.splice(i, 1); }
|
||||
else if (m.blocked && unlocked) { m.blocked = false; m.el.play().catch(() => { m.blocked = true; }); }
|
||||
}
|
||||
}
|
||||
const SFX_IDS = ['cursor', 'tab_l', 'tab_r', 'decide', 'decide_l', 'cancel', 'open', 'close', 'success', 'error'];
|
||||
let sfxPool = null, lastCursor = 0;
|
||||
function loadSfx() {
|
||||
if (sfxPool || !S.media.sfx) return;
|
||||
sfxPool = {};
|
||||
SFX_IDS.forEach(n => { sfxPool[n] = { i: 0, a: [0, 1, 2].map(() => { const a = new Audio('audio/' + n + '.wav'); a.preload = 'auto'; return a; }) }; });
|
||||
}
|
||||
function sfx(n) {
|
||||
if (!sfxPool || S.sound.muted || !S.sound.sfx) return;
|
||||
if (n === 'cursor') { const t = performance.now(); if (t - lastCursor < 55) return; lastCursor = t; }
|
||||
const p = sfxPool[n]; if (!p) return;
|
||||
const a = p.a[p.i++ % 3]; a.currentTime = 0; a.volume = S.sound.sfx * (n === 'cursor' ? .8 : 1); a.play().catch(() => {});
|
||||
}
|
||||
function nowPlaying() {
|
||||
$('#nowT').textContent = curTrack ? TRACKS[curTrack] : S.media.music ? 'Nothing playing' : 'Music comes from your game once it is added';
|
||||
$('#nowp').classList.toggle('paused', !curTrack || S.sound.muted);
|
||||
$('#spk').classList.toggle('muted', S.sound.muted);
|
||||
$('#muteB').textContent = S.sound.muted ? 'Unmute (M)' : 'Mute (M)';
|
||||
}
|
||||
let soundSave = 0;
|
||||
function setVol(which, v, quiet) {
|
||||
S.sound[which] = Math.round(Math.max(0, Math.min(1, v)) * 100) / 100;
|
||||
$$(`[data-vol="${which}"]`).forEach(s => { s.querySelector('i').style.width = S.sound[which] * 100 + '%'; s.querySelector('u').style.left = S.sound[which] * 100 + '%'; });
|
||||
$$(`[data-volv="${which}"]`).forEach(s => s.textContent = Math.round(S.sound[which] * 100) + '%');
|
||||
if (!quiet) { clearTimeout(soundSave); soundSave = setTimeout(() => cmd('sound', S.sound), 400); }
|
||||
}
|
||||
function toggleMute() { S.sound.muted = !S.sound.muted; nowPlaying(); if (!S.sound.muted) sfx('decide'); cmd('sound', S.sound); }
|
||||
document.addEventListener('pointerdown', e => {
|
||||
const s = e.target.closest('.slider[data-vol]'); if (!s) return;
|
||||
e.preventDefault(); setFocus(s, true);
|
||||
const which = s.dataset.vol;
|
||||
const move = ev => { const b = s.getBoundingClientRect(); setVol(which, (ev.clientX - b.left) / b.width); };
|
||||
move(e);
|
||||
const up = () => { removeEventListener('pointermove', move); removeEventListener('pointerup', up); if (which === 'sfx') sfx('cursor'); };
|
||||
addEventListener('pointermove', move); addEventListener('pointerup', up);
|
||||
});
|
||||
|
||||
/* ---------------- screens ---------------- */
|
||||
const MAIN = ['home', 'mods', 'saves', 'settings'];
|
||||
const FIRST_RUN = ['welcome', 'reveal', 'done'];
|
||||
const MUSIC = { welcome: null, reveal: 'saria', work: 'temple', done: 'itemget', home: 'fairy', saves: 'fairy', mods: 'fairy', settings: 'fairy', bench: 'fairy', brun: null, playing: null };
|
||||
let screen = null;
|
||||
function go(name) {
|
||||
if (name === screen || !$('#s-' + name)) return;
|
||||
closeSheet(true); closeVol(true);
|
||||
screen = name;
|
||||
$$('.screen').forEach(s => s.classList.toggle('on', s.id === 's-' + name));
|
||||
const busy = FIRST_RUN.includes(name) || name === 'work' || name === 'brun' || name === 'playing';
|
||||
$('#win').classList.toggle('hidebits', busy);
|
||||
$('#bar').classList.toggle('bare', name === 'brun');
|
||||
const tab = $('#s-' + name).dataset.tab;
|
||||
$$('#nav a').forEach((a, i) => a.classList.toggle('on', String(i) === tab));
|
||||
const m = MUSIC[name];
|
||||
if (name === 'done') music('itemget', false, .3);
|
||||
else if (!(m === 'fairy' && curTrack === 'itemget')) music(m, true, name === 'playing' || name === 'brun' ? 2.2 : 1.4);
|
||||
setFocus($('#' + $('#s-' + name).dataset.first) || focusables()[0], false);
|
||||
if (name === 'mods' && !S.mods.loaded) cmd('mods.list', { tab: S.mods.tab, q: '' });
|
||||
if (name === 'saves') cmd('saves.list');
|
||||
cmd('screen', { s: name });
|
||||
}
|
||||
function afterOneShot(name) { if (name === 'itemget' && (MUSIC[screen] === 'fairy' || screen === 'done')) music('fairy'); }
|
||||
|
||||
/* ---------------- focus: mouse, keyboard and controller share one focus ---------------- */
|
||||
let focused = null;
|
||||
function visible(el) { return !!(el.offsetParent || el.getClientRects().length) && getComputedStyle(el).visibility !== 'hidden'; }
|
||||
function focusables() {
|
||||
if ($('#sheetBg').classList.contains('open')) return $$('[data-f]', $('#sheet')).filter(visible);
|
||||
if ($('#vol').classList.contains('open')) return $$('[data-f]', $('#vol')).concat($('#spk'));
|
||||
const out = $$('[data-f]', $('#s-' + screen)).filter(visible);
|
||||
if (!$('#bar').classList.contains('bare')) out.push(...$$('[data-f]', $('#bar')).filter(visible));
|
||||
return out;
|
||||
}
|
||||
function setFocus(el, sound) {
|
||||
if (!el || el === focused) return;
|
||||
if (focused) focused.classList.remove('kf');
|
||||
focused = el; el.classList.add('kf');
|
||||
if (el.tagName === 'INPUT') el.focus(); else if (document.activeElement && document.activeElement.tagName === 'INPUT') document.activeElement.blur();
|
||||
if (document.body.classList.contains('kb')) el.scrollIntoView({ block: 'nearest' });
|
||||
if (sound) sfx('cursor');
|
||||
}
|
||||
function move(dx, dy) {
|
||||
const list = focusables(); if (!list.length) return;
|
||||
if (!focused || !list.includes(focused)) return setFocus(list[0], true);
|
||||
const a = focused.getBoundingClientRect(), ax = a.left + a.width / 2, ay = a.top + a.height / 2;
|
||||
let best = null, bs = 1e9;
|
||||
for (const el of list) {
|
||||
if (el === focused) continue;
|
||||
const b = el.getBoundingClientRect(), bx = b.left + b.width / 2, by = b.top + b.height / 2;
|
||||
const p = dx ? (bx - ax) * dx : (by - ay) * dy;
|
||||
const edge = dx ? (dx > 0 ? b.left - a.right : a.left - b.right) : (dy > 0 ? b.top - a.bottom : a.top - b.bottom);
|
||||
if (p <= 4 && edge < -2) continue;
|
||||
const s = Math.max(0, edge) + Math.abs(dx ? by - ay : bx - ax) * 2.2 + (p <= 4 ? 1e5 : 0);
|
||||
if (s < bs) { bs = s; best = el; }
|
||||
}
|
||||
if (best) setFocus(best, true);
|
||||
}
|
||||
document.addEventListener('mouseover', e => { const el = e.target.closest('[data-f]'); if (el && focusables().includes(el)) setFocus(el, true); });
|
||||
document.addEventListener('mousemove', () => document.body.classList.remove('kb'));
|
||||
|
||||
/* ---------------- actions ---------------- */
|
||||
function activate(el) {
|
||||
if (!el) return;
|
||||
if (el.tagName === 'INPUT') { el.focus(); return; }
|
||||
if (el.dataset.go) { if (el.dataset.go !== screen) { sfx('decide'); go(el.dataset.go); } return; }
|
||||
const act = el.dataset.act; if (!act) return;
|
||||
const i = act.indexOf(':'), verb = i < 0 ? act : act.slice(0, i), arg = i < 0 ? '' : act.slice(i + 1);
|
||||
if (el.classList.contains('off')) { sfx('error'); return; }
|
||||
if (!['vol', 'mute', 'win'].includes(verb)) sfx(el.dataset.big !== undefined ? 'decide_l' : el.hasAttribute('data-back-sound') ? 'cancel' : 'decide');
|
||||
const A = ACTIONS[verb];
|
||||
if (A) A(arg, el); else cmd(verb, arg ? { arg } : undefined); // anything the page does not know itself is the launcher's
|
||||
}
|
||||
document.addEventListener('click', e => {
|
||||
const j = e.target.closest('[data-j]'); if (j) return jump(j.dataset.j);
|
||||
if (e.target.closest('#jumpBtn')) return toggleJump();
|
||||
if (e.target === $('#sheetBg')) return closeSheet();
|
||||
if (!e.target.closest('#vol') && !e.target.closest('#spk') && $('#vol').classList.contains('open')) closeVol();
|
||||
const el = e.target.closest('[data-act],[data-go]'); if (el) activate(el);
|
||||
});
|
||||
function back() {
|
||||
if ($('#jump').classList.contains('open')) return toggleJump();
|
||||
if ($('#drawer').classList.contains('open')) return ACTIONS.details();
|
||||
if ($('#sheetBg').classList.contains('open')) return closeSheet();
|
||||
if ($('#vol').classList.contains('open')) return closeVol();
|
||||
const b = $('#s-' + screen).dataset.back; if (!b) return;
|
||||
sfx('cancel');
|
||||
if (ACTIONS[b]) return ACTIONS[b]();
|
||||
if (b === 'welcome') cmd('forget'); // back from the reveal: choose another file
|
||||
go(b);
|
||||
}
|
||||
function tab(d) {
|
||||
if (!MAIN.includes(screen) && screen !== 'bench') return;
|
||||
const i = MAIN.indexOf(screen === 'bench' ? 'settings' : screen);
|
||||
sfx(d < 0 ? 'tab_l' : 'tab_r'); go(MAIN[(i + d + 4) % 4]);
|
||||
}
|
||||
let toastT = 0;
|
||||
function toast(html) {
|
||||
const h = $('#toastHost'); h.innerHTML = `<div class="toast">${html}</div>`;
|
||||
clearTimeout(toastT); toastT = setTimeout(() => h.innerHTML = '', 3600);
|
||||
}
|
||||
|
||||
const ACTIONS = {
|
||||
go: s => go(s),
|
||||
win: a => send({ t: 'win', a }),
|
||||
pick: kind => send({ t: 'pick', kind }),
|
||||
vol: () => $('#vol').classList.contains('open') ? closeVol() : openVol(),
|
||||
mute: () => toggleMute(),
|
||||
closesheet: () => closeSheet(),
|
||||
details: () => { const d = $('#drawer'); d.classList.toggle('open'); if (d.classList.contains('open')) { const p = $('#drawerLog'); p.scrollTop = p.scrollHeight; } },
|
||||
stop: () => openSheet(`<h3>${esc(S.work && S.work.stopTitle || 'Stop?')}</h3><p>${esc(S.work && S.work.stopText || '')}</p>` +
|
||||
'<div class="acts"><span class="qlink" data-f data-act="closesheet" id="sh1">Keep going</span><div class="play sm" style="width:200px" data-f data-act="dostop">Stop</div></div>', 'sh1'),
|
||||
dostop: () => { closeSheet(true); cmd('stop'); },
|
||||
workback: () => { cmd('workback'); },
|
||||
modtab: t => { S.mods.tab = t; drawModTabs(); cmd('mods.list', { tab: t, q: $('#modQ').value }); },
|
||||
mod: (id) => openModSheet(id),
|
||||
sc: (i) => openSaveSheet(+i),
|
||||
file: (i) => { S.cur = +i; drawHome(); },
|
||||
bringin: () => openSaveFlow('import'),
|
||||
copyout: () => openSaveFlow('export'),
|
||||
opt: (a, el) => { $$('.opt', el.parentElement).forEach(o => o.classList.toggle('sel', o === el)); },
|
||||
row: (id) => settingRow(id),
|
||||
choose: (id) => cmd('choose', { id }),
|
||||
};
|
||||
|
||||
/* ---------------- sheets and the sound panel ---------------- */
|
||||
let sheetReturn = null;
|
||||
function openSheet(html, first) {
|
||||
sheetReturn = focused; $('#sheet').innerHTML = html; $('#sheetBg').classList.add('open'); sfx('open');
|
||||
focused = null; setFocus($('#' + first) || $('[data-f]', $('#sheet')));
|
||||
}
|
||||
function closeSheet(quiet) {
|
||||
if (!$('#sheetBg').classList.contains('open')) return;
|
||||
$('#sheetBg').classList.remove('open'); if (!quiet) sfx('close');
|
||||
if (sheetReturn && document.contains(sheetReturn) && visible(sheetReturn)) { focused = null; setFocus(sheetReturn); }
|
||||
}
|
||||
function openVol() { $('#vol').classList.add('open'); sfx('open'); setFocus($('[data-vol="music"]')); }
|
||||
function closeVol(quiet) { if (!$('#vol').classList.contains('open')) return; $('#vol').classList.remove('open'); if (!quiet) sfx('close'); setFocus($('#spk')); }
|
||||
/* A list to choose one from (languages, folders, emulators): the launcher sends it, the choice goes back with its id. */
|
||||
function openChoice(m) {
|
||||
const opts = (m.options || []).map((o, i) => `<div class="opt${o.sel ? ' sel' : ''}" data-f data-act="opt" data-id="${esc(o.id)}" id="op${i}"><div><b>${esc(o.name)}</b>${o.sub ? `<span> · ${esc(o.sub)}</span>` : ''}</div><span></span></div>`).join('');
|
||||
openSheet(`<h3>${esc(m.title)}</h3>${m.text ? `<p>${m.text}</p>` : ''}<div class="opts${m.options && m.options.length > 6 ? ' many' : ''}">${opts}</div>` +
|
||||
`<div class="acts"><span class="qlink" data-f data-act="closesheet" data-back-sound>Cancel</span><div class="play sm" style="width:220px" data-f id="choiceOk">${esc(m.ok || 'Choose')}</div></div>`,
|
||||
'op' + Math.max(0, (m.options || []).findIndex(o => o.sel)));
|
||||
$('#choiceOk').onclick = () => { const s = $('.opt.sel', $('#sheet')); closeSheet(true); if (s) cmd(m.reply, { id: s.dataset.id, ctx: m.ctx }); };
|
||||
$('#choiceOk').dataset.act = 'noop';
|
||||
}
|
||||
ACTIONS.noop = () => {};
|
||||
/* A question with buttons (the DLSS licence, uninstall, a replace warning): each button's id goes back. */
|
||||
function openAsk(m) {
|
||||
const btns = (m.buttons || []).map((b, i) => b.main ? `<div class="play sm" style="width:${b.w || 220}px" data-f data-act="answer:${esc(b.id)}" id="ab${i}">${esc(b.label)}</div>`
|
||||
: `<span class="qlink" data-f data-act="answer:${esc(b.id)}" id="ab${i}">${esc(b.label)}</span>`).join('');
|
||||
openSheet(`<h3>${esc(m.title)}</h3><div class="asktext">${m.html || ''}</div><div class="acts">${btns}</div>`, 'ab0');
|
||||
S.ask = m;
|
||||
}
|
||||
ACTIONS.answer = (id) => { closeSheet(true); cmd(S.ask.reply, { id, ctx: S.ask.ctx }); };
|
||||
|
||||
/* ---------------- first run ---------------- */
|
||||
const portal = $('#portal');
|
||||
['dragenter', 'dragover'].forEach(t => document.addEventListener(t, e => { e.preventDefault(); if (screen === 'welcome') portal.classList.add('hot'); }));
|
||||
document.addEventListener('dragleave', e => { if (!e.relatedTarget) portal.classList.remove('hot'); });
|
||||
document.addEventListener('drop', e => {
|
||||
e.preventDefault(); portal.classList.remove('hot'); unlocked = true;
|
||||
const dt = e.dataTransfer, files = [...dt.files];
|
||||
if (!files.length && !dt.getData('text/uri-list')) return;
|
||||
const uris = (dt.getData('text/uri-list') || '').split(/\r?\n/).filter(u => u.startsWith('file://'));
|
||||
const msg = { t: 'drop', screen, names: files.map(f => f.name), files: uris };
|
||||
if (HOST === 'win' && window.chrome.webview.postMessageWithAdditionalObjects) window.chrome.webview.postMessageWithAdditionalObjects(JSON.stringify(msg), dt.files);
|
||||
else send(msg);
|
||||
});
|
||||
function onCheck(m) {
|
||||
portal.classList.toggle('checking', m.st === 'checking'); portal.classList.toggle('bad', m.st === 'bad');
|
||||
$('#portalH').textContent = m.st === 'checking' ? 'Checking your game' : m.st === 'bad' ? (m.title || "That isn't your game") : 'Drop your game here';
|
||||
$('#portalP').textContent = m.st === 'idle' ? 'Your .nup file, or the folder with romfs and exefs in it' : (m.msg || m.name || '');
|
||||
if (m.st === 'bad') sfx('error');
|
||||
}
|
||||
function drawReveal() {
|
||||
const r = S.reveal; if (!r) return;
|
||||
$('#found').innerHTML = r.found || '';
|
||||
$('#choices').innerHTML = (r.rows || []).map(x => `<div class="${x.bad ? 'bad' : ''}"><div><label>${esc(x.label)}</label><b>${esc(x.value)}</b>${x.small ? `<small>${esc(x.small)}</small>` : ''}</div>` +
|
||||
(x.act ? `<span class="ch" data-f data-act="choose:${esc(x.act)}">${esc(x.actLabel || 'Change')}</span>` : '') + '</div>').join('');
|
||||
$('#choices').style.gridTemplateColumns = ({ 1: '1fr', 2: '1fr 1.6fr', 3: '0.9fr 2fr 1fr' })[(r.rows || []).length] || 'repeat(4, 1fr)';
|
||||
$('#under').innerHTML = (r.under ? esc(r.under) + ' · ' : '') + '<span class="lnk" style="color:var(--gold)" data-f data-act="go:welcome" data-back-sound>Choose another file</span>';
|
||||
$('#buildBtn').classList.toggle('off', !r.canBuild);
|
||||
$('#buildBtn').textContent = r.button || 'Build the game';
|
||||
}
|
||||
|
||||
/* ---------------- the working screen: build, update, tools ---------------- */
|
||||
function drawWork(w) {
|
||||
S.work = w = Object.assign(S.work || {}, w);
|
||||
$('#workEb').textContent = w.eb || ''; $('#workTitle').textContent = w.title || ''; $('#workLead').textContent = w.lead || '';
|
||||
$('#workPath').innerHTML = (w.path || []).map(p => `<span class="${p.st || ''}"><i></i>${esc(p.name)}</span>`).join('');
|
||||
$('#workPath').style.display = w.path && w.path.length ? '' : 'none';
|
||||
const f = Math.max(0, Math.min(1, w.frac || 0));
|
||||
$('#workBar').style.width = f * 100 + '%'; $('#workKnob').style.left = f * 100 + '%';
|
||||
const prev = S.workStepsDone || 0, done = (w.steps || []).filter(s => s.st === 'd').length;
|
||||
$('#workSteps').innerHTML = (w.steps || []).map(s => `<div class="${s.st || ''}"><em></em><b>${esc(s.name)}</b><span>${esc(s.right || '')}</span></div>`).join('');
|
||||
if (done > prev && screen === 'work') sfx('success');
|
||||
S.workStepsDone = done;
|
||||
const err = !!w.error;
|
||||
$('#s-work').classList.toggle('failed', err);
|
||||
$('#workErr').style.display = err ? '' : 'none';
|
||||
$('#workBody').style.display = err ? 'none' : '';
|
||||
$('#workRetry').textContent = w.retry || 'Try again';
|
||||
$('#workNote').textContent = w.note || '';
|
||||
$('#workStopWrap').style.display = w.canStop && !err ? '' : 'none';
|
||||
if (err && !S.workErrShown) { sfx('error'); S.workErrShown = true; setFocus($('#workRetry')); }
|
||||
if (!err) S.workErrShown = false;
|
||||
}
|
||||
function addLog(lines) {
|
||||
const p = $('#drawerLog'); const at = p.scrollTop + p.clientHeight >= p.scrollHeight - 4;
|
||||
p.textContent += lines.join('\n') + '\n';
|
||||
if (p.textContent.length > 200000) p.textContent = p.textContent.slice(-150000);
|
||||
if (at) p.scrollTop = p.scrollHeight;
|
||||
}
|
||||
|
||||
/* ---------------- home ---------------- */
|
||||
function picUrl(f) { return f && f.pic ? `url("${f.pic}")` : 'none'; }
|
||||
function drawHome() {
|
||||
const h = S.home; if (!h) return;
|
||||
const files = S.files || [];
|
||||
if (S.cur == null || S.cur >= files.length) S.cur = Math.max(0, files.findIndex(f => f.last));
|
||||
const f = files[S.cur];
|
||||
const showFile = f && h.mode === 'ready';
|
||||
$('#hEb').textContent = showFile ? 'Continue · ' + f.label : h.eb;
|
||||
$('#hH1').textContent = showFile ? (f.place || h.title) : h.title;
|
||||
$('#hMeta').textContent = showFile ? f.meta : h.meta;
|
||||
$('#playBtn').textContent = h.button || 'Play';
|
||||
$('#playBtn').dataset.act = h.act || 'play';
|
||||
$('#playBtn').classList.toggle('off', !!h.off);
|
||||
$('#hLinks').innerHTML = (h.links || []).map(l => l.act ? `<span class="lnk" data-f data-act="${esc(l.act)}">${l.html}</span>` : `<span>${l.html}</span>`).join('');
|
||||
const url = picUrl(f);
|
||||
['#homeImg', '#homePic', '#savesImg', '#modsImg', '#setImg', '#playImg', '#benchImg'].forEach(s => $(s).style.backgroundImage = url);
|
||||
$('#s-home').classList.toggle('nopic', !f);
|
||||
$('#hCap').textContent = f ? `${f.label} · ${f.last ? 'your last save · ' : ''}picture from the game` : '';
|
||||
$('#strip').innerHTML = files.map((x, i) => `<div class="f${i === S.cur ? ' on' : ''}" data-f data-act="file:${i}" id="f${i}"><img src="${esc(x.pic)}" alt=""><small>${esc(x.label)}</small></div>`).join('');
|
||||
$('.files').style.display = files.length ? '' : 'none';
|
||||
const n = h.news;
|
||||
$('#whatsnew').innerHTML = n ? `<h4>${esc(n.title)}${n.more && h.mode !== 'update' ? ' · <span class="lnk" data-f data-act="open:changes">All changes</span>' : ''}</h4>` + n.items.map(i => `<p><b>${esc(i.b)}</b> ${esc(i.p)}</p>`).join('') : '';
|
||||
}
|
||||
function drawPill() {
|
||||
const p = S.pill || {};
|
||||
$('#pill').innerHTML = p.text ? `<i class="dot ${esc(p.dot || '')}"></i><span>${esc(p.text)}</span>` : '';
|
||||
$('#pill').style.display = p.text ? '' : 'none';
|
||||
if (p.act) { $('#pill').dataset.act = p.act; $('#pill').setAttribute('data-f', ''); } else { delete $('#pill').dataset.act; $('#pill').removeAttribute('data-f'); }
|
||||
}
|
||||
|
||||
/* ---------------- saves ---------------- */
|
||||
function drawSaves() {
|
||||
const s = S.saves || { items: [] };
|
||||
$('#savesEb').textContent = s.eb || '';
|
||||
$('#foundSaves').textContent = s.found || 'From an emulator on this PC, or a folder.';
|
||||
$('#sgrid').innerHTML = s.items.map((f, i) => f.empty
|
||||
? `<div class="sc empty" data-f data-act="sc:${i}" id="sc${i}"><div class="p"><span>Empty</span></div><div class="t"><b>${esc(f.label)}</b></div></div>`
|
||||
: `<div class="sc${f.last ? ' on' : ''}" data-f data-act="sc:${i}" id="sc${i}">${f.place ? `<div class="n">${esc(f.label)}</div>` : ''}<div class="p" style="background-image:url('${esc(f.pic)}')"></div>` +
|
||||
`<div class="t"><b>${esc(f.place || f.label)}</b><span>${esc(f.when)}</span></div><div class="m">${esc(f.time || '')}</div></div>`).join('');
|
||||
}
|
||||
function openSaveSheet(i) {
|
||||
const f = (S.saves || {}).items[i]; if (!f || f.empty) return;
|
||||
openSheet(`<h3>${esc(f.label)}${f.place ? ' · ' + esc(f.place) : ''}</h3><p>${esc(f.meta || '')}</p>` +
|
||||
`<div class="acts"><span class="qlink" data-f data-act="closesheet">Close</span><span class="qlink" data-f data-act="saves.open">Open the folder</span>` +
|
||||
`<div class="play sm" style="width:240px" data-f data-act="playslot:${f.slot}" id="sh1">Play</div></div>`, 'sh1');
|
||||
}
|
||||
ACTIONS.playslot = (slot) => { closeSheet(true); cmd('play', { slot: +slot }); };
|
||||
function openSaveFlow(kind) { cmd(kind === 'import' ? 'saves.import' : 'saves.export'); }
|
||||
$$('[data-act="open:backups"]').forEach(e => e.dataset.act = 'saves.backups'); // (the backups folder is the Saves page's own command)
|
||||
|
||||
/* ---------------- mods ---------------- */
|
||||
function drawModTabs() { $$('#modTabs span').forEach(s => s.classList.toggle('on', s.dataset.act === 'modtab:' + S.mods.tab)); $('#modSearch').style.display = S.mods.tab === 'browse' ? '' : 'none'; }
|
||||
function drawMods() {
|
||||
drawModTabs();
|
||||
const m = S.mods;
|
||||
const L = { get: '<em>Install</em>', busy: '<em>Working…</em>', on: '<em class="inst">◆ On</em>', off: '<em class="offm">Off</em>', update: '<em>Update</em>', kit: '<em>Install and start</em>', start: '<em class="inst">Start</em>' };
|
||||
$('#mods').innerHTML = m.items.map((x, i) => `<div class="mod" data-f data-act="mod:${i}" id="mod${i}">${x.img ? `<div class="mi" style="background-image:url('${esc(x.img)}')"></div>` : '<div class="mi none"></div>'}` +
|
||||
`<div><b>${esc(x.name)}</b><span>${esc(x.sub || '')}</span></div>${L[x.state] || ''}</div>`).join('') +
|
||||
(m.more ? `<div class="mod more" data-f data-act="mods.more" id="modMore"><div></div><div><b>More</b><span>Load the next page</span></div></div>` : '');
|
||||
$('#modNote').innerHTML = m.note || '';
|
||||
}
|
||||
function openModSheet(i) {
|
||||
const x = S.mods.items[i]; if (!x) return;
|
||||
const main = { get: 'Install', update: 'Update', kit: 'Install and start', start: 'Start', on: 'Turn off', off: 'Turn on' }[x.state];
|
||||
openSheet(`<h3>${esc(x.name)}</h3><p>${esc(x.sub || '')}</p>${x.desc ? `<div class="asktext modesc">${esc(x.desc)}</div>` : ''}` +
|
||||
`<div class="acts"><span class="qlink" data-f data-act="closesheet">Close</span>` + (x.page ? `<span class="qlink" data-f data-act="modgo:page:${i}">Its page</span>` : '') +
|
||||
(x.removable ? `<span class="qlink" data-f data-act="modgo:remove:${i}">Remove</span>` : '') +
|
||||
(main ? `<div class="play sm" style="width:240px" data-f data-act="modgo:main:${i}" id="sh1">${main}</div>` : '') + '</div>', 'sh1');
|
||||
}
|
||||
ACTIONS.modgo = (a) => { const [what, i] = a.split(':'); const x = S.mods.items[+i]; closeSheet(true); cmd('mods.' + what, { id: x.id, tab: S.mods.tab }); };
|
||||
let qT = 0;
|
||||
$('#modQ').addEventListener('input', () => { clearTimeout(qT); qT = setTimeout(() => cmd('mods.list', { tab: 'browse', q: $('#modQ').value }), 350); });
|
||||
$('#modQ').addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === 'ArrowDown' || e.key === 'Escape') { e.preventDefault(); $('#modQ').blur(); move(0, 1); } e.stopPropagation(); });
|
||||
|
||||
/* ---------------- settings: a list the launcher sends, and the game's own Options menu in tabs ---------------- */
|
||||
S.settab = 'launcher';
|
||||
function launcherRows() {
|
||||
return (S.settings || []).map(r => r.h ? `<h4>${esc(r.h)}</h4>` : r.kind === 'slider' ?
|
||||
`<div class="row-set" style="cursor:default"><b>${esc(r.label)}</b><div class="rng"><div class="slider" data-f data-vol="${esc(r.id)}" id="row-${esc(r.id)}"><i></i><u></u></div><span data-volv="${esc(r.id)}"></span></div><em></em></div>` :
|
||||
`<div class="row-set${r.danger ? ' danger' : ''}${r.off ? ' off' : ''}" data-f data-act="row:${esc(r.id)}" id="row-${esc(r.id)}"><b>${esc(r.label)}</b><span>${esc(r.value || '')}</span><em>${esc(r.actLabel || 'Change')}</em></div>`).join('');
|
||||
}
|
||||
function gameRows(tab) {
|
||||
const g = S.gameopts; if (!g || !g.data || !g.data[tab]) return '';
|
||||
const lock = g.locked ? ' off' : '';
|
||||
return `<p class="gnote">${esc(g.note || '')}</p>` + g.data[tab].map(sec => `<h4>${esc(sec.h)}</h4>` + sec.rows.map(r => r.kind === 'slider'
|
||||
? `<div class="row-set gs${lock}" style="cursor:default" title="${esc(r.help || '')}"><b>${esc(r.label)}</b><div class="rng"><div class="slider" data-f data-gkey="${esc(r.key)}" data-lo="${r.lo}" data-hi="${r.hi}" data-step="${r.step}" data-v="${r.v}" id="g-${esc(r.key)}"><i style="width:${pct(r)}%"></i><u style="left:${pct(r)}%"></u></div><span class="gval">${esc(r.value)}</span></div><em></em></div>`
|
||||
: `<div class="row-set${lock}" data-f data-act="gopt:${esc(r.key)}" id="g-${esc(r.key)}" title="${esc(r.help || '')}"><b>${esc(r.label)}</b><span>${esc(r.value)}</span><em>Change</em></div>`).join('')).join('');
|
||||
}
|
||||
function pct(r) { return r.hi > r.lo ? Math.round((r.v - r.lo) / (r.hi - r.lo) * 1000) / 10 : 0; }
|
||||
function drawSettings() {
|
||||
const tabs = [{ id: 'launcher', name: 'Launcher' }].concat(S.gameopts && S.gameopts.tabs || []);
|
||||
if (!tabs.some(t => t.id === S.settab)) S.settab = 'launcher';
|
||||
const keep = focused && focused.id;
|
||||
$('#setTabs').innerHTML = tabs.map(t => `<span data-f data-act="settab:${t.id}" id="st-${t.id}" class="${t.id === S.settab ? 'on' : ''}">${esc(t.name)}</span>`).join('');
|
||||
$('#set').innerHTML = S.settab === 'launcher' ? launcherRows() : gameRows(S.settab);
|
||||
$('#s-settings').dataset.first = 'st-' + S.settab;
|
||||
setVol('music', S.sound.music, true); setVol('sfx', S.sound.sfx, true);
|
||||
$('#benchCard').style.display = S.bench && S.bench.available && (S.settab === 'launcher' || S.settab === 'graphics') ? '' : 'none';
|
||||
$('#benchGo').classList.toggle('off', !(S.bench && S.bench.ready));
|
||||
$('#benchLast').textContent = S.bench && S.bench.last || '';
|
||||
if (keep && $('#' + keep) && screen === 'settings') { focused = null; setFocus($('#' + keep)); }
|
||||
}
|
||||
ACTIONS.settab = (t) => { S.settab = t; drawSettings(); $('#set').scrollTop = 0; setFocus($('#st-' + t)); };
|
||||
ACTIONS.gopt = (key) => cmd('gopt.choose', { key });
|
||||
/* the game's sliders: drag, or left / right while focused; the value goes to the launcher when let go */
|
||||
function gStep(el, v) {
|
||||
const lo = +el.dataset.lo, hi = +el.dataset.hi, st = +el.dataset.step || 1;
|
||||
v = Math.max(lo, Math.min(hi, lo + Math.round((v - lo) / st) * st));
|
||||
el.dataset.v = v; const p = hi > lo ? (v - lo) / (hi - lo) * 100 : 0;
|
||||
el.querySelector('i').style.width = p + '%'; el.querySelector('u').style.left = p + '%';
|
||||
const lab = el.parentElement.querySelector('.gval'); if (lab) lab.textContent = String(v);
|
||||
return v;
|
||||
}
|
||||
let gSendT = 0;
|
||||
function gSend(el) { clearTimeout(gSendT); gSendT = setTimeout(() => cmd('gopt.value', { key: el.dataset.gkey, value: +el.dataset.v }), 350); }
|
||||
document.addEventListener('pointerdown', e => {
|
||||
const s = e.target.closest('.slider[data-gkey]'); if (!s || s.closest('.off')) return;
|
||||
e.preventDefault(); setFocus(s, true);
|
||||
const mv = ev => { const b = s.getBoundingClientRect(); gStep(s, +s.dataset.lo + (ev.clientX - b.left) / b.width * (+s.dataset.hi - +s.dataset.lo)); };
|
||||
mv(e);
|
||||
const up = () => { removeEventListener('pointermove', mv); removeEventListener('pointerup', up); sfx('cursor'); gSend(s); };
|
||||
addEventListener('pointermove', mv); addEventListener('pointerup', up);
|
||||
});
|
||||
function gNudge(d) { if (!focused || !focused.dataset.gkey || focused.closest('.off')) return false; gStep(focused, +focused.dataset.v + d * (+focused.dataset.step || 1)); sfx('cursor'); gSend(focused); return true; }
|
||||
function settingRow(id) { cmd('setting', { id }); }
|
||||
// (the list is asked for each time the page opens, so it shows what is true now: Steam, shortcuts, the game folder)
|
||||
new MutationObserver(() => { if ($('#s-settings').classList.contains('on')) cmd('settings.list'); }).observe($('#s-settings'), { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
/* ---------------- benchmark ---------------- */
|
||||
/* a scene's frame times (ms) as a small line: higher = slower, the 16.7 ms line (60 fps) dashed */
|
||||
function sparkline(pts, cls) {
|
||||
if (!pts || pts.length < 2) return '';
|
||||
const max = Math.max(20, ...pts) * 1.1, w = 300, h = 46;
|
||||
const d = pts.map((v, i) => `${(i / (pts.length - 1) * w).toFixed(1)},${(h - v / max * h).toFixed(1)}`).join(' ');
|
||||
const y60 = (h - 16.7 / max * h).toFixed(1);
|
||||
return `<svg class="spark ${cls || ''}" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><line x1="0" x2="${w}" y1="${y60}" y2="${y60}" class="l60"/><polyline points="${d}"/></svg>`;
|
||||
}
|
||||
function onBench(b) {
|
||||
if (b.phase === 'run') {
|
||||
if (screen !== 'brun') go('brun');
|
||||
if (b.place) { $('#bPlace').style.backgroundImage = b.place.img ? `url("${b.place.img}")` : 'none'; $('#bName').textContent = b.place.name; }
|
||||
$('#bPass').textContent = b.pass || ''; $('#bLine').textContent = b.line || '';
|
||||
$('#bProg').style.width = Math.min(100, (b.frac || 0) * 100) + '%';
|
||||
} else if (b.phase === 'done') {
|
||||
$('#benchEb').textContent = b.eb || '';
|
||||
$('#places').innerHTML = (b.places || []).map(p => `<div class="place noimg${p.fps2 != null ? ' two' : ''}"><div class="pg">${sparkline(p.graph)}${p.graph2 ? sparkline(p.graph2, 'b') : ''}</div>` +
|
||||
(p.fps2 != null
|
||||
? `<div class="two"><b>${esc(p.name)}</b><span><i>Your settings</i><strong>${p.fps}</strong> fps · low ${p.low}</span><span class="vs"><i>${esc(b.second || '')}</i><strong>${p.fps2}</strong> fps · low ${p.low2}</span></div></div>`
|
||||
: `<div><b>${esc(p.name)}</b><span><strong>${p.fps}</strong> fps · low ${p.low}</span></div></div>`)).join('');
|
||||
$('#verdict').innerHTML = b.verdict || '';
|
||||
$('#recs').innerHTML = (b.recs || []).map(r => `<div class="rec${r.same ? ' same' : ''}"><b>${esc(r.name)}</b><s>${esc(r.from)}</s><em>→</em><strong>${esc(r.to)}</strong></div>`).join('');
|
||||
const c = $('#compareBtn'); c.textContent = b.compare || ''; c.style.display = b.compare ? '' : 'none';
|
||||
$('#applyBtn').classList.toggle('off', !b.apply);
|
||||
$('#applyBtn').textContent = b.apply ? 'Apply' : 'Nothing to change';
|
||||
sfx('success'); go('bench');
|
||||
} else if (b.phase === 'stopped') go('settings');
|
||||
}
|
||||
|
||||
/* ---------------- messages from the launcher ---------------- */
|
||||
onHost(m => {
|
||||
switch (m.t) {
|
||||
case 'hello': document.documentElement.classList.toggle('nochrome', !m.chrome); break;
|
||||
case 'max': document.documentElement.classList.toggle('maxed', m.on); break;
|
||||
case 'state': {
|
||||
const had = { music: S.media.music, sfx: S.media.sfx };
|
||||
for (const k in m) if (k !== 't') S[k] = m[k];
|
||||
if (m.sound) { setVol('music', S.sound.music, true); setVol('sfx', S.sound.sfx, true); }
|
||||
if (m.media) {
|
||||
document.documentElement.classList.toggle('noart', !S.media.art);
|
||||
if (S.media.art) $$('.gamelogo').forEach(i => { if (!i.complete || !i.naturalWidth) i.src = 'img/game/Logo_USEU_00.png?' + (S.media.v || ''); });
|
||||
loadSfx();
|
||||
if (!had.music && S.media.music && screen) { const want = MUSIC[screen]; curTrack = null; music(want === 'itemget' ? 'fairy' : want); }
|
||||
}
|
||||
drawPill(); drawHome(); drawReveal(); drawSaves(); drawSettings(); if (m.mods) drawMods(); nowPlaying();
|
||||
if (m.done) { $('#doneEb').textContent = S.done.eb || ''; $('#doneLead').textContent = S.done.lead || ''; }
|
||||
break;
|
||||
}
|
||||
case 'go': go(m.s); break;
|
||||
case 'check': onCheck(m); break;
|
||||
case 'work': drawWork(m); break;
|
||||
case 'log': addLog(m.lines || []); break;
|
||||
case 'toast': toast(m.html); if (m.sfx) sfx(m.sfx); break;
|
||||
case 'sfx': sfx(m.id); break;
|
||||
case 'choice': openChoice(m); break;
|
||||
case 'ask': openAsk(m); break;
|
||||
case 'bench': onBench(m); break;
|
||||
case 'copy': navigator.clipboard && navigator.clipboard.writeText(m.text).then(() => toast('Copied'), () => toast('Could not copy')); break;
|
||||
}
|
||||
});
|
||||
|
||||
/* ---------------- keyboard ---------------- */
|
||||
document.addEventListener('keydown', e => {
|
||||
if (e.key === 'F2' && !HOST) { e.preventDefault(); return toggleJump(); }
|
||||
if (document.activeElement && document.activeElement.tagName === 'INPUT' && !['Escape', 'Enter', 'ArrowDown', 'ArrowUp', 'Tab'].includes(e.key)) return;
|
||||
const k = e.key; let used = true;
|
||||
if (focused && focused.dataset.vol && (k === 'ArrowLeft' || k === 'ArrowRight')) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + (k === 'ArrowLeft' ? -.05 : .05)); sfx('cursor'); }
|
||||
else if (focused && focused.dataset.gkey && (k === 'ArrowLeft' || k === 'ArrowRight')) gNudge(k === 'ArrowLeft' ? -1 : 1);
|
||||
else if (k === 'ArrowLeft') move(-1, 0); else if (k === 'ArrowRight') move(1, 0);
|
||||
else if (k === 'ArrowUp') move(0, -1); else if (k === 'ArrowDown') move(0, 1);
|
||||
else if (k === 'Enter' || k === ' ') activate(focused);
|
||||
else if (k === 'Escape' || k === 'Backspace') back();
|
||||
else if (k === 'PageUp' || (k === 'q' && !e.ctrlKey)) tab(-1); else if (k === 'PageDown' || (k === 'e' && !e.ctrlKey)) tab(1);
|
||||
else if (k === 'm' || k === 'M') toggleMute();
|
||||
else if (k === 'Tab') { const l = focusables(), i = l.indexOf(focused); setFocus(l[(i + (e.shiftKey ? -1 : 1) + l.length) % l.length], true); }
|
||||
else used = false;
|
||||
if (used) { e.preventDefault(); document.body.classList.add('kb'); }
|
||||
});
|
||||
|
||||
/* ---------------- controller (Xbox layout; the browser maps others to it): A, B, LB, RB, D-pad, left stick, Y mute ---------------- */
|
||||
const held = {}; let stickAt = 0, stickDir = '';
|
||||
function pad(t) {
|
||||
if (!document.hasFocus()) return;
|
||||
const gp = [...(navigator.getGamepads ? navigator.getGamepads() : [])].find(g => g && g.connected); if (!gp) return;
|
||||
const B = i => gp.buttons[i] && gp.buttons[i].pressed;
|
||||
const edge = (i, fn) => { const p = B(i); if (p && !held[i]) { document.body.classList.add('kb'); unlocked = true; fn(); } held[i] = p; };
|
||||
const slide = d => { if (focused && focused.dataset.vol) { setVol(focused.dataset.vol, S.sound[focused.dataset.vol] + d * .05); sfx('cursor'); return true; } return gNudge(d); };
|
||||
edge(0, () => activate(focused)); edge(1, back); edge(4, () => tab(-1)); edge(5, () => tab(1));
|
||||
edge(3, toggleMute); edge(9, () => { if (MAIN.includes(screen)) go('settings'); });
|
||||
edge(12, () => move(0, -1)); edge(13, () => move(0, 1)); edge(14, () => slide(-1) || move(-1, 0)); edge(15, () => slide(1) || move(1, 0));
|
||||
const x = gp.axes[0] || 0, y = gp.axes[1] || 0, dir = Math.abs(x) > .55 ? (x > 0 ? 'r' : 'l') : Math.abs(y) > .55 ? (y > 0 ? 'd' : 'u') : '';
|
||||
if (dir && (dir !== stickDir || t - stickAt > 220)) {
|
||||
document.body.classList.add('kb'); stickAt = t + (dir !== stickDir ? 160 : 0);
|
||||
({ l: () => slide(-1) || move(-1, 0), r: () => slide(1) || move(1, 0), u: () => move(0, -1), d: () => move(0, 1) })[dir]();
|
||||
}
|
||||
stickDir = dir;
|
||||
}
|
||||
function frame(t) { audioTick(t); pad(t); requestAnimationFrame(frame); }
|
||||
requestAnimationFrame(frame);
|
||||
|
||||
/* ---------------- preview only: jump to a screen (the stand-in plays along) ---------------- */
|
||||
function toggleJump() { $('#jump').classList.toggle('open'); }
|
||||
function jump(j) { $('#jump').classList.remove('open'); unlocked = true; if (window.DEMO) window.DEMO.jump(j, fromHost); }
|
||||
if (!HOST && window.DEMO) $('#jump').innerHTML = window.DEMO.jumps.map(([k, n]) => `<a data-j="${k}">${n}</a>`).join('');
|
||||
|
||||
setVol('music', S.sound.music, true); setVol('sfx', S.sound.sfx, true); nowPlaying();
|
||||
send({ t: 'ready' });
|
||||
151
launcher/ui/demo.js
Normal file
151
launcher/ui/demo.js
Normal file
@@ -0,0 +1,151 @@
|
||||
/* The stand-in for the launcher when this page is opened in a plain browser (a design preview): it answers the page's
|
||||
messages with made-up data and sped-up timings. Inside the launcher this file does nothing. Its pictures and sounds
|
||||
(img/save*.jpg, img/game/*, audio/*) are only there in a lab copy, never in the repo or the exe. */
|
||||
'use strict';
|
||||
(function () {
|
||||
if (window.chrome && window.chrome.webview || window.external && typeof window.external.sendMessage === 'function') return;
|
||||
let out = null;
|
||||
const emit = m => setTimeout(() => out && out(m), 0);
|
||||
const FILES = [
|
||||
{ slot: 4, label: 'File 4', place: 'Castle Town Market', when: 'yesterday', meta: '12 h 40 min played · Saved yesterday, 21:40', time: '12 h 40 min played', pic: 'img/save3.jpg', last: true },
|
||||
{ slot: 2, label: 'File 2', place: 'Castle grounds', when: '16 Nov', meta: '9 h 05 min played · Saved 16 Nov', time: '9 h 05 min played', pic: 'img/save1.jpg' },
|
||||
{ slot: 1, label: 'File 1', place: 'Lake Hylia', when: '15 Nov', meta: '7 h 31 min played · Saved 15 Nov', time: '7 h 31 min played', pic: 'img/save0.jpg' },
|
||||
{ slot: 3, label: 'File 3', place: 'Kokiri Forest', when: '12 Nov', meta: '0 h 48 min played · Saved 12 Nov', time: '0 h 48 min played', pic: 'img/save2.jpg' },
|
||||
{ slot: 5, label: 'File 5', place: 'Hyrule Field', when: '11 Nov', meta: '3 h 12 min played · Saved 11 Nov', time: '3 h 12 min played', pic: 'img/save4.jpg' },
|
||||
{ slot: 6, label: 'File 6', place: 'Hyrule Castle', when: '9 Nov', meta: '5 h 50 min played · Saved 9 Nov', time: '5 h 50 min played', pic: 'img/save5.jpg' },
|
||||
];
|
||||
const NEWS = { title: 'New in 0.5.2', items: [{ b: 'Battle music', p: 'ends again after the last enemy.' }, { b: 'Menu text', p: 'always shows on every screen.' }, { b: 'Updates', p: 'download 12 MB and keep your shaders.' }], more: true };
|
||||
const st = { lang: 'English (US)', folder: 'D:\\Games\\Triforce', ver: '0.5.2', update: false, timer: 0, kind: '', sound: { music: .4, sfx: .7, muted: false } };
|
||||
const SET = () => [
|
||||
{ h: 'Launcher' }, { id: 'music', label: 'Music', kind: 'slider' }, { id: 'sfx', label: 'Sounds', kind: 'slider' },
|
||||
{ id: 'autostart', label: 'Start with Windows', value: 'No', actLabel: 'Change' },
|
||||
{ h: 'Game' }, { id: 'folder', label: 'Game folder', value: st.folder, actLabel: 'Move' }, { id: 'glang', label: 'Game language', value: st.lang, actLabel: 'Change' },
|
||||
{ id: 'dlss', label: 'NVIDIA DLSS', value: 'Not included', actLabel: 'Include' }, { id: 'rebuild', label: 'Build the game again', value: 'About 45 minutes', actLabel: 'Build' },
|
||||
{ h: 'Shortcuts' }, { id: 'desktop', label: 'Desktop shortcut', value: 'Yes', actLabel: 'Change' }, { id: 'steam', label: 'Steam', value: 'Not added', actLabel: 'Add to Steam' },
|
||||
{ h: 'Help' }, { id: 'logs', label: 'Log folder', value: '', actLabel: 'Open' }, { id: 'versions', label: 'Versions', value: 'launcher 1.0.0 · game ' + st.ver, actLabel: 'Copy report' },
|
||||
{ h: 'Remove' }, { id: 'uninstall', label: 'Uninstall Triforce', value: 'Your saves stay', actLabel: 'Uninstall', danger: true },
|
||||
];
|
||||
function home() {
|
||||
const s = { t: 'state', files: FILES, settings: SET(), bench: { available: true, last: 'Not run yet on this PC' }, sound: st.sound };
|
||||
if (st.update) {
|
||||
s.home = { mode: 'update', eb: 'An update is ready', title: 'Version 0.5.3', meta: '12 MB download · About 4 minutes · your saves and mods stay', button: 'Update', act: 'update',
|
||||
links: [{ html: '<b>Play 0.5.2 first</b>', act: 'playold' }, { html: 'See all changes', act: 'open:changes' }], news: { title: 'New in 0.5.3', items: [{ b: 'RX 580', p: 'no more white speckles on grass and Link.' }, { b: 'Controller', p: 'LB and RB reach every menu tab.' }, { b: 'Mods', p: 'the whole list, and online co-op.' }] } };
|
||||
s.pill = { text: 'Update ready', dot: 'amber', act: 'update' };
|
||||
} else {
|
||||
s.home = { mode: 'ready', button: 'Play', act: 'play', links: [{ html: `Version ${st.ver} · <b>up to date</b>` }, { html: esc(st.folder), act: 'open:game' }], news: NEWS };
|
||||
s.pill = { text: 'Up to date · ' + st.ver, dot: '' };
|
||||
}
|
||||
return s;
|
||||
}
|
||||
function esc(s) { return String(s).replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])); }
|
||||
function reveal(name) {
|
||||
emit({ t: 'state', media: { art: true, music: true, sfx: true }, reveal: {
|
||||
found: `<b>◆ Your game is ready to build</b> <em>· ${esc(name)} · version 1.0.0</em>`,
|
||||
rows: [{ label: 'Language', value: st.lang, act: 'lang' }, { label: 'Where it goes', value: st.folder, small: '60 GB while building · 212 GB free', act: 'folder' }],
|
||||
under: 'About 45 minutes on this PC, the tools included · you can keep using it meanwhile', canBuild: true } });
|
||||
emit({ t: 'go', s: 'reveal' });
|
||||
}
|
||||
function check(name) {
|
||||
emit({ t: 'check', st: 'checking', name });
|
||||
setTimeout(() => {
|
||||
if (!/\.nup$/i.test(name) && !/folder/.test(name)) return emit({ t: 'check', st: 'bad', msg: `${name} is not a .nup file. Drop your .nup, or the folder with romfs and exefs in it.` });
|
||||
emit({ t: 'check', st: 'idle' }); reveal(name);
|
||||
}, 1200);
|
||||
}
|
||||
function work(kind) {
|
||||
clearInterval(st.timer); st.kind = kind;
|
||||
const steps = kind === 'build' ? [['Downloading Triforce\u2019s tools', 2, '262 MB'], ['Reading your game files', 2, '1 min'], ['Translating the game to PC code', 4.5, '11 min'], ['Compiling', 6, '20 min'], ['Preparing shaders for your graphics card', 5, 'about 13 min on an RTX 4070']]
|
||||
: [['Downloading 0.5.3', 2.5, '12 MB'], ['Rebuilding the changed code', 4, '3 min'], ['Keeping your shaders', 1.2, 'kept']];
|
||||
const mins = kind === 'build' ? 45 : 4, total = steps.reduce((a, s) => a + s[1], 0); let t = 0;
|
||||
const path = kind === 'build' ? [{ name: 'Your game', st: 'done' }, { name: 'Build', st: 'now' }, { name: 'Play' }] : [];
|
||||
const tick = () => {
|
||||
let acc = 0; const p = Math.min(1, t / total), left = Math.ceil(mins * (1 - p));
|
||||
emit({ t: 'work', kind, path, eb: kind === 'build' ? 'Building your game' : 'Updating to 0.5.3', title: left <= 1 ? 'Almost done' : `About ${left} minutes left`, frac: p, canStop: true, error: null,
|
||||
stopTitle: kind === 'build' ? 'Stop the build?' : 'Stop the update?', stopText: 'What is done so far is kept, so it picks up from here next time.',
|
||||
note: kind === 'build' ? 'Keep this window open; you can minimize it. You get a notice when the game is ready.' : 'Your saves, mods and shaders stay.',
|
||||
steps: steps.map(([n, s, real]) => { const a = acc; acc += s; return { name: n, st: t >= acc ? 'd' : t >= a ? 'n' : '', right: t >= acc ? real : t >= a ? 'now' : real }; }) });
|
||||
if (Math.random() < .3) emit({ t: 'log', lines: ['@@progress ' + p.toFixed(3)] });
|
||||
};
|
||||
tick(); emit({ t: 'go', s: 'work' });
|
||||
st.timer = setInterval(() => {
|
||||
t += .1; tick();
|
||||
if (t >= total) {
|
||||
clearInterval(st.timer);
|
||||
setTimeout(() => {
|
||||
if (kind === 'build') { emit(Object.assign(home(), { done: { eb: 'Built in 44 minutes', lead: '24 GB in ' + st.folder + ' · shaders ready for your graphics card · your controller works out of the box' } })); emit({ t: 'go', s: 'done' }); }
|
||||
else { st.update = false; st.ver = '0.5.3'; NEWS.title = 'New in 0.5.3'; emit(home()); emit({ t: 'go', s: 'home' }); emit({ t: 'toast', html: '<b>◆</b> Updated to 0.5.3 · your saves, mods and shaders stayed', sfx: 'success' }); }
|
||||
}, 600);
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
const MODS = [
|
||||
{ id: 'sq', name: 'Squadala!', sub: 'Online co-op · daurosk · work in progress', state: 'kit', desc: 'Play together online. Installs its own kit beside your game and starts it.' },
|
||||
{ id: 'a', name: 'Sample: HD Kokiri textures', sub: 'Textures · sample data', state: 'get' }, { id: 'b', name: 'Sample: Classic HUD', sub: 'Interface · sample data', state: 'get' },
|
||||
{ id: 'c', name: 'Sample: Brighter nights', sub: 'Lighting · sample data', state: 'get' }, { id: 'd', name: 'Sample: Faster text', sub: 'Gameplay · sample data', state: 'get' },
|
||||
{ id: 'e', name: 'Sample: Ocarina notes on screen', sub: 'Interface · sample data', state: 'get' },
|
||||
];
|
||||
const MINE = [{ id: 'm1', name: 'Sample: Quieter Navi', sub: 'In your mods folder', state: 'on', removable: true }, { id: 'm2', name: 'Sample: Tunic recolour', sub: 'In your mods folder', state: 'off', removable: true }];
|
||||
function mods(tab, q) {
|
||||
const items = (tab === 'mine' ? MINE : MODS).filter(m => !q || m.name.toLowerCase().includes(q.toLowerCase()));
|
||||
emit({ t: 'state', mods: { tab, items, loaded: true, note: tab === 'mine' ? 'Changes take effect after the game is built again: <b>about 6 minutes</b>.' : '' } });
|
||||
}
|
||||
function bench() {
|
||||
clearInterval(st.timer); let t = 0; const per = 1.6, total = per * 8;
|
||||
const P = [{ img: 'img/save0.jpg', name: 'Lake Hylia', a: 142, b: 118 }, { img: 'img/save4.jpg', name: 'Hyrule Field', a: 96, b: 71 }, { img: 'img/save3.jpg', name: 'Castle Town Market', a: 88, b: 64 }, { img: 'img/save2.jpg', name: 'Kokiri Forest', a: 121, b: 97 }];
|
||||
st.timer = setInterval(() => {
|
||||
t += .1; const k = Math.min(7, Math.floor(t / per)), p = P[k % 4], pass = k < 4 ? 1 : 2;
|
||||
emit({ t: 'bench', phase: 'run', place: p, pass: `Finding your best settings · pass ${pass} of 2 · ${pass === 1 ? 'your settings' : 'with DLSS'}`, fps: Math.round((pass === 1 ? p.a * .55 : p.a) + Math.sin(t * 7) * 6), frac: t / total });
|
||||
if (t >= total) {
|
||||
clearInterval(st.timer);
|
||||
emit({ t: 'bench', phase: 'done', eb: 'Benchmark finished · 3 min 12 s · RTX 4070 SUPER', places: P.map(p => ({ img: p.img, name: p.name, fps: p.a, low: p.b })),
|
||||
verdict: 'Your PC holds <b>above 60 fps everywhere</b> at your current settings. With DLSS on, it holds above 120 almost everywhere, so a 120 cap plays smoother without dips.',
|
||||
recs: [{ name: 'Game frame rate cap', from: '60', to: '120' }, { name: 'Upscaler', from: 'Off', to: 'NVIDIA DLSS' }, { name: 'Render resolution', from: 'Native', to: 'Quality' }, { name: 'Frame generation', from: 'Off', to: 'Off', same: true }, { name: 'Anti-aliasing', from: 'SMAA', to: 'DLSS' }] });
|
||||
}
|
||||
}, 100);
|
||||
}
|
||||
window.DEMO = {
|
||||
jumps: [['welcome', 'First run: welcome'], ['reveal', 'First run: game found'], ['build', 'First run: building'], ['fail', 'Build failed'], ['done', 'First run: ready'], ['home', 'Home'], ['update', 'Home with an update ready'], ['saves', 'Saves'], ['mods', 'Mods'], ['settings', 'Settings'], ['bench', 'Benchmark']],
|
||||
jump(j, fn) {
|
||||
out = fn; clearInterval(st.timer);
|
||||
if (j === 'welcome') { emit({ t: 'state', media: { art: false, music: false, sfx: true } }); emit({ t: 'go', s: 'welcome' }); }
|
||||
else if (j === 'reveal') reveal('OcarinaOfTime.nup');
|
||||
else if (j === 'build') { emit({ t: 'state', media: { art: true, music: true, sfx: true } }); work('build'); }
|
||||
else if (j === 'fail') { emit({ t: 'state', media: { art: true, music: true, sfx: true } }); emit({ t: 'go', s: 'work' }); emit({ t: 'work', kind: 'build', eb: 'Building your game', title: 'The build stopped', lead: 'The drive ran out of space while compiling. Free up about 20 GB on D: and try again: it carries on from where it stopped.', error: { msg: 'disk full' }, path: [] }); }
|
||||
else if (j === 'done') { emit(Object.assign(home(), { media: { art: true, music: true, sfx: true }, done: { eb: 'Built in 44 minutes', lead: '24 GB in D:\\Games\\Triforce · shaders ready for your graphics card' } })); emit({ t: 'go', s: 'done' }); }
|
||||
else if (j === 'update') { st.update = true; emit(Object.assign(home(), { media: { art: true, music: true, sfx: true } })); emit({ t: 'go', s: 'home' }); }
|
||||
else if (j === 'bench') { emit(Object.assign(home(), { media: { art: true, music: true, sfx: true } })); bench(); }
|
||||
else { st.update = false; emit(Object.assign(home(), { media: { art: true, music: true, sfx: true } })); emit({ t: 'go', s: j }); }
|
||||
},
|
||||
receive(m, fn) {
|
||||
out = fn;
|
||||
if (m.t === 'ready') { emit({ t: 'hello', chrome: true, os: 'windows' }); emit({ t: 'state', sound: st.sound, media: { art: false, music: false, sfx: true } }); const j = location.hash.slice(1); if (j) window.DEMO.jump(j, fn); else emit({ t: 'go', s: 'welcome' }); return; }
|
||||
if (m.t === 'pick') return check(m.kind === 'folder' ? 'OcarinaOfTime (folder)' : 'OcarinaOfTime.nup');
|
||||
if (m.t === 'drop') return check(m.names[0] || 'file');
|
||||
if (m.t === 'win') return emit({ t: 'toast', html: 'Window button: ' + m.a + ' <span style="color:var(--text3)">· in the launcher only</span>' });
|
||||
if (m.t !== 'cmd') return;
|
||||
const c = m.c;
|
||||
if (c === 'build') work('build');
|
||||
else if (c === 'update') work('update');
|
||||
else if (c === 'stop' || c === 'workback') { clearInterval(st.timer); emit({ t: 'go', s: st.kind === 'update' ? 'home' : 'reveal' }); }
|
||||
else if (c === 'retry') work('build');
|
||||
else if (c === 'play' || c === 'playold') { emit({ t: 'go', s: 'playing' }); setTimeout(() => emit({ t: 'go', s: 'home' }), 6000); }
|
||||
else if (c === 'choose' && m.id === 'lang') emit({ t: 'choice', title: 'Game language', reply: 'lang', options: ['English (US)', 'English (UK)', 'Français (France)', 'Français (Canada)', 'Deutsch', 'Español (España)', 'Español (Latinoamérica)', 'Italiano', 'Nederlands', 'Português', 'Русский', '日本語', '한국어', '简体中文', '繁體中文'].map(n => ({ id: n, name: n, sel: n === st.lang })) });
|
||||
else if (c === 'lang') { st.lang = m.id; reveal('OcarinaOfTime.nup'); }
|
||||
else if (c === 'choose' && m.id === 'folder') emit({ t: 'toast', html: 'The system folder picker opens here' });
|
||||
else if (c === 'mods.list') mods(m.tab, m.q);
|
||||
else if (c === 'mods.main') { const x = MODS.concat(MINE).find(x => x.id === m.id); if (x) { x.state = x.state === 'on' ? 'off' : x.state === 'off' ? 'on' : x.state === 'kit' ? 'start' : 'on'; mods(m.tab, ''); emit({ t: 'sfx', id: 'success' }); } }
|
||||
else if (c === 'saves.list') emit({ t: 'state', saves: { eb: 'Six files in your game folder', found: 'From an emulator on this PC, or a folder. Found: Eden (6 files), Ryujinx (2 files).', items: FILES } });
|
||||
else if (c === 'saves.import') emit({ t: 'choice', title: 'Bring saves in', text: 'Pick where your saves are. Whatever they replace is backed up first.', ok: 'Bring them in', reply: 'saves.importfrom', options: [{ id: 'eden', name: 'Eden', sub: '6 files · last played 2 days ago', sel: true }, { id: 'ryu', name: 'Ryujinx', sub: '2 files · last played in March' }, { id: 'dir', name: 'A folder…', sub: 'choose it yourself' }] });
|
||||
else if (c === 'saves.importfrom') emit({ t: 'toast', html: '<b>◆</b> 6 files brought in from Eden · the old ones are in backups', sfx: 'success' });
|
||||
else if (c === 'saves.export') emit({ t: 'choice', title: 'Copy saves out', text: 'Your files, copied. Nothing here changes.', ok: 'Copy them out', reply: 'saves.exportto', options: [{ id: 'eden', name: 'To Eden', sub: 'its files are backed up first', sel: true }, { id: 'dir', name: 'To a folder…' }] });
|
||||
else if (c === 'saves.exportto') emit({ t: 'toast', html: '<b>◆</b> 6 files copied out', sfx: 'success' });
|
||||
else if (c === 'setting' && m.id === 'uninstall') emit({ t: 'ask', title: 'Uninstall Triforce?', html: '<p>Removes the launcher, its tools and the built game.</p><p>Your saves and mods stay in a backup folder.</p>', reply: 'uninstall', buttons: [{ id: 'no', label: 'Keep it' }, { id: 'yes', label: 'Uninstall', main: true }] });
|
||||
else if (c === 'setting') emit({ t: 'toast', html: m.id + ' <span style="color:var(--text3)">· the launcher does this</span>' });
|
||||
else if (c === 'bench') bench();
|
||||
else if (c === 'benchstop') { clearInterval(st.timer); emit({ t: 'bench', phase: 'stopped' }); }
|
||||
else if (c === 'benchapply') { emit({ t: 'go', s: 'settings' }); emit({ t: 'toast', html: '<b>◆</b> Applied · they take effect the next time you play', sfx: 'success' }); }
|
||||
else if (c === 'report' || c === 'details') { }
|
||||
else if (c === 'open') emit({ t: 'toast', html: 'Opens ' + esc(m.arg || '') });
|
||||
},
|
||||
};
|
||||
})();
|
||||
93
launcher/ui/fonts/OFL-Commissioner.txt
Normal file
93
launcher/ui/fonts/OFL-Commissioner.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
Copyright 2019 The Commissioner Project Authors (https://github.com/kosbarts/Commissioner)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
93
launcher/ui/fonts/OFL-CormorantGaramond.txt
Normal file
93
launcher/ui/fonts/OFL-CormorantGaramond.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
Copyright 2015 the Cormorant Project Authors (github.com/CatharsisFonts/Cormorant)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
launcher/ui/fonts/commissioner-11a7fd07e9.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-11a7fd07e9.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/commissioner-8c0c3d1302.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-8c0c3d1302.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/commissioner-b8c95ecfa5.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-b8c95ecfa5.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/commissioner-bfda4e68e5.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-bfda4e68e5.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/commissioner-d76970e37f.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-d76970e37f.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/commissioner-f6bbdade6c.woff2
Normal file
BIN
launcher/ui/fonts/commissioner-f6bbdade6c.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-1f799a916c.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-1f799a916c.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-26a769c817.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-26a769c817.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-4db21dbf6b.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-4db21dbf6b.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-63e97a55b2.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-63e97a55b2.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-6a3809d7b3.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-6a3809d7b3.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-abcaa8b479.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-abcaa8b479.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-c8e477690f.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-c8e477690f.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-dc67de7e1c.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-dc67de7e1c.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-e266b787cb.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-e266b787cb.woff2
Normal file
Binary file not shown.
BIN
launcher/ui/fonts/cormorant-f3bda5d4e1.woff2
Normal file
BIN
launcher/ui/fonts/cormorant-f3bda5d4e1.woff2
Normal file
Binary file not shown.
325
launcher/ui/fonts/fonts.css
Normal file
325
launcher/ui/fonts/fonts.css
Normal file
@@ -0,0 +1,325 @@
|
||||
/* Commissioner and Cormorant Garamond (SIL Open Font License 1.1, see OFL.txt), served from inside the launcher. */
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-b8c95ecfa5.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-f6bbdade6c.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* greek */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-bfda4e68e5.woff2) format('woff2');
|
||||
unicode-range: U+0370-0377, U+037A-037F, U+0384-038A, U+038C, U+038E-03A1, U+03A3-03FF;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-d76970e37f.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-11a7fd07e9.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Commissioner';
|
||||
font-style: normal;
|
||||
font-weight: 100 900;
|
||||
font-display: block;
|
||||
src: url(commissioner-8c0c3d1302.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-1f799a916c.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-c8e477690f.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-6a3809d7b3.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-f3bda5d4e1.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-4db21dbf6b.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-1f799a916c.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-c8e477690f.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-6a3809d7b3.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-f3bda5d4e1.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-4db21dbf6b.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-1f799a916c.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-c8e477690f.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-6a3809d7b3.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-f3bda5d4e1.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: italic;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-4db21dbf6b.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-e266b787cb.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-dc67de7e1c.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-63e97a55b2.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-26a769c817.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
font-display: block;
|
||||
src: url(cormorant-abcaa8b479.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-e266b787cb.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-dc67de7e1c.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-63e97a55b2.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-26a769c817.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 600;
|
||||
font-display: block;
|
||||
src: url(cormorant-abcaa8b479.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
/* cyrillic-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-e266b787cb.woff2) format('woff2');
|
||||
unicode-range: U+0460-052F, U+1C80-1C8A, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
|
||||
}
|
||||
/* cyrillic */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-dc67de7e1c.woff2) format('woff2');
|
||||
unicode-range: U+0301, U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
|
||||
}
|
||||
/* vietnamese */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-63e97a55b2.woff2) format('woff2');
|
||||
unicode-range: U+0102-0103, U+0110-0111, U+0128-0129, U+0168-0169, U+01A0-01A1, U+01AF-01B0, U+0300-0301, U+0303-0304, U+0308-0309, U+0323, U+0329, U+1EA0-1EF9, U+20AB;
|
||||
}
|
||||
/* latin-ext */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-26a769c817.woff2) format('woff2');
|
||||
unicode-range: U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F, U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C4, U+2113, U+2C60-2C7F, U+A720-A7FF;
|
||||
}
|
||||
/* latin */
|
||||
@font-face {
|
||||
font-family: 'Cormorant Garamond';
|
||||
font-style: normal;
|
||||
font-weight: 700;
|
||||
font-display: block;
|
||||
src: url(cormorant-abcaa8b479.woff2) format('woff2');
|
||||
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
|
||||
}
|
||||
BIN
launcher/ui/img/crest.png
Normal file
BIN
launcher/ui/img/crest.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 277 KiB |
149
launcher/ui/index.html
Normal file
149
launcher/ui/index.html
Normal file
@@ -0,0 +1,149 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Triforce</title>
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<link rel="stylesheet" href="ui.css"><link rel="stylesheet" href="theme.css"><link rel="stylesheet" href="v3.css"><link rel="stylesheet" href="proto.css"><link rel="stylesheet" href="app.css"></head>
|
||||
<body>
|
||||
<div id="fit"><div class="win" id="win">
|
||||
|
||||
<!-- ============ FIRST RUN: welcome (no game read yet, so no game art and no music) ============ -->
|
||||
<section class="screen" id="s-welcome" data-first="pickFile">
|
||||
<div class="stage"></div>
|
||||
<div class="welcome"><div class="k">Welcome</div><h1>Play Ocarina of Time on your PC.</h1><p>Triforce turns your own copy of the game into a native PC game: high frame rates, wide screens, mods, and your controller.</p><p>Start with your game file. Nothing is uploaded, and nothing of the game comes with Triforce.</p></div>
|
||||
<div class="portal" id="portal"><i class="c c1"></i><i class="c c2"></i><i class="c c3"></i><i class="c c4"></i><div><div class="ic"></div><h2 id="portalH">Drop your game here</h2><p id="portalP">Your .nup file, or the folder with romfs and exefs in it</p><div class="or"><div class="qbtn" data-f id="pickFile" data-act="pick:file">Choose a file</div><div class="qbtn" data-f data-act="pick:folder">Choose a folder</div></div></div></div>
|
||||
<div class="foot4"><span id="needLine">Windows 10 or 11, or Linux · about 60 GB free while building</span><span><b class="lnk" data-f data-act="open:help">Need help?</b> · <span class="lnk" data-f data-act="open:discord">Discord</span></span></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ FIRST RUN: the reveal (the game is read: its logo and Saria's Song) ============ -->
|
||||
<section class="screen" id="s-reveal" data-first="buildBtn" data-back="welcome">
|
||||
<div class="reveal"></div><div class="grain" style="opacity:.1"></div>
|
||||
<div class="rlogo"><div class="aura"></div><div class="glowl"></div><img class="gamelogo" src="img/game/Logo_USEU_00.png" alt=""></div>
|
||||
<div class="found4" id="found"></div>
|
||||
<div class="choices" id="choices"></div>
|
||||
<div class="buildrow"><div class="orn"></div><div class="play" style="width:330px" data-f id="buildBtn" data-act="build" data-big>Build the game</div><div class="orn r"></div></div>
|
||||
<div class="under" id="under"></div>
|
||||
<div class="nowmusic" style="bottom:auto;top:76px;right:150px"><div class="eq"><i></i><i></i><i></i><i></i></div><em>Saria's Song</em> · from your game</div>
|
||||
</section>
|
||||
|
||||
<!-- ============ WORKING: the build, an update, or the tools download (one screen, filled by the launcher) ============ -->
|
||||
<section class="screen" id="s-work" data-first="workStop">
|
||||
<div class="hall"></div>
|
||||
<div class="mini"><div class="aura"></div><img class="gamelogo" src="img/game/Logo_USEU_00.png" alt=""></div>
|
||||
<div class="path" id="workPath" style="top:300px"></div>
|
||||
<div class="center" style="top:334px"><div class="eb" id="workEb"></div><h1 id="workTitle"></h1><p class="lead" id="workLead"></p></div>
|
||||
<div style="position:absolute;left:0;right:0;top:432px" id="workBody"><div class="gline" id="workLine"><i id="workBar"></i><u id="workKnob"></u></div>
|
||||
<div class="stepl" id="workSteps"></div></div>
|
||||
<div class="workerr" id="workErr"><div class="playrow" style="position:static;justify-content:center"><div class="orn"></div><div class="play sm" style="width:260px" data-f id="workRetry" data-act="retry" data-big>Try again</div><div class="orn r"></div></div>
|
||||
<p><span class="lnk" data-f data-act="report">Copy report</span> · <span class="lnk" data-f data-act="open:log">Open the log</span> · <span class="lnk" data-f data-act="workback" data-back-sound>Back</span></p></div>
|
||||
<div class="workfoot" id="workFoot"><span id="workNote"></span> · <span class="lnk" data-f data-act="details">Show details</span><span id="workStopWrap"> · <span class="lnk" data-f id="workStop" data-act="stop">Stop</span></span></div>
|
||||
<div class="nowmusic"><div class="eq"><i></i><i></i><i></i><i></i></div><em>Temple of Time</em> · from your game</div>
|
||||
<div class="drawer" id="drawer"><div class="dhead"><b>Details</b><span class="lnk" data-act="report">Copy report</span><span class="lnk" data-act="details">Close</span></div><pre id="drawerLog"></pre></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ FIRST RUN: done ============ -->
|
||||
<section class="screen" id="s-done" data-first="doneplay">
|
||||
<div class="hall"></div>
|
||||
<div class="mini"><div class="aura"></div><img class="gamelogo" src="img/game/Logo_USEU_00.png" alt=""></div>
|
||||
<div class="path" style="top:300px"><span class="done"><i></i>Your game</span><span class="done"><i></i>Build</span><span class="now"><i></i>Play</span></div>
|
||||
<div class="center" style="top:350px"><div class="eb" id="doneEb">Built</div><h1>Your game is ready</h1>
|
||||
<p class="lead" id="doneLead"></p></div>
|
||||
<div class="playrow" style="left:0;right:0;top:560px;justify-content:center"><div class="orn"></div><div class="play" data-f id="doneplay" data-act="play" data-big>Play</div><div class="orn r"></div></div>
|
||||
<div style="position:absolute;left:0;right:0;top:680px;text-align:center;font-size:14px;color:var(--text2)">Played before on an emulator? <span class="lnk" style="color:var(--gold)" data-f data-act="bringin">Bring your saves in</span> · <span class="lnk" style="color:var(--gold)" data-f data-act="go:home">Go to the launcher</span></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ HOME ============ -->
|
||||
<section class="screen" id="s-home" data-first="playBtn" data-tab="0">
|
||||
<div class="scene"><div class="img" id="homeImg"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div class="logo"><div class="aura"></div><img class="gamelogo" src="img/game/Logo_USEU_00.png" alt=""></div>
|
||||
<div class="cont"><div class="eb" id="hEb"></div><h1 id="hH1"></h1><div class="meta" id="hMeta"></div></div>
|
||||
<div class="frame" id="hFrame"><div class="pic" id="homePic"></div><div class="edge"></div><div class="top"><i></i><i></i></div><div class="cap"><span></span><span id="hCap"></span></div></div>
|
||||
<div class="glow"></div>
|
||||
<div class="playrow"><div class="orn"></div><div class="play" data-f id="playBtn" data-act="play" data-big>Play</div><div class="orn r"></div></div>
|
||||
<div class="links" id="hLinks"></div>
|
||||
<div class="dock"><div class="rule"><i class="a"></i><i class="b"></i></div>
|
||||
<div class="files"><h4>Your files</h4><div class="strip" id="strip"></div></div>
|
||||
<div class="whatsnew" id="whatsnew"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============ PLAYING (the game is running) ============ -->
|
||||
<section class="screen" id="s-playing" data-first="showGame">
|
||||
<div class="scene"><div class="img" id="playImg" style="filter:blur(30px) saturate(1.1) brightness(.35)"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div class="mini"><div class="aura"></div><img class="gamelogo" src="img/game/Logo_USEU_00.png" alt=""></div>
|
||||
<div class="center" style="top:330px"><div class="eb" id="pEb">Playing now</div><h1>Ocarina of Time is running</h1>
|
||||
<p class="lead">The music stops while you play and comes back when you close the game.</p></div>
|
||||
<div class="act" style="left:0;right:0;top:520px;justify-content:center"><div class="qbtn" data-f id="showGame" data-act="showgame" style="width:260px">Show the game</div></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ SAVES ============ -->
|
||||
<section class="screen" id="s-saves" data-first="sc0" data-back="home" data-tab="2">
|
||||
<div class="scene"><div class="img" id="savesImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="savesEb"></div><h1 style="font-size:54px">Your files</h1></div></div>
|
||||
<div class="sgrid" id="sgrid"></div>
|
||||
<div class="sside"><div class="fbox"><h3>Bring saves in</h3><p id="foundSaves">From an emulator on this PC, or a folder.</p>
|
||||
<div class="play sm" data-f data-act="bringin">Bring saves in</div></div>
|
||||
<div class="fbox"><h3>Copy saves out</h3><p>To an emulator or a folder, to carry on somewhere else.</p><div class="qbtn" style="width:100%" data-f data-act="copyout">Copy saves out</div></div>
|
||||
<p style="margin-top:14px;font-size:13px;color:var(--text3)">Whatever gets replaced is backed up first. <span class="lnk" style="color:var(--gold)" data-f data-act="open:backups">Open backups</span></p></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ MODS ============ -->
|
||||
<section class="screen" id="s-mods" data-first="modTab0" data-back="home" data-tab="1">
|
||||
<div class="scene"><div class="img" id="modsImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="modsEb">From GameBanana, and your mods folder</div><h1 style="font-size:54px">Mods</h1></div></div>
|
||||
<div class="modtabs" id="modTabs"><span data-f id="modTab0" data-act="modtab:browse">Browse</span><span data-f id="modTab1" data-act="modtab:mine">Yours</span></div>
|
||||
<div class="search" id="modSearch"><input id="modQ" data-f placeholder="Search mods" spellcheck="false" autocomplete="off"></div>
|
||||
<div class="mods" id="mods"></div>
|
||||
<div class="modnote" id="modNote"></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ SETTINGS ============ -->
|
||||
<section class="screen" id="s-settings" data-first="row0" data-back="home" data-tab="3">
|
||||
<div class="scene"><div class="img" id="setImg" style="filter:blur(26px) saturate(1.1) brightness(.45)"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="setEb">The launcher and your game</div><h1 style="font-size:54px">Settings</h1></div></div>
|
||||
<div class="settabs" id="setTabs"></div>
|
||||
<div class="set" id="set"></div>
|
||||
<div class="benchcard fbox" id="benchCard"><h3>Find my best settings</h3><p>Your game flies through four places in about 2 minutes with its own panel on screen, then this tells you what your PC runs best.</p>
|
||||
<div class="play sm" style="width:100%;font-size:21px;height:52px" data-f id="benchGo" data-act="bench">Find my best settings</div>
|
||||
<p style="margin:14px 0 0;font-size:12.5px;color:var(--text3)" id="benchLast"></p></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ BENCHMARK RUN ============ -->
|
||||
<section class="screen" id="s-brun" data-first="bStop" data-back="benchstop">
|
||||
<div class="brun"><div class="placebig" id="bPlace"></div><div class="grade"></div><div class="grain"></div>
|
||||
<span class="stop lnk" data-f id="bStop" data-act="benchstop">Stop · Esc</span>
|
||||
<div class="hud"><div class="eb" id="bPass"></div><h1 id="bName"></h1><p class="bline" id="bLine"></p><p class="bhint">About 2 minutes. The game shows where it is and the frame rate. Esc in the game, or Stop here, ends it.</p></div>
|
||||
<div class="prog"><i id="bProg"></i></div></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ BENCHMARK RESULTS ============ -->
|
||||
<section class="screen" id="s-bench" data-first="applyBtn" data-back="settings" data-tab="3">
|
||||
<div class="scene"><div class="img" id="benchImg" style="filter:blur(26px) saturate(1.1) brightness(.5)"></div><div class="grade"></div><div class="grain"></div></div>
|
||||
<div style="position:absolute;left:64px;top:96px"><div class="cont" style="position:static;width:auto"><div class="eb" id="benchEb"></div><h1 style="font-size:54px">Your best settings</h1></div></div>
|
||||
<div class="bench"><div><div class="places" id="places"></div>
|
||||
<p class="verdict" id="verdict"></p></div>
|
||||
<div class="recs"><h3>Recommended</h3><div class="fbox" id="recs"></div>
|
||||
<div class="qbtn compare" data-f data-act="bench.compare" id="compareBtn"></div>
|
||||
<div class="act" style="position:static;margin-top:22px;justify-content:flex-end"><span class="qlink" data-f data-act="go:settings">Keep mine</span><span class="qlink" data-f data-act="bench">Run again</span>
|
||||
<div class="play sm" style="width:220px" data-f id="applyBtn" data-act="benchapply">Apply</div></div></div></div>
|
||||
</section>
|
||||
|
||||
<!-- ============ shared: the bar, the sound panel, the sheet ============ -->
|
||||
<div class="bar" id="bar"><div class="brand flair"><div class="mark"></div><span>Triforce</span></div>
|
||||
<div class="nav" id="nav"><a data-f data-go="home">Play</a><a data-f data-go="mods">Mods</a><a data-f data-go="saves">Saves</a><a data-f data-go="settings">Settings</a></div>
|
||||
<div class="grow"></div><div class="state" id="pill"></div>
|
||||
<div class="spk on" id="spk" data-f data-act="vol"><svg viewBox="0 0 24 24"><path d="M4 9.5h3.5L12 5.5v13l-4.5-4H4z"/><path d="M15.5 9a4.5 4.5 0 0 1 0 6M18 6.5a8 8 0 0 1 0 11"/></svg></div>
|
||||
<div class="wc"><span data-act="win:min"><svg viewBox="0 0 12 12"><path d="M1 6.5h10"/></svg></span><span data-act="win:max"><svg viewBox="0 0 12 12"><rect x="1.5" y="1.5" width="9" height="9"/></svg></span><span data-act="win:close"><svg viewBox="0 0 12 12"><path d="M1.5 1.5l9 9M10.5 1.5l-9 9"/></svg></span></div></div>
|
||||
|
||||
<div class="vol" id="vol"><h5>Sound</h5>
|
||||
<div class="vrow"><b>Music</b><div class="slider" data-f data-vol="music"><i></i><u></u></div><span data-volv="music">40%</span></div>
|
||||
<div class="vrow"><b>Sounds</b><div class="slider" data-f data-vol="sfx"><i></i><u></u></div><span data-volv="sfx">70%</span></div>
|
||||
<div class="nowp" id="nowp"><div class="eq"><i></i><i></i><i></i><i></i></div><em id="nowT">Nothing playing</em><span>· from your game</span></div>
|
||||
<div class="mute"><span>Music stops while you play</span><b data-f data-act="mute" id="muteB">Mute (M)</b></div></div>
|
||||
|
||||
<div class="sheet-bg" id="sheetBg"><div class="sheet fbox" id="sheet"></div></div>
|
||||
<div id="toastHost"></div>
|
||||
</div></div>
|
||||
|
||||
<div id="protonote"><b>Preview</b> · a stand-in answers instead of the launcher: nothing here touches your game · <u style="cursor:pointer" id="jumpBtn">jump to a screen (F2)</u></div>
|
||||
<div id="jump"></div>
|
||||
<script src="demo.js"></script>
|
||||
<script src="app.js"></script>
|
||||
</body></html>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user