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:
ruckus7382sfgsgdf
2026-11-19 10:52:50 -06:00
parent a750a21025
commit fb26495475
167 changed files with 21552 additions and 293 deletions

View 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>&#9670;</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;
}
}

View 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>&#9670; 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>&#9670;</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>&#9670;</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);
}

View 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);
}

View 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 } });
}
}

View 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();
}
}

View 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"); }
}
}

View 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
View 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
View 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",
};
}

View 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; }
}

View 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;
}
}

View 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
View 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
View 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");
}
}

View 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
View 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>