mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-29 04:18:49 -04:00
A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
238 lines
13 KiB
C#
238 lines
13 KiB
C#
// (Triforce) OOTRR, the Ocarina of Time Remake Randomizer (github.com/ootrando/ootrr, GPL-3.0 as Triforce is), as the launcher's
|
|
// Randomizer page uses it: one release of its command-line program, downloaded on first use and checked against the SHA-256 this
|
|
// file names, then run for its settings (settings-dump), a seed (generate) and the seed's files (build, NX2navi's layout:
|
|
// <game>\mods\<name>\romfs, which host/mods.c reads). Nothing of OOTRR is in Triforce's source or its release.
|
|
//
|
|
// randomizer\ootrr\<version>\ootrr(.exe) the program, with its LICENSE, NOTICE and README, and portable.txt (OOTRR keeps its
|
|
// caches in a data folder beside itself, not in the user's profile). Not in tools:
|
|
// an update of the tools replaces that folder whole (11-26)
|
|
// downloads\ootrr\<release file> the release file while it downloads (Downloader: a stopped download goes on from its .part)
|
|
//
|
|
// A file whose hash is not the pinned one is deleted and never unpacked; only the program's own few files are taken out of it,
|
|
// flat into the folder, so nothing in the archive can reach outside it. Another OOTRR release is another pin here.
|
|
using System.Diagnostics;
|
|
using System.Formats.Tar;
|
|
using System.IO.Compression;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Triforce.Logic;
|
|
|
|
/// <summary>One file of an OOTRR release for one system: its name, size and SHA-256 (from the release's SHA256SUMS.txt, which
|
|
/// GitHub's build attestation ties to the tagged source).</summary>
|
|
public sealed record OotrrFile(string Name, long Size, string Sha256);
|
|
|
|
/// <summary>What OOTRR said when it did not do what it was asked: a whole sentence for the page.</summary>
|
|
public sealed class OotrrException : Exception
|
|
{
|
|
/// <summary>The code the program ended with, when it ran and refused; null when it never ran (not installed, not started) or
|
|
/// the launcher itself says no.</summary>
|
|
public int? Exit { get; }
|
|
public OotrrException(string message, int? exit = null) : base(message) { Exit = exit; }
|
|
}
|
|
|
|
/// <summary>A run of the program: its exit code and everything it printed.</summary>
|
|
public sealed record OotrrRun(int Exit, string Out, string Err);
|
|
|
|
public sealed class Ootrr
|
|
{
|
|
/// <summary>The release the launcher uses. To move to another: its version, and each file's size and SHA-256 from its
|
|
/// SHA256SUMS.txt (check them with `gh attestation verify <file> --repo ootrando/ootrr`).</summary>
|
|
public const string Version = "0.8.2";
|
|
public const string Repo = "https://github.com/ootrando/ootrr";
|
|
public static readonly OotrrFile Windows = new("OOTRR-0.8.2-windows-x64-portable.zip", 4694013, "0598aa5f7e3fe93e690437d936456a92c00e6d20b59a9bcd24fb2948afb6fbae");
|
|
public static readonly OotrrFile Linux = new("OOTRR-0.8.2-linux-x86_64.tar.gz", 4760078, "715ee19e1c6e2e487e1800106f8694fc7a756ebc725bd1b501e1256959c79136");
|
|
|
|
/// <summary>The files the launcher takes out of a release (the program by its name on each system; the others as they are).</summary>
|
|
static readonly string[] Keep = { "LICENSE", "NOTICE", "README.md", "portable.txt" };
|
|
const string Stamp = ".triforce-ootrr";
|
|
|
|
readonly TriforceContext ctx;
|
|
readonly Downloader downloader;
|
|
readonly OotrrFile? file;
|
|
/// <summary>file: the release file to fetch in place of the pinned one for this system (a test's own).</summary>
|
|
public Ootrr(TriforceContext ctx, Downloader? downloader = null, OotrrFile? file = null)
|
|
{
|
|
this.ctx = ctx;
|
|
this.downloader = downloader ?? new Downloader(ctx);
|
|
this.file = file;
|
|
}
|
|
|
|
public OotrrFile File => file ?? (ctx.IsWindows ? Windows : Linux);
|
|
public string ExeName => ctx.IsWindows ? "ootrr.exe" : "ootrr";
|
|
public string Folder => Path.Combine(ctx.Home, Randomizer.WorkFolder, "ootrr", Version);
|
|
/// <summary>Where the release file comes from: TRIFORCE_OOTRR_URL over GitHub's release page (a test's own server).</summary>
|
|
public string Url => (Env("TRIFORCE_OOTRR_URL") is { } u ? u.TrimEnd('/') : Repo + "/releases/download/v" + Version) + "/" + File.Name;
|
|
|
|
string? Env(string name) => ctx.Env(name) is { Length: > 0 } v ? v.Trim() : null;
|
|
|
|
/// <summary>The program to run: TRIFORCE_OOTRR_EXE (a test's or a developer's own: in a test run or a local build only, as it
|
|
/// runs any program), else the downloaded one. Null before the download (or when the folder holds a program that is not the
|
|
/// pinned release's).</summary>
|
|
public string? Exe
|
|
{
|
|
get
|
|
{
|
|
if (Env("TRIFORCE_OOTRR_EXE") is { } own && (ctx.TestRoot != null || BuildInfo.IsDev || ctx.Env("TRIFORCE_DEV") == "1"))
|
|
return System.IO.File.Exists(own) ? own : null;
|
|
var exe = Path.Combine(Folder, ExeName);
|
|
return System.IO.File.Exists(exe) && ReadStamp() == File.Sha256 ? exe : null;
|
|
}
|
|
}
|
|
|
|
public bool Have => Exe != null;
|
|
|
|
string? ReadStamp()
|
|
{
|
|
try { return System.IO.File.ReadAllText(Path.Combine(Folder, Stamp)).Trim(); } catch (Exception) { return null; }
|
|
}
|
|
|
|
/// <summary>Downloads the pinned release file, checks its hash and unpacks the program. progress: 0..1 of the download.</summary>
|
|
public async Task InstallAsync(HttpClient http, Action<DownloadProgress>? progress, CancellationToken token)
|
|
{
|
|
if (Have) return;
|
|
var f = File;
|
|
var file = Path.Combine(ctx.DownloadsFolder, "ootrr", f.Name);
|
|
ctx.Require(file);
|
|
ctx.Require(Folder);
|
|
await downloader.ToFileAsync(http, Url, file, f.Size, progress, token).ConfigureAwait(false);
|
|
string hash;
|
|
await using (var s = System.IO.File.OpenRead(file)) hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(s, token).ConfigureAwait(false));
|
|
if (hash != f.Sha256)
|
|
{
|
|
try { System.IO.File.Delete(file); } catch (Exception) { }
|
|
throw new OotrrException("The randomizer's download is not the file Triforce expects (its SHA-256 is " + hash + "). It was deleted and nothing was installed. Try again later.");
|
|
}
|
|
var temp = Folder + ".new";
|
|
if (Directory.Exists(temp)) Directory.Delete(temp, true);
|
|
Directory.CreateDirectory(temp);
|
|
try
|
|
{
|
|
if (f.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) UnpackZip(file, temp);
|
|
else await UnpackTarGz(file, temp, token).ConfigureAwait(false);
|
|
if (!System.IO.File.Exists(Path.Combine(temp, ExeName))) throw new OotrrException("The randomizer's download holds no " + ExeName + ". Nothing was installed.");
|
|
// (portable: OOTRR keeps its caches in a data folder beside itself, so removing the folder removes all of it)
|
|
var portable = Path.Combine(temp, "portable.txt");
|
|
if (!System.IO.File.Exists(portable)) System.IO.File.WriteAllText(portable, "OOTRR portable (written by Triforce's launcher)\n");
|
|
System.IO.File.WriteAllText(Path.Combine(temp, Stamp), f.Sha256 + "\n");
|
|
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
|
|
Directory.Move(temp, Folder);
|
|
}
|
|
catch
|
|
{
|
|
try { Directory.Delete(temp, true); } catch (Exception) { }
|
|
throw;
|
|
}
|
|
try { System.IO.File.Delete(file); } catch (Exception) { }
|
|
ctx.Log.Write("randomizer: OOTRR " + Version + " installed in " + Folder);
|
|
}
|
|
|
|
/// <summary>The name a release entry is taken out under (flat, in the folder), or null for an entry that is not kept.</summary>
|
|
internal string? KeptName(string entry)
|
|
{
|
|
var name = entry.Replace('\\', '/').TrimEnd('/');
|
|
var depth = name.Count(c => c == '/');
|
|
if (depth > 2 || name.Split('/').Any(p => p == ".." || p == ".")) return null;
|
|
var leaf = name.Substring(name.LastIndexOf('/') + 1);
|
|
if (leaf == ExeName) return leaf;
|
|
return Keep.FirstOrDefault(k => string.Equals(k, leaf, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
void UnpackZip(string file, string to)
|
|
{
|
|
using var zip = ZipFile.OpenRead(file);
|
|
foreach (var e in zip.Entries)
|
|
{
|
|
if (e.FullName.EndsWith('/')) continue;
|
|
var name = KeptName(e.FullName);
|
|
if (name == null) continue;
|
|
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
|
|
e.ExtractToFile(Path.Combine(to, name), true);
|
|
}
|
|
}
|
|
|
|
async Task UnpackTarGz(string file, string to, CancellationToken token)
|
|
{
|
|
await using var s = System.IO.File.OpenRead(file);
|
|
await using var gz = new GZipStream(s, CompressionMode.Decompress);
|
|
using var tar = new TarReader(gz);
|
|
for (TarEntry? e; (e = await tar.GetNextEntryAsync(false, token).ConfigureAwait(false)) != null;)
|
|
{
|
|
if (e.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) continue;
|
|
var name = KeptName(e.Name);
|
|
if (name == null || e.DataStream == null) continue;
|
|
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
|
|
var path = Path.Combine(to, name);
|
|
await using (var o = System.IO.File.Create(path)) await e.DataStream.CopyToAsync(o, token).ConfigureAwait(false);
|
|
if (!OperatingSystem.IsWindows() && name == ExeName)
|
|
System.IO.File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |
|
|
UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
|
|
}
|
|
}
|
|
|
|
/// <summary>Removes the downloaded program (the folder of this version, its data folder with it).</summary>
|
|
public void Remove()
|
|
{
|
|
ctx.Require(Folder);
|
|
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
|
|
}
|
|
|
|
// ---------------- running it ----------------
|
|
|
|
/// <summary>Runs the program with these arguments (each one whole, never through a shell) in its own folder. line: each line
|
|
/// it prints, as it prints it. Cancelling ends it. Throws OotrrException when it is not there or ends with an error, with the
|
|
/// error it printed.</summary>
|
|
public async Task<OotrrRun> RunAsync(IEnumerable<string> args, Action<string>? line, CancellationToken token)
|
|
{
|
|
var exe = Exe ?? throw new OotrrException("The randomizer is not installed yet.");
|
|
var si = new ProcessStartInfo(exe)
|
|
{
|
|
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true,
|
|
StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
|
|
WorkingDirectory = Path.GetDirectoryName(Path.GetFullPath(exe))!,
|
|
};
|
|
foreach (var a in args) si.ArgumentList.Add(a);
|
|
// (OOTRR's own update check and browser stay off: the launcher runs commands, never its web page)
|
|
si.Environment["NO_COLOR"] = "1";
|
|
using var p = new Process { StartInfo = si };
|
|
var o = new StringBuilder();
|
|
var e = new StringBuilder();
|
|
// (a line handler that throws is logged: thrown on the reader's thread it would end the launcher)
|
|
p.OutputDataReceived += (_, d) =>
|
|
{
|
|
if (d.Data == null) return;
|
|
lock (o) o.AppendLine(d.Data);
|
|
try { line?.Invoke(d.Data); } catch (Exception x) { ctx.Log.Write("randomizer: a line of its output was not taken: " + x.Message); }
|
|
};
|
|
p.ErrorDataReceived += (_, d) => { if (d.Data == null) return; lock (e) e.AppendLine(d.Data); };
|
|
try { p.Start(); }
|
|
catch (Exception x) when (x is System.ComponentModel.Win32Exception || x is IOException)
|
|
{
|
|
throw new OotrrException("The randomizer could not be started: " + x.Message);
|
|
}
|
|
p.BeginOutputReadLine();
|
|
p.BeginErrorReadLine();
|
|
try { await p.WaitForExitAsync(token).ConfigureAwait(false); }
|
|
catch (OperationCanceledException)
|
|
{
|
|
// (it is gone before the caller takes its folders away: a build still writing would keep files open in them)
|
|
try { p.Kill(true); p.WaitForExit(5000); } catch (Exception) { }
|
|
throw;
|
|
}
|
|
p.WaitForExit(); // (the last lines of both streams are read)
|
|
var run = new OotrrRun(p.ExitCode, o.ToString(), e.ToString());
|
|
if (run.Exit != 0) throw new OotrrException(ErrorOf(run), run.Exit);
|
|
return run;
|
|
}
|
|
|
|
/// <summary>What a failed run says: its last line on the error stream that is not a warning, else on its output.</summary>
|
|
internal static string ErrorOf(OotrrRun run)
|
|
{
|
|
static string? Last(string text, bool skipWarnings) => text.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0 &&
|
|
!(skipWarnings && l.StartsWith("warning:", StringComparison.OrdinalIgnoreCase))).LastOrDefault();
|
|
var why = Last(run.Err, true) ?? Last(run.Out, false) ?? "it ended with code " + run.Exit;
|
|
if (why.StartsWith("error:", StringComparison.OrdinalIgnoreCase)) why = why.Substring(6).Trim();
|
|
return "The randomizer stopped: " + why;
|
|
}
|
|
}
|