mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-19 16:20:01 -04:00
Triforce v0.5.0
In-game mods (GameBanana browser, search and installs, with the Mask Salesman), code-patch and cheat mods, the devs' test18 to test45 work (full performance overlay, frame pacing on, steady frame rate, save export and import, bug capture, new options rows, Setup's Mods page and Add to Steam), occlusion queries and new defaults, Auto resolution that scales, replay helper threads and robust buffers off by default, the options in sections.
This commit is contained in:
676
setup/Guard.cs
Normal file
676
setup/Guard.cs
Normal file
@@ -0,0 +1,676 @@
|
||||
// What keeps a run of Setup from damaging an install. Nothing here needs the window or the PC's real install: each part is plain
|
||||
// logic over what it is handed, and tests/test_setup_*.py compile this file alone and run it.
|
||||
// Instance one Setup at a time for an install
|
||||
// Space room on a disk, asked before it is needed
|
||||
// Download a file fetched through a .part file that a cut download goes on from, checked before it is used
|
||||
// Partial (Triforce) a copy written as <name>.partial and renamed into place once complete, never seen half done
|
||||
// SaveLock (Triforce) the save's lock the game holds while it runs, held by Setup across a copy of a save
|
||||
// Report what a player copies after a build that stopped, without their name in it
|
||||
// Handover Setup replacing itself with a newer one, and taking its place back when that one does not start
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
/// One Setup at a time for an install. Two of them on one folder each downloaded the tools into the same files, unpacked them over
|
||||
/// each other and built into the same game folder (nx2/make_game.py stops a build it finds running on its work folder, so the
|
||||
/// first Setup's build ended without a reason). The first Setup holds a named mutex for as long as it runs; Windows lets go of it
|
||||
/// when the process ends, however it ends. A second start for the same folder asks the first to come to the front (a named event
|
||||
/// the first one waits on) and ends. Both names are made from the folder Setup works in and, in a test run (TRIFORCE_TEST_ROOT),
|
||||
/// from the test folder too: a test run never shares a lock with the PC's real install.
|
||||
static class Instance
|
||||
{
|
||||
static Mutex? held;
|
||||
static EventWaitHandle? call; // (set by a second Setup: "come to the front")
|
||||
static ManualResetEvent? quit; // (ends the thread that waits for that)
|
||||
static Thread? waiting;
|
||||
static Action? come;
|
||||
static (string Folder, string? TestRoot)? where;
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool AllowSetForegroundWindow(int process);
|
||||
|
||||
/// One spelling for a folder, however it was typed
|
||||
static string Same(string path)
|
||||
{
|
||||
try { path = Path.GetFullPath(path); } catch (Exception) { }
|
||||
return path.TrimEnd('\\', '/').ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// The lock's name for a folder: a number made from the whole path (and the test folder's), then the end of the path for
|
||||
/// whoever looks at it. (Local\: one user's session. An install is one user's, HKCU and %LOCALAPPDATA%)
|
||||
public static string Name(string folder, string? testRoot)
|
||||
{
|
||||
var text = Same(folder) + (testRoot != null ? "|" + Same(testRoot) : "");
|
||||
var h = 14695981039346656037UL; // (FNV-1a, 64 bits: a name, not a secret)
|
||||
foreach (var c in text) { h ^= c; h *= 1099511628211UL; }
|
||||
var tail = new string(Same(folder).Select(c => char.IsLetterOrDigit(c) ? c : '-').ToArray());
|
||||
return @"Local\TriforceSetup-" + h.ToString("x16") + "-" + (tail.Length > 60 ? tail.Substring(tail.Length - 60) : tail);
|
||||
}
|
||||
|
||||
/// True when this process is now the one Setup of that folder (or was already), false when another one is. Where no lock
|
||||
/// can be made at all nobody is refused: Setup must still start there. Taken and let go on the same thread (a mutex is a
|
||||
/// thread's).
|
||||
public static bool Take(string folder, string? testRoot)
|
||||
{
|
||||
if (held != null) return true;
|
||||
where = (folder, testRoot);
|
||||
var name = Name(folder, testRoot);
|
||||
Mutex m;
|
||||
try { m = new Mutex(false, name); }
|
||||
catch (UnauthorizedAccessException) { return false; } // (it is there, and belongs to a Setup run as administrator)
|
||||
catch (Exception) { return true; }
|
||||
try
|
||||
{
|
||||
if (!m.WaitOne(0)) { m.Dispose(); return false; }
|
||||
}
|
||||
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
|
||||
catch (Exception) { m.Dispose(); return true; }
|
||||
held = m;
|
||||
try
|
||||
{
|
||||
call = new EventWaitHandle(false, EventResetMode.AutoReset, name + "-show");
|
||||
call.Reset(); // (a call meant for the Setup before this one)
|
||||
}
|
||||
catch (Exception) { call = null; }
|
||||
if (come != null) Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The lock again after Release (a Setup that let go of it for its successor, which then did not start)
|
||||
public static bool TakeAgain() => where is not { } w || Take(w.Folder, w.TestRoot);
|
||||
|
||||
/// What the one Setup does when a second one is started: called on a thread of its own, each time
|
||||
public static void Listen(Action onCall)
|
||||
{
|
||||
come = onCall;
|
||||
if (held != null) Wait();
|
||||
}
|
||||
|
||||
static void Wait()
|
||||
{
|
||||
if (call == null || come == null || waiting != null) return;
|
||||
var (c, q, act) = (call, quit = new ManualResetEvent(false), come);
|
||||
waiting = new Thread(() =>
|
||||
{
|
||||
try { while (WaitHandle.WaitAny(new WaitHandle[] { q, c }) == 1) act(); }
|
||||
catch (Exception) { }
|
||||
}) { IsBackground = true };
|
||||
waiting.Start();
|
||||
}
|
||||
|
||||
/// Lets go of the folder: before the Setup that takes this one's place is started, and when the window has closed
|
||||
public static void Release()
|
||||
{
|
||||
try { quit?.Set(); waiting?.Join(2000); } catch (Exception) { }
|
||||
waiting = null;
|
||||
quit = null;
|
||||
try { call?.Dispose(); } catch (Exception) { }
|
||||
call = null;
|
||||
if (held == null) return;
|
||||
// (on another thread than the one that took it Windows refuses: then closing it is all there is, and the end of the
|
||||
// process lets go)
|
||||
try { held.ReleaseMutex(); } catch (Exception) { }
|
||||
held.Dispose();
|
||||
held = null;
|
||||
}
|
||||
|
||||
/// A second Setup asks the one that holds the folder to come to the front. False when there is nobody to ask (yet)
|
||||
public static bool CallForward(string folder, string? testRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!EventWaitHandle.TryOpenExisting(Name(folder, testRoot) + "-show", out var c)) return false;
|
||||
using (c)
|
||||
{
|
||||
// (Windows lets only the program in front hand the front on: this one, just started by the player, may)
|
||||
try { AllowSetForegroundWindow(-1); } catch (Exception) { }
|
||||
return c.Set();
|
||||
}
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// Room on a disk, asked before it is needed. A download or an unpacking that ran out of room stopped somewhere in the middle
|
||||
/// with Windows' own words for it and left half of itself behind; asked first, the player is told how much it takes and how
|
||||
/// much there is, before anything is written.
|
||||
static class Space
|
||||
{
|
||||
/// What a disk keeps free beyond what is about to be written to it
|
||||
public const long Margin = 32L << 20;
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool GetDiskFreeSpaceExW(string folder, out ulong forCaller, out ulong total, out ulong free);
|
||||
|
||||
/// The free bytes of the disk that holds a folder, asked of the nearest folder above it that is there (the folder itself may
|
||||
/// still be to make); null when that cannot be asked. (A test puts its own answer here.)
|
||||
public static Func<string, long?> Free = Ask;
|
||||
|
||||
static long? Ask(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var d = Path.GetFullPath(folder); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
|
||||
if (Directory.Exists(d))
|
||||
return GetDiskFreeSpaceExW(d, out var mine, out _, out _) ? (long)Math.Min(mine, (ulong)long.MaxValue) : null;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// The disk of a folder as the player knows it: C:\
|
||||
public static string Disk(string folder)
|
||||
{
|
||||
try { return Path.GetPathRoot(Path.GetFullPath(folder)) is { Length: > 0 } root ? root : folder; }
|
||||
catch (Exception) { return folder; }
|
||||
}
|
||||
|
||||
/// Null when the free bytes are room for need more of them and the margin, or are not known; else the sentence that says
|
||||
/// there is no room for what, how much it takes and how much is free (what it takes rounded up and what is free rounded
|
||||
/// down, so the two numbers never read the same)
|
||||
public static string? Problem(string what, long need, long? free, string disk)
|
||||
{
|
||||
need = Math.Max(0, need) + Margin;
|
||||
if (free is not { } f || f >= need) return null;
|
||||
return "There is no room for " + what + " on " + disk + ": it takes " + ((need + (1 << 20) - 1) >> 20) + " MB there, and " + (Math.Max(0, f) >> 20) +
|
||||
" MB are free. Make room and try again.";
|
||||
}
|
||||
|
||||
/// Is this the error of a disk that filled while it was written to?
|
||||
public static bool Full(Exception? e)
|
||||
{
|
||||
for (; e != null; e = e.InnerException)
|
||||
if (e is IOException && (uint)e.HResult >> 16 == 0x8007 && ((e.HResult & 0xFFFF) == 112 || (e.HResult & 0xFFFF) == 39))
|
||||
return true; // (ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// There is no room for what is about to be written (Space.Problem's sentence), said before any of it is
|
||||
sealed class NoRoomException : IOException
|
||||
{
|
||||
public NoRoomException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// A download stopped before its end (the connection was cut, went silent or closed early): its part is kept, and the next try
|
||||
/// goes on from it
|
||||
sealed class CutOffException : IOException
|
||||
{
|
||||
public CutOffException(string message, Exception? inner = null) : base(message, inner) { }
|
||||
}
|
||||
|
||||
/// A file fetched over HTTP into place through <file>.part, and checked before it is used.
|
||||
///
|
||||
/// A download that was cut off (the connection, Cancel, Setup closed) leaves its part file, and the next one goes on from it with
|
||||
/// a Range request where the server answers those; a server that does not sends the whole file, and the part is written over.
|
||||
/// A part is gone on from only as a part of the same file: <file>.part.of beside it names the address and the size it was begun
|
||||
/// for and the server's mark for the file it sent (its ETag, else its date), which goes back with the request (If-Range), so a
|
||||
/// file published again under the same address comes whole and is never joined to the beginning of the one before. A part
|
||||
/// without that note, or from a server that marks its files in neither way, is fetched anew.
|
||||
///
|
||||
/// The file gets its name only once it has the size the release lists (else the one the server names), and a server that names
|
||||
/// another size than the release's is not believed before its first byte.
|
||||
static class Download
|
||||
{
|
||||
/// How long the server may send nothing before the download is given up (its part stays to be gone on from). A read that
|
||||
/// waits on the network hears no cancellation: it is left waiting and its connection closed behind it, for Cancel too.
|
||||
public static TimeSpan Stall = TimeSpan.FromSeconds(60);
|
||||
|
||||
static void Remove(string file)
|
||||
{
|
||||
try { File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
|
||||
static string Mb(long bytes) => (bytes >> 20).ToString();
|
||||
|
||||
/// The server's mark for the file it sends, to hand back with If-Range: a strong ETag, else the date it was last changed
|
||||
static string Mark(HttpResponseMessage response) =>
|
||||
response.Headers.ETag is { IsWeak: false } tag ? tag.ToString()
|
||||
: response.Content.Headers.LastModified is { } changed ? changed.UtcDateTime.ToString("r") : "";
|
||||
|
||||
/// url to file, with progress (0..1, and the bytes that are there). size is what the release lists for it, 0 when it lists none
|
||||
public static async Task ToFile(HttpClient http, string url, string file, long size, Action<double, long> progress, CancellationToken token)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
var part = file + ".part";
|
||||
var note = part + ".of";
|
||||
long have = 0;
|
||||
RangeConditionHeaderValue? same = null;
|
||||
void Forget() { Remove(part); Remove(note); }
|
||||
if (File.Exists(part))
|
||||
{
|
||||
// (what the part is a part of: only the same address, size and mark are gone on from, and never a part as long as the file)
|
||||
string[] of = { };
|
||||
try { of = File.ReadAllLines(note); } catch (Exception) { }
|
||||
var length = new FileInfo(part).Length;
|
||||
if (of.Length >= 3 && of[0] == url && of[1] == size.ToString() && RangeConditionHeaderValue.TryParse(of[2], out same) && length > 0 && (size <= 0 || length < size))
|
||||
have = length;
|
||||
else Forget();
|
||||
}
|
||||
|
||||
using var stall = new CancellationTokenSource();
|
||||
using var either = CancellationTokenSource.CreateLinkedTokenSource(token, stall.Token);
|
||||
for (var again = false; ; again = true)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (have > 0)
|
||||
{
|
||||
request.Headers.Range = new RangeHeaderValue(have, null);
|
||||
request.Headers.IfRange = same;
|
||||
}
|
||||
stall.CancelAfter(Stall);
|
||||
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, either.Token).ConfigureAwait(false);
|
||||
var left = false; // (the answer was left with a read still waiting on it)
|
||||
try
|
||||
{
|
||||
var range = response.StatusCode == HttpStatusCode.PartialContent ? response.Content.Headers.ContentRange : null;
|
||||
// (416: the part is no part of what the server has now. A range other than the one asked for: not to be joined on.
|
||||
// Either way the whole file is asked for, once)
|
||||
if (have > 0 && !again && (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable || response.StatusCode == HttpStatusCode.PartialContent && !(range is { HasRange: true } && range.From == have)))
|
||||
{
|
||||
Forget();
|
||||
have = 0;
|
||||
continue;
|
||||
}
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.StatusCode == HttpStatusCode.PartialContent && (have == 0 || !(range is { HasRange: true } && range.From == have)))
|
||||
throw new IOException("The server sent a piece of " + name + " that was not asked for.");
|
||||
// (200 to a request for the rest: the server knows no ranges, or the file is another one now. The whole file comes)
|
||||
if (response.StatusCode != HttpStatusCode.PartialContent) have = 0;
|
||||
|
||||
// the whole file's size: the release's, which the server must not contradict; else the server's
|
||||
var told = have > 0 ? range!.Length ?? have + response.Content.Headers.ContentLength : response.Content.Headers.ContentLength;
|
||||
if (size > 0 && told is { } other && other != size)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server offers " + other + " bytes as " + name + ", and the release lists " + size + ". Nothing was downloaded.");
|
||||
}
|
||||
var total = size > 0 ? size : told ?? 0;
|
||||
if (total > 0 && Space.Problem(name, total - have, Space.Free(file), Space.Disk(file)) is { } none) throw new NoRoomException(none);
|
||||
if (have == 0)
|
||||
{
|
||||
Remove(part);
|
||||
try { File.WriteAllLines(note, new[] { url, size.ToString(), Mark(response) }); } catch (Exception) { }
|
||||
}
|
||||
progress(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have);
|
||||
|
||||
var from = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
|
||||
var gone = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var tooMuch = false;
|
||||
using (var to = new FileStream(part, have > 0 ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
using (either.Token.Register(() => gone.TrySetResult(true)))
|
||||
{
|
||||
var buffer = new byte[1 << 20];
|
||||
var shown = DateTime.MinValue;
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
stall.CancelAfter(Stall);
|
||||
var read = from.ReadAsync(buffer, 0, buffer.Length, either.Token);
|
||||
if (await Task.WhenAny(read, gone.Task).ConfigureAwait(false) != read)
|
||||
{
|
||||
// (Cancel, or nothing came: the read is left where it waits, whatever becomes of it)
|
||||
left = true;
|
||||
_ = read.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
|
||||
throw new OperationCanceledException();
|
||||
}
|
||||
var n = await read.ConfigureAwait(false);
|
||||
stall.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
if (n <= 0) break;
|
||||
await to.WriteAsync(buffer, 0, n).ConfigureAwait(false);
|
||||
have += n;
|
||||
// (a server that sends more than the file would fill the disk)
|
||||
if (total > 0 && have > total) { tooMuch = true; break; }
|
||||
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
|
||||
{
|
||||
shown = DateTime.UtcNow;
|
||||
progress(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (token.IsCancellationRequested) throw new OperationCanceledException(token);
|
||||
var of = total > 0 ? " of " + Mb(total) : "";
|
||||
if (stall.IsCancellationRequested)
|
||||
throw new CutOffException("The download of " + name + " stopped after " + Mb(have) + of + " MB: nothing more came for " + (int)Stall.TotalSeconds +
|
||||
" seconds. Try again: it goes on from there.");
|
||||
if (Space.Full(e)) throw;
|
||||
throw new CutOffException("The download of " + name + " was cut off after " + Mb(have) + of + " MB. Try again: it goes on from there.", e);
|
||||
}
|
||||
}
|
||||
if (tooMuch)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server sent more than the " + total + " bytes of " + name + ". Nothing of it was kept.");
|
||||
}
|
||||
if (total > 0 && have < total)
|
||||
throw new CutOffException("The download of " + name + " ended early, after " + Mb(have) + " of " + Mb(total) + " MB. Try again: it goes on from there.");
|
||||
break;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// (closing an answer can wait for the network as its read did: one that was left is closed where nobody waits for that)
|
||||
if (left) _ = Task.Run(() => { try { response.Dispose(); } catch (Exception) { } });
|
||||
else response.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// (before it is used: what is on the disk is what was counted)
|
||||
var there = new FileInfo(part).Length;
|
||||
if (there != have)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException(name + " is " + there + " bytes on the disk where " + have + " were downloaded. Nothing of it was kept.");
|
||||
}
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
File.Move(part, file);
|
||||
Remove(note);
|
||||
progress(1, have);
|
||||
}
|
||||
}
|
||||
|
||||
/// (Triforce) A copy that is never seen half done. Setup copied itself into the install folder and a save over the one there
|
||||
/// file by file, in place: a full disk, a file held open or Setup closed in the middle left a Setup that does not start under
|
||||
/// the name every shortcut starts, or half a save. Now the copy is written as <name>.partial beside its place and renamed into
|
||||
/// it once complete; what was there is replaced in one step (a file) or moved aside as <name>.old and removed after (a
|
||||
/// folder), and moved back when the new one cannot go in. A failure removes the partial and leaves what was there as it was.
|
||||
static class Partial
|
||||
{
|
||||
public const string Suffix = ".partial", Aside = ".old";
|
||||
|
||||
/// (testing) called with the partial once it is complete, before it goes into its place: a test checks what holds then, or
|
||||
/// throws to stand for a failure there
|
||||
public static Action<string>? Copied { get; set; }
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool MoveFileExW(string from, string to, int flags);
|
||||
|
||||
/// A file or a folder and what is in it, gone; quietly when it cannot be
|
||||
public static void Remove(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); }
|
||||
else if (Directory.Exists(path)) Directory.Delete(path, true);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// from copied to to, through to.partial: an older to is replaced in one step only once the copy is complete
|
||||
public static void CopyFile(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
File.Copy(from, partial, false);
|
||||
Copied?.Invoke(partial);
|
||||
if (!MoveFileExW(partial, to, 1 | 8)) // (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
|
||||
throw new IOException("Could not put " + to + " in place (Windows error " + Marshal.GetLastWin32Error() + ").");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder from copied as to.partial (one there from a copy that was cut off is removed first); its path. A failure
|
||||
/// removes what it wrote
|
||||
public static string Stage(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
Tree(from, partial);
|
||||
return partial;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
static void Tree(string from, string to)
|
||||
{
|
||||
Directory.CreateDirectory(to);
|
||||
foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), false);
|
||||
foreach (var d in Directory.GetDirectories(from)) Tree(d, Path.Combine(to, Path.GetFileName(d)));
|
||||
}
|
||||
|
||||
/// A complete partial folder put in to's place: the folder there moved aside as to.old first and removed after, or moved
|
||||
/// back when the new one cannot go in (the partial is then removed)
|
||||
public static void SwapIn(string partial, string to)
|
||||
{
|
||||
var old = to + Aside;
|
||||
try
|
||||
{
|
||||
Copied?.Invoke(partial);
|
||||
Remove(old);
|
||||
if (Directory.Exists(to)) Directory.Move(to, old);
|
||||
try { Directory.Move(partial, to); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(old)) Directory.Move(old, to); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
Remove(old);
|
||||
}
|
||||
|
||||
/// What a copy that was cut off (Setup closed in the middle of it) left beside to: the folder moved aside goes back when to
|
||||
/// is gone, and a partial goes
|
||||
public static void Recover(string to)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(to + Aside)) Directory.Move(to + Aside, to); } catch (Exception) { }
|
||||
if (Directory.Exists(to)) Remove(to + Aside);
|
||||
Remove(to + Suffix);
|
||||
}
|
||||
}
|
||||
|
||||
/// (Triforce) The save's lock between the game and Setup. The game holds <user>\save.lock open without sharing from its first
|
||||
/// save mount to its end (host/save_tx.h save_tx_lock); NX2navi holds <profile>\instance.lock the same way. Setup took a
|
||||
/// look at the running programs and then copied: a game started in between (the copy, or the player's choice before it)
|
||||
/// mounted a save half copied, and wrote it over the copy when it closed. Taken by Setup across the whole copy, the lock says
|
||||
/// for certain whether the game runs, and a game started meanwhile waits for it before it mounts its save.
|
||||
static class SaveLock
|
||||
{
|
||||
public const string Running = "The game is running: quit it first. It keeps its save open while it runs, and would write over the copy.";
|
||||
|
||||
/// The lock of a save folder <user>\save\<uid> (or a commit waiting in <user>\save-tx\<uid>\ready-<n>): <user>\save.lock, or
|
||||
/// instance.lock in NX2navi's profile folder; null for another kind of save folder (an emulator's), which has none
|
||||
public static string? PathOf(string save)
|
||||
{
|
||||
string dir;
|
||||
try { dir = Path.GetFullPath(save).TrimEnd('\\', '/'); }
|
||||
catch (Exception) { return null; }
|
||||
var parent = Path.GetDirectoryName(dir);
|
||||
if (parent != null && Path.GetDirectoryName(parent) is { } tx && string.Equals(Path.GetFileName(tx), "save-tx", StringComparison.OrdinalIgnoreCase))
|
||||
parent = Path.Combine(Path.GetDirectoryName(tx) ?? tx, "save");
|
||||
if (parent == null || !string.Equals(Path.GetFileName(parent), "save", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
var user = Path.GetDirectoryName(parent);
|
||||
if (string.IsNullOrEmpty(user)) return null;
|
||||
return Path.Combine(user, string.Equals(Path.GetFileName(user), "profile", StringComparison.OrdinalIgnoreCase) ? "instance.lock" : "save.lock");
|
||||
}
|
||||
|
||||
/// The lock of a save folder, held until it is disposed (an open handle that shares nothing). Null when the folder has none
|
||||
/// or it cannot be made there (nothing is locked: the copy goes on as before). InvalidOperationException (Running) when a
|
||||
/// game holds it
|
||||
public static FileStream? Take(string save)
|
||||
{
|
||||
if (PathOf(save) is not { } path) return null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
}
|
||||
catch (IOException e) when ((e.HResult & 0xFFFF) == 32 || (e.HResult & 0xFFFF) == 33) // (ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION)
|
||||
{
|
||||
throw new InvalidOperationException(Running);
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a player copies after a build that stopped, to paste where they ask for help: what Setup knows of the build, the build's
|
||||
/// last lines and setup.log's. The folder of the player's Windows account, which carries their name and is in most paths of a
|
||||
/// log, reads %USERPROFILE% in it.
|
||||
static class Report
|
||||
{
|
||||
/// How many of its last lines each log gives
|
||||
public const int Lines = 200;
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
static extern uint GetShortPathNameW(string path, StringBuilder into, uint size);
|
||||
|
||||
/// A folder's short name (C:\Users\LONGNA~1), which programs print for temporary files, when it has another one than its own
|
||||
public static string? Short(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var into = new StringBuilder(1024);
|
||||
var n = GetShortPathNameW(folder, into, (uint)into.Capacity);
|
||||
return n > 0 && n < into.Capacity && !string.Equals(into.ToString(), folder, StringComparison.OrdinalIgnoreCase) ? into.ToString() : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// The last lines of a text, at most so many, without the empty ones at its end
|
||||
public static string Tail(string text, int lines)
|
||||
{
|
||||
var all = text.Replace("\r", "").TrimEnd('\n', ' ').Split('\n');
|
||||
return string.Join(Environment.NewLine, all.Skip(Math.Max(0, all.Length - lines)));
|
||||
}
|
||||
|
||||
/// The text with each of the folders (the account's own, and its short name) read as %USERPROFILE%: in any case of its
|
||||
/// letters, with either slash or doubled ones between its parts, as a build's tools print paths. A folder that only begins
|
||||
/// with the same letters (C:\Users\Ann and C:\Users\Anna) is another one and stays.
|
||||
public static string NoName(string text, params string?[] folders)
|
||||
{
|
||||
foreach (var folder in folders.Where(f => !string.IsNullOrWhiteSpace(f)).OrderByDescending(f => f!.Length))
|
||||
{
|
||||
var parts = folder!.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) continue; // (a whole drive is nobody's name)
|
||||
var pattern = (folder.StartsWith("\\") || folder.StartsWith("/") ? @"[\\/]+" : "") + string.Join(@"[\\/]+", parts.Select(Regex.Escape)) + @"(?![\p{L}\p{N}])";
|
||||
text = Regex.Replace(text, pattern, "%USERPROFILE%", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// The report: what Setup knows, then the last lines of what the build said and of setup.log
|
||||
public static string Compose(IEnumerable<string> known, string build, string log, params string?[] folders)
|
||||
{
|
||||
var s = new StringBuilder();
|
||||
foreach (var line in known) s.AppendLine(line);
|
||||
s.AppendLine().AppendLine("---- the build's last lines ----").AppendLine(Tail(build, Lines));
|
||||
s.AppendLine().AppendLine("---- setup.log's last lines ----").AppendLine(Tail(log, Lines));
|
||||
return NoName(s.ToString(), folders);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Setup an update brought could not start, and what was done about it
|
||||
sealed class NotStartedException : Exception
|
||||
{
|
||||
public NotStartedException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// Setup replacing itself with a newer one, so that a new one that does not start is not what the player is left with.
|
||||
///
|
||||
/// The new exe takes the running one's name, the running one keeps running under another (Windows lets a running program be
|
||||
/// renamed, not written over), and the new one is started. No second program watches over this: the old Setup itself stays,
|
||||
/// out of sight, until the new one gives a sign that its window is up (a named event, named as Instance's lock is). A new
|
||||
/// Setup that cannot be started, or that ends with an error's exit code before that sign, is taken back: the old exe goes
|
||||
/// over it under the old name in one step, and the old Setup shows itself again. One that gives no sign and goes on running
|
||||
/// is left alone (slow to start, or a release that gives none): only what is known to have failed is undone.
|
||||
static class Handover
|
||||
{
|
||||
/// Up: its window came up. Failed: it could not come up. Unclear: neither is known (it runs on without the sign, or ended
|
||||
/// without an error, as a second Setup does that found another one open)
|
||||
public enum Outcome { Up, Failed, Unclear }
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool MoveFileExW(string from, string to, int flags);
|
||||
|
||||
static string Sign(string folder, string? testRoot) => Instance.Name(folder, testRoot) + "-up";
|
||||
|
||||
/// The old Setup, before it starts the new one: the sign it will wait for
|
||||
public static EventWaitHandle Expect(string folder, string? testRoot) => new(false, EventResetMode.ManualReset, Sign(folder, testRoot));
|
||||
|
||||
/// The new Setup, once its window is up: tells the Setup that started it, when one waits to hear it
|
||||
public static void Up(string folder, string? testRoot)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (EventWaitHandle.TryOpenExisting(Sign(folder, testRoot), out var up))
|
||||
using (up) up.Set();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// What became of the Setup that was started, within the time given
|
||||
public static Outcome Watch(Process started, WaitHandle up, TimeSpan limit)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var until = DateTime.UtcNow + limit; ;)
|
||||
{
|
||||
if (up.WaitOne(100)) return Outcome.Up;
|
||||
if (started.HasExited) return up.WaitOne(0) ? Outcome.Up : started.ExitCode != 0 ? Outcome.Failed : Outcome.Unclear;
|
||||
if (DateTime.UtcNow > until) return Outcome.Unclear;
|
||||
}
|
||||
}
|
||||
catch (Exception) { return Outcome.Unclear; }
|
||||
}
|
||||
|
||||
/// The running Setup (self) steps aside as previous, and fresh takes its name. A second step that fails is undone: there is
|
||||
/// always a Setup under the name the shortcuts start
|
||||
public static void Swap(string fresh, string self, string previous)
|
||||
{
|
||||
if (File.Exists(previous)) File.Delete(previous);
|
||||
File.Move(self, previous);
|
||||
try { File.Move(fresh, self); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Move(previous, self); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// The Setup before (previous, which may be the program that calls this) back over the one that did not start, in one step,
|
||||
/// so that no moment is without a Setup under that name. Tried for a few seconds: a virus scanner may still hold the new
|
||||
/// file. False when it could not be done, and then nothing was changed
|
||||
public static bool Restore(string previous, string self, int tries = 20)
|
||||
{
|
||||
for (var i = 0; i < tries; i++)
|
||||
{
|
||||
if (i > 0) Thread.Sleep(250);
|
||||
try
|
||||
{
|
||||
if (File.Exists(previous) && MoveFileExW(previous, self, 1 | 8)) return true; // (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
136
setup/Main.xaml
136
setup/Main.xaml
@@ -260,6 +260,24 @@
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<!-- (Triforce) words in the caption that are a setting: the Sounds choice (Shell.Sounds.cs) -->
|
||||
<Style x:Key="CaptionWords" TargetType="Button" BasedOn="{StaticResource Caption}">
|
||||
<Setter Property="Foreground" Value="{StaticResource TextDim}"/>
|
||||
<Setter Property="Width" Value="NaN"/>
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="#00000000">
|
||||
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="14,0"/>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True"><Setter Property="Foreground" Value="{StaticResource Gold}"/></Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
<Style x:Key="CaptionClose" TargetType="Button" BasedOn="{StaticResource Caption}">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
@@ -476,6 +494,32 @@
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- a row of a list one thing is picked from (the saves found, the mods): a gold bar beside the chosen one, a hairline under each -->
|
||||
<Style x:Key="Row" TargetType="ListBoxItem">
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<Grid Background="#00000000">
|
||||
<Border x:Name="B" Background="#00000000" Padding="16,10,12,10">
|
||||
<ContentPresenter/>
|
||||
</Border>
|
||||
<Rectangle x:Name="Bar" Width="2" HorizontalAlignment="Left" Fill="{StaticResource Gold}" Opacity="0" Margin="0,8"/>
|
||||
<Rectangle Style="{StaticResource Hair}" VerticalAlignment="Bottom"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="B" Property="Background" Value="#8012100C"/></Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="B" Property="Background" Value="#D912100C"/>
|
||||
<Setter TargetName="Bar" Property="Opacity" Value="1"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<Style TargetType="ToolTip">
|
||||
<Setter Property="Foreground" Value="{StaticResource Text}"/>
|
||||
<Setter Property="FontSize" Value="12"/>
|
||||
@@ -508,6 +552,11 @@
|
||||
<TextBlock x:Name="VersionText" Margin="14,0,0,1" VerticalAlignment="Center" FontSize="10.5" Foreground="{StaticResource TextFaint}"/>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" shell:WindowChrome.IsHitTestVisibleInChrome="True">
|
||||
<!-- (Triforce) the game's own menu sounds in Setup: Off, Low, Medium, High, the next one at each click -->
|
||||
<Button x:Name="SoundsButton" Style="{StaticResource CaptionWords}">
|
||||
<t:Caps x:Name="SoundsLabel" Label="Sounds" Gaps="1" FontSize="9.5" FontWeight="SemiBold"
|
||||
Foreground="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
<Button x:Name="MinButton" Style="{StaticResource Caption}" ToolTip="Minimize">
|
||||
<Rectangle Width="10" Height="1" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
@@ -592,15 +641,20 @@
|
||||
<StackPanel Grid.Row="1" Margin="0,30,0,0">
|
||||
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
|
||||
<Grid Margin="0,13,0,13">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="172"/><ColumnDefinition/></Grid.ColumnDefinitions>
|
||||
<Grid.ColumnDefinitions><ColumnDefinition Width="172"/><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="1,5,0,0">
|
||||
<Rectangle x:Name="GameMark" Style="{StaticResource Diamond}"/>
|
||||
<t:Caps Label="Your game" Style="{StaticResource FieldLabel}" Margin="12,0,0,0"/>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1">
|
||||
<StackPanel Grid.Column="1" Margin="0,0,16,0">
|
||||
<TextBlock x:Name="GameLine" Style="{StaticResource Value}"/>
|
||||
<TextBlock x:Name="GamePath" Style="{StaticResource Small}" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis" Margin="0,1,0,0"/>
|
||||
</StackPanel>
|
||||
<!-- (Triforce) with a game built: its mods (Shell.Mods.cs), and the game as a shortcut in Steam's library (Steam.cs) -->
|
||||
<StackPanel Grid.Column="2" VerticalAlignment="Top" Margin="0,-3,0,-7">
|
||||
<Button x:Name="ModsButton" Style="{StaticResource Link}" Content="Mods" HorizontalAlignment="Right"/>
|
||||
<Button x:Name="SteamButton" Style="{StaticResource Link}" Content="Add to Steam" HorizontalAlignment="Right" Margin="0,-5,0,0"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
|
||||
<Grid Margin="0,13,0,13">
|
||||
@@ -667,34 +721,7 @@
|
||||
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
|
||||
<t:Caps x:Name="SavesListLabel" Style="{StaticResource FieldLabel}" Label="Take the saves from" Margin="0,0,0,6"/>
|
||||
<ListBox x:Name="SaveList" Grid.Row="1" Background="#00000000" BorderThickness="0" Padding="0" Margin="-1,0,0,0"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" FocusVisualStyle="{x:Null}">
|
||||
<ListBox.ItemContainerStyle>
|
||||
<Style TargetType="ListBoxItem">
|
||||
<Setter Property="Cursor" Value="Hand"/>
|
||||
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<Grid Background="#00000000">
|
||||
<Border x:Name="B" Background="#00000000" Padding="16,10,12,10">
|
||||
<ContentPresenter/>
|
||||
</Border>
|
||||
<Rectangle x:Name="Bar" Width="2" HorizontalAlignment="Left" Fill="{StaticResource Gold}" Opacity="0" Margin="0,8"/>
|
||||
<Rectangle Style="{StaticResource Hair}" VerticalAlignment="Bottom"/>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="B" Property="Background" Value="#8012100C"/></Trigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="B" Property="Background" Value="#D912100C"/>
|
||||
<Setter TargetName="Bar" Property="Opacity" Value="1"/>
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ListBox.ItemContainerStyle>
|
||||
</ListBox>
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" FocusVisualStyle="{x:Null}" ItemContainerStyle="{StaticResource Row}"/>
|
||||
</Grid>
|
||||
<TextBlock x:Name="SavesInfo" Grid.Row="3" Style="{StaticResource Small}" Foreground="{StaticResource Text}" Margin="0,12,0,16" MinHeight="38"/>
|
||||
<Grid Grid.Row="4">
|
||||
@@ -707,6 +734,49 @@
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- page: mods (Triforce: the mods folder of the game as the game reads it, Mods.cs: on and off, the order, conflicts, adding
|
||||
from an archive, removing) -->
|
||||
<Grid x:Name="ModsPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
|
||||
<StackPanel>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
|
||||
<t:Caps Label="Mods" Style="{StaticResource Eyebrow}"/>
|
||||
</StackPanel>
|
||||
<TextBlock Text="Your mods" Style="{StaticResource Title}"/>
|
||||
<TextBlock Style="{StaticResource Body}" Margin="0,12,0,0"
|
||||
Text="Each folder in your game's mods folder is a mod. Where two change the same file, the one further down this list wins."/>
|
||||
</StackPanel>
|
||||
<Grid Grid.Row="1" Margin="0,18,0,0">
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="0,-5,0,0">
|
||||
<Button x:Name="ModsAdd" Style="{StaticResource Link}" Content="Add a mod" Margin="0,0,22,0"/>
|
||||
<Button x:Name="ModsOpen" Style="{StaticResource Link}" Content="Open the folder" Margin="0,0,22,0"/>
|
||||
<Button x:Name="ModsRescan" Style="{StaticResource Link}" Content="Look again"/>
|
||||
</StackPanel>
|
||||
<Button x:Name="ModsConflicts" Style="{StaticResource Link}" Content="Copy conflicts" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,-5,0,0" Visibility="Collapsed"/>
|
||||
<Rectangle Style="{StaticResource Hair}" VerticalAlignment="Bottom" Margin="0,30,0,0"/>
|
||||
</Grid>
|
||||
<ListBox x:Name="ModList" Grid.Row="2" Background="#00000000" BorderThickness="0" Padding="0" Margin="-1,0,0,0"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" FocusVisualStyle="{x:Null}" ItemContainerStyle="{StaticResource Row}"/>
|
||||
<TextBlock x:Name="ModsInfo" Grid.Row="3" Style="{StaticResource Small}" Foreground="{StaticResource Text}" Margin="0,12,0,14" MinHeight="57"/>
|
||||
<Grid Grid.Row="4">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<!-- (a mod with code patches or cheats was added, removed or switched since the game was built: they are compiled in) -->
|
||||
<Button x:Name="ModsBuild" Style="{StaticResource Link}" Foreground="{StaticResource Gold300}" VerticalAlignment="Center" HorizontalAlignment="Left" Visibility="Collapsed"/>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<Button x:Name="ModsBack" Style="{StaticResource Quiet}" Height="44" Padding="13,0" Content="Back" Margin="0,0,6,0"/>
|
||||
<Button x:Name="ModsUp" Style="{StaticResource Quiet}" Height="44" Padding="11,0" Margin="0,0,6,0" ToolTip="Load it earlier: the mods after it win over it">
|
||||
<Path Data="M0,5 L5,0 L10,5" StrokeThickness="1.4" Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
<Button x:Name="ModsDown" Style="{StaticResource Quiet}" Height="44" Padding="11,0" Margin="0,0,6,0" ToolTip="Load it later: it wins over the mods before it">
|
||||
<Path Data="M0,0 L5,5 L10,0" StrokeThickness="1.4" Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
|
||||
</Button>
|
||||
<Button x:Name="ModsRemove" Style="{StaticResource Quiet}" Height="44" Padding="13,0" Content="Remove" Margin="0,0,8,0"/>
|
||||
<Button x:Name="ModsToggle" Style="{StaticResource Primary}" MinWidth="140" Content="Switch off" IsEnabled="False"/>
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<!-- page: the forge (choose the game) -->
|
||||
<Grid x:Name="SetupPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
|
||||
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
|
||||
@@ -810,7 +880,11 @@
|
||||
</Grid>
|
||||
<Grid Grid.Row="2" Height="44">
|
||||
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
|
||||
<ToggleButton x:Name="ShowLog" Style="{StaticResource Link}" VerticalAlignment="Center" HorizontalAlignment="Left"/>
|
||||
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Left">
|
||||
<ToggleButton x:Name="ShowLog" Style="{StaticResource Link}" VerticalAlignment="Center"/>
|
||||
<!-- (after a build that stopped: what Setup knows of it, its last lines and setup.log's go to the clipboard, Shell.cs CopyTheReport) -->
|
||||
<Button x:Name="CopyReport" Style="{StaticResource Link}" VerticalAlignment="Center" Margin="22,0,0,0" Visibility="Collapsed"/>
|
||||
</StackPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<Button x:Name="OpenButton" Style="{StaticResource Quiet}" Height="44" Visibility="Collapsed" Margin="0,0,12,0"/>
|
||||
<Button x:Name="BackButton" Style="{StaticResource Quiet}" Height="44" Visibility="Collapsed"/>
|
||||
|
||||
857
setup/Mods.cs
Normal file
857
setup/Mods.cs
Normal file
@@ -0,0 +1,857 @@
|
||||
// (Triforce) The mods of a game folder as they lie on the disk: what the Mods page (Shell.Mods.cs) lists and does. Nothing here
|
||||
// needs the window: tests/test_setup_mods.py compiles this file with Guard.cs and runs it on folders of its own.
|
||||
//
|
||||
// The rules are the game's (host/mods.c). Nothing here changes them or keeps a list of its own, so a player who arranges the
|
||||
// folders by hand and one who uses the page see the same thing:
|
||||
// <game>\mods\<name>\romfs\... a mod is a folder, up to four levels down, that holds romfs, exefs or cheats
|
||||
// a name that starts with - or _ switches the folder off, and every mod in it (a name that starts with a dot is not looked at)
|
||||
// the name that sorts last wins among the mods that carry the same file (compared without case, as the game does)
|
||||
// On and off is a rename: with a "-" in front, or without. The order is a number in front of the name ("01-", "02-": what the
|
||||
// readme tells players to do by hand), kept apart from the mod's own name, so "-02-Tall grass" is the mod Tall grass, second,
|
||||
// switched off. RomFS files and cheats are read when the game starts; code patches (exefs) are built into the game, so a
|
||||
// change of those waits for the next build (CodeState).
|
||||
//
|
||||
// Every change is a rename or a new folder inside the mods folder and nowhere else (Within), and none is made while the game
|
||||
// runs (GameRuns). A mod that is removed goes to mods\.removed, which the game does not look at: nothing is ever deleted
|
||||
// but what an archive's own unpacking left in its temporary folder.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
/// What the Mods page tells the player when something cannot be done: a whole sentence, in plain words
|
||||
sealed class ModsException : Exception
|
||||
{
|
||||
public ModsException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// One mod as the game would find it
|
||||
sealed class Mod
|
||||
{
|
||||
public string Path = ""; // (its folder, in full)
|
||||
public string Rel = ""; // (its place under the mods folder, "/" between folders: what the game sorts by)
|
||||
public string Top = ""; // (the folder of the mods folder it is, or is in)
|
||||
public string Folder = ""; // (its folder's name as it is on the disk)
|
||||
public string Name = ""; // (its own name: the folder's without the switch and the number)
|
||||
public int? Number; // (the number its folder's name starts with, "01-", when it has one)
|
||||
public bool On;
|
||||
public string? OffAbove; // (the folder above it whose name switches it off, when it is not its own name that does)
|
||||
public List<string> Files = new(); // (its RomFS files as the game looks them up: lower case, "/" between folders)
|
||||
public long Bytes; // (of those files)
|
||||
public int Patches, Cheats; // (the files in its exefs and in its cheats folder)
|
||||
public bool RomfsIsLink; // (its romfs folder is a link, which the game leaves out)
|
||||
|
||||
public bool Deep => Rel.IndexOf('/') >= 0;
|
||||
/// Does it carry something that is built into the game (and so waits for the next build)?
|
||||
public bool Code => Patches > 0 || Cheats > 0;
|
||||
/// It carries code patches: what is built into the game (its cheats are read when the game starts: host/mod_cheats.c)
|
||||
public bool Built => Patches > 0;
|
||||
public override string ToString() => Rel;
|
||||
}
|
||||
|
||||
/// A file more than one of the mods that are on carry: the last of them, in the order the game loads them, wins
|
||||
sealed class Conflict
|
||||
{
|
||||
public string File = "";
|
||||
public List<Mod> Mods = new();
|
||||
public Mod Winner => Mods[Mods.Count - 1];
|
||||
}
|
||||
|
||||
static class Mods
|
||||
{
|
||||
/// The game this is built for: a mod in an emulator's layout names the game it is made for by this number
|
||||
public const string TitleId = "0400486024DEC000";
|
||||
/// What the page says when a mod with code patches was added, removed or switched since the game was built
|
||||
public const string BuildAgain = "Build again to apply";
|
||||
/// Where removed mods go, and where an archive is unpacked and checked before its mod moves in. Both names start with a
|
||||
/// dot: the game does not look at such folders (host/mods.c find_mods)
|
||||
public const string Removed = ".removed", Adding = ".adding-", Moving = ".moving-";
|
||||
static readonly string[] Parts = { "romfs", "exefs", "cheats" };
|
||||
|
||||
/// The most an archive may unpack to, and the most files it may hold (the game's own RomFS is 12 GB in 18,000 files)
|
||||
public static long MaxBytes = 32L << 30;
|
||||
public static int MaxFiles = 200000;
|
||||
/// How deep a path in an archive may go (the game follows a RomFS 32 folders down)
|
||||
public const int MaxDepth = 40;
|
||||
|
||||
/// Does the game of this game folder run? Asked before every change. (Shell.Mods.cs puts the look at the processes here, a
|
||||
/// test its own answer.)
|
||||
public static Func<string, bool> GameRuns = _ => false;
|
||||
|
||||
/// Windows' own tar.exe (bsdtar, in every Windows 10 and 11), which reads .7z and .rar; null when this PC has none.
|
||||
/// Only the one in System32 is ever started, never whatever "tar" the PATH names. (A test puts its own answer here.)
|
||||
public static Func<string?> Tar = () =>
|
||||
{
|
||||
var tar = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "tar.exe");
|
||||
return File.Exists(tar) ? tar : null;
|
||||
};
|
||||
|
||||
public static string FolderOf(string game) => System.IO.Path.Combine(game, "mods");
|
||||
|
||||
// ---- names ----
|
||||
|
||||
/// A folder's name taken apart: switched off (it starts with - or _), its number ("01-": two or three digits and a
|
||||
/// hyphen, so that "4K-grass" and "2024-pack" keep their names whole) and the mod's own name
|
||||
public static (bool Off, int? Number, string Name) Parse(string folder)
|
||||
{
|
||||
var off = folder.Length > 0 && (folder[0] == '-' || folder[0] == '_');
|
||||
var rest = folder.TrimStart('-', '_');
|
||||
var m = Regex.Match(rest, @"^(\d{2,3})-(.+)$", RegexOptions.Singleline);
|
||||
return m.Success ? (off, int.Parse(m.Groups[1].Value), m.Groups[2].Value) : (off, null, rest);
|
||||
}
|
||||
|
||||
/// As the game compares names (host/mods.c mod_cmp, _stricmp): byte by byte, the letters A to Z without case
|
||||
public static int Compare(string a, string b)
|
||||
{
|
||||
byte[] x = Encoding.UTF8.GetBytes(a), y = Encoding.UTF8.GetBytes(b);
|
||||
for (var i = 0; i < x.Length && i < y.Length; i++)
|
||||
{
|
||||
int p = x[i] >= 'A' && x[i] <= 'Z' ? x[i] + 32 : x[i], q = y[i] >= 'A' && y[i] <= 'Z' ? y[i] + 32 : y[i];
|
||||
if (p != q) return p - q;
|
||||
}
|
||||
return x.Length - y.Length;
|
||||
}
|
||||
|
||||
/// A RomFS path as the game looks it up (host/mods.c lower_slash): "/" between folders, A to Z in lower case
|
||||
static string Key(string rel)
|
||||
{
|
||||
var s = new StringBuilder(rel.Length);
|
||||
foreach (var c in rel) s.Append(c == '\\' ? '/' : c >= 'A' && c <= 'Z' ? (char)(c + 32) : c);
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
/// A mod's place in the list: its path as the game sorts it, read without the switches, so that a mod stays where it
|
||||
/// is when it is switched off
|
||||
static string Place(string rel) => string.Join("/", rel.Split('/').Select(p => p.TrimStart('-', '_')));
|
||||
|
||||
static bool Same(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
static string Hex8() => Guid.NewGuid().ToString("N").Substring(0, 8);
|
||||
|
||||
// ---- only inside the mods folder ----
|
||||
|
||||
static string Full(string path) => System.IO.Path.GetFullPath(path).TrimEnd('\\', '/');
|
||||
|
||||
/// Is the path the mods folder or inside it? Every folder made, renamed or written to is asked this first
|
||||
public static bool Inside(string mods, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
string root = Full(mods), full = Full(path);
|
||||
return Same(full, root) || full.StartsWith(root + "\\", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
static void Within(string mods, string path)
|
||||
{
|
||||
if (!Inside(mods, path)) throw new InvalidOperationException("Setup would have written outside the mods folder (" + path + "), and did not.");
|
||||
}
|
||||
|
||||
static void MakeFolder(string mods, string dir)
|
||||
{
|
||||
Within(mods, dir);
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
static void MoveFolder(string mods, string from, string to)
|
||||
{
|
||||
Within(mods, from);
|
||||
Within(mods, to);
|
||||
Directory.Move(from, to);
|
||||
}
|
||||
|
||||
static void Refuse(string mods)
|
||||
{
|
||||
if (GameRuns(System.IO.Path.GetDirectoryName(Full(mods)) ?? mods))
|
||||
throw new ModsException("Close the game first. Mods are added, switched, ordered and removed only while it is not running.");
|
||||
}
|
||||
|
||||
static string[] Folders(string dir)
|
||||
{
|
||||
try { return Directory.GetDirectories(dir); } catch (Exception) { return new string[0]; }
|
||||
}
|
||||
|
||||
static bool IsLink(string path)
|
||||
{
|
||||
try { return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
// ---- the list ----
|
||||
|
||||
/// The mods of a mods folder as the game finds them (host/mods.c find_mods), those that are off too, in the order the
|
||||
/// game loads them: the last one wins a file two of them carry
|
||||
/// (carried: false leaves out what each mod carries: the folders are found, their files not looked at)
|
||||
public static List<Mod> List(string mods, bool carried = true)
|
||||
{
|
||||
var found = new List<Mod>();
|
||||
if (Directory.Exists(mods)) Walk(mods, "", 0, null, found, carried);
|
||||
// (the game's order among the mods that are on; one that is off keeps the place it would have without its switch)
|
||||
found.Sort((a, b) =>
|
||||
{
|
||||
var c = Compare(Place(a.Rel), Place(b.Rel));
|
||||
return c != 0 ? c : string.CompareOrdinal(a.Rel, b.Rel);
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/// offAbove: the first folder above this one whose name switches off everything in it
|
||||
static void Walk(string dir, string rel, int depth, string? offAbove, List<Mod> found, bool carried)
|
||||
{
|
||||
var folder = depth > 0 ? System.IO.Path.GetFileName(dir) : "";
|
||||
var (isOff, number, name) = Parse(folder);
|
||||
// (romfs and exefs make a folder a mod for the game, whatever they are; a cheats folder for the build)
|
||||
bool Has(string part) => Directory.Exists(System.IO.Path.Combine(dir, part)) || part != "cheats" && File.Exists(System.IO.Path.Combine(dir, part));
|
||||
if (depth > 0 && Parts.Any(Has))
|
||||
{
|
||||
var m = new Mod
|
||||
{
|
||||
Path = dir, Rel = rel, Top = rel.Split('/')[0], Folder = folder, Name = name.Length > 0 ? name : folder, Number = number,
|
||||
On = offAbove == null && !isOff, OffAbove = offAbove,
|
||||
};
|
||||
if (carried) Fill(m);
|
||||
found.Add(m);
|
||||
return;
|
||||
}
|
||||
if (depth >= 4) return;
|
||||
foreach (var sub in Folders(dir))
|
||||
{
|
||||
var child = System.IO.Path.GetFileName(sub);
|
||||
if (child.Length == 0 || child[0] == '.') continue;
|
||||
Walk(sub, rel.Length > 0 ? rel + "/" + child : child, depth + 1, offAbove ?? (isOff ? folder : null), found, carried);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file the game reads for one of its RomFS paths ("Sound/Resource/x.bwav"): that of the last mod, among those that
|
||||
/// are on, that carries it (as host/mods.c looks it up: the path without case, a link to a folder not followed, the
|
||||
/// romfs folder itself neither when it is one), else the game's own under <game>\romfs. Null when neither has it.
|
||||
/// (For Setup's own use of the game's interface sounds, Sound.cs: the mods are found, their files not all looked at.)
|
||||
public static string? RomfsFile(string game, string rel)
|
||||
{
|
||||
var parts = rel.Replace('\\', '/').Split('/').Where(p => p.Length > 0).ToArray();
|
||||
if (parts.Length == 0 || parts.Any(p => p == "." || p == ".." || p.IndexOf(':') >= 0)) return null;
|
||||
string? In(string romfs)
|
||||
{
|
||||
var at = romfs;
|
||||
for (var i = 0; ; i++)
|
||||
{
|
||||
if (!Directory.Exists(at) || IsLink(at)) return null;
|
||||
at = System.IO.Path.Combine(at, parts[i]);
|
||||
if (i == parts.Length - 1) return File.Exists(at) ? at : null;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
foreach (var m in Enumerable.Reverse(List(FolderOf(game), false)).Where(m => m.On))
|
||||
if (In(System.IO.Path.Combine(m.Path, "romfs")) is { } theirs) return theirs;
|
||||
var own = System.IO.Path.Combine(new[] { game, "romfs" }.Concat(parts).ToArray());
|
||||
return File.Exists(own) ? own : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// What a mod carries: its RomFS files as the game indexes them (host/mods.c index_romfs: 32 folders deep, a link to a
|
||||
/// folder left out, the romfs folder itself too when it is one), and how many files its exefs and cheats folders hold
|
||||
static void Fill(Mod m)
|
||||
{
|
||||
var romfs = System.IO.Path.Combine(m.Path, "romfs");
|
||||
if (Directory.Exists(romfs))
|
||||
{
|
||||
if (IsLink(romfs)) m.RomfsIsLink = true;
|
||||
else Index(m, romfs, "", 0);
|
||||
}
|
||||
m.Files.Sort(string.CompareOrdinal);
|
||||
m.Patches = Count(System.IO.Path.Combine(m.Path, "exefs"));
|
||||
m.Cheats = Count(System.IO.Path.Combine(m.Path, "cheats"));
|
||||
}
|
||||
|
||||
static void Index(Mod m, string dir, string rel, int depth)
|
||||
{
|
||||
if (depth > 32) return;
|
||||
FileSystemInfo[] entries;
|
||||
try { entries = new DirectoryInfo(dir).GetFileSystemInfos(); } catch (Exception) { return; }
|
||||
foreach (var e in entries)
|
||||
{
|
||||
var isDir = (e.Attributes & FileAttributes.Directory) != 0;
|
||||
if (isDir && (e.Attributes & FileAttributes.ReparsePoint) != 0) continue;
|
||||
var path = rel.Length > 0 ? rel + "/" + e.Name : e.Name;
|
||||
if (isDir) Index(m, e.FullName, path, depth + 1);
|
||||
else
|
||||
{
|
||||
m.Files.Add(Key(path));
|
||||
try { m.Bytes += ((FileInfo)e).Length; } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int Count(string dir)
|
||||
{
|
||||
try { return Directory.Exists(dir) && !IsLink(dir) ? Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Length : 0; }
|
||||
catch (Exception) { return 0; }
|
||||
}
|
||||
|
||||
/// What a mod carries, in words: "1,204 game files, 2 code patch files, 1 cheat file"
|
||||
public static string Carries(Mod m)
|
||||
{
|
||||
string Some(int n, string one, string many) => n.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) + " " + (n == 1 ? one : many);
|
||||
var parts = new List<string>();
|
||||
if (m.Files.Count > 0 || !m.Code) parts.Add(m.RomfsIsLink ? "a romfs folder that is a link (the game leaves it out)" : Some(m.Files.Count, "game file", "game files"));
|
||||
if (m.Patches > 0) parts.Add(Some(m.Patches, "code patch file", "code patch files"));
|
||||
if (m.Cheats > 0) parts.Add(Some(m.Cheats, "cheat file", "cheat files"));
|
||||
return string.Join(", ", parts);
|
||||
}
|
||||
|
||||
// ---- conflicts ----
|
||||
|
||||
/// The files more than one of the mods that are on carry, each with its mods in the order the game loads them (the last
|
||||
/// one wins), sorted by file
|
||||
public static List<Conflict> Conflicts(IEnumerable<Mod> mods)
|
||||
{
|
||||
var by = new Dictionary<string, Conflict>(StringComparer.Ordinal);
|
||||
foreach (var m in mods.Where(m => m.On))
|
||||
foreach (var f in m.Files)
|
||||
{
|
||||
if (!by.TryGetValue(f, out var c)) by[f] = c = new Conflict { File = f };
|
||||
if (!c.Mods.Contains(m)) c.Mods.Add(m);
|
||||
}
|
||||
return by.Values.Where(c => c.Mods.Count > 1).OrderBy(c => c.File, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
/// For one mod: each other mod it shares files with, how many, and whether this one wins them (it loads later)
|
||||
public static List<(Mod Other, int Files, bool Wins)> Shared(Mod mod, IList<Mod> all, IEnumerable<Conflict> conflicts)
|
||||
{
|
||||
var count = new Dictionary<Mod, int>();
|
||||
foreach (var c in conflicts.Where(c => c.Mods.Contains(mod)))
|
||||
foreach (var other in c.Mods.Where(o => o != mod))
|
||||
count[other] = count.TryGetValue(other, out var n) ? n + 1 : 1;
|
||||
return count.OrderBy(p => all.IndexOf(p.Key)).Select(p => (p.Key, p.Value, all.IndexOf(mod) > all.IndexOf(p.Key))).ToList();
|
||||
}
|
||||
|
||||
/// Every conflict as text, for the clipboard: the file, the mods that carry it, and which one the game takes
|
||||
public static string ConflictText(IEnumerable<Conflict> conflicts)
|
||||
{
|
||||
var s = new StringBuilder();
|
||||
foreach (var c in conflicts)
|
||||
s.AppendLine(c.File + " <- " + c.Winner.Rel + " wins over " + string.Join(", ", c.Mods.Take(c.Mods.Count - 1).Select(m => m.Rel)));
|
||||
return s.ToString();
|
||||
}
|
||||
|
||||
// ---- what the game must be built again for ----
|
||||
|
||||
/// The code patches of the mods that are on, as one short mark: it changes when such a mod is added, removed, switched
|
||||
/// or edited, or when their order changes, and stays when only RomFS mods or cheats change or the folders are numbered
|
||||
/// anew. "" when no mod that is on carries any. Setup keeps the mark of the last build (Shell.Mods.cs)
|
||||
public static string CodeState(IEnumerable<Mod> mods)
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (var m in mods.Where(m => m.On && m.Built))
|
||||
{
|
||||
lines.Add("mod " + m.Name);
|
||||
foreach (var part in new[] { "exefs" }) // (not "cheats": the game reads those itself, at its start)
|
||||
{
|
||||
var dir = System.IO.Path.Combine(m.Path, part);
|
||||
string[] files = { };
|
||||
try { if (Directory.Exists(dir) && !IsLink(dir)) files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); } catch (Exception) { }
|
||||
foreach (var f in files.OrderBy(f => f, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var info = new FileInfo(f);
|
||||
lines.Add(part + f.Substring(dir.Length).ToLowerInvariant() + "|" + info.Length + "|" + info.LastWriteTimeUtc.Ticks);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lines.Count == 0) return "";
|
||||
var h = 14695981039346656037UL; // (FNV-1a, 64 bits: a mark, not a secret)
|
||||
foreach (var c in string.Join("\n", lines)) { h ^= c; h *= 1099511628211UL; }
|
||||
return h.ToString("x16");
|
||||
}
|
||||
|
||||
/// Is the game to be built again for its mods? built is the mark Setup kept at the last build: null when it kept none
|
||||
/// (then any code a mod that is on carries is news), and anything that is no mark ("changed": a mod with code was
|
||||
/// touched before any build was marked) never matches
|
||||
public static bool NeedsBuild(string state, string? built) => built == null ? state.Length > 0 : state != built;
|
||||
|
||||
// ---- on and off ----
|
||||
|
||||
/// Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns the folder as it is
|
||||
/// called now
|
||||
public static string SetOn(string mods, Mod mod, bool on)
|
||||
{
|
||||
Refuse(mods);
|
||||
if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var (off, _, _) = Parse(mod.Folder);
|
||||
if (on && mod.OffAbove != null)
|
||||
throw new ModsException(mod.Name + " is inside the folder " + mod.OffAbove + ", whose name switches off everything in it. Take the - or _ off that folder's name.");
|
||||
if (on == !off) return mod.Path;
|
||||
var name = on ? mod.Folder.TrimStart('-', '_') : "-" + mod.Folder;
|
||||
if (name.Length == 0 || name[0] == '.') throw new ModsException("Without the " + mod.Folder[0] + " in front, the folder " + mod.Folder + " has no name the game looks at. Rename it by hand.");
|
||||
var parent = System.IO.Path.GetDirectoryName(mod.Path)!;
|
||||
var target = System.IO.Path.Combine(parent, name);
|
||||
if (Directory.Exists(target) || File.Exists(target))
|
||||
throw new ModsException("There is already a folder named " + name + " in the mods folder. Rename or remove one of the two first.");
|
||||
try { MoveFolder(mods, mod.Path, target); }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException(mod.Name + " could not be switched " + (on ? "on" : "off") + ": " + e.Message + " Close any window that shows its folder and try again.");
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
// ---- the order ----
|
||||
|
||||
/// The folders of the mods folder that are mods or hold them, in the order the game loads them
|
||||
public static List<string> Tops(IEnumerable<Mod> mods) => mods.Select(m => m.Top).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
|
||||
/// Moves a mod one place: later (it then wins over the mod it passes) or earlier. The folders of the mods folder are
|
||||
/// numbered anew, 01- 02- ..., each keeping its own name and its switch; a mod deeper down (mods\contents\...) moves with
|
||||
/// the folder of the mods folder it is in. False when it is at that end already
|
||||
public static bool Move(string mods, Mod mod, bool later)
|
||||
{
|
||||
Refuse(mods);
|
||||
var tops = Tops(List(mods));
|
||||
var at = tops.FindIndex(t => Same(t, mod.Top));
|
||||
if (at < 0) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var to = at + (later ? 1 : -1);
|
||||
if (to < 0 || to >= tops.Count) return false;
|
||||
(tops[at], tops[to]) = (tops[to], tops[at]);
|
||||
Number(mods, tops);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// The folders, in this order, under the numbers 01- 02- ... (three digits from a hundred folders on): all of them or,
|
||||
/// when one cannot be renamed, none
|
||||
static void Number(string mods, List<string> tops)
|
||||
{
|
||||
var digits = tops.Count >= 100 ? "000" : "00";
|
||||
var plan = new List<(string From, string To)>();
|
||||
for (var i = 0; i < tops.Count; i++)
|
||||
{
|
||||
var (_, _, name) = Parse(tops[i]);
|
||||
var switches = tops[i].Substring(0, tops[i].Length - tops[i].TrimStart('-', '_').Length);
|
||||
var to = switches + (i + 1).ToString(digits) + "-" + name;
|
||||
if (!string.Equals(tops[i], to, StringComparison.Ordinal)) plan.Add((tops[i], to));
|
||||
}
|
||||
var leaving = new HashSet<string>(plan.Select(p => p.From), StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var (_, to) in plan)
|
||||
{
|
||||
var path = System.IO.Path.Combine(mods, to);
|
||||
if (!leaving.Contains(to) && (Directory.Exists(path) || File.Exists(path)))
|
||||
throw new ModsException("There is already something named " + to + " in the mods folder, where a mod's folder would be renamed to. Rename or remove it first. Nothing was changed.");
|
||||
}
|
||||
// (a new name that is another folder's old one, two mods of one name changing places: each goes through a name of its
|
||||
// own first, one the game does not look at)
|
||||
var steps = new List<(string From, string To)>();
|
||||
if (plan.Any(p => leaving.Contains(p.To)))
|
||||
{
|
||||
var aside = Moving + Hex8() + "-";
|
||||
steps.AddRange(plan.Select((p, i) => (p.From, aside + i)));
|
||||
steps.AddRange(plan.Select((p, i) => (aside + i, p.To)));
|
||||
}
|
||||
else steps.AddRange(plan);
|
||||
var done = new List<(string From, string To)>();
|
||||
try
|
||||
{
|
||||
foreach (var (from, to) in steps)
|
||||
{
|
||||
MoveFolder(mods, System.IO.Path.Combine(mods, from), System.IO.Path.Combine(mods, to));
|
||||
done.Add((from, to));
|
||||
}
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
var back = true;
|
||||
for (var i = done.Count - 1; i >= 0; i--)
|
||||
try { MoveFolder(mods, System.IO.Path.Combine(mods, done[i].To), System.IO.Path.Combine(mods, done[i].From)); }
|
||||
catch (Exception) { back = false; }
|
||||
throw new ModsException("The mods could not be put in that order: " + e.Message + (back ? " Nothing was changed." : " Some folders have their new names and some their old ones.") +
|
||||
" Close any window that shows a mod's folder and try again.");
|
||||
}
|
||||
}
|
||||
|
||||
// ---- removing ----
|
||||
|
||||
/// Takes a mod out of the game's sight: its folder moves into mods\.removed (under a free name), which the game does not
|
||||
/// look at. Nothing is deleted. Returns where it is now
|
||||
public static string Remove(string mods, Mod mod)
|
||||
{
|
||||
Refuse(mods);
|
||||
if (!Directory.Exists(mod.Path)) throw new ModsException(mod.Name + " is no longer in the mods folder.");
|
||||
var bin = System.IO.Path.Combine(mods, Removed);
|
||||
try
|
||||
{
|
||||
MakeFolder(mods, bin);
|
||||
var target = Free(bin, mod.Folder.TrimStart('-', '_') is { Length: > 0 } n ? n : "mod");
|
||||
MoveFolder(mods, mod.Path, target);
|
||||
return target;
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException(mod.Name + " could not be removed: " + e.Message + " Close any window that shows its folder and try again.");
|
||||
}
|
||||
}
|
||||
|
||||
/// dir\name, or the first of "name (2)", "name (3)" ... that is not there
|
||||
static string Free(string dir, string name)
|
||||
{
|
||||
for (var k = 1; ; k++)
|
||||
{
|
||||
var path = System.IO.Path.Combine(dir, k == 1 ? name : name + " (" + k + ")");
|
||||
if (!Directory.Exists(path) && !File.Exists(path)) return path;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- adding from an archive ----
|
||||
|
||||
static readonly HashSet<string> Devices = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
|
||||
|
||||
/// Is this a name Windows keeps for a device, with or without an extension (NUL, con.txt)? A file called so is the device
|
||||
public static bool IsDevice(string name)
|
||||
{
|
||||
var dot = name.IndexOf('.');
|
||||
var stem = (dot >= 0 ? name.Substring(0, dot) : name).TrimEnd(' ');
|
||||
// (COM1 to COM9 and LPT1 to LPT9; Windows takes the raised digits 1, 2 and 3 for digits there too)
|
||||
if (stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)))
|
||||
return stem[3] >= '1' && stem[3] <= '9' || stem[3] == (char)0xB9 || stem[3] == (char)0xB2 || stem[3] == (char)0xB3;
|
||||
return Devices.Contains(stem);
|
||||
}
|
||||
|
||||
/// Why a file of an archive must not be unpacked under its name, null when it may be: a path that leaves the folder it is
|
||||
/// unpacked into (from the disk's root, with a drive's letter, through ..), a device's name, a colon (a hidden stream of
|
||||
/// another file) and, where the name is known exactly (exact: a zip's own list), what Windows would drop or refuse, so that
|
||||
/// no file lands under another name than its own
|
||||
public static string? Unsafe(string name, bool exact)
|
||||
{
|
||||
var n = name.Replace('\\', '/');
|
||||
if (n.Trim().Length == 0) return "a file without a name";
|
||||
if (n[0] == '/') return "a path that starts at the disk's root";
|
||||
if (n.IndexOf(':') >= 0) return "a name with a colon or a drive's letter";
|
||||
var parts = n.Split('/').Where(p => p.Length > 0 && p != ".").ToArray();
|
||||
if (parts.Length > MaxDepth) return "folders more than " + MaxDepth + " deep";
|
||||
foreach (var p in parts)
|
||||
{
|
||||
if (p == "..") return "a path that leaves its own folder (..)";
|
||||
if (p.All(c => c == '.' || c == ' ')) return "a name of dots and spaces only";
|
||||
if (IsDevice(p)) return "a name Windows keeps for a device (" + p + ")";
|
||||
if (!exact) continue;
|
||||
if (p[p.Length - 1] == '.' || p[p.Length - 1] == ' ') return "a name that ends in a dot or a space, which Windows drops";
|
||||
if (p.Any(c => c < 32 || "<>\"|?*".IndexOf(c) >= 0)) return "a name with a character Windows does not allow";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static string Short(string name) => name.Length > 120 ? name.Substring(0, 117) + "..." : name;
|
||||
|
||||
/// Adds a mod from a .zip, .7z or .rar file. The archive is unpacked into a folder of its own inside the mods folder (one
|
||||
/// the game does not look at), what lies there is checked, the folder that holds romfs, exefs or cheats is looked for, and
|
||||
/// only then does that folder move into the mods folder under the mod's name. Anything else ends with a sentence that says
|
||||
/// why, and with nothing added. Returns the new mod
|
||||
public static Mod Add(string mods, string archive, Action<double>? progress = null)
|
||||
{
|
||||
Refuse(mods);
|
||||
var kind = System.IO.Path.GetExtension(archive).ToLowerInvariant();
|
||||
if (kind != ".zip" && kind != ".7z" && kind != ".rar") throw new ModsException("That is no .zip, .7z or .rar file.");
|
||||
if (!File.Exists(archive)) throw new ModsException("The file is not there: " + archive);
|
||||
string temp;
|
||||
try
|
||||
{
|
||||
MakeFolder(mods, mods);
|
||||
Sweep(mods);
|
||||
temp = System.IO.Path.Combine(mods, Adding + Hex8());
|
||||
MakeFolder(mods, temp);
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new ModsException("The mods folder could not be written to: " + e.Message);
|
||||
}
|
||||
try
|
||||
{
|
||||
var into = System.IO.Path.Combine(temp, "x");
|
||||
if (kind == ".zip") UnpackZip(mods, archive, into, progress);
|
||||
else UnpackWithTar(mods, archive, into, kind);
|
||||
Check(into, kind != ".zip");
|
||||
var root = FindRoot(into);
|
||||
// (the mod's name: its own folder's in the archive, else the archive's)
|
||||
var given = Same(root, into) || Generic(System.IO.Path.GetFileName(root)) ? System.IO.Path.GetFileNameWithoutExtension(archive) : System.IO.Path.GetFileName(root);
|
||||
var name = Clean(given);
|
||||
// (where the folders are numbered, the new mod gets the next number: it loads last, and wins, wherever its name would sort)
|
||||
var numbers = Tops(List(mods)).Select(t => Parse(t).Number).Where(n => n != null).Select(n => n!.Value).ToList();
|
||||
if (numbers.Count > 0 && Parse(name).Number == null) name = (numbers.Max() + 1).ToString(numbers.Max() + 1 >= 100 ? "000" : "00") + "-" + name;
|
||||
var target = Free(mods, name);
|
||||
MoveFolder(mods, root, target);
|
||||
progress?.Invoke(1);
|
||||
return List(mods).FirstOrDefault(m => Same(m.Path, target)) ?? throw new ModsException("The mod was unpacked into " + target + ", but the game would not find it there.");
|
||||
}
|
||||
catch (ModsException) { throw; }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is NotSupportedException || e is ArgumentException)
|
||||
{
|
||||
throw new ModsException(Space.Full(e) ? "The disk filled while the archive was unpacked. Nothing was added." : "The archive could not be unpacked: " + e.Message + " Nothing was added.");
|
||||
}
|
||||
finally { Delete(mods, temp); }
|
||||
}
|
||||
|
||||
/// What an adding that was cut off (Setup closed in the middle of it) left in the mods folder a day ago or longer
|
||||
static void Sweep(string mods)
|
||||
{
|
||||
foreach (var d in Folders(mods))
|
||||
try
|
||||
{
|
||||
if (Regex.IsMatch(System.IO.Path.GetFileName(d), "^" + Regex.Escape(Adding) + "[0-9a-f]{8}$") && DateTime.UtcNow - Directory.GetLastWriteTimeUtc(d) > TimeSpan.FromDays(1))
|
||||
Delete(mods, d);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// Removes the folder an archive was unpacked into, with what is left in it. A link in it is removed as a link: what it
|
||||
/// points to is never followed into
|
||||
static void Delete(string mods, string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Within(mods, dir);
|
||||
if (!Same(System.IO.Path.GetDirectoryName(Full(dir)) ?? "", Full(mods)) || !System.IO.Path.GetFileName(Full(dir)).StartsWith(Adding, StringComparison.Ordinal)) return;
|
||||
Empty(dir);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
static void Empty(string dir)
|
||||
{
|
||||
foreach (var e in new DirectoryInfo(dir).GetFileSystemInfos())
|
||||
{
|
||||
try
|
||||
{
|
||||
if ((e.Attributes & FileAttributes.ReadOnly) != 0) e.Attributes &= ~FileAttributes.ReadOnly;
|
||||
if ((e.Attributes & FileAttributes.Directory) != 0 && (e.Attributes & FileAttributes.ReparsePoint) == 0) Empty(e.FullName);
|
||||
else if ((e.Attributes & FileAttributes.Directory) != 0) Directory.Delete(e.FullName, false);
|
||||
else File.Delete(e.FullName);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
try { Directory.Delete(dir, false); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// A zip, with .NET's own reader (what unpacks Setup's tools, Setup.cs Tools.Unpack). Its list is checked whole before the
|
||||
/// first file is written: every name, no links, no two files of one name, what it says it unpacks to against the bound and
|
||||
/// against the room on the disk. A file that turns out longer than its entry said stops the unpacking
|
||||
static void UnpackZip(string mods, string archive, string into, Action<double>? progress)
|
||||
{
|
||||
ZipArchive zip;
|
||||
try { zip = ZipFile.OpenRead(archive); }
|
||||
catch (Exception e) when (e is InvalidDataException || e is IOException || e is UnauthorizedAccessException || e is NotSupportedException)
|
||||
{
|
||||
throw new ModsException("That is not a zip file Setup can read (" + e.Message + "). Nothing was added.");
|
||||
}
|
||||
using (zip)
|
||||
{
|
||||
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> entries;
|
||||
try { entries = zip.Entries; }
|
||||
// (.NET reads the list of names only now, and gives up on a name with a character no path may have)
|
||||
catch (ArgumentException) { throw new ModsException("The archive holds a name with a character Windows does not allow. Nothing was unpacked."); }
|
||||
catch (InvalidDataException e) { throw new ModsException("That is not a zip file Setup can read (" + e.Message + "). Nothing was added."); }
|
||||
if (entries.Count > MaxFiles) throw new ModsException("The archive holds " + entries.Count + " files, more than the " + MaxFiles + " a mod may have. Nothing was added.");
|
||||
long total = 0;
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var e in entries)
|
||||
{
|
||||
if (Unsafe(e.FullName, true) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Short(e.FullName) + "\". Nothing was unpacked.");
|
||||
// (how the zip marks what an entry is: Unix's file type in the high half of its attributes, Windows' in the low)
|
||||
var type = (e.ExternalAttributes >> 16) & 0xF000;
|
||||
if (type == 0xA000 || (e.ExternalAttributes & 0x400) != 0) throw new ModsException("The archive holds a link (\"" + Short(e.FullName) + "\"), which could point anywhere on this PC. Nothing was unpacked.");
|
||||
if (type != 0 && type != 0x8000 && type != 0x4000) throw new ModsException("The archive holds something that is neither a file nor a folder (\"" + Short(e.FullName) + "\"). Nothing was unpacked.");
|
||||
var plain = string.Join("/", e.FullName.Replace('\\', '/').Split('/').Where(p => p.Length > 0 && p != "."));
|
||||
if (plain.Length == 0) continue;
|
||||
if (!seen.Add(plain)) throw new ModsException("The archive holds two files of one name (\"" + Short(e.FullName) + "\"). Nothing was unpacked.");
|
||||
if (e.Length < 0 || e.Length > MaxBytes || (total += e.Length) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (Space.Problem("this mod", total + entries.Count * 4096L, Space.Free(mods), Space.Disk(mods)) is { } none) throw new ModsException(none);
|
||||
MakeFolder(mods, into);
|
||||
var root = Full(into) + "\\";
|
||||
long written = 0;
|
||||
var buffer = new byte[1 << 16];
|
||||
for (var i = 0; i < entries.Count; i++)
|
||||
{
|
||||
var e = entries[i];
|
||||
var name = e.FullName.Replace('\\', '/');
|
||||
var dest = System.IO.Path.GetFullPath(System.IO.Path.Combine(into, name.Replace('/', '\\')));
|
||||
if (!(dest + "\\").StartsWith(root, StringComparison.OrdinalIgnoreCase)) throw new ModsException("The archive holds a path that leaves its own folder: \"" + Short(e.FullName) + "\".");
|
||||
Within(mods, dest);
|
||||
if (name.EndsWith("/")) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(dest)!);
|
||||
long size = 0;
|
||||
using (var from = e.Open())
|
||||
using (var to = new FileStream(dest, FileMode.CreateNew, FileAccess.Write, FileShare.None))
|
||||
for (int n; (n = from.Read(buffer, 0, buffer.Length)) > 0;)
|
||||
{
|
||||
if ((size += n) > e.Length || (written += n) > MaxBytes) throw new ModsException("The archive unpacks to more than it says (\"" + Short(e.FullName) + "\"). Nothing was added.");
|
||||
to.Write(buffer, 0, n);
|
||||
}
|
||||
try { File.SetLastWriteTime(dest, e.LastWriteTime.DateTime); } catch (Exception) { }
|
||||
if ((i & 31) == 0) progress?.Invoke(0.95 * i / entries.Count);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static string TooBig() => "The archive unpacks to more than " + (MaxBytes >> 30) + " GB, the most a mod may take. Nothing was added.";
|
||||
|
||||
static string ByHand(string kind) => " Unpack the " + kind + " file yourself and put the mod's folder (the one that holds romfs) into the mods folder.";
|
||||
|
||||
/// A .7z or .rar, with Windows' own tar.exe: nothing that reads them is in Setup or in the repository. Its list is asked
|
||||
/// for first, twice: the names (checked as a zip's are, as far as tar's spelling of them can be trusted) and the long form,
|
||||
/// whose first letter says what each entry is (a link is refused) and whose fifth word is its size (counted against the
|
||||
/// bound and the room on the disk). tar then unpacks into the folder, without -P: it refuses paths that leave it. What
|
||||
/// lies there afterwards is checked again, as files (Check)
|
||||
static void UnpackWithTar(string mods, string archive, string into, string kind)
|
||||
{
|
||||
var tar = Tar();
|
||||
if (tar == null)
|
||||
throw new ModsException("This PC has no tar.exe in its System32 folder (Windows 10 and 11 bring one), and Setup opens " + kind + " files with nothing else." + ByHand(kind));
|
||||
MakeFolder(mods, into);
|
||||
var (code, names, error) = Run(tar, "-tf \"" + archive + "\"", into, MaxFiles + 1);
|
||||
if (code != 0) throw new ModsException("This PC's tar.exe could not read the " + kind + " file (" + Reason(error, code) + ")." + ByHand(kind));
|
||||
if (names.Count > MaxFiles) throw new ModsException("The archive holds more than the " + MaxFiles + " files a mod may have. Nothing was added.");
|
||||
foreach (var n in names)
|
||||
if (Unsafe(n, false) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Short(n) + "\". Nothing was unpacked.");
|
||||
var (code2, lines, error2) = Run(tar, "-tvf \"" + archive + "\"", into, MaxFiles + 1);
|
||||
if (code2 != 0 || lines.Count != names.Count) throw new ModsException("This PC's tar.exe could not list the " + kind + " file (" + Reason(error2, code2) + ")." + ByHand(kind));
|
||||
long total = 0;
|
||||
for (var i = 0; i < lines.Count; i++)
|
||||
{
|
||||
var words = lines[i].Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (words.Length < 6 || words[0].Length < 10 || !long.TryParse(words[4], out var size) || size < 0)
|
||||
throw new ModsException("This PC's tar.exe lists the " + kind + " file in a way Setup cannot read, so it was not unpacked." + ByHand(kind));
|
||||
if (words[0][0] == 'l' || words[0][0] == 'h') throw new ModsException("The archive holds a link (\"" + Short(names[i]) + "\"), which could point anywhere on this PC. Nothing was unpacked.");
|
||||
if (words[0][0] != '-' && words[0][0] != 'd') throw new ModsException("The archive holds something that is neither a file nor a folder (\"" + Short(names[i]) + "\"). Nothing was unpacked.");
|
||||
if (size > MaxBytes || (total += size) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (Space.Problem("this mod", total + names.Count * 4096L, Space.Free(mods), Space.Disk(mods)) is { } none) throw new ModsException(none);
|
||||
Within(mods, into);
|
||||
var (code3, _, error3) = Run(tar, "-xf \"" + archive + "\" -C \"" + into + "\"", into, 0);
|
||||
if (code3 != 0) throw new ModsException("This PC's tar.exe could not unpack the " + kind + " file (" + Reason(error3, code3) + "). Nothing was added." + ByHand(kind));
|
||||
}
|
||||
|
||||
static string Reason(string error, int code)
|
||||
{
|
||||
var line = error.Replace("\r", "").Split('\n').Select(l => l.Trim()).FirstOrDefault(l => l.Length > 0);
|
||||
return line != null ? Short(line) : "exit code " + code;
|
||||
}
|
||||
|
||||
/// tar with these words, its lines (at most so many: one more and it is stopped) and what it said of errors
|
||||
static (int Code, List<string> Lines, string Error) Run(string exe, string arguments, string dir, int most)
|
||||
{
|
||||
var si = new ProcessStartInfo(exe, arguments)
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = dir,
|
||||
};
|
||||
using var p = Process.Start(si)!;
|
||||
var error = p.StandardError.ReadToEndAsync();
|
||||
var lines = new List<string>();
|
||||
for (string? line; (line = p.StandardOutput.ReadLine()) != null;)
|
||||
{
|
||||
if (line.Length == 0) continue;
|
||||
lines.Add(line);
|
||||
if (lines.Count > most && most > 0)
|
||||
{
|
||||
try { p.Kill(); } catch (Exception) { }
|
||||
break;
|
||||
}
|
||||
}
|
||||
p.WaitForExit();
|
||||
string said;
|
||||
try { said = error.Result; } catch (Exception) { said = ""; }
|
||||
return (lines.Count > most && most > 0 ? 0 : p.ExitCode, lines, said);
|
||||
}
|
||||
|
||||
// (BY_HANDLE_FILE_INFORMATION: its three times are pairs of 32-bit numbers, so nothing in it is aligned to 8 bytes)
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
struct FileInformation
|
||||
{
|
||||
public uint Attributes;
|
||||
public long Created, Accessed, Written;
|
||||
public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out FileInformation information);
|
||||
|
||||
/// Has the file a second name somewhere (a hard link)? Writing to one of them writes to the other
|
||||
static bool HasOtherName(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var f = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return GetFileInformationByHandle(f.SafeFileHandle, out var information) && information.Links > 1;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// What an archive unpacked to, looked at as it lies on the disk before any of it moves into the mods folder: no link of
|
||||
/// any kind, nothing under a device's name, not more files or bytes than a mod may have
|
||||
static void Check(string into, bool links)
|
||||
{
|
||||
var files = 0;
|
||||
long bytes = 0;
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (depth > MaxDepth) throw new ModsException("The archive's folders go more than " + MaxDepth + " deep. Nothing was added.");
|
||||
foreach (var e in new DirectoryInfo(dir).GetFileSystemInfos())
|
||||
{
|
||||
var shown = Short(e.FullName.Substring(Full(into).Length + 1));
|
||||
if ((e.Attributes & FileAttributes.ReparsePoint) != 0) throw new ModsException("The archive holds a link (\"" + shown + "\"), which could point anywhere on this PC. Nothing was added.");
|
||||
if (IsDevice(e.Name)) throw new ModsException("The archive holds a name Windows keeps for a device (\"" + shown + "\"). Nothing was added.");
|
||||
if ((e.Attributes & FileAttributes.Directory) != 0) { Look(e.FullName, depth + 1); continue; }
|
||||
if (links && HasOtherName(e.FullName)) throw new ModsException("The archive holds a link (\"" + shown + "\"), which could point anywhere on this PC. Nothing was added.");
|
||||
if (++files > MaxFiles) throw new ModsException("The archive holds more than the " + MaxFiles + " files a mod may have. Nothing was added.");
|
||||
if ((bytes += ((FileInfo)e).Length) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
}
|
||||
Look(into, 0);
|
||||
}
|
||||
|
||||
/// The folder of what was unpacked that is the mod: the one that holds romfs, exefs or cheats, looked for four folders
|
||||
/// down as the game looks. None, several (a download with versions to choose from) or one for another game are said so
|
||||
static string FindRoot(string into)
|
||||
{
|
||||
var found = new List<string>();
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (Parts.Any(p => Directory.Exists(System.IO.Path.Combine(dir, p)))) { found.Add(dir); return; }
|
||||
if (depth >= 4) return;
|
||||
foreach (var sub in Folders(dir)) Look(sub, depth + 1);
|
||||
}
|
||||
Look(into, 0);
|
||||
if (found.Count == 0)
|
||||
throw new ModsException("The archive holds no romfs, exefs or cheats folder, so Setup cannot tell where the mod's files belong. Nothing was added. " +
|
||||
"(A mod's files go into mods\\<name>\\romfs, laid out as the game's own files are.)");
|
||||
if (found.Count > 1)
|
||||
{
|
||||
var names = found.Select(f => System.IO.Path.GetFileName(f)).Take(4).ToList();
|
||||
throw new ModsException("The archive holds " + found.Count + " mods (" + string.Join(", ", names) + (found.Count > 4 ? ", ..." : "") + "), most likely versions to choose from. Nothing was added. " +
|
||||
"Unpack it yourself and put the one you want into the mods folder.");
|
||||
}
|
||||
// (an emulator's layout, ...\contents\<title id>\romfs: made for the game of that number)
|
||||
var title = System.IO.Path.GetFileName(found[0]);
|
||||
if (!Same(found[0], into) && Regex.IsMatch(title, "^[0-9A-Fa-f]{16}$") && !Same(title, TitleId))
|
||||
throw new ModsException("The archive holds a mod for another game (title " + title.ToUpperInvariant() + "), not for this one (" + TitleId + "). Nothing was added.");
|
||||
return found[0];
|
||||
}
|
||||
|
||||
/// A folder's name in an archive that says nothing about the mod: an emulator's layout, or the part itself
|
||||
static bool Generic(string name) =>
|
||||
Regex.IsMatch(name, "^[0-9A-Fa-f]{16}$") || new[] { "contents", "atmosphere", "mods", "mod" }.Any(g => Same(g, name));
|
||||
|
||||
/// A name for the mod's folder from an archive's or a folder's name: what Windows allows, and nothing in front that would
|
||||
/// switch the mod off or hide it from the game
|
||||
public static string Clean(string name)
|
||||
{
|
||||
var s = new string(name.Where(c => c >= 32 && "<>:\"/\\|?*".IndexOf(c) < 0).ToArray()).Trim();
|
||||
s = s.TrimStart('-', '_', '.', ' ').TrimEnd('.', ' ');
|
||||
if (s.Length > 80) s = s.Substring(0, 80).TrimEnd('.', ' ');
|
||||
return s.Length == 0 || IsDevice(s) ? "Mod" : s;
|
||||
}
|
||||
}
|
||||
@@ -281,23 +281,37 @@ static class Saves
|
||||
|
||||
/// Copies one save set over another: the destination's old files are moved to the backup folder first (nothing is merged slot by
|
||||
/// slot: the copy is exactly the source). Returns the backup folder, or null when there was nothing to back up.
|
||||
/// ((Triforce) The games' save locks are held across all of it (Guard.cs SaveLock: a game that runs refuses it, one started
|
||||
/// meanwhile waits), and the copy is made as <save>.partial and swapped in once complete (Guard.cs Partial): a copy that fails
|
||||
/// or is cut off leaves the destination as it was, never half a save. TRIFORCE_SAVE_LOCK=0: no lock, as before)
|
||||
public static string? Copy(string from, string to, string backupRoot, string label)
|
||||
{
|
||||
var src = Path.GetFullPath(from).TrimEnd('\\');
|
||||
var dst = Path.GetFullPath(to).TrimEnd('\\');
|
||||
if (!Install.Allowed(dst)) throw new InvalidOperationException(Install.TestOnly);
|
||||
if (string.Equals(src, dst, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("That is the same save folder.");
|
||||
var locking = Environment.GetEnvironmentVariable("TRIFORCE_SAVE_LOCK") != "0";
|
||||
using var dstLock = locking ? SaveLock.Take(dst) : null;
|
||||
using var srcLock = locking && !string.Equals(SaveLock.PathOf(src), SaveLock.PathOf(dst), StringComparison.OrdinalIgnoreCase) ? SaveLock.Take(src) : null;
|
||||
Partial.Recover(dst);
|
||||
var partial = Partial.Stage(src, dst);
|
||||
string? backup = null;
|
||||
if (Directory.Exists(dst) && Directory.EnumerateFileSystemEntries(dst).Any())
|
||||
try
|
||||
{
|
||||
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
|
||||
backup = Path.Combine(backupRoot, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + safe);
|
||||
Directory.CreateDirectory(backup);
|
||||
CopyTree(dst, backup);
|
||||
Directory.Delete(dst, true);
|
||||
if (Directory.Exists(dst) && Directory.EnumerateFileSystemEntries(dst).Any())
|
||||
{
|
||||
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
|
||||
backup = Path.Combine(backupRoot, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + safe);
|
||||
Directory.CreateDirectory(backup);
|
||||
CopyTree(dst, backup);
|
||||
}
|
||||
}
|
||||
Directory.CreateDirectory(dst);
|
||||
CopyTree(src, dst);
|
||||
catch (Exception)
|
||||
{
|
||||
Partial.Remove(partial);
|
||||
throw;
|
||||
}
|
||||
Partial.SwapIn(partial, dst);
|
||||
// (into Triforce: its working copy and any finished commit still waiting belong to the save that was replaced, and the game
|
||||
// would put such a commit over the copy at its next start)
|
||||
if (TriforceTx(dst) is { } tx && Directory.Exists(tx))
|
||||
|
||||
165
setup/Setup.cs
165
setup/Setup.cs
@@ -46,9 +46,33 @@ static class Program
|
||||
[STAThread]
|
||||
static int Main(string[] args)
|
||||
{
|
||||
// ((Triforce) Long paths. The manifest's longPathAware (build.ps1) is not enough for .NET Framework's own path checks: an
|
||||
// exe that csc builds has no TargetFramework attribute, is taken as written for 4.0, and keeps the legacy path handling
|
||||
// that refuses 260 characters and more (PathTooLongException, in a test with Windows' LongPathsEnabled on). These two
|
||||
// switches are what 4.6.2 and newer default to; they must be set before any path is looked at (Install's fields below:
|
||||
// System.IO keeps the first value it reads). TRIFORCE_LEGACY_PATHS=1: as before)
|
||||
if (Environment.GetEnvironmentVariable("TRIFORCE_LEGACY_PATHS") != "1")
|
||||
{
|
||||
AppContext.SetSwitch("Switch.System.IO.UseLegacyPathHandling", false);
|
||||
AppContext.SetSwitch("Switch.System.IO.BlockLongPaths", false);
|
||||
}
|
||||
try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; } catch (Exception) { }
|
||||
Install.NoWrites = args.Contains("--snapshot");
|
||||
if (args.Contains("--uninstall")) return Install.Uninstall(args.Contains("--quiet")) ? 0 : 1;
|
||||
// (one Setup at a time for an install, Guard.cs Instance: the folder Setup works in names the lock)
|
||||
var home = Install.InstalledDir ?? Install.SelfDir;
|
||||
if (args.Contains("--uninstall"))
|
||||
{
|
||||
// (not under a Setup that is open: its tools and its build's work folder would go while it uses them)
|
||||
if (!Instance.Take(home, Install.TestRoot))
|
||||
{
|
||||
Log("not uninstalled: Triforce Setup is open for " + home);
|
||||
Instance.CallForward(home, Install.TestRoot);
|
||||
if (!args.Contains("--quiet"))
|
||||
MessageBox.Show("Triforce Setup is open. Close it, then uninstall again.", "Uninstall Triforce", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return 1;
|
||||
}
|
||||
return Install.Uninstall(args.Contains("--quiet")) ? 0 : 1;
|
||||
}
|
||||
// (silent install: --install-to <folder> [--no-desktop] [--no-startmenu]; the installed Setup then starts as usual)
|
||||
var to = Array.IndexOf(args, "--install-to");
|
||||
if (to >= 0 && to + 1 < args.Length)
|
||||
@@ -76,6 +100,7 @@ static class Program
|
||||
var cv = Array.IndexOf(args, "--convert-saves");
|
||||
if (cv >= 0 && cv + 2 < args.Length)
|
||||
{
|
||||
if (!Instance.Take(home, Install.TestRoot)) { Log("convert-saves: not done, Triforce Setup is open for " + home); return 1; }
|
||||
var b = Saves.Copy(args[cv + 1], args[cv + 2], Path.Combine(Install.SelfDir, "save-backups"), "test");
|
||||
Log("convert-saves " + args[cv + 1] + " -> " + args[cv + 2] + ", backup " + (b ?? "none"));
|
||||
return 0;
|
||||
@@ -115,6 +140,27 @@ static class Program
|
||||
{
|
||||
try { Directory.CreateDirectory(unattended!); File.AppendAllText(Path.Combine(unattended!, "error.txt"), e + Environment.NewLine); } catch (Exception) { }
|
||||
}
|
||||
// (a second start for the same install must not fetch, build, update or convert saves beside the first: it asks the
|
||||
// first one's window to the front and ends. --snapshot only draws the pages, reading and writing nothing of an install)
|
||||
if (shots < 0)
|
||||
for (var tries = 0; !Instance.Take(home, Install.TestRoot); tries++)
|
||||
{
|
||||
if (Instance.CallForward(home, Install.TestRoot))
|
||||
{
|
||||
Log("Triforce Setup is already open for " + home + ": its window was asked to the front, and this start ends");
|
||||
return 0;
|
||||
}
|
||||
// (nobody to ask: the first one is only just starting or closing. In a moment it can be asked, or the folder is free)
|
||||
if (tries >= 30)
|
||||
{
|
||||
Log("Triforce Setup is already running for " + home + " and does not answer: this start ends");
|
||||
if (unattended == null)
|
||||
MessageBox.Show("Triforce Setup is already running, but its window could not be brought to the front.\n\nClose it (in Task Manager: TriforceSetup.exe) and start Triforce again.",
|
||||
"Triforce Setup", MessageBoxButton.OK, MessageBoxImage.Information);
|
||||
return 1;
|
||||
}
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
var app = new Application { ShutdownMode = ShutdownMode.OnMainWindowClose };
|
||||
app.DispatcherUnhandledException += (_, e) =>
|
||||
{
|
||||
@@ -125,6 +171,8 @@ static class Program
|
||||
Shell w;
|
||||
try { w = new Shell(args); }
|
||||
catch (Exception e) when (unattended != null) { Report(e); return 3; }
|
||||
Instance.Listen(() => w.Window.Dispatcher.BeginInvoke(new Action(w.ComeForward)));
|
||||
w.Window.Closed += (_, _) => Instance.Release(); // (a start just after closing finds the folder free)
|
||||
return app.Run(w.Window);
|
||||
}
|
||||
|
||||
@@ -247,8 +295,10 @@ static class Install
|
||||
if (!Allowed(dir)) throw new InvalidOperationException(TestOnly);
|
||||
Directory.CreateDirectory(dir);
|
||||
var exe = Path.Combine(dir, Program.SetupAsset);
|
||||
// ((Triforce) through <exe>.partial, renamed into place once complete: a copy cut off in the middle left a Setup that does
|
||||
// not start under the name every shortcut starts. Guard.cs Partial)
|
||||
if (!string.Equals(Path.GetFullPath(exe), Path.GetFullPath(Self), StringComparison.OrdinalIgnoreCase))
|
||||
File.Copy(Self, exe, true);
|
||||
Partial.CopyFile(Self, exe);
|
||||
Write(UninstallKey, "DisplayName", Program.AppName);
|
||||
Write(UninstallKey, "DisplayIcon", exe + ",0");
|
||||
Write(UninstallKey, "DisplayVersion", Program.Version);
|
||||
@@ -359,36 +409,7 @@ sealed class Release
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
/// A file downloaded with progress (0..1) into place (a .part file until complete)
|
||||
public static async Task Download(HttpClient http, string url, string file, long size, Action<double, long> progress, CancellationToken token)
|
||||
{
|
||||
var part = file + ".part";
|
||||
using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token))
|
||||
{
|
||||
response.EnsureSuccessStatusCode();
|
||||
var total = response.Content.Headers.ContentLength ?? size;
|
||||
using var from = await response.Content.ReadAsStreamAsync();
|
||||
using var to = File.Create(part);
|
||||
var buffer = new byte[1 << 20];
|
||||
long have = 0;
|
||||
var shown = DateTime.MinValue;
|
||||
for (int n; (n = await from.ReadAsync(buffer, 0, buffer.Length, token)) > 0;)
|
||||
{
|
||||
await to.WriteAsync(buffer, 0, n, token);
|
||||
have += n;
|
||||
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
|
||||
{
|
||||
shown = DateTime.UtcNow;
|
||||
progress(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have);
|
||||
}
|
||||
}
|
||||
if (total > 0 && have != total) throw new IOException("The download ended early (" + (have >> 20) + " of " + (total >> 20) + " MB).");
|
||||
progress(1, have);
|
||||
}
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
File.Move(part, file);
|
||||
}
|
||||
// (its files are fetched by Guard.cs's Download: through a .part file a cut download goes on from, checked against the size listed here)
|
||||
}
|
||||
|
||||
/// The Triforce tools beside the installed Setup: nx2/make_game.py and its own Python.
|
||||
@@ -426,37 +447,78 @@ sealed class Tools
|
||||
return null;
|
||||
}
|
||||
|
||||
/// What an unpacking that was cut off left behind (Setup closed in the middle of it): a tools.part of up to a gigabyte that is
|
||||
/// never used and stood in the way of the next try's room, and a tools.old whose removal failed
|
||||
public static void Sweep()
|
||||
{
|
||||
try { if (Directory.Exists(Folder + ".part")) Directory.Delete(Folder + ".part", true); } catch (Exception) { }
|
||||
// ((Triforce) Setup closed between the two moves of Unpack: the tools that were there are the rollback point, and go back)
|
||||
try { if (!Directory.Exists(Folder) && Directory.Exists(Folder + ".old")) Directory.Move(Folder + ".old", Folder); } catch (Exception) { }
|
||||
try { if (Directory.Exists(Folder) && Directory.Exists(Folder + ".old")) Directory.Delete(Folder + ".old", true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// Unpacks Triforce-Tools.zip as the tools folder (the old one replaced only once the new one is complete)
|
||||
public static void Unpack(string zip, string tag, Action<double> progress)
|
||||
{
|
||||
var target = Folder;
|
||||
var part = target + ".part";
|
||||
if (Directory.Exists(part)) Directory.Delete(part, true);
|
||||
Directory.CreateDirectory(part);
|
||||
using (var z = ZipFile.OpenRead(zip))
|
||||
try
|
||||
{
|
||||
// (the zip holds tools/... or the tools' contents at its root)
|
||||
// (and zips packed on Windows may say tools\... instead)
|
||||
var prefix = z.Entries.All(e => e.FullName.Replace('\\', '/').StartsWith("tools/", StringComparison.OrdinalIgnoreCase)) ? "tools/" : "";
|
||||
var full = Path.GetFullPath(part) + Path.DirectorySeparatorChar;
|
||||
for (var i = 0; i < z.Entries.Count; i++)
|
||||
using (var z = ZipFile.OpenRead(zip))
|
||||
{
|
||||
var e = z.Entries[i];
|
||||
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
|
||||
if (name.Length == 0) continue;
|
||||
var dest = Path.GetFullPath(Path.Combine(part, name));
|
||||
if (!dest.StartsWith(full, StringComparison.OrdinalIgnoreCase)) continue; // (no paths out of the folder)
|
||||
if (name.EndsWith("/")) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
|
||||
e.ExtractToFile(dest, true);
|
||||
if ((i & 15) == 0) progress((double)i / z.Entries.Count);
|
||||
// (room for all of it, asked before the first file: the zip says what each one unpacks to, and 4 KB are counted for
|
||||
// each on top, since a file takes whole clusters. The tools there now stay until the new ones are complete, so they
|
||||
// make no room. Guard.cs Space)
|
||||
var bytes = z.Entries.Sum(e => e.Length) + z.Entries.Count * 4096L;
|
||||
if (Space.Problem("the Triforce tools", bytes, Space.Free(part), Space.Disk(part)) is { } none) throw new NoRoomException(none);
|
||||
Directory.CreateDirectory(part);
|
||||
// (the zip holds tools/... or the tools' contents at its root)
|
||||
// (and zips packed on Windows may say tools\... instead)
|
||||
var prefix = z.Entries.All(e => e.FullName.Replace('\\', '/').StartsWith("tools/", StringComparison.OrdinalIgnoreCase)) ? "tools/" : "";
|
||||
// ((Triforce) every name is checked before the first file is written, as a mod's archive's are (Mods.Unsafe): a
|
||||
// name Windows keeps for a device (NUL, COM1, con.txt), a colon (a hidden stream, a drive's letter), a name that
|
||||
// ends in a dot or a space (Windows drops them: the file lands under another name), a path out of the folder.
|
||||
// Such a zip is refused whole: a name was only skipped when it left the folder, and the others were written)
|
||||
foreach (var e in z.Entries)
|
||||
{
|
||||
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
|
||||
if (name.Length > 0 && Mods.Unsafe(name, true) is { } why)
|
||||
throw new InvalidDataException("The tools' zip holds " + why + " (\"" + (name.Length > 120 ? name.Substring(0, 117) + "..." : name) + "\"): it was not unpacked.");
|
||||
}
|
||||
var full = Path.GetFullPath(part) + Path.DirectorySeparatorChar;
|
||||
for (var i = 0; i < z.Entries.Count; i++)
|
||||
{
|
||||
var e = z.Entries[i];
|
||||
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
|
||||
if (name.Length == 0) continue;
|
||||
var dest = Path.GetFullPath(Path.Combine(part, name));
|
||||
if (!dest.StartsWith(full, StringComparison.OrdinalIgnoreCase)) continue; // (no paths out of the folder)
|
||||
if (name.EndsWith("/")) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
|
||||
e.ExtractToFile(dest, true);
|
||||
if ((i & 15) == 0) progress((double)i / z.Entries.Count);
|
||||
}
|
||||
}
|
||||
File.WriteAllText(Path.Combine(part, "version.txt"), tag + "\n");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// (half a tools folder, a gigabyte of it, is of no use and stood in the way of the next try's room)
|
||||
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
File.WriteAllText(Path.Combine(part, "version.txt"), tag + "\n");
|
||||
var old = target + ".old";
|
||||
if (Directory.Exists(old)) Directory.Delete(old, true);
|
||||
if (Directory.Exists(target)) Directory.Move(target, old);
|
||||
Directory.Move(part, target);
|
||||
try { Directory.Move(part, target); }
|
||||
catch (Exception)
|
||||
{
|
||||
// ((Triforce) the tools that were there go back: a move that failed (a virus scanner holding the new folder) left no
|
||||
// tools folder at all, and the next start found no tools)
|
||||
try { if (!Directory.Exists(target) && Directory.Exists(old)) Directory.Move(old, target); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
try { if (Directory.Exists(old)) Directory.Delete(old, true); } catch (Exception) { }
|
||||
progress(1);
|
||||
}
|
||||
@@ -531,6 +593,9 @@ sealed class Runner
|
||||
var i = args.IndexOf(name);
|
||||
if (i >= 0 && i + 1 < args.Count && !Install.Allowed(args[i + 1])) { Finished?.Invoke(Install.TestOnly); return; }
|
||||
}
|
||||
// (and it works in its own build folder, the one its uninstall removes. Left to itself make_game.py works in the PC's
|
||||
// real one, %LOCALAPPDATA%\Triforce\build, and begins by stopping whatever build runs there)
|
||||
if (Install.TestRoot != null && !args.Contains("--work")) args.AddRange(new[] { "--work", Path.Combine(Install.TestRoot, "build") });
|
||||
using var p = Process.Start(Info(tools, args, ngxSdk))!;
|
||||
process = p;
|
||||
p.ErrorDataReceived += (_, e) => { if (e.Data != null) Line?.Invoke(e.Data); };
|
||||
|
||||
@@ -34,6 +34,9 @@ sealed partial class Shell
|
||||
HomeGoButton.Click += (_, _) => homeGo?.Invoke();
|
||||
NewFolderLink.Click += (_, _) => { NewFolderLink.IsChecked = false; ShowSetup(); };
|
||||
InitSaves();
|
||||
InitMods();
|
||||
InitSteam();
|
||||
InitSounds();
|
||||
}
|
||||
|
||||
// ---- welcome back ----
|
||||
@@ -50,7 +53,7 @@ sealed partial class Shell
|
||||
var built = hasGame ? BuiltVersion(folder!) : null;
|
||||
Program.Log("home: GameFolder=[" + (folder ?? "null") + "] exe=[" + (folder != null ? GameExe(folder) ?? "null" : "-") + "] built=[" + (built ?? "null") + "] tools=[" + (tools ?? "null") + "] latest=[" + (latest?.Tag ?? "null") + "]");
|
||||
|
||||
var setupNewer = latest != null && Program.Version != "dev" && latest.Tag != Program.Version && latest.SetupUrl != null;
|
||||
var setupNewer = latest != null && SetupNewer(latest);
|
||||
var toolsNewer = latest != null && latest.Tag != tools;
|
||||
var gameBehind = hasGame && built != null && tools != null && built != tools; // (new tools already here, game not rebuilt yet)
|
||||
var update = setupNewer || toolsNewer || gameBehind;
|
||||
@@ -58,6 +61,7 @@ sealed partial class Shell
|
||||
|
||||
HomeFill(hasGame, hasGame ? "Triforce " + (built ?? tools ?? "?") : null, folder, built, target, update, offline);
|
||||
ShowSavesLine();
|
||||
LoadSounds(); // (the game folder may be another one, or its mods other ones: Shell.Sounds.cs)
|
||||
Show(HomePage);
|
||||
if (!update) stage.Gleam(450);
|
||||
|
||||
@@ -123,6 +127,6 @@ sealed partial class Shell
|
||||
HomeGoButton.Content = hasGame ? "Play" : "Build my game";
|
||||
NotNowButton.Visibility = Visibility.Collapsed;
|
||||
}
|
||||
NewFolderLink.Visibility = hasGame ? Visibility.Visible : Visibility.Collapsed;
|
||||
NewFolderLink.Visibility = ModsButton.Visibility = SteamButton.Visibility = hasGame ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
}
|
||||
|
||||
313
setup/Shell.Mods.cs
Normal file
313
setup/Shell.Mods.cs
Normal file
@@ -0,0 +1,313 @@
|
||||
// (Triforce) The Mods page, reached from "Your game" on the welcome-back page once a game is built. It shows the game folder's
|
||||
// mods folder as the game reads it and changes it only by what a player could do by hand (Mods.cs: a "-" in front of a
|
||||
// folder's name, a number in front, a folder moved in or out).
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
sealed partial class Shell
|
||||
{
|
||||
Grid ModsPage = null!;
|
||||
ListBox ModList = null!;
|
||||
TextBlock ModsInfo = null!;
|
||||
Button ModsButton = null!, ModsAdd = null!, ModsOpen = null!, ModsRescan = null!, ModsConflicts = null!, ModsBack = null!, ModsUp = null!,
|
||||
ModsDown = null!, ModsRemove = null!, ModsToggle = null!, ModsBuild = null!;
|
||||
List<Mod> mods = new();
|
||||
List<Conflict> conflicts = new();
|
||||
bool modsBusy;
|
||||
string? modsSaid; // (what the last change ended with, shown until another mod is picked)
|
||||
|
||||
void InitMods()
|
||||
{
|
||||
ModsPage = Part<Grid>("ModsPage");
|
||||
ModList = Part<ListBox>("ModList");
|
||||
ModsInfo = Part<TextBlock>("ModsInfo");
|
||||
ModsButton = Part<Button>("ModsButton");
|
||||
ModsAdd = Part<Button>("ModsAdd"); ModsOpen = Part<Button>("ModsOpen"); ModsRescan = Part<Button>("ModsRescan"); ModsConflicts = Part<Button>("ModsConflicts");
|
||||
ModsBack = Part<Button>("ModsBack"); ModsUp = Part<Button>("ModsUp"); ModsDown = Part<Button>("ModsDown"); ModsRemove = Part<Button>("ModsRemove");
|
||||
ModsToggle = Part<Button>("ModsToggle"); ModsBuild = Part<Button>("ModsBuild");
|
||||
|
||||
// (no folder is renamed while the game runs: Mods.cs asks this before every change)
|
||||
Mods.GameRuns = GameRuns;
|
||||
|
||||
ModsButton.Click += (_, _) => ShowMods();
|
||||
ModsBack.Click += (_, _) => ShowHome(homeOffline);
|
||||
ModsRescan.Click += (_, _) => _ = LoadMods(PickedMod?.Path, null);
|
||||
ModsOpen.Click += (_, _) => OpenModsFolder();
|
||||
ModsAdd.Click += (_, _) => PickArchive();
|
||||
ModsConflicts.Click += (_, _) => CopyConflicts();
|
||||
ModsToggle.Click += (_, _) => { if (PickedMod is { } m) ChangeMods(m, folder => Mods.SetOn(folder, m, !m.On), m.Name + " is " + (m.On ? "off" : "on") + " from the game's next start."); };
|
||||
ModsUp.Click += (_, _) => { if (PickedMod is { } m) ChangeMods(m, folder => Mods.Move(folder, m, false) ? null : m.Path, null); };
|
||||
ModsDown.Click += (_, _) => { if (PickedMod is { } m) ChangeMods(m, folder => Mods.Move(folder, m, true) ? null : m.Path, null); };
|
||||
ModsRemove.Click += (_, _) =>
|
||||
{
|
||||
if (PickedMod is not { } m) return;
|
||||
Ask("Remove " + m.Name + "? Its folder moves into mods\\" + Mods.Removed + ", where the game does not look. Nothing is deleted.", "Remove", T(S.Back),
|
||||
() => ChangeMods(m, folder => { Mods.Remove(folder, m); return null; }, m.Name + " was removed. Its folder is kept in mods\\" + Mods.Removed + "."));
|
||||
};
|
||||
ModsBuild.Click += (_, _) => BuildForMods();
|
||||
ModList.SelectionChanged += (_, _) => { if (!modsBusy) { modsSaid = null; ModsRefresh(); } };
|
||||
Window.Drop += (_, e) =>
|
||||
{
|
||||
if (ModsPage.Visibility == Visibility.Visible && e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } paths) AddMod(paths[0]);
|
||||
};
|
||||
}
|
||||
|
||||
/// Does a program of this name run from inside a folder? One whose own folder cannot be asked counts when unknown says so
|
||||
static bool Running(string name, string folder, bool unknown)
|
||||
{
|
||||
foreach (var p in Process.GetProcessesByName(name))
|
||||
using (p)
|
||||
{
|
||||
string? exe = null;
|
||||
try { exe = p.MainModule?.FileName; } catch (Exception) { }
|
||||
if (exe == null ? unknown : Mods.Inside(folder, exe)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Does the game of this game folder run? It read its mods folder when it started, and a folder renamed under it is a
|
||||
/// file it can no longer open. (Another game folder's game is another game. In a test run only a game inside the test
|
||||
/// folder counts, as for the saves: Saves.cs RunningGame.)
|
||||
static bool GameRuns(string folder) => new[] { "Triforce", "hookshot" }.Any(name => Running(name, folder, Install.TestRoot == null));
|
||||
|
||||
// ---- the page ----
|
||||
|
||||
static string? ModsFolder() => GameFolder() is { } game ? Mods.FolderOf(game) : null;
|
||||
Mod? PickedMod => (ModList.SelectedItem as FrameworkElement)?.Tag as Mod;
|
||||
|
||||
void ShowMods()
|
||||
{
|
||||
Show(ModsPage);
|
||||
_ = LoadMods(null, null);
|
||||
}
|
||||
|
||||
/// The mods folder read again, and shown: pick is the folder of the mod to have picked after it, said what to say under the list
|
||||
async Task LoadMods(string? pick, string? said, bool bad = false)
|
||||
{
|
||||
var folder = ModsFolder();
|
||||
List<Mod> found;
|
||||
try { found = folder != null ? await Task.Run(() => Mods.List(folder)) : new List<Mod>(); }
|
||||
catch (Exception e) { found = new List<Mod>(); said = "The mods folder could not be read: " + e.Message; bad = true; }
|
||||
ModsFill(found, pick, said, bad);
|
||||
}
|
||||
|
||||
/// The page for a list of mods (also what --snapshot shows, with sample mods)
|
||||
void ModsFill(List<Mod> found, string? pick, string? said, bool bad = false)
|
||||
{
|
||||
mods = found;
|
||||
conflicts = Mods.Conflicts(mods);
|
||||
LoadSounds(); // (a mod may carry one of the two sounds Setup plays, or no longer: Shell.Sounds.cs)
|
||||
modsBusy = true; // (the list being filled is no pick of the player's)
|
||||
ModList.ItemsSource = mods.Select(ModRow).ToList();
|
||||
var at = pick != null ? mods.FindIndex(m => string.Equals(m.Path, pick, StringComparison.OrdinalIgnoreCase)) : -1;
|
||||
ModList.SelectedIndex = at >= 0 ? at : mods.Count > 0 ? 0 : -1;
|
||||
if (ModList.SelectedItem != null) ModList.ScrollIntoView(ModList.SelectedItem);
|
||||
modsBusy = false;
|
||||
modsSaid = said;
|
||||
ModsRefresh(bad);
|
||||
}
|
||||
|
||||
/// One mod: its name, on or off to the right, what it carries and whom it shares files with under it
|
||||
FrameworkElement ModRow(Mod m)
|
||||
{
|
||||
var g = new Grid { Tag = m };
|
||||
g.ColumnDefinitions.Add(new ColumnDefinition());
|
||||
g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
|
||||
g.RowDefinitions.Add(new RowDefinition());
|
||||
g.RowDefinitions.Add(new RowDefinition());
|
||||
var name = new TextBlock
|
||||
{
|
||||
Text = m.Deep ? m.Name + " (" + System.IO.Path.GetDirectoryName(m.Rel.Replace('/', '\\')) + ")" : m.Name, Foreground = Brush(m.On ? "TextHi" : "TextDim"), FontSize = 14,
|
||||
TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 0, 16, 0),
|
||||
};
|
||||
var state = new TextBlock { Text = m.On ? "On" : "Off", Foreground = Brush(m.On ? "Gold" : "TextFaint"), FontSize = 12, VerticalAlignment = VerticalAlignment.Center };
|
||||
var shared = Mods.Shared(m, mods, conflicts);
|
||||
var what = Mods.Carries(m);
|
||||
if (shared.Count == 1) what += " · " + (shared[0].Wins ? "wins " : "loses ") + Files(shared[0].Files) + (shared[0].Wins ? " over " : " to ") + shared[0].Other.Name;
|
||||
else if (shared.Count > 1) what += " · shares files with " + shared.Count + " mods";
|
||||
var carries = new TextBlock { Text = what, Foreground = Brush("TextFaint"), FontSize = 11.5, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 3, 0, 0) };
|
||||
Grid.SetColumn(state, 1);
|
||||
Grid.SetRow(carries, 1);
|
||||
Grid.SetColumnSpan(carries, 2);
|
||||
g.Children.Add(name);
|
||||
g.Children.Add(state);
|
||||
g.Children.Add(carries);
|
||||
return g;
|
||||
}
|
||||
|
||||
static string Files(int n) => n == 1 ? "1 file" : n.ToString("N0", System.Globalization.CultureInfo.InvariantCulture) + " files";
|
||||
|
||||
/// What the page says about the mod that is picked: what it carries, when a change of it takes effect, and for each mod
|
||||
/// it shares files with, how many and who wins them
|
||||
string ModWords(Mod m)
|
||||
{
|
||||
var s = m.Name + " is " + (m.On ? "on" : m.OffAbove != null ? "off, as everything in the folder " + m.OffAbove + " is" : "off") + " and carries " + Mods.Carries(m) + ".";
|
||||
if (m.Built) s += " Code patches are built into the game: after a change of them, build the game again.";
|
||||
if (m.Cheats > 0) s += " Its cheats are read when the game starts; switch each one on in the game's Options, on the System tab.";
|
||||
if (m.Deep) s += " It keeps its place in the order together with its folder, " + m.Top + ".";
|
||||
foreach (var (other, files, wins) in Mods.Shared(m, mods, conflicts).Take(2))
|
||||
{
|
||||
var which = conflicts.Where(c => c.Mods.Contains(m) && c.Mods.Contains(other)).Select(c => c.File).ToList();
|
||||
s += " " + Files(files) + (files == 1 ? " is" : " are") + " also in " + other.Name + ", and " + (wins ? m.Name : other.Name) + " wins (" + which[0] + (which.Count > 1 ? ", ..." : "") + ").";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
void ModsRefresh(bool bad = false)
|
||||
{
|
||||
var game = GameFolder();
|
||||
var m = PickedMod;
|
||||
var tops = Mods.Tops(mods);
|
||||
var at = m != null ? tops.FindIndex(t => string.Equals(t, m.Top, StringComparison.OrdinalIgnoreCase)) : -1;
|
||||
ModsToggle.IsEnabled = m != null && !modsBusy;
|
||||
ModsToggle.Content = m is { On: false } ? "Switch on" : "Switch off";
|
||||
ModsRemove.IsEnabled = m != null && !modsBusy;
|
||||
ModsUp.IsEnabled = at > 0 && !modsBusy;
|
||||
ModsDown.IsEnabled = at >= 0 && at < tops.Count - 1 && !modsBusy;
|
||||
ModsAdd.IsEnabled = ModsRescan.IsEnabled = !modsBusy;
|
||||
ModsConflicts.Content = "Copy conflicts";
|
||||
ModsConflicts.Visibility = conflicts.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||
ModsInfo.Foreground = Brush(bad ? "Bad" : "Text");
|
||||
ModsInfo.Text = modsSaid ?? (game == null ? "Build your game first: mods live in its game folder."
|
||||
: m != null ? ModWords(m)
|
||||
: "No mods yet. Add a mod takes a .zip, .7z or .rar file; or put a mod's folder (the one that holds romfs) into " + Mods.FolderOf(game) + " yourself.");
|
||||
// (code patches and cheats are compiled in: said for as long as the mods that carry them are not the ones of the last build)
|
||||
var build = game != null && Mods.NeedsBuild(Mods.CodeState(mods), ModsBuilt(game));
|
||||
ModsBuild.Content = Mods.BuildAgain;
|
||||
ModsBuild.Visibility = build ? Visibility.Visible : Visibility.Collapsed;
|
||||
}
|
||||
|
||||
/// One change of the mods, off the window's thread: change gets the mods folder and returns the folder of the mod to have
|
||||
/// picked afterwards (null: the mod where it is now, by its name). Then the folder is read again, and done is said
|
||||
async void ChangeMods(Mod? mod, Func<string, string?> change, string? done)
|
||||
{
|
||||
var folder = ModsFolder();
|
||||
if (folder == null || modsBusy) return;
|
||||
if (!Install.Allowed(folder)) { modsSaid = Install.TestOnly; ModsRefresh(true); return; }
|
||||
modsBusy = true;
|
||||
ModsRefresh();
|
||||
string? pick = mod?.Path, said = done;
|
||||
var bad = false;
|
||||
try
|
||||
{
|
||||
var to = await Task.Run(() => change(folder));
|
||||
Program.Log("mods: " + (done ?? "the order changed") + " (" + folder + ")");
|
||||
// (a mod with code patches changed before any build was marked: built in or not, the game is not as its mods are)
|
||||
if (mod is { Built: true } && GameFolder() is { } game && ModsBuilt(game) == null) Install.Set("ModsBuilt", game + "|changed");
|
||||
pick = to;
|
||||
}
|
||||
catch (ModsException e) { said = e.Message; bad = true; }
|
||||
catch (Exception e)
|
||||
{
|
||||
Program.Log("mods: " + e);
|
||||
said = "That did not work: " + e.Message;
|
||||
bad = true;
|
||||
}
|
||||
modsBusy = false;
|
||||
// (where the folder has another name now, the mod is found by its own)
|
||||
var now = await Task.Run(() => Mods.List(folder));
|
||||
pick ??= now.FirstOrDefault(m => mod != null && m.Name == mod.Name && string.Equals(System.IO.Path.GetDirectoryName(m.Path), System.IO.Path.GetDirectoryName(mod.Path), StringComparison.OrdinalIgnoreCase))?.Path;
|
||||
ModsFill(now, pick, said, bad);
|
||||
}
|
||||
|
||||
void PickArchive()
|
||||
{
|
||||
if (FolderPicker.Answers.Count > 0) { AddMod(FolderPicker.Answers.Dequeue()); return; } // (testing, TRIFORCE_UI_SCRIPT)
|
||||
var d = new OpenFileDialog { Filter = "Mods (*.zip, *.7z, *.rar)|*.zip;*.7z;*.rar", Title = "Choose the mod's archive" };
|
||||
if (d.ShowDialog(Window) == true) AddMod(d.FileName);
|
||||
}
|
||||
|
||||
/// Add a mod: the archive is unpacked into the mods folder, checked there, and its mod moved into place (Mods.Add)
|
||||
async void AddMod(string archive)
|
||||
{
|
||||
var folder = ModsFolder();
|
||||
if (folder == null || modsBusy) return;
|
||||
if (!Install.Allowed(folder)) { modsSaid = Install.TestOnly; ModsRefresh(true); return; }
|
||||
modsBusy = true;
|
||||
modsSaid = "Unpacking " + System.IO.Path.GetFileName(archive) + "...";
|
||||
ModsRefresh();
|
||||
string? pick = PickedMod?.Path, said;
|
||||
var bad = false;
|
||||
try
|
||||
{
|
||||
var mod = await Task.Run(() => Mods.Add(folder, archive));
|
||||
Program.Log("mods: added " + mod.Rel + " from an archive (" + folder + ")");
|
||||
if (mod.Code && GameFolder() is { } game && ModsBuilt(game) == null) Install.Set("ModsBuilt", game + "|changed");
|
||||
pick = mod.Path;
|
||||
said = mod.Name + " was added: " + Mods.Carries(mod) + "." + (mod.Code ? " Its code patches and cheats take effect once the game is built again." : " It loads at the game's next start.");
|
||||
}
|
||||
catch (ModsException e) { said = e.Message; bad = true; }
|
||||
catch (Exception e)
|
||||
{
|
||||
Program.Log("mods: " + e);
|
||||
said = "The mod could not be added: " + e.Message;
|
||||
bad = true;
|
||||
}
|
||||
modsBusy = false;
|
||||
await LoadMods(pick, said, bad);
|
||||
}
|
||||
|
||||
void OpenModsFolder()
|
||||
{
|
||||
var folder = ModsFolder();
|
||||
if (folder == null) return;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(folder) && Install.Allowed(folder)) Directory.CreateDirectory(folder);
|
||||
if (scriptFile == null) Process.Start(new ProcessStartInfo("explorer.exe", "\"" + folder + "\"") { UseShellExecute = true });
|
||||
}
|
||||
catch (Exception e) { Program.Log("mods: the folder could not be opened: " + e.Message); }
|
||||
}
|
||||
|
||||
/// Every file more than one mod carries, with its winner, onto the clipboard
|
||||
void CopyConflicts()
|
||||
{
|
||||
try
|
||||
{
|
||||
Clipboard.SetDataObject(Mods.ConflictText(conflicts), true);
|
||||
ModsConflicts.Content = "Copied";
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Program.Log("the conflicts could not be copied: " + e.Message);
|
||||
ModsConflicts.Content = T(S.ReportNotCopied);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- code patches and cheats: built in ----
|
||||
|
||||
/// The mark of the mods' code the game folder was last built with (Mods.CodeState), null when Setup kept none for it
|
||||
static string? ModsBuilt(string game) =>
|
||||
Install.Get("ModsBuilt") is { } kept && kept.StartsWith(game + "|", StringComparison.OrdinalIgnoreCase) ? kept.Substring(game.Length + 1) : null;
|
||||
|
||||
/// A build of this game folder ended well (Shell.cs Ended): the code patches and cheats of its mods are in it as they are now
|
||||
void MarkModsBuilt(string game)
|
||||
{
|
||||
try { Install.Set("ModsBuilt", game + "|" + Mods.CodeState(Mods.List(Mods.FolderOf(game)))); }
|
||||
catch (Exception e) { Program.Log("mods: the build's mark could not be kept: " + e.Message); }
|
||||
}
|
||||
|
||||
/// "Build again to apply": the game folder built again from the game files it keeps, as an update is
|
||||
void BuildForMods()
|
||||
{
|
||||
var game = GameFolder();
|
||||
if (game == null) return;
|
||||
Ask("Build your game again with its mods' code patches? Only what changed is compiled again, so it usually takes a few minutes.", "Build again", T(S.Back), () =>
|
||||
{
|
||||
if (Tools.Find() is not { } tools) { modsSaid = T(S.ToolsMissing); ModsRefresh(true); return; }
|
||||
if (GameRuns(game)) { modsSaid = "Close the game first: it cannot be built again while it runs."; ModsRefresh(true); return; }
|
||||
OutPath.Text = game;
|
||||
BeginUpdate();
|
||||
Run(tools, new List<string> { "--update", game }, keepRows: true);
|
||||
});
|
||||
}
|
||||
}
|
||||
119
setup/Shell.Sounds.cs
Normal file
119
setup/Shell.Sounds.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
// (Triforce) Where Setup sounds: the game's own decide sound when a button, a link or a row of a list is chosen or a choice
|
||||
// changes, its cancel sound when the player goes back, cancels or answers no (Sound.cs has the sounds and where they come
|
||||
// from: the player's own game, never a file of Setup's). Only what the player does sounds: a page the programme turns, a
|
||||
// list it fills, the cursor moving over things do not. And nothing sounds in a run without a player (--snapshot, a script,
|
||||
// a test folder) or while the game runs.
|
||||
//
|
||||
// The setting is "Sounds" at the window's top, beside the minimize button: a click goes on to the next of Off, Low (as it
|
||||
// starts), Medium and High, and plays the decide sound at it. Kept with Setup's other settings (Sounds in HKCU\Software\Triforce).
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
sealed partial class Shell
|
||||
{
|
||||
Sounds sounds = null!;
|
||||
Button SoundsButton = null!;
|
||||
Caps SoundsLabel = null!;
|
||||
bool byHand; // (inside the player's own click or key on a list: a choice that changes now is theirs)
|
||||
bool gameUp;
|
||||
bool playing; // ((Triforce) Play was chosen: its start sound plays, no click's over it
|
||||
int gameAsked = Environment.TickCount - 60000;
|
||||
|
||||
/// The buttons that go back, cancel or say no: the cancel sound. Every other button and link: the decide sound
|
||||
static readonly HashSet<string> GoBack = new() { "SavesBack", "ModsBack", "SetupBack", "BackButton", "AskNo", "FetchCancel", "CancelButton", "NotNowButton" };
|
||||
|
||||
void InitSounds()
|
||||
{
|
||||
SoundsButton = Part<Button>("SoundsButton");
|
||||
SoundsLabel = Part<Caps>("SoundsLabel");
|
||||
var scripted = Environment.GetEnvironmentVariable("TRIFORCE_UI_SCRIPT") is { Length: > 0 };
|
||||
sounds = new Sounds(Sounds.PlayerFor(snapshot != null, scripted, Install.TestRoot, Environment.GetEnvironmentVariable("TRIFORCE_SOUND_LOG")), GameSounds, Install.Get("Sounds"));
|
||||
ShowSoundsLevel();
|
||||
SoundsButton.Click += (_, _) =>
|
||||
{
|
||||
sounds.Level = Sounds.Next(sounds.Level);
|
||||
Install.Set("Sounds", sounds.Level);
|
||||
ShowSoundsLevel();
|
||||
sounds.Play(Sounds.Decide); // (how loud it is now)
|
||||
};
|
||||
// (handledEventsToo: a button's own handler has run by now, and may have marked the click as handled)
|
||||
Window.AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(SoundOfClick), true);
|
||||
Window.AddHandler(Selector.SelectionChangedEvent, new SelectionChangedEventHandler(SoundOfChoice), true);
|
||||
Window.PreviewMouseDown += (_, e) => ByHand(e.OriginalSource);
|
||||
Window.PreviewMouseUp += (_, e) => ByHand(e.OriginalSource);
|
||||
Window.PreviewKeyDown += (_, e) =>
|
||||
{
|
||||
ByHand(Keyboard.FocusedElement);
|
||||
// (Esc answers a question with no: Shell.cs Wire, whose handler comes after this one and hides the question)
|
||||
if (e.Key == Key.Escape && AskLayer.Visibility == Visibility.Visible) sounds.Play(Sounds.Cancel);
|
||||
};
|
||||
Window.Loaded += (_, _) => LoadSounds();
|
||||
}
|
||||
|
||||
void ShowSoundsLevel()
|
||||
{
|
||||
var level = sounds.Level;
|
||||
SoundsLabel.Label = "Sounds · " + char.ToUpperInvariant(level[0]) + level.Substring(1);
|
||||
SoundsButton.ToolTip = level == "off" ? "Setup is silent. Click for the game's own menu sounds, low"
|
||||
: "Setup plays your game's own menu sounds (none before a game is built). Click to change how loud";
|
||||
}
|
||||
|
||||
/// The game's two sounds taken up from the game folder there is now, off the window's thread: at the start, and wherever
|
||||
/// the game folder or its mods may have changed (the welcome-back page, the Mods page's list, a build that ended)
|
||||
void LoadSounds()
|
||||
{
|
||||
var game = GameFolder();
|
||||
Task.Run(() => sounds.Load(game));
|
||||
}
|
||||
|
||||
/// Does the game run? Asked of Windows at most every two seconds. (In a test run only a game inside the test folder
|
||||
/// counts, as for the saves and the mods: the PC's own game has nothing to do with it)
|
||||
bool GameSounds()
|
||||
{
|
||||
var now = Environment.TickCount;
|
||||
if (unchecked(now - gameAsked) < 2000) return gameUp;
|
||||
gameAsked = now;
|
||||
return gameUp = Install.TestRoot != null ? new[] { "Triforce", "hookshot" }.Any(name => Running(name, Install.TestRoot, false)) : Sounds.GameProcess();
|
||||
}
|
||||
|
||||
static bool Inside<T>(object? from) where T : DependencyObject
|
||||
{
|
||||
for (var at = from as DependencyObject; at != null; at = at is Visual ? VisualTreeHelper.GetParent(at) : LogicalTreeHelper.GetParent(at))
|
||||
if (at is T) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// A press or a key on a row of a list (or of the language's list): until this input has been dealt with, a choice that
|
||||
/// changes is the player's. One the programme makes later (a list filled anew) is not
|
||||
void ByHand(object? on)
|
||||
{
|
||||
if (!Inside<ListBoxItem>(on) && !Inside<ComboBoxItem>(on) && !Inside<ComboBox>(on)) return;
|
||||
byHand = true;
|
||||
Window.Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(() => byHand = false));
|
||||
}
|
||||
|
||||
void SoundOfChoice(object sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (byHand && e.AddedItems.Count > 0 && e.OriginalSource is ListBox or ComboBox) sounds.Play(Sounds.Decide);
|
||||
}
|
||||
|
||||
void SoundOfClick(object sender, RoutedEventArgs e)
|
||||
{
|
||||
// (the window's own buttons, links, ticks and segments: not the parts of a scroll bar or of the language's list, and
|
||||
// not minimize and close; the Sounds setting plays its own)
|
||||
if (e.OriginalSource is not ButtonBase { Name: { Length: > 0 } name } button || button is RepeatButton || button.TemplatedParent != null) return;
|
||||
if (button == SoundsButton || name == "MinButton" || name == "CloseButton") return;
|
||||
if (playing) return; // ((Triforce) Play's own sound plays: Shell.cs Play)
|
||||
sounds.Play(GoBack.Contains(name) ? Sounds.Cancel : Sounds.Decide);
|
||||
}
|
||||
}
|
||||
84
setup/Shell.Steam.cs
Normal file
84
setup/Shell.Steam.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
// (Triforce) Add to Steam, the link beside "Your game" on the welcome-back page: the game as a shortcut in the player's Steam
|
||||
// library (Steam.cs), with pictures drawn from Setup's own crest (SteamArt.cs). Steam's files are another program's: they are
|
||||
// looked at when the link is clicked, and written only from the question the player then answers.
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
sealed partial class Shell
|
||||
{
|
||||
Button SteamButton = null!;
|
||||
|
||||
void InitSteam()
|
||||
{
|
||||
SteamButton = Part<Button>("SteamButton");
|
||||
// (a test run has its own Steam folder, which the PC's Steam, running or not, has nothing to do with)
|
||||
if (Install.TestRoot != null) Steam.Running = root => Running("steam", root, false);
|
||||
SteamButton.Click += (_, _) => SteamClicked();
|
||||
}
|
||||
|
||||
/// Steam's folder: the one Steam names in the registry. A test run has only the Steam folder inside its own folder,
|
||||
/// and never asks for the PC's
|
||||
static string? SteamRoot()
|
||||
{
|
||||
var root = Install.TestRoot != null ? System.IO.Path.Combine(Install.TestRoot, "Steam") : Steam.FromRegistry();
|
||||
return root != null && Steam.Valid(root) ? root : null;
|
||||
}
|
||||
|
||||
/// A notice over the whole window, with one button
|
||||
void Tell(string text) => Ask(text, "OK", "", () => { });
|
||||
|
||||
/// The link beside "Your game": what is there is looked at now, and the player is asked before anything is written. For
|
||||
/// the account Steam was last signed in with, named in the question
|
||||
void SteamClicked()
|
||||
{
|
||||
var folder = Install.Get("GameFolder");
|
||||
var exe = folder != null ? GameExe(folder) : null;
|
||||
if (exe == null) return;
|
||||
try
|
||||
{
|
||||
var root = SteamRoot();
|
||||
if (root == null) { Tell("Steam was not found on this PC."); return; }
|
||||
var user = Steam.Users(root).FirstOrDefault();
|
||||
if (user == null) { Tell("Nobody has signed in to Steam on this PC yet. Start Steam, sign in once, close it, then try again."); return; }
|
||||
if (!Install.Allowed(user.Config)) { Tell(Install.TestOnly); return; }
|
||||
var whose = user.Name.Length > 0 ? user.Name + "'s Steam library" : "your Steam library";
|
||||
if (Steam.Running(root)) { Tell(Steam.CloseFirst); return; }
|
||||
var there = Steam.Where(user, exe);
|
||||
if (there != null && string.Equals(there, exe, StringComparison.OrdinalIgnoreCase))
|
||||
Ask("Triforce is in " + whose + ". Remove it from there?", "Remove from Steam", T(S.Back), () => SteamWrite(user, exe, whose, false));
|
||||
else if (there != null)
|
||||
Ask("Triforce is in " + whose + ", for the game in " + System.IO.Path.GetDirectoryName(there) + ". Set it to this game folder?", "Set to this folder", T(S.Back), () => SteamWrite(user, exe, whose, true));
|
||||
else
|
||||
Ask("Add Triforce to " + whose + "? Steam then starts the game itself, without Setup.", "Add to Steam", T(S.Back), () => SteamWrite(user, exe, whose, true));
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Program.Log("steam: " + e.Message);
|
||||
Tell("Steam's folder could not be read: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// The player said yes: the shortcut and its pictures written into the account's config folder, or taken out of it
|
||||
void SteamWrite(SteamUser user, string exe, string whose, bool add)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Install.Allowed(user.Config)) throw new SteamException(Install.TestOnly);
|
||||
var changed = add ? Steam.Add(user, exe, SteamArt.Make()) : Steam.Remove(user, exe);
|
||||
// (no account's name or number in the log: it is pasted where help is asked for)
|
||||
Program.Log("steam: the shortcut was " + (add ? changed ? "added" : "set to " + exe : "removed") + " for the account Steam was last signed in with");
|
||||
SteamButton.Content = add ? "Remove from Steam" : "Add to Steam";
|
||||
Tell(add ? "Triforce is in " + whose + " now, among the non-Steam games. Start Steam to see it."
|
||||
: "Triforce is no longer in " + whose + ". The file as it was before is kept beside it (shortcuts.vdf" + Steam.Backup + ").");
|
||||
}
|
||||
catch (SteamException e) { Tell(e.Message); }
|
||||
catch (Exception e)
|
||||
{
|
||||
Program.Log("steam: " + e);
|
||||
Tell("Steam's shortcuts could not be changed: " + e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
// real flows in an off-screen window; it carries on in the Setup that an install or a self-update
|
||||
// starts (the place in the list is kept beside the file). Pictures and script.log go to
|
||||
// TRIFORCE_UI_SHOTS. Used with TRIFORCE_TEST_ROOT (Setup.cs), which keeps the install in one folder.
|
||||
// TRIFORCE_SOUND_LOG=<file> such a run makes no sound; with this, each sound a player's Setup would have played is a line
|
||||
// in that file (Sound.cs NotedPlayer)
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
@@ -191,7 +193,7 @@ sealed partial class Shell
|
||||
BuildTitle.Text = T(S.Stopped);
|
||||
BuildNote.Text = "The compiler stopped at sa/gen/code_041.c (exit code 1). See the details.";
|
||||
BuildNote.Foreground = Brush("Bad");
|
||||
SetButtons(back: true);
|
||||
SetButtons(back: true, report: true);
|
||||
await Shot(dir, "17-build-stopped");
|
||||
BuildNote.Foreground = Brush("Text");
|
||||
|
||||
@@ -221,6 +223,47 @@ sealed partial class Shell
|
||||
SavesTarget.Text = "";
|
||||
SavesGo.IsEnabled = false;
|
||||
await Shot(dir, "19-saves-none");
|
||||
|
||||
// mods: a list with mods that share files, one off, one whose code waits for a build; and none yet
|
||||
Mod Sample(string folder, int files, int patches, int cheats, params string[] shared)
|
||||
{
|
||||
var (off, number, name) = Mods.Parse(folder);
|
||||
var m = new Mod { Path = game + @"\mods\" + folder, Rel = folder, Top = folder, Folder = folder, Name = name, Number = number, On = !off, Patches = patches, Cheats = cheats };
|
||||
m.Files.AddRange(shared);
|
||||
for (var i = shared.Length; i < files; i++) m.Files.Add(folder.ToLowerInvariant() + "/" + i);
|
||||
return m;
|
||||
}
|
||||
var sample = new List<Mod>
|
||||
{
|
||||
Sample("01-Clearer water", 38, 0, 0), Sample("02-Greener fields", 1204, 0, 0, "pack/actor/grass.pack.zs", "pack/actor/tree.pack.zs"),
|
||||
Sample("03-Tall grass", 212, 0, 0, "pack/actor/grass.pack.zs", "pack/actor/tree.pack.zs"), Sample("-04-Night sky", 16, 0, 0),
|
||||
Sample("05-Sixty frames", 0, 2, 1),
|
||||
};
|
||||
Show(ModsPage);
|
||||
ModsFill(sample, sample[2].Path, null);
|
||||
ModsInfo.Text = ModWords(sample[2]);
|
||||
ModsBuild.Visibility = Visibility.Visible;
|
||||
await Shot(dir, "20-mods");
|
||||
ModsFill(sample, sample[4].Path, "Sixty frames was added: 2 code patch files, 1 cheat file. Its code patches and cheats take effect once the game is built again.");
|
||||
ModsBuild.Visibility = Visibility.Visible;
|
||||
await Shot(dir, "21-mods-added");
|
||||
ModsFill(new List<Mod>(), null, @"No mods yet. Add a mod takes a .zip, .7z or .rar file; or put a mod's folder (the one that holds romfs) into " + game + @"\mods yourself.");
|
||||
await Shot(dir, "22-mods-none");
|
||||
ModsFill(sample, sample[0].Path, "The archive holds a path that leaves its own folder (..): \"../../Windows/evil.dll\". Nothing was unpacked.", true);
|
||||
await Shot(dir, "23-mods-refused");
|
||||
|
||||
// Add to Steam: the question, and Steam running
|
||||
HomeFill(true, "Triforce v1.1.0", game, "v1.1.0", "v1.1.0", false, null);
|
||||
Show(HomePage);
|
||||
Ask("Add Triforce to Link's Steam library? Steam then starts the game itself, without Setup.", "Add to Steam", T(S.Back), () => { });
|
||||
await Shot(dir, "24-steam-ask");
|
||||
HideAsk();
|
||||
Tell(Steam.CloseFirst);
|
||||
await Shot(dir, "25-steam-close-first");
|
||||
HideAsk();
|
||||
// (and the shortcut's pictures as they would be written into Steam's grid folder, in steam\: drawn, never fetched)
|
||||
Directory.CreateDirectory(System.IO.Path.Combine(dir, "steam"));
|
||||
foreach (var picture in SteamArt.Make()) File.WriteAllBytes(System.IO.Path.Combine(dir, "steam", picture.Key + ".png"), picture.Value);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -289,6 +332,7 @@ sealed partial class Shell
|
||||
case "text": Part<TextBox>(a).Text = b; break;
|
||||
case "pick": FolderPicker.Answers.Enqueue(a + (b.Length > 0 ? " " + b : "")); break;
|
||||
case "select": SaveList.SelectedIndex = int.Parse(a); break;
|
||||
case "mod": ModList.SelectedIndex = int.Parse(a); break; // mod <n>: the mod picked on the Mods page (pick <file>: the archive Add a mod takes)
|
||||
case "sleep": await Task.Delay(int.Parse(a)); break;
|
||||
case "shot": await Shot(scriptShots!, a, 700); break;
|
||||
case "frames": // frames <name> <count> <ms apart>: what is on screen now and at each step after (to look at motion)
|
||||
|
||||
239
setup/Shell.cs
239
setup/Shell.cs
@@ -26,6 +26,9 @@ sealed partial class Shell
|
||||
{
|
||||
public readonly Window Window;
|
||||
const long NeededBytes = 60L << 30;
|
||||
// (what the tools take unpacked, until their zip is here to say it exactly: v0.4.0's Triforce-Tools.zip is 284 MB and unpacks
|
||||
// to 1.1 GB in 13,230 files, 3.9 times its size)
|
||||
const int ToolsUnpackedTimes = 5;
|
||||
// (the build's steps, and the stone each one lights when it is done; the last one makes the whole crest gleam)
|
||||
static readonly (string Id, S Text, int Stone)[] Stages =
|
||||
{ ("read", S.Read, Art.Emerald), ("lift", S.Lift, Art.Sapphire), ("compile", S.Compile, Art.Ruby), ("finish", S.Finish, -1) };
|
||||
@@ -135,6 +138,9 @@ sealed partial class Shell
|
||||
FitToScreen();
|
||||
// (asked once the window is up: an off-screen run showed a SourceInitialized handler added here is never called)
|
||||
Window.Loaded += (_, _) => Frame();
|
||||
// (started by the Setup it replaces, which stays until it hears that this window is up: StartNewSetup, Guard.cs Handover)
|
||||
if (relaunched) Window.Loaded += (_, _) => Handover.Up(Install.InstalledDir ?? Install.SelfDir, Install.TestRoot);
|
||||
if (Application.Current is { } app) app.SessionEnding += (_, _) => sessionEnding = true;
|
||||
if (snapshot != null)
|
||||
{
|
||||
Window.WindowStartupLocation = WindowStartupLocation.Manual;
|
||||
@@ -229,8 +235,8 @@ sealed partial class Shell
|
||||
// already built started at one click: 45 minutes and the same game again. Back goes home; Build asks first then)
|
||||
BuildButton.Click += (_, _) =>
|
||||
{
|
||||
if (HasGame) Ask("You have already built a game folder. Do you want to build it again? It takes about 45 minutes.", "Build again", T(S.Back), StartBuild);
|
||||
else StartBuild();
|
||||
if (HasGame) Ask("You have already built a game folder. Do you want to build it again? It takes about 45 minutes.", "Build again", T(S.Back), BuildIfRoom);
|
||||
else BuildIfRoom();
|
||||
};
|
||||
SetupBack = Part<Button>("SetupBack");
|
||||
// (11-13) NVIDIA DLSS in the game that is built: NVIDIA's files come under NVIDIA's own license, so the tick stays only
|
||||
@@ -249,6 +255,10 @@ sealed partial class Shell
|
||||
() => { DlssTick.IsChecked = true; Install.Set("Dlss", "1"); });
|
||||
};
|
||||
SetupBack.Click += (_, _) => ShowHome(homeOffline);
|
||||
// (a build that stopped: what there is to send in one click, where the details had to be selected and copied by hand and
|
||||
// setup.log found in the install folder)
|
||||
CopyReport = Part<Button>("CopyReport");
|
||||
CopyReport.Click += (_, _) => CopyTheReport();
|
||||
CancelButton.Click += (_, _) => { fetch?.Cancel(); runner?.Cancel(); };
|
||||
BackButton.Click += (_, _) => ShowSetup();
|
||||
OpenButton.Click += (_, _) => Process.Start(new ProcessStartInfo("explorer.exe", "\"" + finished + "\"") { UseShellExecute = true });
|
||||
@@ -266,16 +276,18 @@ sealed partial class Shell
|
||||
|
||||
void CloseWindow() => Window.Close();
|
||||
|
||||
/// A question over the whole window: the gold button does it, the other one (or Esc) leaves things as they are
|
||||
/// A question over the whole window: the gold button does it, the other one (or Esc) leaves things as they are. (Without
|
||||
/// words for the other one it is a notice: one button)
|
||||
void Ask(string question, string yes, string no, Action onYes)
|
||||
{
|
||||
AskText.Text = question;
|
||||
AskYes.Content = yes;
|
||||
AskNo.Content = no;
|
||||
AskNo.Visibility = no.Length > 0 ? Visibility.Visible : Visibility.Collapsed;
|
||||
askYes = onYes;
|
||||
AskLayer.Visibility = Visibility.Visible;
|
||||
Fx.Once(AskLayer, UIElement.OpacityProperty, 0, 1, Fx.Base);
|
||||
AskNo.Focus();
|
||||
(no.Length > 0 ? AskNo : AskYes).Focus();
|
||||
}
|
||||
|
||||
void HideAsk()
|
||||
@@ -286,10 +298,10 @@ sealed partial class Shell
|
||||
|
||||
void Show(Grid page)
|
||||
{
|
||||
foreach (var p in new[] { InstallPage, FetchPage, HomePage, SavesPage, SetupPage, BuildPage }) p.Visibility = p == page ? Visibility.Visible : Visibility.Collapsed;
|
||||
foreach (var p in new[] { InstallPage, FetchPage, HomePage, SavesPage, ModsPage, SetupPage, BuildPage }) p.Visibility = p == page ? Visibility.Visible : Visibility.Collapsed;
|
||||
if (page != BuildPage && ShowLog.IsChecked == true) ShowLog.IsChecked = false;
|
||||
// (nothing to wait for on these pages: the crest whole, every stone alight)
|
||||
if (page == InstallPage || page == HomePage || page == SavesPage || page == SetupPage) stage.All(true);
|
||||
if (page == InstallPage || page == HomePage || page == SavesPage || page == ModsPage || page == SetupPage) stage.All(true);
|
||||
if (shown == page) return;
|
||||
shown = page;
|
||||
Fx.Arrive(page);
|
||||
@@ -300,7 +312,11 @@ sealed partial class Shell
|
||||
void Begin()
|
||||
{
|
||||
var dir = Install.InstalledDir;
|
||||
try { var old = System.IO.Path.Combine(dir ?? Install.SelfDir, "TriforceSetup.old.exe"); if (File.Exists(old)) File.Delete(old); } catch (Exception) { }
|
||||
var before = System.IO.Path.Combine(dir ?? Install.SelfDir, "TriforceSetup.old.exe");
|
||||
void RemoveBefore() { try { if (File.Exists(before)) File.Delete(before); } catch (Exception) { } }
|
||||
RemoveBefore();
|
||||
// (the Setup this one replaced still runs for a moment, until it has heard that this window is up, StartNewSetup: again once it is gone)
|
||||
if (relaunched) Task.Delay(5000).ContinueWith(_ => RemoveBefore());
|
||||
if (autoBuild != null && Tools.Find() is { } auto)
|
||||
{
|
||||
Program.Log("auto-build (test) " + string.Join(" | ", autoBuild));
|
||||
@@ -357,15 +373,91 @@ sealed partial class Shell
|
||||
}
|
||||
}
|
||||
|
||||
void Relaunch(string exe, bool afterSelfUpdate)
|
||||
/// Starts the Setup that takes this one's place (the installed one after an install, the new one after an update) with what
|
||||
/// this one was asked to do, and closes. (stay: not closed yet: after its own update Setup waits for the new one, StartNewSetup)
|
||||
Process? Relaunch(string exe, bool afterSelfUpdate, bool stay = false)
|
||||
{
|
||||
var a = new List<string>();
|
||||
if (updateFolder != null) { a.Add("--update"); a.Add("\"" + updateFolder + "\""); }
|
||||
if (afterSelfUpdate) a.Add("--relaunched");
|
||||
if (merge && updateFolder == null) a.Add("--merge");
|
||||
Process.Start(new ProcessStartInfo(exe, string.Join(" ", a)) { UseShellExecute = false, WorkingDirectory = System.IO.Path.GetDirectoryName(exe)! });
|
||||
// (the Setup started here takes this install over: it must find the folder free, Guard.cs Instance)
|
||||
Instance.Release();
|
||||
Process? next;
|
||||
try { next = Process.Start(new ProcessStartInfo(exe, string.Join(" ", a)) { UseShellExecute = false, WorkingDirectory = System.IO.Path.GetDirectoryName(exe)! }); }
|
||||
catch (Exception) { Instance.TakeAgain(); throw; }
|
||||
if (stay) return next;
|
||||
fetch = null;
|
||||
Window.Close();
|
||||
return next;
|
||||
}
|
||||
|
||||
bool sessionEnding; // (Windows is shutting down or the player logging off: programs are being ended)
|
||||
|
||||
/// Is the release's Setup one to replace this one with? Not one that could not start on this PC (StartNewSetup): that one is not
|
||||
/// fetched again, and this Setup goes on with the release's tools until the next release brings another
|
||||
bool SetupNewer(Release r) => Program.Version != "dev" && r.Tag != Program.Version && r.SetupUrl != null && Install.Get("SetupSkip") != r.Tag;
|
||||
|
||||
/// After Setup replaced itself (the new exe under its name, this one running on as TriforceSetup.old.exe): the new one is
|
||||
/// started, and this one waits out of sight until the new window is up, then goes. A new Setup that cannot be started, or
|
||||
/// ends at once with an error, would be all the player has under their shortcut: this one takes its name back instead
|
||||
/// (Guard.cs Handover), shows itself again and says so, and that release's Setup is not fetched again.
|
||||
async Task StartNewSetup(string self, string old, string tag)
|
||||
{
|
||||
// (testing, TRIFORCE_UI_SCRIPT: the script goes on in the new Setup, and this one must not go on running its steps beside it)
|
||||
if (scriptFile != null) { Relaunch(self, true); return; }
|
||||
EventWaitHandle up;
|
||||
try { up = Handover.Expect(Install.InstalledDir ?? Install.SelfDir, Install.TestRoot); }
|
||||
catch (Exception) { Relaunch(self, true); return; } // (no sign can be waited for here: started and left to itself, as it always was)
|
||||
var outcome = Handover.Outcome.Unclear;
|
||||
var why = "";
|
||||
using (up)
|
||||
{
|
||||
Process? next = null;
|
||||
try { next = Relaunch(self, true, stay: true); }
|
||||
catch (Exception e) { outcome = Handover.Outcome.Failed; why = e.Message; }
|
||||
if (next != null)
|
||||
{
|
||||
Window.Hide();
|
||||
try { outcome = await Task.Run(() => Handover.Watch(next, up, TimeSpan.FromSeconds(30))); }
|
||||
catch (Exception) { }
|
||||
try { if (outcome == Handover.Outcome.Failed) why = "it ended at once, with exit code 0x" + next.ExitCode.ToString("X8"); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
Program.Log("Setup " + tag + " after the restart: " + (outcome == Handover.Outcome.Up ? "its window is up" : outcome == Handover.Outcome.Failed ? "it did not start (" + why + ")" : "no sign of its window, left to itself"));
|
||||
// (when Windows ends the session the new Setup is ended like everything else, which says nothing about it. And when another
|
||||
// Setup has the folder by now, the new one started after all: the player started it again)
|
||||
if (outcome != Handover.Outcome.Failed || sessionEnding || !Instance.TakeAgain())
|
||||
{
|
||||
fetch = null;
|
||||
Window.Close();
|
||||
return;
|
||||
}
|
||||
var back = await Task.Run(() => Handover.Restore(old, self));
|
||||
Program.Log(back ? "Setup " + Program.Version + " is back under its name, and Setup " + tag + " will not be fetched again" : "Setup " + Program.Version + " could not be put back under its name");
|
||||
if (back) Install.Set("SetupSkip", tag);
|
||||
Window.Show();
|
||||
Window.Activate();
|
||||
throw new NotStartedException(back
|
||||
? "Triforce Setup " + tag + " could not start on this PC (" + why + "), so Setup " + Program.Version + " is back in its place. Try again goes on with this one."
|
||||
: "Triforce Setup " + tag + " could not start on this PC (" + why + "), and Setup " + Program.Version + " could not be put back in its place. Keep this window open and download Triforce Setup again from " + Program.Home + ".");
|
||||
}
|
||||
|
||||
/// A second Setup was started for this install (Guard.cs Instance): it has ended, and this window comes to the front in its place
|
||||
public void ComeForward()
|
||||
{
|
||||
Program.Log("a second Setup was started for this install: this window comes to the front instead");
|
||||
if (snapshot != null || scriptFile != null) return; // (testing: the window stays off the screen)
|
||||
try
|
||||
{
|
||||
if (!Window.IsVisible) return;
|
||||
if (Window.WindowState == WindowState.Minimized) Window.WindowState = WindowState.Normal;
|
||||
Window.Activate();
|
||||
// (Windows may only flash the taskbar button of a window that is not in front: a moment as the topmost one brings it there)
|
||||
Window.Topmost = true;
|
||||
Window.Topmost = false;
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
// ---- gather: the update check, Setup's own update, the tools ----
|
||||
@@ -450,7 +542,7 @@ sealed partial class Shell
|
||||
FetchUnknown(false);
|
||||
FetchCancel.IsEnabled = true;
|
||||
var offline = e is HttpRequestException || e is TaskCanceledException && !cancelled;
|
||||
FetchTitle.Text = cancelled ? "Stopped" : offline ? "The Triforce site could not be reached" : "Something went wrong";
|
||||
FetchTitle.Text = cancelled ? "Stopped" : offline ? "The Triforce site could not be reached" : e is NoRoomException ? "Not enough room on the disk" : e is CutOffException ? "The download stopped" : e is NotStartedException ? "The new Setup could not start" : "Something went wrong";
|
||||
FetchNote.Text = cancelled ? "Nothing was changed." : offline ? "Check your internet connection, then try again." : e.Message;
|
||||
FetchNote.Foreground = Brush(cancelled ? "Text" : "Bad");
|
||||
FetchStep.Text = "";
|
||||
@@ -476,21 +568,20 @@ sealed partial class Shell
|
||||
{
|
||||
using var http = Http();
|
||||
// 1. Setup itself
|
||||
if (!relaunched && Program.Version != "dev" && release.Tag != Program.Version && release.SetupUrl != null)
|
||||
if (Install.Get("SetupSkip") == release.Tag) Program.Log("Setup " + release.Tag + " is not fetched: it could not start on this PC (SetupSkip)");
|
||||
if (!relaunched && SetupNewer(release) && release.SetupUrl != null)
|
||||
{
|
||||
FetchState("A new Setup is here", "Triforce Setup " + release.Tag + " replaces " + Program.Version + ". It restarts by itself and carries on.", "Downloading Setup " + release.Tag);
|
||||
var dir = Install.InstalledDir ?? Install.SelfDir;
|
||||
var fresh = System.IO.Path.Combine(dir, "TriforceSetup.new.exe");
|
||||
FetchProgress(0, "");
|
||||
await Release.Download(http, release.SetupUrl, fresh, release.SetupSize, (f, have) => Ui(() => FetchProgress(f, (have >> 10) + " KB")), token);
|
||||
await Download.ToFile(http, release.SetupUrl, fresh, release.SetupSize, (f, have) => Ui(() => FetchProgress(f, (have >> 10) + " KB")), token);
|
||||
var self = System.IO.Path.Combine(dir, Program.SetupAsset);
|
||||
var old = System.IO.Path.Combine(dir, "TriforceSetup.old.exe");
|
||||
if (File.Exists(old)) File.Delete(old);
|
||||
File.Move(self, old);
|
||||
File.Move(fresh, self);
|
||||
Handover.Swap(fresh, self, old);
|
||||
Program.Log("Setup updated to " + release.Tag + ", restarting");
|
||||
merge = true;
|
||||
Relaunch(self, true);
|
||||
await StartNewSetup(self, old, release.Tag);
|
||||
return;
|
||||
}
|
||||
stage.Set(Art.Sapphire, true);
|
||||
@@ -507,18 +598,42 @@ sealed partial class Shell
|
||||
var cache = System.IO.Path.Combine(Install.InstalledDir ?? Install.SelfDir, "downloads");
|
||||
Directory.CreateDirectory(cache);
|
||||
var zip = System.IO.Path.Combine(cache, "Triforce-Tools-" + string.Concat(release.Tag.Where(c => char.IsLetterOrDigit(c) || c == '.' || c == '-')) + ".zip");
|
||||
// (room for the zip and for what it unpacks to, asked before the first byte is fetched, Guard.cs Space: a disk that filled
|
||||
// in the middle left half a download or half a tools folder and an error that named no cause. What an unpacking that was
|
||||
// cut off left behind goes first. The part of the zip a try before this one fetched is gone on from, Guard.cs Download,
|
||||
// so only the rest takes room; and a zip that is there whole, by its size, from a try that got no further than its
|
||||
// unpacking, is not fetched again)
|
||||
await Task.Run(Tools.Sweep);
|
||||
long Length(string file) { try { return File.Exists(file) ? new FileInfo(file).Length : 0; } catch (Exception) { return 0; } }
|
||||
var whole = release.ToolsSize > 0 && Length(zip) == release.ToolsSize;
|
||||
var unpacked = release.ToolsSize * ToolsUnpackedTimes;
|
||||
if (release.ToolsSize > 0 && Space.Problem("the Triforce tools (a download of " + (release.ToolsSize >> 20) + " MB that unpacks to about " + (unpacked >> 20) + " MB)",
|
||||
(whole ? 0 : Math.Max(0, release.ToolsSize - Length(zip + ".part"))) + unpacked, Space.Free(cache), Space.Disk(cache)) is { } none)
|
||||
throw new NoRoomException(none);
|
||||
FetchProgress(0, "");
|
||||
await Release.Download(http, release.ToolsUrl, zip, release.ToolsSize, (f, got) => Ui(() =>
|
||||
{
|
||||
FetchProgress(f, (got >> 20) + " / " + (release.ToolsSize >> 20) + " MB");
|
||||
stage.Charge(Art.Ruby, f * 0.7);
|
||||
}), token);
|
||||
if (!whole)
|
||||
await Download.ToFile(http, release.ToolsUrl, zip, release.ToolsSize, (f, got) => Ui(() =>
|
||||
{
|
||||
FetchProgress(f, (got >> 20) + " / " + (release.ToolsSize >> 20) + " MB");
|
||||
stage.Charge(Art.Ruby, f * 0.7);
|
||||
}), token);
|
||||
else Program.Log("tools " + release.Tag + ": the zip is here already, whole (" + release.ToolsSize + " bytes)");
|
||||
FetchStep.Text = "Unpacking the tools";
|
||||
FetchCancel.IsEnabled = false;
|
||||
FetchProgress(0, "");
|
||||
await Task.Run(() => Tools.Unpack(zip, release.Tag, f => Ui(() => { FetchProgress(f, ""); stage.Charge(Art.Ruby, 0.7 + f * 0.3); })));
|
||||
try { await Task.Run(() => Tools.Unpack(zip, release.Tag, f => Ui(() => { FetchProgress(f, ""); stage.Charge(Art.Ruby, 0.7 + f * 0.3); }))); }
|
||||
catch (Exception e) when (e is not NoRoomException && !Space.Full(e))
|
||||
{
|
||||
// (a zip that does not unpack is fetched again at the next try, not tried again; one there was no room for is kept)
|
||||
try { File.Delete(zip); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
FetchCancel.IsEnabled = true;
|
||||
try { File.Delete(zip); } catch (Exception) { }
|
||||
// (the zip, and what downloads of other releases left there: parts nothing will go on from)
|
||||
string[] leavings = { };
|
||||
try { leavings = Directory.GetFiles(cache, "Triforce-Tools-*"); } catch (Exception) { }
|
||||
foreach (var f in leavings)
|
||||
try { File.Delete(f); } catch (Exception) { }
|
||||
Program.Log("tools " + release.Tag + " unpacked into " + Tools.Folder);
|
||||
}
|
||||
stage.Set(Art.Ruby, true);
|
||||
@@ -542,6 +657,9 @@ sealed partial class Shell
|
||||
{
|
||||
fetch = null;
|
||||
Program.Log("update failed: " + e.GetType().Name + ": " + e.Message);
|
||||
// (a disk that filled while it was written to all the same, another program's doing: said as that, with the disk's name)
|
||||
if (Space.Full(e))
|
||||
e = new NoRoomException(Space.Disk(Install.InstalledDir ?? Install.SelfDir) + " is full: the download or the tools could not be written. Make room there and try again.");
|
||||
Failed(e, e is OperationCanceledException && token.IsCancellationRequested);
|
||||
}
|
||||
}
|
||||
@@ -553,6 +671,8 @@ sealed partial class Shell
|
||||
|
||||
static bool HasGame => Install.Get("GameFolder") is { } g && GameExe(g) != null;
|
||||
Button SetupBack = null!; // (the build page's way back home)
|
||||
Button CopyReport = null!; // (after a build that stopped: what a player sends, Guard.cs Report)
|
||||
string? buildLine, stopped; // (the build that ran last: what it was started with, and what it stopped by)
|
||||
CheckBox DlssTick = null!; // (NVIDIA DLSS, its license accepted)
|
||||
static bool DlssChosen => Install.Get("Dlss") == "1";
|
||||
/// Where NVIDIA's DLSS SDK is kept: beside Setup, not in the tools folder (an update replaces that one whole)
|
||||
@@ -647,9 +767,19 @@ sealed partial class Shell
|
||||
// (Setup just asked about updates: the game's own offer, host/hos_update.c, would ask again)
|
||||
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = folder };
|
||||
si.EnvironmentVariables["HOOKSHOT_NO_UPDATE_CHECK"] = "1";
|
||||
// ((Triforce) 11-17, his "when you select play in the launcher i want the same sound that plays when you press load
|
||||
// game": the Load list's sound, before the game is there (Setup is silent while it runs); the window goes at once,
|
||||
// Setup itself once the sound is over: it would stop with Setup)
|
||||
playing = true;
|
||||
sounds.Play(Sounds.Start);
|
||||
var wait = sounds.Seconds(Sounds.Start);
|
||||
Process.Start(si);
|
||||
Program.Log("started the game: " + exe);
|
||||
Window.Close();
|
||||
if (wait <= 0) { Window.Close(); return; }
|
||||
Window.Hide();
|
||||
var t = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromSeconds(Math.Min(wait, 3) + 0.1) };
|
||||
t.Tick += (_, _) => { t.Stop(); Window.Close(); };
|
||||
t.Start();
|
||||
}
|
||||
|
||||
void ApplyLanguage()
|
||||
@@ -663,6 +793,7 @@ sealed partial class Shell
|
||||
SaveToLabel.Label = T(S.SaveTo);
|
||||
BuildButton.Content = T(S.Build);
|
||||
ShowLog.Content = T(ShowLog.IsChecked == true ? S.HideDetails : S.ShowDetails);
|
||||
CopyReport.Content = T(S.CopyReport);
|
||||
CancelButton.Content = T(S.Cancel);
|
||||
BackButton.Content = T(S.Back);
|
||||
OpenButton.Content = T(S.OpenFolder);
|
||||
@@ -756,6 +887,17 @@ sealed partial class Shell
|
||||
|
||||
// ---- the build ----
|
||||
|
||||
/// The Build button: with less room on the disk than a build takes, the player is told both numbers first. (The line under the
|
||||
/// form only turned red, and such a build stopped somewhere in its 45 minutes. Going on stays possible, as it was: the 60 GB are
|
||||
/// a first build's, and a folder that already holds the game's files takes far less.)
|
||||
void BuildIfRoom()
|
||||
{
|
||||
if (Space.Free(OutPath.Text) is { } free && free < NeededBytes)
|
||||
Ask(Space.Disk(OutPath.Text) + " has " + (free >> 30) + " GB free. A build takes about " + (NeededBytes >> 30) + " GB and may stop halfway without them. Build anyway?",
|
||||
"Build anyway", T(S.Back), StartBuild);
|
||||
else StartBuild();
|
||||
}
|
||||
|
||||
void StartBuild()
|
||||
{
|
||||
var tools = Tools.Find();
|
||||
@@ -800,7 +942,9 @@ sealed partial class Shell
|
||||
// from AMD's repository and put beside the game: nx2/make_game.py --fsr, scripts/fsr_sdk.py. The Upscaler row offers
|
||||
// it only on a card AMD's library says runs it)
|
||||
if (!args.Contains("--fsr") && !args.Contains("--no-fsr")) args.Add("--fsr");
|
||||
Program.Log("build: make_game.py " + string.Join(" ", args) + " (tools " + tools.Root + ")");
|
||||
buildLine = "make_game.py " + string.Join(" ", args) + " (tools " + tools.Root + ")";
|
||||
stopped = null;
|
||||
Program.Log("build: " + buildLine);
|
||||
runner = new Runner(tools, args, dlss ? NgxSdk : null);
|
||||
ShowClock();
|
||||
runner.Line += l => Ui(() => Line(l));
|
||||
@@ -848,6 +992,8 @@ sealed partial class Shell
|
||||
BuildTitle.Text = T(S.Ready);
|
||||
BuildNote.Text = finished + " · " + T(S.BuiltIn) + " " + Span(elapsed.Elapsed);
|
||||
Install.Set("GameFolder", finished);
|
||||
MarkModsBuilt(finished); // (the mods' code patches and cheats are in it as they are now: Shell.Mods.cs)
|
||||
LoadSounds(); // (a game folder now, or another one: its interface sounds are Setup's, Shell.Sounds.cs)
|
||||
SetButtons(done: true);
|
||||
return;
|
||||
}
|
||||
@@ -855,7 +1001,43 @@ sealed partial class Shell
|
||||
BuildNote.Text = failure == "cancelled" ? T(S.CancelledNote) : failure ?? "";
|
||||
BuildNote.Foreground = Brush(failure == "cancelled" ? "Text" : "Bad");
|
||||
if (current != null && rows.TryGetValue(current, out var row)) row.Stopped();
|
||||
SetButtons(back: true);
|
||||
stopped = failure;
|
||||
SetButtons(back: true, report: failure != "cancelled");
|
||||
}
|
||||
|
||||
/// Copy report, after a build that stopped: what Setup knows of it, the last lines of its details and of setup.log, onto the
|
||||
/// clipboard to paste where help is asked for (Guard.cs Report: the account's folder reads %USERPROFILE% in it, so the
|
||||
/// player's name does not go along)
|
||||
void CopyTheReport()
|
||||
{
|
||||
var home = Install.InstalledDir ?? Install.SelfDir;
|
||||
string Room(string folder) => Space.Free(folder) is { } free ? " (" + Space.Disk(folder) + " has " + (free >> 30) + " GB free)" : "";
|
||||
var step = "its start";
|
||||
foreach (var (id, text, _) in Stages)
|
||||
if (id == current) step = "\"" + Strings.All[0].Text[(int)text] + "\"";
|
||||
var known = new[]
|
||||
{
|
||||
"Triforce Setup " + Program.Version + ", tools " + (Tools.InstalledVersion ?? "none") + ", " + Environment.OSVersion.VersionString,
|
||||
"The build stopped at " + step + " after " + Span(elapsed.Elapsed) + ": " + (stopped ?? "no reason given"),
|
||||
buildLine ?? "",
|
||||
"Game folder: " + OutPath.Text + Room(OutPath.Text),
|
||||
"Setup: " + home + Room(home),
|
||||
};
|
||||
var log = "";
|
||||
try { log = File.ReadAllText(System.IO.Path.Combine(home, "setup.log")); } catch (Exception) { }
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
try
|
||||
{
|
||||
// (kept on the clipboard when Setup closes)
|
||||
Clipboard.SetDataObject(Report.Compose(known, Log.Text, log, profile, Report.Short(profile)), true);
|
||||
CopyReport.Content = T(S.ReportCopied);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// (another program has the clipboard open)
|
||||
Program.Log("the report could not be copied: " + e.Message);
|
||||
CopyReport.Content = T(S.ReportNotCopied);
|
||||
}
|
||||
}
|
||||
|
||||
void ShowClock()
|
||||
@@ -865,8 +1047,11 @@ sealed partial class Shell
|
||||
|
||||
static string Span(TimeSpan t) => t.TotalHours >= 1 ? (int)t.TotalHours + " h " + t.Minutes + " min" : t.TotalMinutes >= 1 ? t.Minutes + " min" : t.Seconds + " s";
|
||||
|
||||
void SetButtons(bool cancel = false, bool done = false, bool back = false)
|
||||
void SetButtons(bool cancel = false, bool done = false, bool back = false, bool report = false)
|
||||
{
|
||||
// (Copy report: only after a build that stopped by itself, and under its first words each time it is offered)
|
||||
CopyReport.Content = T(S.CopyReport);
|
||||
CopyReport.Visibility = report ? Visibility.Visible : Visibility.Collapsed;
|
||||
CancelButton.Visibility = cancel ? Visibility.Visible : Visibility.Collapsed;
|
||||
PlayButton.Visibility = OpenButton.Visibility = done ? Visibility.Visible : Visibility.Collapsed;
|
||||
BackButton.Visibility = back ? Visibility.Visible : Visibility.Collapsed;
|
||||
|
||||
336
setup/Sound.cs
Normal file
336
setup/Sound.cs
Normal file
@@ -0,0 +1,336 @@
|
||||
// (Triforce) Setup's sounds: two of the game's own interface sounds, the decide sound and the cancel sound of its menus, read
|
||||
// from the player's built game and played when a button, link or row is chosen and when the player goes back (Shell.Sounds.cs
|
||||
// says where). Nothing here needs the window: tests/test_setup_sound.py compiles this file with Mods.cs and Guard.cs and runs
|
||||
// it on sound files it authors itself.
|
||||
//
|
||||
// No sound is in the repository, in a release or in Setup, and Setup makes none of its own: until a game is built, and for
|
||||
// a file that is missing or does not decode, it is silent, without a word. The two files are decoded in memory and stay
|
||||
// there: nothing made from the game's audio is written to the disk.
|
||||
//
|
||||
// <game>\romfs\Sound\Resource\Stream\SE_Sys_Do00.bwav decide
|
||||
// <game>\romfs\Sound\Resource\Stream\SE_Sys_Cancel00.bwav cancel
|
||||
// <game>\romfs\Sound\Resource\Stream\SE_Sys_SysMenu_DecideL00.bwav start ((Triforce, 11-17) Play: the sound of the game's Load
|
||||
// list when a save is chosen)
|
||||
// or the file a mod puts in their place, by the game's own rule (Mods.RomfsFile): the game would play the mod's.
|
||||
//
|
||||
// BWAV (from NX2navi's runtime/menu_sound.c, the owner's, as is the decoder below): "BWAV", a byte order mark, a version, a
|
||||
// CRC32, a prefetch flag (u16) and the channel count (u16 at 0x0E), then 0x4C bytes for each channel: codec (u16: 0 PCM16,
|
||||
// 1 DSP-ADPCM), pan (u16: 0 left, 1 right, 2 middle), sample rate (u32), sample count (u32), the count again, 16 DSP
|
||||
// coefficients (s16), the place of the samples in the file (u32 at 0x30), ... DSP-ADPCM is frames of 8 bytes: a header (the
|
||||
// coefficient pair's index, the scale's exponent) and 14 samples of four bits. The interface sounds are 48 kHz DSP-ADPCM in
|
||||
// two channels. All numbers little-endian.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
/// A decoded sound: left and right in turn, -1 to 1
|
||||
sealed class Clip
|
||||
{
|
||||
public int Rate;
|
||||
public float[] Samples = { };
|
||||
public int Frames => Samples.Length / 2;
|
||||
}
|
||||
|
||||
static class Bwav
|
||||
{
|
||||
/// How long a sound may be, in seconds (the interface sounds last about one): a count beyond it is no such file
|
||||
public const int MaxSeconds = 10;
|
||||
|
||||
static int U16(byte[] b, long at) => b[at] | b[at + 1] << 8;
|
||||
static long U32(byte[] b, long at) => b[at] | (long)b[at + 1] << 8 | (long)b[at + 2] << 16 | (long)b[at + 3] << 24;
|
||||
|
||||
/// The file decoded, or null when it is no BWAV file of one or two channels of PCM16 or DSP-ADPCM that is whole. Every
|
||||
/// place read is asked against the file's length first: a file cut off or with numbers that point past its end is refused
|
||||
/// here, not by an exception
|
||||
public static Clip? Decode(byte[]? b)
|
||||
{
|
||||
if (b == null || b.Length < 0x10 || b[0] != 'B' || b[1] != 'W' || b[2] != 'A' || b[3] != 'V') return null;
|
||||
var channels = U16(b, 0x0E);
|
||||
if (channels < 1 || channels > 2 || 0x10 + channels * 0x4C > b.Length) return null;
|
||||
long rate = U32(b, 0x10 + 4), frames = U32(b, 0x10 + 8);
|
||||
if (rate < 8000 || rate > 96000 || frames == 0 || frames > rate * MaxSeconds) return null;
|
||||
// (first whether every channel's samples are in the file, then the room for them: a file that only says it is long gets none)
|
||||
for (var c = 0; c < channels; c++)
|
||||
if (!Whole(b, 0x10 + c * 0x4C, frames)) return null;
|
||||
var pcm = new float[frames * 2];
|
||||
for (var c = 0; c < channels; c++) Channel(b, 0x10 + c * 0x4C, pcm, frames);
|
||||
// (one channel, in the middle: in both, at the level that sounds as loud)
|
||||
if (channels == 1)
|
||||
for (var i = 0; i < pcm.Length; i++) pcm[i] *= 0.7071f;
|
||||
return new Clip { Rate = (int)rate, Samples = pcm };
|
||||
}
|
||||
|
||||
/// Is the channel one of the two codecs, with all of its samples (as many as the sound has, at most) inside the file?
|
||||
static bool Whole(byte[] b, long info, long frames)
|
||||
{
|
||||
var codec = U16(b, info);
|
||||
long count = Math.Min(U32(b, info + 8), frames), at = U32(b, info + 0x30);
|
||||
return codec == 0 ? at + count * 2 <= b.Length : codec == 1 && at + (count + 13) / 14 * 8 <= b.Length;
|
||||
}
|
||||
|
||||
/// One channel (Whole has looked at it) added into its side: pan 0 left, 1 right, anything else both
|
||||
static void Channel(byte[] b, long info, float[] into, long frames)
|
||||
{
|
||||
int codec = U16(b, info), pan = U16(b, info + 2);
|
||||
long count = Math.Min(U32(b, info + 8), frames), at = U32(b, info + 0x30);
|
||||
const float scale = 1f / 32768f;
|
||||
if (codec == 0)
|
||||
{
|
||||
for (long i = 0; i < count; i++)
|
||||
{
|
||||
var v = (short)U16(b, at + 2 * i) * scale;
|
||||
if (pan != 1) into[2 * i] += v;
|
||||
if (pan != 0) into[2 * i + 1] += v;
|
||||
}
|
||||
return;
|
||||
}
|
||||
var pairs = new int[16];
|
||||
for (var i = 0; i < 16; i++) pairs[i] = (short)U16(b, info + 0x10 + 2 * i);
|
||||
long h1 = 0, h2 = 0;
|
||||
for (long i = 0; i < count; i++)
|
||||
{
|
||||
var frame = at + i / 14 * 8;
|
||||
var k = (int)(i % 14);
|
||||
int index = b[frame] >> 4 & 7, shift = b[frame] & 15;
|
||||
var nibble = b[frame + 1 + k / 2] >> ((k & 1) != 0 ? 0 : 4) & 15;
|
||||
if (nibble >= 8) nibble -= 16;
|
||||
var s = ((long)(nibble << shift) << 11) + pairs[2 * index] * h1 + pairs[2 * index + 1] * h2;
|
||||
var v = Math.Max(-32768, Math.Min(32767, (s + 1024) >> 11));
|
||||
h2 = h1;
|
||||
h1 = v;
|
||||
if (pan != 1) into[2 * i] += v * scale;
|
||||
if (pan != 0) into[2 * i + 1] += v * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What plays a sound. (The window's is WinPlayer; a test puts its own here, and a test run of Setup none at all.)
|
||||
interface ISoundPlayer
|
||||
{
|
||||
/// Starts a WAV file's bytes, in place of whatever plays. The same array is handed in again for the same sound
|
||||
void Play(string what, byte[] wav);
|
||||
/// The arrays handed in so far will not come again: whatever plays is stopped
|
||||
void Forget();
|
||||
}
|
||||
|
||||
/// Windows' own PlaySound, from memory, without waiting for the sound to end and without Windows' "ding" where a sound cannot
|
||||
/// be played. It reads the bytes while it plays, so each array stays pinned in its place until it is forgotten, and then one
|
||||
/// forgetting longer
|
||||
sealed class WinPlayer : ISoundPlayer
|
||||
{
|
||||
[DllImport("winmm.dll", EntryPoint = "PlaySoundW", SetLastError = true)]
|
||||
static extern bool PlaySound(IntPtr sound, IntPtr module, uint flags);
|
||||
const uint Async = 0x0001, NoDefault = 0x0002, Memory = 0x0004;
|
||||
|
||||
readonly Dictionary<byte[], GCHandle> held = new();
|
||||
List<GCHandle> let = new();
|
||||
|
||||
public void Play(string what, byte[] wav)
|
||||
{
|
||||
if (!held.TryGetValue(wav, out var pinned)) held[wav] = pinned = GCHandle.Alloc(wav, GCHandleType.Pinned);
|
||||
PlaySound(pinned.AddrOfPinnedObject(), IntPtr.Zero, Memory | Async | NoDefault);
|
||||
}
|
||||
|
||||
public void Forget()
|
||||
{
|
||||
try { PlaySound(IntPtr.Zero, IntPtr.Zero, 0); } catch (Exception) { }
|
||||
foreach (var h in let) h.Free();
|
||||
let = held.Values.ToList();
|
||||
held.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// (testing, TRIFORCE_SOUND_LOG=<file> in a test run of Setup: no sound is made; each one that would have played is a line
|
||||
/// in that file, with the size of its WAV block and its loudest sample)
|
||||
sealed class NotedPlayer : ISoundPlayer
|
||||
{
|
||||
readonly string file;
|
||||
public NotedPlayer(string file) { this.file = file; }
|
||||
|
||||
public void Play(string what, byte[] wav)
|
||||
{
|
||||
var peak = 0;
|
||||
for (var i = 44; i + 1 < wav.Length; i += 2) peak = Math.Max(peak, Math.Abs((int)(short)(wav[i] | wav[i + 1] << 8)));
|
||||
try { File.AppendAllText(file, what + " " + wav.Length + " bytes, peak " + peak + Environment.NewLine); } catch (Exception) { }
|
||||
}
|
||||
|
||||
public void Forget() { }
|
||||
}
|
||||
|
||||
sealed class Sounds
|
||||
{
|
||||
public const string Decide = "decide", Cancel = "cancel", Start = "start";
|
||||
/// The game's files, as its RomFS names them
|
||||
public static readonly (string Sound, string File)[] Files =
|
||||
{
|
||||
(Decide, "Sound/Resource/Stream/SE_Sys_Do00.bwav"), (Cancel, "Sound/Resource/Stream/SE_Sys_Cancel00.bwav"),
|
||||
(Start, "Sound/Resource/Stream/SE_Sys_SysMenu_DecideL00.bwav"),
|
||||
};
|
||||
/// The setting's choices: the loudest sample's share of full scale (NX2navi's launcher's levels)
|
||||
public static readonly (string Name, double Share)[] Levels = { ("off", 0), ("low", 0.18), ("medium", 0.40), ("high", 0.75) };
|
||||
public const string Default = "low";
|
||||
/// The most of a sound file that is read (the game's two are 63 KB and 50 KB)
|
||||
public const int MaxFile = 4 << 20;
|
||||
|
||||
/// A setting's value as one of the choices: the default for none, or for one that is no choice
|
||||
public static string Known(string? level) => Levels.Any(l => l.Name == level) ? level! : Default;
|
||||
public static double Share(string? level) => Levels.First(l => l.Name == Known(level)).Share;
|
||||
/// The choice after this one, around: off, low, medium, high, off
|
||||
public static string Next(string? level) => Levels[(Array.FindIndex(Levels, l => l.Name == Known(level)) + 1) % Levels.Length].Name;
|
||||
|
||||
/// What plays the sounds of this run of Setup. Nothing in a run that only looks at Setup or drives it without a person:
|
||||
/// --snapshot, a script (TRIFORCE_UI_SCRIPT) or a test folder (TRIFORCE_TEST_ROOT). Such a run, when it asks (noted: the
|
||||
/// file of TRIFORCE_SOUND_LOG), gets the sounds written down instead of played; --snapshot not even that
|
||||
public static ISoundPlayer? PlayerFor(bool snapshot, bool scripted, string? testRoot, string? noted)
|
||||
{
|
||||
if (snapshot) return null;
|
||||
if (scripted || testRoot != null) return string.IsNullOrEmpty(noted) ? null : new NotedPlayer(noted!);
|
||||
return new WinPlayer();
|
||||
}
|
||||
|
||||
/// Does the game run, any game folder's? Its own sound is playing then, and Setup's would play over it
|
||||
public static bool GameProcess()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var name in new[] { "Triforce", "hookshot" })
|
||||
{
|
||||
var found = Process.GetProcessesByName(name);
|
||||
foreach (var p in found) p.Dispose();
|
||||
if (found.Length > 0) return true;
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return false;
|
||||
}
|
||||
|
||||
/// The sound as a WAV file's bytes, 16 bits in two channels, with its loudest sample at that share of full scale; a
|
||||
/// sample that would pass full scale stays at it. Null for a sound that is all silence
|
||||
public static byte[]? Wav(Clip clip, double share)
|
||||
{
|
||||
var peak = 0f;
|
||||
foreach (var v in clip.Samples) peak = Math.Max(peak, Math.Abs(v));
|
||||
if (peak <= 0 || clip.Samples.Length == 0) return null;
|
||||
var data = clip.Samples.Length * 2;
|
||||
var wav = new byte[44 + data];
|
||||
void Tag(int at, string tag) { for (var i = 0; i < 4; i++) wav[at + i] = (byte)tag[i]; }
|
||||
void Put(int at, int value, int bytes) { for (var i = 0; i < bytes; i++) wav[at + i] = (byte)(value >> 8 * i); }
|
||||
Tag(0, "RIFF"); Put(4, 36 + data, 4); Tag(8, "WAVE");
|
||||
Tag(12, "fmt "); Put(16, 16, 4); Put(20, 1, 2); Put(22, 2, 2); Put(24, clip.Rate, 4); Put(28, clip.Rate * 4, 4); Put(32, 4, 2); Put(34, 16, 2);
|
||||
Tag(36, "data"); Put(40, data, 4);
|
||||
var gain = share / peak * 32767;
|
||||
for (var i = 0; i < clip.Samples.Length; i++)
|
||||
Put(44 + 2 * i, (int)Math.Max(-32767, Math.Min(32767, Math.Round(clip.Samples[i] * gain))), 2);
|
||||
return wav;
|
||||
}
|
||||
|
||||
readonly ISoundPlayer? player;
|
||||
readonly Func<bool> gameRuns;
|
||||
readonly object gate = new();
|
||||
readonly Dictionary<string, Clip> clips = new();
|
||||
readonly Dictionary<string, byte[]> wavs = new();
|
||||
string level = Default, from = "";
|
||||
bool broken;
|
||||
|
||||
/// player: null for a Setup that makes no sound at all (then no file is read either). gameRuns: asked before each sound
|
||||
public Sounds(ISoundPlayer? player, Func<bool> gameRuns, string? level = null)
|
||||
{
|
||||
this.player = player;
|
||||
this.gameRuns = gameRuns;
|
||||
this.level = Known(level);
|
||||
}
|
||||
|
||||
/// The setting. Changing it stops what plays
|
||||
public string Level
|
||||
{
|
||||
get { lock (gate) return level; }
|
||||
set
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
if (Known(value) == level) return;
|
||||
level = Known(value);
|
||||
Renew();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The WAV blocks anew, for the sounds and the level there are now
|
||||
void Renew()
|
||||
{
|
||||
try { player?.Forget(); } catch (Exception) { broken = true; }
|
||||
wavs.Clear();
|
||||
var share = Share(level);
|
||||
if (share <= 0) return;
|
||||
foreach (var c in clips)
|
||||
if (Wav(c.Value, share) is { } wav) wavs[c.Key] = wav;
|
||||
}
|
||||
|
||||
/// Takes up the two sounds of a game folder (null: no game yet), from its files or a mod's. Again whenever the game folder
|
||||
/// or its mods may have changed: nothing is read again while the same files, by size and time, are the ones to play.
|
||||
/// Whatever cannot be read or decoded is no sound: nothing is said, nothing thrown
|
||||
public void Load(string? game)
|
||||
{
|
||||
if (player == null) return;
|
||||
try
|
||||
{
|
||||
var chosen = new List<(string Sound, string? File, string Mark)>();
|
||||
foreach (var (sound, rel) in Files)
|
||||
{
|
||||
var file = game != null ? Mods.RomfsFile(game, rel) : null;
|
||||
var mark = "";
|
||||
if (file != null)
|
||||
{
|
||||
var info = new FileInfo(file);
|
||||
mark = file + "|" + info.Length + "|" + info.LastWriteTimeUtc.Ticks;
|
||||
}
|
||||
chosen.Add((sound, file, mark));
|
||||
}
|
||||
var all = string.Join("\n", chosen.Select(c => c.Mark));
|
||||
lock (gate)
|
||||
if (all == from) return;
|
||||
var read = new Dictionary<string, Clip>();
|
||||
foreach (var (sound, file, _) in chosen)
|
||||
{
|
||||
if (file == null || new FileInfo(file).Length > MaxFile) continue;
|
||||
if (Bwav.Decode(File.ReadAllBytes(file)) is { } clip) read[sound] = clip;
|
||||
}
|
||||
lock (gate)
|
||||
{
|
||||
from = all;
|
||||
clips.Clear();
|
||||
foreach (var c in read) clips[c.Key] = c.Value;
|
||||
Renew();
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// Plays one of the two, in place of whatever plays. Silent when the setting is Off, the game has no such sound, the game
|
||||
/// runs, or this Setup makes no sound; and from the first time the PC cannot play one (no sound device), for good
|
||||
/// How long a sound lasts, in seconds (0: none to play)
|
||||
public double Seconds(string sound)
|
||||
{
|
||||
lock (gate) return clips.TryGetValue(sound, out var c) && c.Rate > 0 && wavs.ContainsKey(sound) ? (double)c.Frames / c.Rate : 0;
|
||||
}
|
||||
|
||||
public void Play(string sound)
|
||||
{
|
||||
if (player == null) return;
|
||||
lock (gate)
|
||||
{
|
||||
if (broken || !wavs.TryGetValue(sound, out var wav)) return;
|
||||
try
|
||||
{
|
||||
if (gameRuns()) return;
|
||||
player.Play(sound, wav);
|
||||
}
|
||||
catch (Exception) { broken = true; }
|
||||
}
|
||||
}
|
||||
}
|
||||
554
setup/Steam.cs
Normal file
554
setup/Steam.cs
Normal file
@@ -0,0 +1,554 @@
|
||||
// (Triforce) Add to Steam: the game as a "non-Steam game" in the player's Steam library, with pictures drawn from Triforce's own
|
||||
// crest (SteamArt.cs). Nothing here needs the window, and Steam's folder is always handed in: tests/test_setup_steam.py compiles
|
||||
// this file alone and runs it on Steam folders it makes itself. No test and no test run of Setup looks at the PC's real Steam.
|
||||
//
|
||||
// Steam keeps an account's shortcuts in <Steam>\userdata\<account>\config\shortcuts.vdf, a binary file of named values:
|
||||
// 00 name 00 ... 08 a map (its values, then 08)
|
||||
// 01 name 00 text 00 a text
|
||||
// 02 name 00 4 bytes a number (03, 04 and 06 are four bytes too; 07 and 0A are eight)
|
||||
// The whole file is one map, "shortcuts", of one map for each shortcut, named "0", "1", ...; then one more 08 ends the file.
|
||||
// This file is another program's: it is read whole, every shortcut and every value in it that is not ours goes back byte for
|
||||
// byte (they are never taken apart and put together again: the bytes between ours are copied), a file that does not read to
|
||||
// its very end as such a file is refused and left alone, the new file is written beside the old one and takes its name in one
|
||||
// step, and the file as it was is kept (shortcuts.vdf.triforce-backup: before the last change; shortcuts.vdf.before-triforce:
|
||||
// before the first).
|
||||
//
|
||||
// Steam reads the file when it starts and writes its own list back when it closes (NX2navi's launcher found the same, and
|
||||
// closed Steam itself for it): a shortcut written while Steam runs would not show and would be gone at Steam's next exit. So
|
||||
// nothing is written while Steam runs: "Close Steam first".
|
||||
//
|
||||
// The shortcut starts the game itself, Triforce.exe in its folder, not Setup. Its pictures go into config\grid under the
|
||||
// shortcut's number, as Steam names them (Pictures).
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
/// What the player is told when the shortcut cannot be written or removed: a whole sentence
|
||||
sealed class SteamException : Exception
|
||||
{
|
||||
public SteamException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// An account that signed in to Steam on this PC
|
||||
sealed class SteamUser
|
||||
{
|
||||
public string Root = "", Id = "", Name = ""; // (Steam's folder, the account's folder under userdata, the name its owner chose)
|
||||
public bool Recent; // (the one Steam was last signed in with)
|
||||
public long Seen; // (when it last signed in, as Steam writes it; 0 when unknown)
|
||||
public string Config => Path.Combine(Root, "userdata", Id, "config");
|
||||
public string Shortcuts => Path.Combine(Config, "shortcuts.vdf");
|
||||
public string Grid => Path.Combine(Config, "grid");
|
||||
}
|
||||
|
||||
static class Steam
|
||||
{
|
||||
/// The shortcut's name in the library
|
||||
public const string Name = "Triforce";
|
||||
/// The game's program, by any of its names (Shell.cs GameExe)
|
||||
public static readonly string[] GameExes = { "Triforce.exe", "hookshot.exe" };
|
||||
public const string Backup = ".triforce-backup", First = ".before-triforce", Temp = ".triforce-tmp";
|
||||
public const string CloseFirst = "Close Steam first. Steam writes its own list of shortcuts when it closes, and would take this change away again.";
|
||||
|
||||
/// The pictures of a shortcut: what each is, the end of its file's name after the shortcut's number in config\grid, and
|
||||
/// the size Steam's library shows it at (the cover, the wide tile, the background of the game's page, the logo over that
|
||||
/// background, and the icon the shortcut names)
|
||||
public static readonly (string Kind, string File, int Width, int Height)[] Pictures =
|
||||
{
|
||||
("portrait", "p.png", 600, 900), ("wide", ".png", 920, 430), ("hero", "_hero.png", 1920, 620), ("logo", "_logo.png", 640, 360), ("icon", "_icon.png", 256, 256),
|
||||
};
|
||||
|
||||
/// Is Steam running? Asked before every write. (Shell.Mods.cs puts its own look here for a test run, a test its own answer.)
|
||||
public static Func<string, bool> Running = _ =>
|
||||
{
|
||||
var found = Process.GetProcessesByName("steam");
|
||||
foreach (var p in found) p.Dispose();
|
||||
return found.Length > 0;
|
||||
};
|
||||
|
||||
// ---- the binary file ----
|
||||
|
||||
sealed class Node
|
||||
{
|
||||
public byte Type;
|
||||
public string Name = "";
|
||||
public int Start, Value, End; // (its type byte; the first byte after its name; one past its last byte)
|
||||
public List<Node>? Values; // (a map's)
|
||||
}
|
||||
|
||||
static SteamException Bad(string why) => new("Steam's shortcuts file is not as Steam writes it (" + why + "), so Setup left it alone. Nothing was changed.");
|
||||
|
||||
/// The file's values, or a SteamException when it is not a file of named values from its first byte to its last
|
||||
static List<Node> Read(byte[] b)
|
||||
{
|
||||
var at = 0;
|
||||
var top = Map(b, ref at, 0);
|
||||
if (at != b.Length) throw Bad("it goes on after its end");
|
||||
return top;
|
||||
}
|
||||
|
||||
static List<Node> Map(byte[] b, ref int at, int depth)
|
||||
{
|
||||
if (depth > 16) throw Bad("its maps are nested too deep");
|
||||
var values = new List<Node>();
|
||||
for (;;)
|
||||
{
|
||||
if (at >= b.Length) throw Bad("it is cut off");
|
||||
var n = new Node { Start = at, Type = b[at++] };
|
||||
if (n.Type == 8) return values;
|
||||
var end = Array.IndexOf(b, (byte)0, at);
|
||||
if (end < 0) throw Bad("it is cut off");
|
||||
n.Name = Encoding.UTF8.GetString(b, at, end - at);
|
||||
n.Value = at = end + 1;
|
||||
switch (n.Type)
|
||||
{
|
||||
case 0: n.Values = Map(b, ref at, depth + 1); break;
|
||||
case 1:
|
||||
end = Array.IndexOf(b, (byte)0, at);
|
||||
if (end < 0) throw Bad("it is cut off");
|
||||
at = end + 1;
|
||||
break;
|
||||
case 2: case 3: case 4: case 6: at += 4; break;
|
||||
case 7: case 10: at += 8; break;
|
||||
default: throw Bad("it holds a value of a kind Setup does not know, " + n.Type);
|
||||
}
|
||||
if (at > b.Length) throw Bad("it is cut off");
|
||||
n.End = at;
|
||||
values.Add(n);
|
||||
}
|
||||
}
|
||||
|
||||
static Node? Named(IEnumerable<Node> values, string name, int type) =>
|
||||
values.FirstOrDefault(v => v.Type == type && string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
static string Text(byte[] b, Node n) => Encoding.UTF8.GetString(b, n.Value, n.End - 1 - n.Value);
|
||||
|
||||
static byte[] Cut(byte[] b, int from, int to)
|
||||
{
|
||||
var part = new byte[to - from];
|
||||
Array.Copy(b, from, part, 0, part.Length);
|
||||
return part;
|
||||
}
|
||||
|
||||
static void PutText(List<byte> o, string name, string text)
|
||||
{
|
||||
if (text.IndexOf('\0') >= 0) throw new SteamException("A path with a zero in it cannot be written into Steam's shortcuts file.");
|
||||
o.Add(1);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(name));
|
||||
o.Add(0);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(text));
|
||||
o.Add(0);
|
||||
}
|
||||
|
||||
static void PutNumber(List<byte> o, string name, uint number)
|
||||
{
|
||||
o.Add(2);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(name));
|
||||
o.Add(0);
|
||||
o.AddRange(BitConverter.GetBytes(number));
|
||||
}
|
||||
|
||||
/// The number Steam knows a shortcut by, and names its pictures by: the CRC-32 of its Exe and AppName as they stand in
|
||||
/// the file, with the top bit set
|
||||
public static uint Id(string exe, string name)
|
||||
{
|
||||
var crc = 0xFFFFFFFFu;
|
||||
foreach (var x in Encoding.UTF8.GetBytes(exe + name))
|
||||
{
|
||||
crc ^= x;
|
||||
for (var k = 0; k < 8; k++) crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320u : crc >> 1;
|
||||
}
|
||||
return ~crc | 0x80000000u;
|
||||
}
|
||||
|
||||
/// The map "shortcuts" of a file that was read
|
||||
static Node Shortcuts(List<Node> top) => Named(top, "shortcuts", 0) ?? throw Bad("it has no list of shortcuts");
|
||||
|
||||
/// Is this shortcut ours? By its number (this game folder's), or by the name Triforce on a program called as the game is
|
||||
/// (a game folder that was moved): another program the player named Triforce is not
|
||||
static bool Ours(byte[] b, Node shortcut, uint id)
|
||||
{
|
||||
if (shortcut.Values == null) return false;
|
||||
if (Named(shortcut.Values, "appid", 2) is { } number && BitConverter.ToUInt32(b, number.Value) == id) return true;
|
||||
if (Named(shortcut.Values, "AppName", 1) is not { } name || Text(b, name) != Name) return false;
|
||||
if (Named(shortcut.Values, "Exe", 1) is not { } exe) return false;
|
||||
var file = Text(b, exe).Trim().Trim('"').Replace('/', '\\');
|
||||
file = file.Substring(file.LastIndexOf('\\') + 1);
|
||||
return GameExes.Any(g => string.Equals(g, file, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// Are the shortcuts named "0", "1", ... in their order, as Steam names them?
|
||||
static bool Counted(Node shortcuts) => shortcuts.Values!.Select((v, i) => v.Type == 0 && v.Name == i.ToString()).All(ok => ok);
|
||||
|
||||
static byte[] Empty()
|
||||
{
|
||||
var o = new List<byte> { 0 };
|
||||
o.AddRange(Encoding.UTF8.GetBytes("shortcuts"));
|
||||
o.AddRange(new byte[] { 0, 8, 8 });
|
||||
return o.ToArray();
|
||||
}
|
||||
|
||||
/// The file (no bytes: none yet) with our shortcut in it: added after the others, or, where one of ours is there, with its
|
||||
/// number, name, program, folder and icon set and everything else in it as it was (what the player set in Steam for it:
|
||||
/// launch options, tags, hidden). wasThere says which. Every other byte of the file is the same
|
||||
public static byte[] With(byte[] file, string exe, string startDir, string icon, out uint id, out bool wasThere)
|
||||
{
|
||||
id = Id(exe, Name);
|
||||
if (file.Length == 0) file = Empty();
|
||||
var shortcuts = Shortcuts(Read(file));
|
||||
var number = id;
|
||||
var ours = shortcuts.Values!.FirstOrDefault(s => Ours(file, s, number));
|
||||
wasThere = ours != null;
|
||||
var o = new List<byte>();
|
||||
if (ours != null)
|
||||
{
|
||||
// (its own values in their places, set; the ones it lacks after them)
|
||||
string[] set = { "appid", "AppName", "Exe", "StartDir", "icon" };
|
||||
void Put(string which, string spelled)
|
||||
{
|
||||
if (which == "appid") PutNumber(o, spelled, number);
|
||||
else PutText(o, spelled, which == "AppName" ? Name : which == "Exe" ? exe : which == "StartDir" ? startDir : icon);
|
||||
}
|
||||
o.AddRange(Cut(file, 0, ours.Value));
|
||||
var put = new HashSet<string>();
|
||||
foreach (var v in ours.Values!)
|
||||
{
|
||||
var which = set.FirstOrDefault(s => string.Equals(s, v.Name, StringComparison.OrdinalIgnoreCase));
|
||||
if (which == null) { o.AddRange(Cut(file, v.Start, v.End)); continue; }
|
||||
// (written under the name as the file spells it, "exe" in files of older Steams; a second value of one name is dropped)
|
||||
if (put.Add(which)) Put(which, v.Name);
|
||||
}
|
||||
foreach (var s in set.Where(s => !put.Contains(s))) Put(s, s);
|
||||
o.Add(8);
|
||||
o.AddRange(Cut(file, ours.End, file.Length));
|
||||
}
|
||||
else
|
||||
{
|
||||
// (named as Steam would name the next one; in a file whose names are not Steam's count, the first number not taken)
|
||||
var key = shortcuts.Values!.Count;
|
||||
if (!Counted(shortcuts))
|
||||
for (key = 0; shortcuts.Values.Any(v => v.Name == key.ToString()); key++) { }
|
||||
o.AddRange(Cut(file, 0, shortcuts.End - 1));
|
||||
o.Add(0);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(key.ToString()));
|
||||
o.Add(0);
|
||||
// (the values of a shortcut in the order Steam writes them)
|
||||
PutNumber(o, "appid", number);
|
||||
PutText(o, "AppName", Name);
|
||||
PutText(o, "Exe", exe);
|
||||
PutText(o, "StartDir", startDir);
|
||||
PutText(o, "icon", icon);
|
||||
PutText(o, "ShortcutPath", "");
|
||||
PutText(o, "LaunchOptions", "");
|
||||
PutNumber(o, "IsHidden", 0);
|
||||
PutNumber(o, "AllowDesktopConfig", 1);
|
||||
PutNumber(o, "AllowOverlay", 1);
|
||||
PutNumber(o, "OpenVR", 0);
|
||||
PutNumber(o, "Devkit", 0);
|
||||
PutText(o, "DevkitGameID", "");
|
||||
PutNumber(o, "DevkitOverrideAppID", 0);
|
||||
PutNumber(o, "LastPlayTime", 0);
|
||||
PutText(o, "FlatpakAppID", "");
|
||||
o.AddRange(new byte[] { 0 });
|
||||
o.AddRange(Encoding.UTF8.GetBytes("tags"));
|
||||
o.AddRange(new byte[] { 0, 8 });
|
||||
o.Add(8);
|
||||
o.AddRange(Cut(file, shortcuts.End - 1, file.Length));
|
||||
}
|
||||
return Proved(file, o.ToArray(), number, Math.Max(1, shortcuts.Values.Count(s => Ours(file, s, number))));
|
||||
}
|
||||
|
||||
/// The file without our shortcuts (ids: the numbers they had, whose pictures can go). The same bytes when none of ours is
|
||||
/// in it. The shortcuts after ours are named anew where the file counted them 0, 1, 2 ... as Steam does, so that the count
|
||||
/// has no gap; their values are the same bytes
|
||||
public static byte[] Without(byte[] file, string exe, out List<uint> ids)
|
||||
{
|
||||
ids = new List<uint>();
|
||||
if (file.Length == 0) return file;
|
||||
var shortcuts = Shortcuts(Read(file));
|
||||
var number = Id(exe, Name);
|
||||
if (!shortcuts.Values!.Any(s => Ours(file, s, number))) return file;
|
||||
var counted = Counted(shortcuts);
|
||||
var o = new List<byte>();
|
||||
o.AddRange(Cut(file, 0, shortcuts.Value));
|
||||
var kept = 0;
|
||||
foreach (var s in shortcuts.Values!)
|
||||
{
|
||||
if (Ours(file, s, number))
|
||||
{
|
||||
ids.Add(Named(s.Values!, "appid", 2) is { } n ? BitConverter.ToUInt32(file, n.Value) : number);
|
||||
continue;
|
||||
}
|
||||
if (counted)
|
||||
{
|
||||
o.Add(s.Type);
|
||||
o.AddRange(Encoding.UTF8.GetBytes(kept.ToString()));
|
||||
o.Add(0);
|
||||
o.AddRange(Cut(file, s.Value, s.End));
|
||||
}
|
||||
else o.AddRange(Cut(file, s.Start, s.End));
|
||||
kept++;
|
||||
}
|
||||
o.AddRange(Cut(file, shortcuts.End - 1, file.Length));
|
||||
return Proved(file, o.ToArray(), number, 0);
|
||||
}
|
||||
|
||||
/// Does the file hold a shortcut of ours? False for a file that cannot be read
|
||||
public static bool Has(byte[] file, string exe)
|
||||
{
|
||||
try { return file.Length > 0 && Shortcuts(Read(file)).Values!.Any(s => Ours(file, s, Id(exe, Name))); }
|
||||
catch (SteamException) { return false; }
|
||||
}
|
||||
|
||||
/// Before a new file is written: it reads as a shortcuts file, holds as many of ours as it should, and every shortcut of
|
||||
/// the old one that is not ours is in it, in the same order, with the same bytes. Anything else is a mistake of Setup's
|
||||
/// own, and then nothing is written
|
||||
static byte[] Proved(byte[] old, byte[] fresh, uint id, int ours)
|
||||
{
|
||||
List<byte[]> Others(byte[] b, out int mine)
|
||||
{
|
||||
var all = Shortcuts(Read(b)).Values!;
|
||||
mine = all.Count(s => Ours(b, s, id));
|
||||
return all.Where(s => !Ours(b, s, id)).Select(s => Cut(b, s.Value, s.End)).ToList();
|
||||
}
|
||||
var before = Others(old, out _);
|
||||
var after = Others(fresh, out var now);
|
||||
if (now != ours || before.Count != after.Count || before.Where((x, i) => !x.SequenceEqual(after[i])).Any())
|
||||
throw new SteamException("Setup could not put Steam's shortcuts file together again without changing other shortcuts, so it left the file alone. Nothing was changed.");
|
||||
return fresh;
|
||||
}
|
||||
|
||||
// ---- Steam on this PC ----
|
||||
|
||||
/// Is this a Steam folder?
|
||||
public static bool Valid(string root) => Directory.Exists(Path.Combine(root, "userdata")) || File.Exists(Path.Combine(root, "steam.exe"));
|
||||
|
||||
/// Steam's folder as Steam wrote it into the registry (read, never written), else the usual one; null when Steam is not
|
||||
/// on this PC. (Never asked in a test run: Shell.Mods.cs SteamRoot.)
|
||||
public static string? FromRegistry()
|
||||
{
|
||||
string? folder = null;
|
||||
try
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam", false);
|
||||
folder = key?.GetValue("SteamPath") as string;
|
||||
}
|
||||
catch (Exception) { }
|
||||
if (string.IsNullOrWhiteSpace(folder))
|
||||
folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Steam");
|
||||
try { folder = Path.GetFullPath(folder!.Replace('/', '\\')); } catch (Exception) { return null; }
|
||||
return Valid(folder) ? folder : null;
|
||||
}
|
||||
|
||||
/// The words and braces of one of Steam's text files ("name" "value", "name" { ... })
|
||||
static List<string> Words(string text)
|
||||
{
|
||||
var words = new List<string>();
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (c == '{' || c == '}') words.Add(c.ToString());
|
||||
else if (c == '/' && i + 1 < text.Length && text[i + 1] == '/') { while (i < text.Length && text[i] != '\n') i++; }
|
||||
else if (c == '"')
|
||||
{
|
||||
var s = new StringBuilder("\"");
|
||||
for (i++; i < text.Length && text[i] != '"'; i++)
|
||||
{
|
||||
if (text[i] == '\\' && i + 1 < text.Length) i++;
|
||||
s.Append(text[i]);
|
||||
}
|
||||
words.Add(s.ToString());
|
||||
}
|
||||
}
|
||||
return words;
|
||||
}
|
||||
|
||||
/// The accounts that have a folder under userdata, the one to use first: the one Steam marks as its most recent
|
||||
/// (config\loginusers.vdf), then by when each last signed in, then, for accounts that file does not name, by when their
|
||||
/// folder was last written to
|
||||
public static List<SteamUser> Users(string root)
|
||||
{
|
||||
var users = new List<SteamUser>();
|
||||
string[] folders = { };
|
||||
try { folders = Directory.GetDirectories(Path.Combine(root, "userdata")); } catch (Exception) { }
|
||||
foreach (var f in folders)
|
||||
{
|
||||
var id = Path.GetFileName(f);
|
||||
if (id != "0" && id.Length <= 10 && id.All(c => c >= '0' && c <= '9')) users.Add(new SteamUser { Root = root, Id = id });
|
||||
}
|
||||
try
|
||||
{
|
||||
var words = Words(File.ReadAllText(Path.Combine(root, "config", "loginusers.vdf")));
|
||||
const long first = 76561197960265728; // (an account's number in that file is this much more than its folder's name)
|
||||
SteamUser? user = null;
|
||||
var depth = 0;
|
||||
for (var i = 0; i < words.Count; i++)
|
||||
{
|
||||
if (words[i] == "{") { depth++; continue; }
|
||||
if (words[i] == "}") { depth--; if (depth < 2) user = null; continue; }
|
||||
var word = words[i].Substring(1);
|
||||
if (depth == 1 && i + 1 < words.Count && words[i + 1] == "{")
|
||||
user = long.TryParse(word, out var id64) && id64 > first ? users.FirstOrDefault(u => u.Id == (id64 - first).ToString()) : null;
|
||||
else if (depth == 2 && user != null && i + 1 < words.Count && words[i + 1].StartsWith("\""))
|
||||
{
|
||||
var value = words[++i].Substring(1);
|
||||
if (string.Equals(word, "PersonaName", StringComparison.OrdinalIgnoreCase)) user.Name = value;
|
||||
else if (string.Equals(word, "MostRecent", StringComparison.OrdinalIgnoreCase)) user.Recent = value == "1";
|
||||
else if (string.Equals(word, "Timestamp", StringComparison.OrdinalIgnoreCase)) long.TryParse(value, out user.Seen);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
DateTime Written(SteamUser u)
|
||||
{
|
||||
try { return Directory.GetLastWriteTimeUtc(Directory.Exists(u.Config) ? u.Config : Path.GetDirectoryName(u.Config)!); } catch (Exception) { return DateTime.MinValue; }
|
||||
}
|
||||
return users.OrderByDescending(u => u.Recent).ThenByDescending(u => u.Seen).ThenByDescending(Written).ThenBy(u => u.Id, StringComparer.Ordinal).ToList();
|
||||
}
|
||||
|
||||
// ---- writing ----
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool MoveFileExW(string from, string to, int flags);
|
||||
|
||||
/// Only an account's own config folder is ever written to
|
||||
static void Within(SteamUser user, string path)
|
||||
{
|
||||
var config = Path.GetFullPath(user.Config).TrimEnd('\\') + "\\";
|
||||
if (!Path.GetFullPath(path).StartsWith(config, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidOperationException("Setup would have written outside Steam's settings folder for the account (" + path + "), and did not.");
|
||||
}
|
||||
|
||||
/// A file written whole or not at all: beside its place first, then under its name in one step
|
||||
static void WriteWhole(SteamUser user, string file, byte[] bytes)
|
||||
{
|
||||
Within(user, file);
|
||||
var temp = file + Temp;
|
||||
try
|
||||
{
|
||||
using (var f = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
{
|
||||
f.Write(bytes, 0, bytes.Length);
|
||||
f.Flush(true);
|
||||
}
|
||||
if (!MoveFileExW(temp, file, 1 | 8)) // (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
|
||||
throw new IOException("Windows did not let " + Path.GetFileName(file) + " be replaced (error " + Marshal.GetLastWin32Error() + ").");
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Delete(temp); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] Bytes(string file)
|
||||
{
|
||||
try { return File.ReadAllBytes(file); }
|
||||
catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException) { return new byte[0]; }
|
||||
}
|
||||
|
||||
/// The new shortcuts file in place of the old one (old: what was read and worked from). The file as it was is kept
|
||||
/// first; should the file have changed since it was read, nothing is written
|
||||
static void Replace(SteamUser user, byte[] old, byte[] fresh)
|
||||
{
|
||||
var file = user.Shortcuts;
|
||||
if (old.SequenceEqual(fresh) && File.Exists(file)) return;
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
if (!Bytes(file).SequenceEqual(old)) throw new SteamException("Steam's shortcuts file changed while Setup worked on it. Nothing was changed. Close Steam and try again.");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
if (!File.Exists(file + First)) WriteWhole(user, file + First, old);
|
||||
WriteWhole(user, file + Backup, old);
|
||||
}
|
||||
WriteWhole(user, file, fresh);
|
||||
}
|
||||
|
||||
static T Guarded<T>(Func<T> work)
|
||||
{
|
||||
try { return work(); }
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
|
||||
{
|
||||
throw new SteamException("Steam's files could not be written: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Is our shortcut in this account's library?
|
||||
public static bool Added(SteamUser user, string gameExe)
|
||||
{
|
||||
try { return Has(Bytes(user.Shortcuts), Quoted(gameExe)); } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
/// The program our shortcut in this account's library starts (its path, without the quotes around it); null when the
|
||||
/// account has no shortcut of ours, or its file cannot be read
|
||||
public static string? Where(SteamUser user, string gameExe)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Bytes(user.Shortcuts);
|
||||
if (file.Length == 0) return null;
|
||||
var number = Id(Quoted(gameExe), Name);
|
||||
var ours = Shortcuts(Read(file)).Values!.FirstOrDefault(s => Ours(file, s, number));
|
||||
if (ours == null) return null;
|
||||
return Named(ours.Values!, "Exe", 1) is { } exe ? Text(file, exe).Trim().Trim('"') : "";
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
static string Quoted(string path) => "\"" + path + "\"";
|
||||
|
||||
/// Adds the game to an account's library, or sets a shortcut of ours that is there to this game folder: gameExe is the
|
||||
/// game's own program, started in its own folder. pictures: each kind of Pictures as a PNG file's bytes; where the
|
||||
/// shortcut was there already, only the pictures that are missing are written (the player may have set their own in
|
||||
/// Steam). True when the shortcut is new
|
||||
public static bool Add(SteamUser user, string gameExe, IDictionary<string, byte[]> pictures) => Guarded(() =>
|
||||
{
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
if (!Directory.Exists(Path.GetDirectoryName(user.Config)))
|
||||
throw new SteamException("Steam has no folder for that account. Start Steam, sign in once, close it, then try again.");
|
||||
var old = Bytes(user.Shortcuts);
|
||||
var exe = Quoted(gameExe);
|
||||
var icon = Path.Combine(user.Grid, Id(exe, Name) + "_icon.png");
|
||||
var fresh = With(old, exe, Quoted(Path.GetDirectoryName(gameExe) ?? ""), pictures.ContainsKey("icon") ? icon : gameExe, out var id, out var wasThere);
|
||||
Within(user, user.Grid);
|
||||
Directory.CreateDirectory(user.Grid);
|
||||
// (the shortcut had another number, the game folder having moved: its pictures, the player's own among them, go along)
|
||||
var had = new List<uint>();
|
||||
if (wasThere) Without(old, exe, out had);
|
||||
foreach (var (kind, name, _, _) in Pictures)
|
||||
{
|
||||
var file = Path.Combine(user.Grid, id + name);
|
||||
foreach (var before in had.Where(h => h != id).Select(h => Path.Combine(user.Grid, h + name)).Where(File.Exists))
|
||||
{
|
||||
Within(user, before);
|
||||
if (File.Exists(file)) File.Delete(before); else File.Move(before, file);
|
||||
}
|
||||
if (pictures.TryGetValue(kind, out var png) && (!wasThere || !File.Exists(file))) WriteWhole(user, file, png);
|
||||
}
|
||||
Replace(user, old, fresh);
|
||||
return !wasThere;
|
||||
});
|
||||
|
||||
/// Takes our shortcut out of an account's library again, and its pictures out of config\grid. False when it was not there
|
||||
public static bool Remove(SteamUser user, string gameExe) => Guarded(() =>
|
||||
{
|
||||
if (Running(user.Root)) throw new SteamException(CloseFirst);
|
||||
var old = Bytes(user.Shortcuts);
|
||||
var fresh = Without(old, Quoted(gameExe), out var ids);
|
||||
if (ids.Count == 0) return false;
|
||||
Replace(user, old, fresh);
|
||||
foreach (var id in ids)
|
||||
foreach (var (_, name, _, _) in Pictures)
|
||||
{
|
||||
var file = Path.Combine(user.Grid, id + name);
|
||||
Within(user, file);
|
||||
try { if (File.Exists(file)) File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
142
setup/SteamArt.cs
Normal file
142
setup/SteamArt.cs
Normal file
@@ -0,0 +1,142 @@
|
||||
// (Triforce) The pictures of the game's Steam shortcut (Steam.cs), drawn here from Setup's own crest (assets/triforce.png, the
|
||||
// one picture in Setup: Art.cs) in the hall the window shows it in: near-black, one warm light, the lattice in it. Nothing is
|
||||
// fetched and nothing is taken from the game. --snapshot writes them out to look at (Shell.Test.cs).
|
||||
// portrait the library's cover: the crest over the name
|
||||
// wide the wide tile: the same, lower
|
||||
// hero the background of the game's page in the library: the hall with the crest to the right, no words (Steam puts
|
||||
// the logo over it)
|
||||
// logo the crest and the name on nothing, for over the hero
|
||||
// icon the crest alone
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
|
||||
namespace TriforceSetup;
|
||||
|
||||
static class SteamArt
|
||||
{
|
||||
static readonly Typeface Serif = new(new FontFamily("Palatino Linotype, Book Antiqua, Georgia"), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
|
||||
|
||||
/// Each picture of Steam.Pictures as a PNG file's bytes, in the size listed there
|
||||
public static Dictionary<string, byte[]> Make()
|
||||
{
|
||||
if (Art.Crest == null) Art.Load();
|
||||
var made = new Dictionary<string, byte[]>();
|
||||
foreach (var (kind, _, width, height) in Steam.Pictures)
|
||||
{
|
||||
var picture = new DrawingVisual();
|
||||
RenderOptions.SetBitmapScalingMode(picture, BitmapScalingMode.HighQuality);
|
||||
using (var dc = picture.RenderOpen()) Draw(dc, kind, width, height);
|
||||
var bitmap = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
|
||||
bitmap.Render(picture);
|
||||
bitmap.Freeze();
|
||||
var png = new PngBitmapEncoder();
|
||||
png.Frames.Add(BitmapFrame.Create(bitmap));
|
||||
using var bytes = new MemoryStream();
|
||||
png.Save(bytes);
|
||||
made[kind] = bytes.ToArray();
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
static void Draw(DrawingContext dc, string kind, double w, double h)
|
||||
{
|
||||
switch (kind)
|
||||
{
|
||||
case "portrait":
|
||||
Hall(dc, w, h, w / 2, h * 0.40, w * 0.95);
|
||||
Crest(dc, w / 2, h * 0.40, w * 0.62);
|
||||
Rule(dc, w / 2, h * 0.705, w * 0.36);
|
||||
Name(dc, w / 2, h * 0.775, w * 0.105, false);
|
||||
break;
|
||||
case "wide":
|
||||
Hall(dc, w, h, w / 2, h * 0.42, h * 1.25);
|
||||
Crest(dc, w / 2, h * 0.40, h * 0.60);
|
||||
Name(dc, w / 2, h * 0.83, h * 0.125, false);
|
||||
break;
|
||||
case "hero":
|
||||
Hall(dc, w, h, w * 0.74, h * 0.50, h * 1.35);
|
||||
Crest(dc, w * 0.74, h * 0.50, h * 0.74);
|
||||
break;
|
||||
case "logo":
|
||||
Crest(dc, w / 2, h * 0.36, h * 0.66);
|
||||
Name(dc, w / 2, h * 0.84, h * 0.20, true);
|
||||
break;
|
||||
default: // (the icon)
|
||||
Crest(dc, w / 2, h / 2, w * 0.96);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static RadialGradientBrush Radial(Point centre, double radius, params (Color c, double at)[] stops)
|
||||
{
|
||||
var b = new RadialGradientBrush { MappingMode = BrushMappingMode.Absolute, Center = centre, GradientOrigin = centre, RadiusX = radius, RadiusY = radius };
|
||||
foreach (var (c, at) in stops) b.GradientStops.Add(new GradientStop(c, at));
|
||||
b.Freeze();
|
||||
return b;
|
||||
}
|
||||
|
||||
/// The hall: dark, a light from above, the gold light around the crest's place with the lattice in it, the corners darker
|
||||
static void Hall(DrawingContext dc, double w, double h, double x, double y, double reach)
|
||||
{
|
||||
var all = new Rect(0, 0, w, h);
|
||||
dc.PushClip(new RectangleGeometry(all));
|
||||
dc.DrawRectangle(Fx.Paint(Fx.Ink900), null, all);
|
||||
var top = new LinearGradientBrush(Fx.Rgb(0xFFECAA, 0.05), Fx.Rgb(0xFFECAA, 0), 90);
|
||||
top.Freeze();
|
||||
dc.DrawRectangle(top, null, new Rect(0, 0, w, h * 0.45));
|
||||
var centre = new Point(x, y);
|
||||
dc.DrawRectangle(Radial(centre, reach, (Fx.Rgb(Fx.Gold500, 0.26), 0), (Fx.Rgb(Fx.Gold500, 0.08), 0.45), (Fx.Rgb(Fx.Gold500, 0), 1)), null, all);
|
||||
dc.PushOpacityMask(Radial(centre, reach, (Colors.White, 0), (Color.FromArgb(120, 255, 255, 255), 0.5), (Colors.Transparent, 0.95)));
|
||||
dc.DrawRectangle(Art.Lattice(Math.Max(28, reach / 6.4), Fx.Rgb(Fx.Gold500, 0.07)), null, all);
|
||||
dc.Pop();
|
||||
var far = Math.Sqrt(w * w + h * h) / 2;
|
||||
// (black without any of it, not Colors.Transparent: that one is white, and on its way to black it greyed the corners)
|
||||
var clear = Color.FromArgb(0, 0, 0, 0);
|
||||
dc.DrawRectangle(Radial(new Point(w / 2, h / 2), far, (clear, 0), (clear, 0.55), (Color.FromArgb(150, 0, 0, 0), 1)), null, all);
|
||||
dc.Pop();
|
||||
}
|
||||
|
||||
/// The crest as painted, so wide, around a point
|
||||
static void Crest(DrawingContext dc, double x, double y, double width)
|
||||
{
|
||||
var height = width * Art.Crest.PixelHeight / Art.Crest.PixelWidth;
|
||||
dc.DrawImage(Art.Crest, new Rect(x - width / 2, y - height / 2, width, height));
|
||||
}
|
||||
|
||||
/// A hairline of gold that fades to both sides, a small diamond in its middle
|
||||
static void Rule(DrawingContext dc, double x, double y, double width)
|
||||
{
|
||||
var line = new LinearGradientBrush();
|
||||
line.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold500, 0), 0));
|
||||
line.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold500, 0.7), 0.5));
|
||||
line.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold500, 0), 1));
|
||||
line.Freeze();
|
||||
dc.DrawRectangle(line, null, new Rect(x - width / 2, y - 0.75, width, 1.5));
|
||||
dc.PushTransform(new RotateTransform(45, x, y));
|
||||
dc.DrawRectangle(Fx.Paint(Fx.Gold300), null, new Rect(x - 4.5, y - 4.5, 9, 9));
|
||||
dc.Pop();
|
||||
}
|
||||
|
||||
/// The name in the window's own serif, capitals set apart, its middle at a point. On nothing (the logo) it gets a soft dark
|
||||
/// edge, since Steam lays it over whatever the background is
|
||||
static void Name(DrawingContext dc, double x, double y, double size, bool onNothing)
|
||||
{
|
||||
FormattedText Words(Brush brush) =>
|
||||
new(Fx.Track(Program.AppName.ToUpperInvariant(), 3), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, Serif, size, brush, 1.0);
|
||||
var words = Words(Fx.Paint(Fx.TextHi));
|
||||
var at = new Point(x - words.WidthIncludingTrailingWhitespace / 2, y - words.Height / 2);
|
||||
if (onNothing)
|
||||
{
|
||||
var edge = words.BuildGeometry(at);
|
||||
var pen = new Pen(Fx.Paint(0x000000, 0.55), size * 0.09) { LineJoin = PenLineJoin.Round };
|
||||
pen.Freeze();
|
||||
dc.DrawGeometry(null, pen, edge);
|
||||
}
|
||||
dc.DrawText(words, at);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ enum S
|
||||
Stopped, Cancelled, CancelledNote, CloseQuestion, LanguageLabel, StopClose, KeepBuilding,
|
||||
// (the update, English only for now: Strings.Text falls back to it)
|
||||
Download, Updating, UpdateFailed,
|
||||
// (the report of a build that stopped, English only as well)
|
||||
CopyReport, ReportCopied, ReportNotCopied,
|
||||
}
|
||||
|
||||
static class Strings
|
||||
@@ -35,6 +37,7 @@ static class Strings
|
||||
"Putting the game folder together", "Show details", "Hide details", "Cancel", "Back", "Open folder", "Play", "Your game is ready", "built in",
|
||||
"The build stopped", "Build cancelled", "You can start again from the same folder.", "Stop the build and close?", "Language", "Stop and close", "Keep building",
|
||||
"Downloading the new version", "Updating your game", "The update could not be downloaded",
|
||||
"Copy report", "Report copied", "The clipboard is in use: try again",
|
||||
};
|
||||
static readonly string[] Fr =
|
||||
{
|
||||
|
||||
@@ -97,7 +97,7 @@ $cscArgs = @('/nologo', '/target:winexe', '/langversion:latest', '/nullable:enab
|
||||
"/out:$exe", "/win32icon:$gen\triforce.ico", "/win32manifest:$gen\app.manifest", '/nowarn:CS8618,CS8632,CS1701,CS1702')
|
||||
$cscArgs += $refs | ForEach-Object { "/reference:$_" }
|
||||
$cscArgs += "/resource:$here\Main.xaml,Main.xaml", "/resource:$gen\triforce.png,triforce.png", "/resource:$gen\icon.png,icon.png"
|
||||
$cscArgs += "$here\Setup.cs", "$here\Shell.cs", "$here\Shell.Home.cs", "$here\Shell.Saves.cs", "$here\Shell.Test.cs", "$here\Stage.cs", "$here\Art.cs", "$here\Look.cs", "$here\Saves.cs", "$here\Strings.cs", "$gen\AssemblyInfo.cs"
|
||||
$cscArgs += "$here\Setup.cs", "$here\Guard.cs", "$here\Shell.cs", "$here\Shell.Home.cs", "$here\Shell.Saves.cs", "$here\Shell.Mods.cs", "$here\Shell.Steam.cs", "$here\Shell.Sounds.cs", "$here\Shell.Test.cs", "$here\Stage.cs", "$here\Art.cs", "$here\Look.cs", "$here\Saves.cs", "$here\Mods.cs", "$here\Steam.cs", "$here\SteamArt.cs", "$here\Sound.cs", "$here\Strings.cs", "$gen\AssemblyInfo.cs"
|
||||
& $csc @cscArgs
|
||||
if ($LASTEXITCODE -ne 0) { throw "csc failed ($LASTEXITCODE)" }
|
||||
"built $exe ($Version, {0:N0} KB)" -f ((Get-Item $exe).Length / 1KB)
|
||||
|
||||
@@ -35,7 +35,7 @@ New-Item -ItemType Directory -Force $tools | Out-Null
|
||||
# tree without the picture builds a screen with the wordmark alone: every pack up to v0.3.5 left the assets folder out, so
|
||||
# no player's game showed the crest while its shaders were prepared. Reported for AMD cards, where that screen stays longest)
|
||||
if (-not (Test-Path (Join-Path $repo 'assets\triforce.png') -PathType Leaf)) { throw 'assets\triforce.png is missing: the tools would build a game without the crest on its start-up screen' }
|
||||
$files = git -C $repo ls-files -- nx2 host gpu scripts third_party LICENSE assets/triforce.png
|
||||
$files = git -C $repo ls-files -- nx2 host gpu scripts third_party LICENSE assets/triforce.png assets/triforce_assets
|
||||
foreach ($f in $files) {
|
||||
$src = Join-Path $repo $f
|
||||
if (-not (Test-Path $src -PathType Leaf)) { continue }
|
||||
|
||||
Reference in New Issue
Block a user