mirror of
https://git.triforceproject.com/triforce/source
synced 2026-11-20 08:39:58 -04:00
Triforce v0.5.2
The new launcher (Windows and Linux: the game's own look, music and settings, saves and mods pages, smaller updates in parts), benchmark mode (Find my best settings: the game tours four places by itself and writes its results), Quit and Restart in the pause menu under Mods, Squadala! in the Mods menu, battle music above 60 fps, menu text, the controller in the menus with the game in the background, the whole GameBanana list, RX 580 and RX 5000/6000 shader fixes, the pipeline cache kept through an update, async present black flashes, and faster builds.
This commit is contained in:
199
launcher/Logic/Guard/Download.cs
Normal file
199
launcher/Logic/Guard/Download.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>How far a download is: 0..1 (0 while the size is unknown), the bytes there, the whole size (0 unknown).</summary>
|
||||
public readonly record struct DownloadProgress(double Fraction, long Bytes, long Total);
|
||||
|
||||
/// <summary>A file fetched over HTTP into place through <file>.part, and checked before it is used (old Guard.cs Download).
|
||||
///
|
||||
/// A download that was cut off (the connection, Cancel, the launcher closed) leaves its part file, and the next one goes on from
|
||||
/// it with a Range request where the server answers those; a server that does not sends the whole file, and the part is written
|
||||
/// over. A part is gone on from only as a part of the same file: <file>.part.of beside it names the address and the size it
|
||||
/// was begun for and the server's mark for the file it sent (its ETag, else its date), which goes back with the request
|
||||
/// (If-Range), so a file published again under the same address comes whole and is never joined to the beginning of the one
|
||||
/// before. A part without that note, or from a server that marks its files in neither way, is fetched anew.
|
||||
///
|
||||
/// The file gets its name only once it has the size the release lists (else the one the server names), and a server that names
|
||||
/// another size than the release's is not believed before its first byte.</summary>
|
||||
public sealed class Downloader
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public Downloader(TriforceContext ctx) { this.ctx = ctx; }
|
||||
|
||||
/// <summary>How long the server may send nothing before the download is given up (its part stays to be gone on from). A read
|
||||
/// that waits on the network hears no cancellation: it is left waiting and its connection closed behind it, for Cancel too.</summary>
|
||||
public TimeSpan Stall { get; set; } = TimeSpan.FromSeconds(60);
|
||||
|
||||
static void Remove(string file)
|
||||
{
|
||||
try { File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
|
||||
static string Mb(long bytes) => (bytes >> 20).ToString();
|
||||
|
||||
/// <summary>The server's mark for the file it sends, to hand back with If-Range: a strong ETag, else the date it was last changed.</summary>
|
||||
static string Mark(HttpResponseMessage response) =>
|
||||
response.Headers.ETag is { IsWeak: false } tag ? tag.ToString()
|
||||
: response.Content.Headers.LastModified is { } changed ? changed.UtcDateTime.ToString("r") : "";
|
||||
|
||||
/// <summary>url to file, with progress. size is what the release lists for it, 0 when it lists none.</summary>
|
||||
public async Task ToFileAsync(HttpClient http, string url, string file, long size, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
var name = Path.GetFileName(file);
|
||||
var part = file + ".part";
|
||||
var note = part + ".of";
|
||||
long have = 0;
|
||||
RangeConditionHeaderValue? same = null;
|
||||
void Forget() { Remove(part); Remove(note); }
|
||||
void Say(double f, long b, long t) => progress?.Invoke(new DownloadProgress(f, b, t));
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(file))!);
|
||||
if (File.Exists(part))
|
||||
{
|
||||
// (what the part is a part of: only the same address, size and mark are gone on from, and never a part as long as the file)
|
||||
string[] of = { };
|
||||
try { of = File.ReadAllLines(note); } catch (Exception) { }
|
||||
var length = new FileInfo(part).Length;
|
||||
if (of.Length >= 3 && of[0] == url && of[1] == size.ToString() && RangeConditionHeaderValue.TryParse(of[2], out same) && length > 0 && (size <= 0 || length < size))
|
||||
have = length;
|
||||
else Forget();
|
||||
}
|
||||
|
||||
using var stall = new CancellationTokenSource();
|
||||
using var either = CancellationTokenSource.CreateLinkedTokenSource(token, stall.Token);
|
||||
for (var again = false; ; again = true)
|
||||
{
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
if (have > 0)
|
||||
{
|
||||
request.Headers.Range = new RangeHeaderValue(have, null);
|
||||
request.Headers.IfRange = same;
|
||||
}
|
||||
stall.CancelAfter(Stall);
|
||||
HttpResponseMessage response;
|
||||
try { response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, either.Token).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) when (!token.IsCancellationRequested && stall.IsCancellationRequested)
|
||||
{
|
||||
throw new CutOffException("The server did not answer for " + (int)Stall.TotalSeconds + " seconds about " + name + ". Try again.");
|
||||
}
|
||||
var left = false; // (the answer was left with a read still waiting on it)
|
||||
try
|
||||
{
|
||||
var range = response.StatusCode == HttpStatusCode.PartialContent ? response.Content.Headers.ContentRange : null;
|
||||
// (416: the part is no part of what the server has now. A range other than the one asked for: not to be joined on.
|
||||
// Either way the whole file is asked for, once)
|
||||
if (have > 0 && !again && (response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable ||
|
||||
response.StatusCode == HttpStatusCode.PartialContent && !(range is { HasRange: true } && range.From == have)))
|
||||
{
|
||||
Forget();
|
||||
have = 0;
|
||||
continue;
|
||||
}
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.StatusCode == HttpStatusCode.PartialContent && (have == 0 || !(range is { HasRange: true } && range.From == have)))
|
||||
throw new IOException("The server sent a piece of " + name + " that was not asked for.");
|
||||
// (200 to a request for the rest: the server knows no ranges, or the file is another one now. The whole file comes)
|
||||
if (response.StatusCode != HttpStatusCode.PartialContent) have = 0;
|
||||
|
||||
// the whole file's size: the release's, which the server must not contradict; else the server's
|
||||
var told = have > 0 ? range!.Length ?? have + response.Content.Headers.ContentLength : response.Content.Headers.ContentLength;
|
||||
if (size > 0 && told is { } other && other != size)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server offers " + other + " bytes as " + name + ", and the release lists " + size + ". Nothing was downloaded.");
|
||||
}
|
||||
var total = size > 0 ? size : told ?? 0;
|
||||
if (total > 0 && ctx.SpaceProblem(name, total - have, file) is { } none) throw new NoRoomException(none);
|
||||
if (have == 0)
|
||||
{
|
||||
Remove(part);
|
||||
try { File.WriteAllLines(note, new[] { url, size.ToString(), Mark(response) }); } catch (Exception) { }
|
||||
}
|
||||
Say(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have, total);
|
||||
|
||||
var from = await response.Content.ReadAsStreamAsync(either.Token).ConfigureAwait(false);
|
||||
var gone = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var tooMuch = false;
|
||||
using (var to = new FileStream(part, have > 0 ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.None))
|
||||
using (either.Token.Register(() => gone.TrySetResult(true)))
|
||||
{
|
||||
var buffer = new byte[1 << 20];
|
||||
var shown = DateTime.MinValue;
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
stall.CancelAfter(Stall);
|
||||
var read = from.ReadAsync(buffer, 0, buffer.Length, either.Token);
|
||||
if (await Task.WhenAny(read, gone.Task).ConfigureAwait(false) != read)
|
||||
{
|
||||
// (Cancel, or nothing came: the read is left where it waits, whatever becomes of it)
|
||||
left = true;
|
||||
_ = read.ContinueWith(t => t.Exception, TaskContinuationOptions.OnlyOnFaulted);
|
||||
throw new OperationCanceledException();
|
||||
}
|
||||
var n = await read.ConfigureAwait(false);
|
||||
stall.CancelAfter(Timeout.InfiniteTimeSpan);
|
||||
if (n <= 0) break;
|
||||
await to.WriteAsync(buffer.AsMemory(0, n), CancellationToken.None).ConfigureAwait(false);
|
||||
have += n;
|
||||
// (a server that sends more than the file would fill the disk)
|
||||
if (total > 0 && have > total) { tooMuch = true; break; }
|
||||
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
|
||||
{
|
||||
shown = DateTime.UtcNow;
|
||||
Say(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have, total);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
if (token.IsCancellationRequested) throw new OperationCanceledException(token);
|
||||
var of = total > 0 ? " of " + Mb(total) : "";
|
||||
if (stall.IsCancellationRequested)
|
||||
throw new CutOffException("The download of " + name + " stopped after " + Mb(have) + of + " MB: nothing more came for " + (int)Stall.TotalSeconds +
|
||||
" seconds. Try again: it goes on from there.");
|
||||
if (ctx.Platform.IsDiskFull(e)) throw;
|
||||
throw new CutOffException("The download of " + name + " was cut off after " + Mb(have) + of + " MB. Try again: it goes on from there.", e);
|
||||
}
|
||||
}
|
||||
if (tooMuch)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException("The server sent more than the " + total + " bytes of " + name + ". Nothing of it was kept.");
|
||||
}
|
||||
if (total > 0 && have < total)
|
||||
throw new CutOffException("The download of " + name + " ended early, after " + Mb(have) + " of " + Mb(total) + " MB. Try again: it goes on from there.");
|
||||
break;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// (closing an answer can wait for the network as its read did: one that was left is closed where nobody waits for that)
|
||||
if (left) _ = Task.Run(() => { try { response.Dispose(); } catch (Exception) { } });
|
||||
else response.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// (before it is used: what is on the disk is what was counted)
|
||||
var there = new FileInfo(part).Length;
|
||||
if (there != have)
|
||||
{
|
||||
Forget();
|
||||
throw new IOException(name + " is " + there + " bytes on the disk where " + have + " were downloaded. Nothing of it was kept.");
|
||||
}
|
||||
if (File.Exists(file)) File.Delete(file);
|
||||
File.Move(part, file);
|
||||
Remove(note);
|
||||
Say(1, have, have);
|
||||
}
|
||||
|
||||
/// <summary>The HttpClient every release request goes through: no overall timeout (a 300 MB download takes what it takes; the
|
||||
/// release check has its own 20 s), the launcher's User-Agent (old Shell.cs Http).</summary>
|
||||
public static HttpClient CreateHttp()
|
||||
{
|
||||
var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
|
||||
http.DefaultRequestHeaders.UserAgent.ParseAdd(BuildInfo.UserAgent);
|
||||
return http;
|
||||
}
|
||||
}
|
||||
328
launcher/Logic/Guard/Instance.cs
Normal file
328
launcher/Logic/Guard/Instance.cs
Normal file
@@ -0,0 +1,328 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net.Sockets;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>One launcher at a time for an install (old Guard.cs Instance). Two of them on one folder each downloaded the tools into
|
||||
/// the same files, unpacked them over each other and built into the same game folder. The first one holds a named mutex for as
|
||||
/// long as it runs; Windows lets go of it when the process ends, however it ends. A second start for the same folder asks the
|
||||
/// first to come to the front (a named event the first one waits on) and ends.
|
||||
///
|
||||
/// The names are the old Setup's exactly (research/02 2.6), so an old Setup started from a stale download defers to the new
|
||||
/// launcher and the other way round: Local\TriforceSetup-<FNV-1a 64 of the folder (and "|" test root), 16 hex>-<the folder's last
|
||||
/// 60 characters, each one that is not a letter or digit as ->; the event "<name>-show" brings the holder forward, and
|
||||
/// "<name>-up" is the handover's sign (Handover).
|
||||
///
|
||||
/// A mutex belongs to the thread that took it: here one thread of its own takes it, holds it and lets go of it, so the
|
||||
/// launcher's async code may Release from any thread (the old Setup's Release on another thread only closed the handle).
|
||||
/// Linux: a lock file (flock through FileShare.None) in $XDG_RUNTIME_DIR, and a unix socket for "come forward".</summary>
|
||||
public sealed class InstanceLock : IDisposable
|
||||
{
|
||||
/// <summary>One spelling for a folder, however it was typed.</summary>
|
||||
static string Same(string path)
|
||||
{
|
||||
try { path = Path.GetFullPath(path); } catch (Exception) { }
|
||||
return path.TrimEnd('\\', '/').ToUpperInvariant();
|
||||
}
|
||||
|
||||
/// <summary>FNV-1a 64 over the UTF-16 code units of a text (offset 14695981039346656037, prime 1099511628211).</summary>
|
||||
public static ulong Fnv1a64(string text)
|
||||
{
|
||||
var h = 14695981039346656037UL;
|
||||
foreach (var c in text) { h ^= c; h *= 1099511628211UL; }
|
||||
return h;
|
||||
}
|
||||
|
||||
/// <summary>The lock's name for a folder: a number made from the whole path (and the test folder's), then the end of the path
|
||||
/// for whoever looks at it. (Local\: one user's session. An install is one user's, HKCU and %LOCALAPPDATA%)</summary>
|
||||
public static string Name(string folder, string? testRoot)
|
||||
{
|
||||
var text = Same(folder) + (testRoot != null ? "|" + Same(testRoot) : "");
|
||||
var h = Fnv1a64(text);
|
||||
var tail = new string(Same(folder).Select(c => char.IsLetterOrDigit(c) ? c : '-').ToArray());
|
||||
return @"Local\TriforceSetup-" + h.ToString("x16") + "-" + (tail.Length > 60 ? tail.Substring(tail.Length - 60) : tail);
|
||||
}
|
||||
|
||||
/// <summary>The handover's sign: "<name>-up" (Handover).</summary>
|
||||
public static string UpName(string folder, string? testRoot) => Name(folder, testRoot) + "-up";
|
||||
public static string ShowName(string folder, string? testRoot) => Name(folder, testRoot) + "-show";
|
||||
|
||||
readonly string folder;
|
||||
readonly string? testRoot;
|
||||
// (Windows: the thread that owns the mutex, and what it is asked to do)
|
||||
BlockingCollection<Action>? asks;
|
||||
Thread? owner;
|
||||
Mutex? held;
|
||||
EventWaitHandle? call;
|
||||
ManualResetEvent? quit;
|
||||
Thread? waiting;
|
||||
Action? come;
|
||||
// (Linux)
|
||||
FileStream? lockFile;
|
||||
Socket? listener;
|
||||
|
||||
InstanceLock(string folder, string? testRoot) { this.folder = folder; this.testRoot = testRoot; }
|
||||
|
||||
public bool Held => held != null || lockFile != null;
|
||||
|
||||
/// <summary>The lock of this folder, or null when another launcher holds it. Where no lock can be made at all nobody is
|
||||
/// refused: the launcher must still start there (a lock that holds nothing is returned).</summary>
|
||||
public static InstanceLock? TryTake(string folder, string? testRoot)
|
||||
{
|
||||
var l = new InstanceLock(folder, testRoot);
|
||||
return l.Take() ? l : null;
|
||||
}
|
||||
|
||||
bool Take()
|
||||
{
|
||||
if (Held) return true;
|
||||
if (!OperatingSystem.IsWindows()) return TakeFile();
|
||||
asks ??= StartOwner();
|
||||
var done = new TaskCompletionSource<bool>();
|
||||
asks.Add(() => done.SetResult(TakeMutex()));
|
||||
return done.Task.GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
BlockingCollection<Action> StartOwner()
|
||||
{
|
||||
var q = new BlockingCollection<Action>();
|
||||
owner = new Thread(() => { foreach (var a in q.GetConsumingEnumerable()) a(); }) { IsBackground = true, Name = "Triforce instance lock" };
|
||||
owner.Start();
|
||||
return q;
|
||||
}
|
||||
|
||||
bool TakeMutex() // (on the owner thread)
|
||||
{
|
||||
var name = Name(folder, testRoot);
|
||||
Mutex m;
|
||||
try { m = new Mutex(false, name); }
|
||||
catch (UnauthorizedAccessException) { return false; } // (it is there, and belongs to a launcher run as administrator)
|
||||
catch (Exception) { return true; }
|
||||
try
|
||||
{
|
||||
if (!m.WaitOne(0)) { m.Dispose(); return false; }
|
||||
}
|
||||
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
|
||||
catch (Exception) { m.Dispose(); return true; }
|
||||
held = m;
|
||||
try
|
||||
{
|
||||
call = new EventWaitHandle(false, EventResetMode.AutoReset, name + "-show");
|
||||
call.Reset(); // (a call meant for the launcher before this one)
|
||||
}
|
||||
catch (Exception) { call = null; }
|
||||
if (come != null) Wait();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The lock again after Release (a launcher that let go of it for its successor, which then did not start).</summary>
|
||||
public bool TakeAgain() => Take();
|
||||
|
||||
/// <summary>What the holder does when a second launcher is started: called on a thread of its own, each time.</summary>
|
||||
public void Listen(Action onCall)
|
||||
{
|
||||
come = onCall;
|
||||
if (held != null || lockFile != null) Wait();
|
||||
}
|
||||
|
||||
void Wait()
|
||||
{
|
||||
if (come == null || waiting != null) return;
|
||||
var act = come;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
if (call == null) return;
|
||||
var (c, q) = (call, quit = new ManualResetEvent(false));
|
||||
waiting = new Thread(() =>
|
||||
{
|
||||
try { while (WaitHandle.WaitAny(new WaitHandle[] { q, c }) == 1) act(); }
|
||||
catch (Exception) { }
|
||||
}) { IsBackground = true, Name = "Triforce come forward" };
|
||||
waiting.Start();
|
||||
return;
|
||||
}
|
||||
var l = listener;
|
||||
if (l == null) return;
|
||||
waiting = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
using var s = l.Accept();
|
||||
act();
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
}) { IsBackground = true, Name = "Triforce come forward" };
|
||||
waiting.Start();
|
||||
}
|
||||
|
||||
/// <summary>Lets go of the folder: before the launcher that takes this one's place is started, and when the window has closed.</summary>
|
||||
public void Release()
|
||||
{
|
||||
try { quit?.Set(); waiting?.Join(2000); } catch (Exception) { }
|
||||
try { listener?.Dispose(); } catch (Exception) { }
|
||||
listener = null;
|
||||
waiting = null;
|
||||
quit = null;
|
||||
try { call?.Dispose(); } catch (Exception) { }
|
||||
call = null;
|
||||
if (lockFile != null)
|
||||
{
|
||||
try { lockFile.Dispose(); } catch (Exception) { }
|
||||
lockFile = null;
|
||||
try { File.Delete(SocketPath(folder, testRoot)); } catch (Exception) { }
|
||||
}
|
||||
if (held == null || asks == null) return;
|
||||
var done = new TaskCompletionSource();
|
||||
asks.Add(() =>
|
||||
{
|
||||
try { held?.ReleaseMutex(); } catch (Exception) { }
|
||||
held?.Dispose();
|
||||
held = null;
|
||||
done.SetResult();
|
||||
});
|
||||
done.Task.Wait(5000);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Release();
|
||||
asks?.CompleteAdding();
|
||||
}
|
||||
|
||||
/// <summary>A second launcher asks the one that holds the folder to come to the front. False when there is nobody to ask (yet).</summary>
|
||||
public static bool CallForward(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
try
|
||||
{
|
||||
using var s = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
s.Connect(new UnixDomainSocketEndPoint(SocketPath(folder, testRoot)));
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!EventWaitHandle.TryOpenExisting(ShowName(folder, testRoot), out var c)) return false;
|
||||
using (c)
|
||||
{
|
||||
// (Windows lets only the program in front hand the front on: this one, just started by the player, may)
|
||||
try { AllowSetForegroundWindow(-1); } catch (Exception) { }
|
||||
return c.Set();
|
||||
}
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool AllowSetForegroundWindow(int process);
|
||||
|
||||
// ---- Linux ----
|
||||
|
||||
static string RuntimeDir => Environment.GetEnvironmentVariable("XDG_RUNTIME_DIR") is { Length: > 0 } r && Directory.Exists(r) ? r : Path.GetTempPath();
|
||||
static string FileStem(string folder, string? testRoot) => "triforce-" + Fnv1a64(Same(folder) + (testRoot != null ? "|" + Same(testRoot) : "")).ToString("x16");
|
||||
static string LockPath(string folder, string? testRoot) => Path.Combine(RuntimeDir, FileStem(folder, testRoot) + ".lock");
|
||||
// (a unix socket's path is at most 108 bytes: the hash alone names it)
|
||||
static string SocketPath(string folder, string? testRoot) => Path.Combine(RuntimeDir, FileStem(folder, testRoot) + ".sock");
|
||||
|
||||
bool TakeFile()
|
||||
{
|
||||
try { lockFile = new FileStream(LockPath(folder, testRoot), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); }
|
||||
catch (IOException) { return false; } // (another launcher has it)
|
||||
catch (Exception) { return true; } // (no lock can be made here: nobody is refused)
|
||||
try
|
||||
{
|
||||
var sock = SocketPath(folder, testRoot);
|
||||
try { File.Delete(sock); } catch (Exception) { }
|
||||
listener = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
|
||||
listener.Bind(new UnixDomainSocketEndPoint(sock));
|
||||
listener.Listen(4);
|
||||
}
|
||||
catch (Exception) { listener = null; }
|
||||
if (come != null) Wait();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The launcher replacing itself with a newer one, so that a new one that does not start is not what the player is left
|
||||
/// with (old Guard.cs Handover). The new exe takes the running one's name, the running one keeps running under another (Windows
|
||||
/// lets a running program be renamed, not written over), and the new one is started. The old one stays, out of sight, until the
|
||||
/// new one gives a sign that its window is up (the named event "<lock name>-up"). A new launcher that cannot be started, or that
|
||||
/// ends with an error's exit code before that sign, is taken back. One that gives no sign and goes on running is left alone.</summary>
|
||||
public static class Handover
|
||||
{
|
||||
/// <summary>Up: its window came up. Failed: it could not come up. Unclear: neither is known.</summary>
|
||||
public enum Outcome { Up, Failed, Unclear }
|
||||
|
||||
/// <summary>The old launcher, before it starts the new one: the sign it will wait for. Null where there are no named events.</summary>
|
||||
public static EventWaitHandle? Expect(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
return new EventWaitHandle(false, EventResetMode.ManualReset, InstanceLock.UpName(folder, testRoot));
|
||||
}
|
||||
|
||||
/// <summary>The new launcher, once its window is up: tells the launcher that started it, when one waits to hear it. Without
|
||||
/// it an old Setup waits 30 s hidden and then quits (research/02 2.8 point 3).</summary>
|
||||
public static void Up(string folder, string? testRoot)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return;
|
||||
try
|
||||
{
|
||||
if (EventWaitHandle.TryOpenExisting(InstanceLock.UpName(folder, testRoot), out var up))
|
||||
using (up) up.Set();
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>What became of the launcher that was started, within the time given (polled every 100 ms).</summary>
|
||||
public static Outcome Watch(Process started, WaitHandle? up, TimeSpan limit)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var until = DateTime.UtcNow + limit; ;)
|
||||
{
|
||||
if (up != null) { if (up.WaitOne(100)) return Outcome.Up; }
|
||||
else started.WaitForExit(100); // (no sign to wait for: only how it ends says anything)
|
||||
if (started.HasExited) return up != null && up.WaitOne(0) ? Outcome.Up : started.ExitCode != 0 ? Outcome.Failed : Outcome.Unclear;
|
||||
if (DateTime.UtcNow > until) return Outcome.Unclear;
|
||||
}
|
||||
}
|
||||
catch (Exception) { return Outcome.Unclear; }
|
||||
}
|
||||
|
||||
/// <summary>The running launcher (self) steps aside as previous, and fresh takes its name. A second step that fails is undone:
|
||||
/// there is always a launcher under the name the shortcuts start.</summary>
|
||||
public static void Swap(string fresh, string self, string previous)
|
||||
{
|
||||
if (File.Exists(previous)) File.Delete(previous);
|
||||
File.Move(self, previous);
|
||||
try { File.Move(fresh, self); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { File.Move(previous, self); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The launcher before (previous, which may be the program that calls this) back over the one that did not start, in
|
||||
/// one step. Tried for a few seconds: a virus scanner may still hold the new file. False when it could not be done.</summary>
|
||||
public static bool Restore(IPlatform platform, string previous, string self, int tries = 20)
|
||||
{
|
||||
for (var i = 0; i < tries; i++)
|
||||
{
|
||||
if (i > 0) Thread.Sleep(250);
|
||||
try
|
||||
{
|
||||
if (File.Exists(previous)) { platform.ReplaceFile(previous, self); return true; }
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
103
launcher/Logic/Guard/Partial.cs
Normal file
103
launcher/Logic/Guard/Partial.cs
Normal file
@@ -0,0 +1,103 @@
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>(Triforce) A copy that is never seen half done (old Guard.cs Partial). The old Setup copied itself into the install
|
||||
/// folder and a save over the one there file by file, in place: a full disk, a file held open or Setup closed in the middle left
|
||||
/// a Setup that does not start under the name every shortcut starts, or half a save. Now the copy is written as
|
||||
/// <name>.partial beside its place and renamed into it once complete; what was there is replaced in one step (a file) or
|
||||
/// moved aside as <name>.old and removed after (a folder), and moved back when the new one cannot go in.</summary>
|
||||
public sealed class Partial
|
||||
{
|
||||
public const string Suffix = ".partial", Aside = ".old";
|
||||
readonly IPlatform platform;
|
||||
public Partial(IPlatform platform) { this.platform = platform; }
|
||||
|
||||
/// <summary>(testing) called with the partial once it is complete, before it goes into its place: a test checks what holds
|
||||
/// then, or throws to stand for a failure there.</summary>
|
||||
public Action<string>? Copied { get; set; }
|
||||
|
||||
/// <summary>A file or a folder and what is in it, gone; quietly when it cannot be.</summary>
|
||||
public static void Remove(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.Exists(path)) { File.SetAttributes(path, FileAttributes.Normal); File.Delete(path); }
|
||||
else if (Directory.Exists(path)) Directory.Delete(path, true);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>from copied to to, through to.partial: an older to is replaced in one step only once the copy is complete.</summary>
|
||||
public void CopyFile(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
File.Copy(from, partial, false);
|
||||
Copied?.Invoke(partial);
|
||||
platform.ReplaceFile(partial, to);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folder from copied as to.partial (one there from a copy that was cut off is removed first); its path.</summary>
|
||||
public string Stage(string from, string to)
|
||||
{
|
||||
var partial = to + Suffix;
|
||||
try
|
||||
{
|
||||
Remove(partial);
|
||||
Tree(from, partial);
|
||||
return partial;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
static void Tree(string from, string to)
|
||||
{
|
||||
Directory.CreateDirectory(to);
|
||||
foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), false);
|
||||
foreach (var d in Directory.GetDirectories(from)) Tree(d, Path.Combine(to, Path.GetFileName(d)));
|
||||
}
|
||||
|
||||
/// <summary>A complete partial folder put in to's place: the folder there moved aside as to.old first and removed after, or
|
||||
/// moved back when the new one cannot go in (the partial is then removed).</summary>
|
||||
public void SwapIn(string partial, string to)
|
||||
{
|
||||
var old = to + Aside;
|
||||
try
|
||||
{
|
||||
Copied?.Invoke(partial);
|
||||
Remove(old);
|
||||
if (Directory.Exists(to)) Directory.Move(to, old);
|
||||
try { Directory.Move(partial, to); }
|
||||
catch (Exception)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(old)) Directory.Move(old, to); } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Remove(partial);
|
||||
throw;
|
||||
}
|
||||
Remove(old);
|
||||
}
|
||||
|
||||
/// <summary>What a copy that was cut off left beside to: the folder moved aside goes back when to is gone, and a partial goes.</summary>
|
||||
public static void Recover(string to)
|
||||
{
|
||||
try { if (!Directory.Exists(to) && Directory.Exists(to + Aside)) Directory.Move(to + Aside, to); } catch (Exception) { }
|
||||
if (Directory.Exists(to)) Remove(to + Aside);
|
||||
Remove(to + Suffix);
|
||||
}
|
||||
}
|
||||
65
launcher/Logic/Guard/Report.cs
Normal file
65
launcher/Logic/Guard/Report.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What a player copies after a build that stopped, to paste where they ask for help: what the launcher knows of the
|
||||
/// build, the build's last lines and setup.log's. The folder of the player's account, which carries their name and is in most
|
||||
/// paths of a log, reads %USERPROFILE% in it (old Guard.cs Report).</summary>
|
||||
public static class Report
|
||||
{
|
||||
/// <summary>How many of its last lines each log gives.</summary>
|
||||
public const int Lines = 200;
|
||||
|
||||
/// <summary>The last lines of a text, at most so many, without the empty ones at its end.</summary>
|
||||
public static string Tail(string text, int lines)
|
||||
{
|
||||
var all = text.Replace("\r", "").TrimEnd('\n', ' ').Split('\n');
|
||||
return string.Join(Environment.NewLine, all.Skip(Math.Max(0, all.Length - lines)));
|
||||
}
|
||||
|
||||
/// <summary>The text with each of the folders (the account's own, and its short name) read as %USERPROFILE%: in any case of
|
||||
/// its letters, with either slash or doubled ones between its parts, as a build's tools print paths. A folder that only
|
||||
/// begins with the same letters (C:\Users\Ann and C:\Users\Anna) is another one and stays.</summary>
|
||||
public static string NoName(string text, params string?[] folders)
|
||||
{
|
||||
foreach (var folder in folders.Where(f => !string.IsNullOrWhiteSpace(f)).OrderByDescending(f => f!.Length))
|
||||
{
|
||||
var parts = folder!.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (parts.Length < 2) continue; // (a whole drive is nobody's name)
|
||||
var pattern = (folder.StartsWith("\\") || folder.StartsWith("/") ? @"[\\/]+" : "") + string.Join(@"[\\/]+", parts.Select(Regex.Escape)) + @"(?![\p{L}\p{N}])";
|
||||
text = Regex.Replace(text, pattern, "%USERPROFILE%", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// <summary>The report: what the launcher knows, then the last lines of what the build said and of setup.log.</summary>
|
||||
public static string Compose(IEnumerable<string> known, string build, string log, params string?[] folders)
|
||||
{
|
||||
var s = new StringBuilder();
|
||||
foreach (var line in known) s.AppendLine(line);
|
||||
s.AppendLine().AppendLine("---- the build's last lines ----").AppendLine(Tail(build, Lines));
|
||||
s.AppendLine().AppendLine("---- setup.log's last lines ----").AppendLine(Tail(log, Lines));
|
||||
return NoName(s.ToString(), folders);
|
||||
}
|
||||
|
||||
/// <summary>The report for a build that stopped (old Shell.cs CopyTheReport): the launcher's and tools' versions, the OS, the
|
||||
/// step it stopped at, why, the command, the game folder and the install with their free space, then the logs.</summary>
|
||||
public static string ForBuild(TriforceContext ctx, BuildResult? result, string buildLines, string? toolsVersion)
|
||||
{
|
||||
string Room(string folder) => ctx.FreeBytes(folder) is { } free ? " (" + ctx.Platform.Disk(folder) + " has " + (free >> 30) + " GB free)" : "";
|
||||
var step = result?.StoppedAt is { } s && BuildStages.Find(s) is { } st ? "\"" + st.Text + "\"" : "its start";
|
||||
var known = new[]
|
||||
{
|
||||
"Triforce " + BuildInfo.Version + ", tools " + (toolsVersion ?? "none") + ", " + Environment.OSVersion.VersionString,
|
||||
"The build stopped at " + step + " after " + BuildClock.Span(result?.Elapsed ?? TimeSpan.Zero) + ": " + (result?.Failure ?? "no reason given"),
|
||||
result?.CommandLine ?? "",
|
||||
"Game folder: " + (result?.OutFolder ?? "") + (result?.OutFolder is { } o ? Room(o) : ""),
|
||||
"Launcher: " + ctx.Home + Room(ctx.Home),
|
||||
};
|
||||
var profile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
string? shortName = null;
|
||||
if (OperatingSystem.IsWindows()) shortName = WindowsPlatform.ShortName(profile);
|
||||
return Compose(known, buildLines, ctx.Log.ReadAll(), profile, shortName);
|
||||
}
|
||||
}
|
||||
48
launcher/Logic/Guard/SaveLock.cs
Normal file
48
launcher/Logic/Guard/SaveLock.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>(Triforce) The save's lock between the game and the launcher (old Guard.cs SaveLock). The game holds
|
||||
/// <user>\save.lock open without sharing from its first save mount to its end (host/save_tx.h save_tx_lock); NX2navi holds
|
||||
/// <profile>\instance.lock the same way. Taken by the launcher across the whole copy, the lock says for certain whether the game
|
||||
/// runs, and a game started meanwhile waits for it before it mounts its save.
|
||||
///
|
||||
/// Linux: .NET takes FileShare.None as an advisory flock there, and the game takes none (research/02 section 11: "No Linux guard
|
||||
/// exists today"), so on Linux only the process check (Saves.RunningGame) guards a copy.</summary>
|
||||
public static class SaveLock
|
||||
{
|
||||
public const string Running = "The game is running: quit it first. It keeps its save open while it runs, and would write over the copy.";
|
||||
|
||||
/// <summary>The lock of a save folder <user>\save\<uid> (or a commit waiting in <user>\save-tx\<uid>\ready-<n>):
|
||||
/// <user>\save.lock, or instance.lock in NX2navi's profile folder; null for another kind of save folder (an emulator's).</summary>
|
||||
public static string? PathOf(string save)
|
||||
{
|
||||
string dir;
|
||||
try { dir = Path.GetFullPath(save).TrimEnd('\\', '/'); }
|
||||
catch (Exception) { return null; }
|
||||
var parent = Path.GetDirectoryName(dir);
|
||||
if (parent != null && Path.GetDirectoryName(parent) is { } tx && string.Equals(Path.GetFileName(tx), "save-tx", StringComparison.OrdinalIgnoreCase))
|
||||
parent = Path.Combine(Path.GetDirectoryName(tx) ?? tx, "save");
|
||||
if (parent == null || !string.Equals(Path.GetFileName(parent), "save", StringComparison.OrdinalIgnoreCase)) return null;
|
||||
var user = Path.GetDirectoryName(parent);
|
||||
if (string.IsNullOrEmpty(user)) return null;
|
||||
return Path.Combine(user, string.Equals(Path.GetFileName(user), "profile", StringComparison.OrdinalIgnoreCase) ? "instance.lock" : "save.lock");
|
||||
}
|
||||
|
||||
/// <summary>The lock of a save folder, held until it is disposed (an open handle that shares nothing). Null when the folder has
|
||||
/// none or it cannot be made there (nothing is locked: the copy goes on as before). InvalidOperationException (Running) when a
|
||||
/// game holds it.</summary>
|
||||
public static FileStream? Take(string save)
|
||||
{
|
||||
if (PathOf(save) is not { } path) return null;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
|
||||
}
|
||||
catch (IOException e) when ((e.HResult & 0xFFFF) == 32 || (e.HResult & 0xFFFF) == 33 || !OperatingSystem.IsWindows() && (e.HResult & 0xFFFF) == 11)
|
||||
{
|
||||
// (ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION; EWOULDBLOCK from flock)
|
||||
throw new InvalidOperationException(Running);
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
}
|
||||
47
launcher/Logic/Guard/Space.cs
Normal file
47
launcher/Logic/Guard/Space.cs
Normal file
@@ -0,0 +1,47 @@
|
||||
// What keeps a run of the launcher from damaging an install (old setup/Guard.cs). Nothing here needs a window.
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>Room on a disk, asked before it is needed. A download or an unpacking that ran out of room stopped somewhere in the
|
||||
/// middle with Windows' own words for it and left half of itself behind; asked first, the player is told how much it takes and
|
||||
/// how much there is, before anything is written.</summary>
|
||||
public static class Space
|
||||
{
|
||||
/// <summary>What a disk keeps free beyond what is about to be written to it.</summary>
|
||||
public const long Margin = 32L << 20;
|
||||
|
||||
/// <summary>Null when the free bytes are room for need more of them and the margin, or are not known; else the sentence that
|
||||
/// says there is no room for what, how much it takes and how much is free (what it takes rounded up and what is free rounded
|
||||
/// down, so the two numbers never read the same).</summary>
|
||||
public static string? Problem(string what, long need, long? free, string disk)
|
||||
{
|
||||
need = Math.Max(0, need) + Margin;
|
||||
if (free is not { } f || f >= need) return null;
|
||||
return "There is no room for " + what + " on " + disk + ": it takes " + ((need + (1 << 20) - 1) >> 20) + " MB there, and " + (Math.Max(0, f) >> 20) +
|
||||
" MB are free. Make room and try again.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>There is no room for what is about to be written (Space.Problem's sentence), said before any of it is.</summary>
|
||||
public sealed class NoRoomException : IOException
|
||||
{
|
||||
public NoRoomException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>A download stopped before its end (the connection was cut, went silent or closed early): its part is kept, and the
|
||||
/// next try goes on from it.</summary>
|
||||
public sealed class CutOffException : IOException
|
||||
{
|
||||
public CutOffException(string message, Exception? inner = null) : base(message, inner) { }
|
||||
}
|
||||
|
||||
/// <summary>The launcher an update brought could not start, and what was done about it.</summary>
|
||||
public sealed class NotStartedException : Exception
|
||||
{
|
||||
public NotStartedException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>The release server has no release (404, an empty list, an empty tag).</summary>
|
||||
public sealed class NoReleaseException : InvalidOperationException
|
||||
{
|
||||
public NoReleaseException() : base("There is no Triforce release yet.") { }
|
||||
}
|
||||
Reference in New Issue
Block a user