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:
ruckus7382sfgsgdf
2026-11-17 22:40:50 -06:00
parent 93eeb714c2
commit 6f338c8f56
600 changed files with 116254 additions and 2522 deletions

View File

@@ -10,7 +10,21 @@ public partial class App : Application
// Why it stopped is one "error <text>" line on stdout (the stream a launcher reads) and again on stderr
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length > 0 && e.Args[0] == "--cli")
var cli = e.Args.Length > 0 && e.Args[0] == "--cli";
// ((Triforce) one builder at a time for its tools, Instance.cs: asked before any build or window)
if (Tools.Find() is { } tools && !Instance.Take(tools.Root))
{
if (cli)
{
var said = "error " + Instance.Refusal(tools.Root).Replace("\n\n", " ");
Console.Out.WriteLine(said);
Console.Error.WriteLine(said);
}
else MessageBox.Show(Instance.Refusal(tools.Root), "Hookshot Builder", MessageBoxButton.OK, MessageBoxImage.Information);
Environment.Exit(1);
return;
}
if (cli)
{
Environment.Exit(Cli(e.Args.Skip(1).ToList()));
return;

View File

@@ -0,0 +1,53 @@
using System;
using System.IO;
using System.Threading;
namespace HookshotBuilder;
/// (Triforce, handoff §5) One Hookshot Builder at a time for its build tools. Two of them on one tools folder ran make_game.py on
/// the same work folder, and make_game.py stops a build it finds running there: the first one's build ended without a reason.
/// The first builder holds a named mutex for as long as it runs (Windows lets go of it when the process ends, however it ends);
/// a second one for the same tools says so and ends. The name comes from the tools folder (Tools.Root), so builders of other
/// folders, Triforce Setup (its lock is named after its own folder) and the game (after its game folder) never meet it.
/// HOOKSHOT_SINGLE_INSTANCE=0: no lock (as before). Plain logic: tests/test_builder_instance.py compiles this file alone
static class Instance
{
static Mutex? held;
/// The lock's name for a tools folder: one for each spelling of it (case, '/' or '\', a separator at its end), a 64-bit FNV-1a
/// of that spelling. Local\: this user's session
public static string Name(string root)
{
try { root = Path.GetFullPath(root); } catch (Exception) { }
var text = root.Replace('/', '\\').TrimEnd('\\').ToUpperInvariant();
var h = 14695981039346656037UL; // (a name, not a secret)
foreach (var c in text) { h ^= c; h *= 1099511628211UL; }
return @"Local\HookshotBuilder-" + h.ToString("x16");
}
/// True when this process now holds the tools folder (or did already; it waited up to waitMs for a builder that was ending),
/// false when another builder does. Where no lock can be made at all nobody is refused
public static bool Take(string root, int waitMs = 5000)
{
if (held != null) return true;
if (Environment.GetEnvironmentVariable("HOOKSHOT_SINGLE_INSTANCE") == "0") return true;
Mutex m;
try { m = new Mutex(false, Name(root)); }
catch (UnauthorizedAccessException) { return false; } // (it is there, and belongs to a builder run as administrator)
catch (Exception) { return true; }
try
{
if (!m.WaitOne(waitMs)) { 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;
return true;
}
/// What a second builder says
public static string Refusal(string root) =>
"Hookshot Builder is already running for these build tools:\n\n" + root +
"\n\nUse the window that is open, or close it and start the builder again. (Two builders on one tools folder would build " +
"into the same work folder and stop each other's build.)";
}

View File

@@ -0,0 +1,123 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
namespace HookshotBuilder;
/// (Triforce) What the setup (builder/setup/setup.c) lends from the installed version to the one it puts together, and the lock
/// every setup holds while it does. An update moves the folders of parts that did not change (Python, the compiler...) from
/// versions\<installed> into versions\<tag>.part and writes each down first in its reused.txt (the installed version's tag,
/// then a folder a line); a cut-off setup leaves them there. Free gives them back (UndoEveryReuse, setup.c undo_every_reuse,
/// the same rules) and never deletes a <tag>.part that still holds them (Lent): deleted, the installed version lost them for
/// good. Plain logic: tests/test_builder_setup_lock.py compiles this file alone
static class Reuse
{
public const string Note = "reused.txt";
/// True when folder is an unfinished version (a versions\*.part) that still holds folders of another version
public static bool Lent(string folder) =>
Path.GetFileName(folder.TrimEnd('\\', '/')).EndsWith(".part", StringComparison.OrdinalIgnoreCase) &&
File.Exists(Path.Combine(folder, Note));
/// The setup's lock for a setup folder (setup.c setup_lock_name and setup_parts.lock_name, the same): a 64-bit FNV-1a of the
/// folder's full path with '\' between its parts, none at its end, a to z in upper case. Local\: this user's session
public static string LockName(string setupBase)
{
try { setupBase = Path.GetFullPath(setupBase); } catch (Exception) { }
var text = setupBase.Replace('/', '\\').TrimEnd('\\');
var h = 14695981039346656037UL; // (a name, not a secret)
foreach (var c in text) { h ^= c >= 'a' && c <= 'z' ? (uint)(c - 32) : c; h *= 1099511628211UL; }
return @"Local\HookshotBuilder-Setup-" + h.ToString("x16");
}
/// The setup folder held by this thread until Dispose (one that holds nothing where no lock can be made at all), or null
/// when a setup held it for waitMs: one is installing now
public static Held? TakeLock(string setupBase, int waitMs = 0)
{
Mutex m;
try { m = new Mutex(false, LockName(setupBase)); }
catch (UnauthorizedAccessException) { return null; } // (it is there, and belongs to a setup run as administrator)
catch (Exception) { return new Held(null); }
try
{
if (!m.WaitOne(waitMs)) { m.Dispose(); return null; }
}
catch (AbandonedMutexException) { } // (its holder ended without letting go: Windows hands it on, and it is ours)
catch (Exception) { m.Dispose(); return new Held(null); }
return new Held(m);
}
public sealed class Held : IDisposable
{
Mutex? m;
internal Held(Mutex? m) => this.m = m;
public void Dispose()
{
if (m == null) return;
try { m.ReleaseMutex(); } catch (Exception) { }
m.Dispose();
m = null;
}
}
/// The folders a setup moved from the installed version into install (a <tag>.part), moved back: each only where that version
/// has none; the note goes once all went back. True: nothing is left to move back
public static bool Undo(string versions, string install)
{
var note = Path.Combine(install, Note);
string[] lines;
try { lines = File.ReadAllLines(note).Where(l => l.Trim().Length > 0).ToArray(); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return !File.Exists(note); }
if (lines.Length == 0 || !NameOk(lines[0], false)) // (no version named: nothing was moved yet)
{
try { File.Delete(note); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
return true;
}
var ok = true;
foreach (var rel in lines.Skip(1))
{
if (!NameOk(rel, true)) continue;
var from = Path.Combine(install, rel.Replace('/', '\\'));
var back = Path.Combine(versions, lines[0], rel.Replace('/', '\\'));
if (!(Directory.Exists(from) || File.Exists(from)) || Directory.Exists(back) || File.Exists(back)) continue;
try
{
Directory.CreateDirectory(Path.GetDirectoryName(back)!);
if (Directory.Exists(from)) Directory.Move(from, back);
else File.Move(from, back);
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { ok = false; }
}
if (ok)
try { File.Delete(note); } catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
return ok;
}
/// Undo for every versions\*.part with a note; the first whose folders could not all go back (each is tried), null when none
public static string? UndoEveryReuse(string versions)
{
string? left = null;
string[] dirs;
try { dirs = Directory.GetDirectories(versions); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; }
foreach (var d in dirs.OrderBy(d => d, StringComparer.Ordinal))
if (Lent(d) && !Undo(versions, d)) left ??= d;
return left;
}
/// A name from the note (setup.c list_name_ok, the same): letters, digits and . _ + - only (with path, '/' or '\' between
/// its parts), no "." or ".." part, no drive, no root
static bool NameOk(string s, bool path)
{
if (s.Length == 0 || s[0] == '/' || s[0] == '\\') return false;
foreach (var c in s)
if (!(c is >= 'a' and <= 'z' or >= 'A' and <= 'Z' or >= '0' and <= '9' or '.' or '_' or '+' or '-' ||
(path && (c == '/' || c == '\\'))))
return false;
foreach (var part in path ? s.Split('/', '\\') : new[] { s })
if (part.Length == 0 || part == "." || part == "..") return false;
return true;
}
}

View File

@@ -75,17 +75,20 @@ static class Storage
/// What Free lets go. afterBuild: what goes once the game is ready, the compiled objects of the build (objcache, which make_game.py
/// prunes to them) and their system headers' stamp kept, so that the next update compiles only what changed (issue 1287: every
/// update compiled all ~600 files again, an hour and more). The Free up space button lets those go too
static IEnumerable<string> Freeable(bool afterBuild = false)
/// update compiled all ~600 files again, an hour and more). The Free up space button lets those go too. (Triforce) Never an
/// unfinished version that still holds folders of the installed one (Reuse.Lent): deleted, the installed version lost its
/// Python or its compiler for good. installing: a setup holds the folder now, and what it is putting together (downloads\,
/// versions\) stays. Nothing is changed here: Measure counts it
static IEnumerable<string> Freeable(bool afterBuild = false, bool installing = false)
{
foreach (var d in afterBuild ? new[] { "sa", "exefs", "probe" } : new[] { "objcache", "sa", "exefs", "probe" })
yield return Path.Combine(Work, d);
foreach (var d in new[] { "downloads", "update" })
foreach (var d in installing ? new[] { "update" } : new[] { "downloads", "update" })
yield return Path.Combine(Base, d);
var versions = Path.Combine(Base, "versions");
if (Directory.Exists(versions))
if (Directory.Exists(versions) && !installing)
foreach (var v in Directory.EnumerateDirectories(versions))
if (!Kept(v)) yield return v;
if (!Kept(v) && !Reuse.Lent(v)) yield return v;
}
/// Bytes in the builder's folder and the build files folder, and in what Free lets go (an object hard-linked in both sa\build and
@@ -103,12 +106,18 @@ static class Storage
/// Lets go of what Measure counts as freeable; returns the bytes it could not delete (a file in use)
public static long Free(bool afterBuild = false)
{
foreach (var d in Freeable(afterBuild)) Delete(d);
// ((Triforce) what a cut-off setup moved from the installed version goes back first (Reuse.UndoEveryReuse), and then its
// <tag>.part is freeable; one whose folders could not all go back stays. With the setup's folder held: a setup running now
// is not undone under it, and its folders are left alone)
using var setup = Reuse.TakeLock(Base);
var installing = setup == null;
if (!installing) Reuse.UndoEveryReuse(Path.Combine(Base, "versions"));
foreach (var d in Freeable(afterBuild, installing)) Delete(d);
if (!afterBuild) Delete(Path.Combine(Work, "system_headers.txt")); // (the stamp of the compiled objects' system headers goes with them)
if (!afterBuild) return Measure().freeable;
var seen = new HashSet<(uint, ulong)>(); // (what of the after-build set is still there: a file in use)
long left = 0;
foreach (var d in Freeable(afterBuild: true)) left += Size(d, seen);
foreach (var d in Freeable(afterBuild: true, installing)) left += Size(d, seen);
return left;
}

View File

@@ -302,27 +302,85 @@ static class Updater
using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
if (!response.IsSuccessStatusCode) throw HttpFailure(response);
var total = response.Content.Headers.ContentLength ?? size;
await using var from = await response.Content.ReadAsStreamAsync(token);
await using var to = File.Create(path);
var buffer = new byte[1 << 20];
long have = 0;
var shown = DateTime.MinValue;
int n;
while (true)
// ((Triforce) the size the release lists, which the server must not contradict; the server's only where none is listed (the
// server's went first, and a short or other file passed as whole). Room for it asked before the first byte, and the bytes
// written to <file>.part, which becomes the file only once complete: a failure removes it)
var told = response.Content.Headers.ContentLength;
if (size > 0 && told is { } other && other != size)
throw new IOException($"The server offers {other} bytes as {Path.GetFileName(path)}, and the release lists {size}. Nothing was downloaded.");
var total = size > 0 ? size : told ?? 0;
if (total > 0 && NoRoom(path, total) is { } none) throw new IOException(none);
var part = path + ".part";
try
{
try { n = await from.ReadAsync(buffer, token); }
catch (IOException e) { throw new HttpRequestException("The download connection ended unexpectedly.", e); }
if (n == 0) break;
await to.WriteAsync(buffer.AsMemory(0, n), token);
have += n;
if (progress != null && total > 0 && DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(200))
await using (var from = await response.Content.ReadAsStreamAsync(token))
await using (var to = File.Create(part))
{
shown = DateTime.UtcNow;
progress(Math.Min(1.0, (double)have / total));
var buffer = new byte[1 << 20];
long have = 0;
var shown = DateTime.MinValue;
int n;
while (true)
{
try { n = await from.ReadAsync(buffer, token); }
catch (IOException e) { throw new HttpRequestException("The download connection ended unexpectedly.", e); }
if (n == 0) break;
await to.WriteAsync(buffer.AsMemory(0, n), token);
have += n;
if (total > 0 && have > total) throw new IOException($"The server sent more than the {total} bytes of {Path.GetFileName(path)}.");
if (progress != null && total > 0 && DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(200))
{
shown = DateTime.UtcNow;
progress(Math.Min(1.0, (double)have / total));
}
}
if (total > 0 && have != total) throw new HttpRequestException($"The download ended early ({have >> 20} of {total >> 20} MB).");
}
File.Move(part, path, true);
}
if (total > 0 && have != total) throw new HttpRequestException($"The download ended early ({have >> 20} of {total >> 20} MB).");
catch (Exception)
{
try { File.Delete(part); } catch (Exception) { }
throw;
}
}
/// ((Triforce) setup/Guard.cs Space, the same rule) Null when the disk of path has room for need bytes and 32 MB more (or
/// cannot be asked); else the sentence that says how much it takes and how much is free
static string? NoRoom(string path, long need)
{
long free;
try { free = new DriveInfo(Path.GetPathRoot(Path.GetFullPath(path))!).AvailableFreeSpace; }
catch (Exception) { return null; }
need += 32L << 20;
return free >= need ? null
: $"There is no room for {Path.GetFileName(path)} on {Path.GetPathRoot(Path.GetFullPath(path))}: it takes {(need + (1 << 20) - 1) >> 20} MB there, and {free >> 20} MB are free. Make room and try again.";
}
static readonly HashSet<string> Devices = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
/// ((Triforce) setup/Mods.cs Unsafe, the same rules) Why a zip's member must not be unpacked under its name, null when it may:
/// a path from the disk's root or through "..", a colon (a drive's letter, a hidden stream), a name Windows keeps for a device
/// (with or without an extension), a name that ends in a dot or a space (Windows drops them), a character Windows refuses
internal static string? UnsafeName(string name)
{
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";
foreach (var p in n.Split('/'))
{
if (p.Length == 0 || p == ".") continue;
if (p == "..") return "a path that leaves its own folder (..)";
if (p[p.Length - 1] == '.' || p[p.Length - 1] == ' ') return "a name that ends in a dot or a space, which Windows drops";
var dot = p.IndexOf('.');
var stem = (dot >= 0 ? p.Substring(0, dot) : p).TrimEnd(' ');
if (Devices.Contains(stem) || stem.Length == 4 && (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) &&
(stem[3] is >= '1' and <= '9' || stem[3] == (char)0xB9 || stem[3] == (char)0xB2 || stem[3] == (char)0xB3))
return "a name Windows keeps for a device (" + p + ")";
if (p.Any(c => c < 32 || "<>\"|?*".IndexOf(c) >= 0)) return "a name with a character Windows does not allow";
}
return null;
}
static HttpRequestException HttpFailure(HttpResponseMessage response) =>
@@ -335,14 +393,41 @@ static class Updater
error is HttpRequestException { StatusCode: { } status } ? $" (HTTP {(int)status})" : "";
/// The zip's HookshotBuilder folder, as target (an older one there replaced)
/// ((Triforce) every name checked first (UnsafeName: such a zip is refused whole), a failure removes the part, and an older
/// target is moved aside and back when the new one cannot take its place: before, it was deleted first, and a move that
/// failed then left neither)
static async Task<string> Unpack(string zip, string target)
{
var part = target + ".part";
if (Directory.Exists(part)) Directory.Delete(part, true);
await Task.Run(() => ZipFile.ExtractToDirectory(zip, part));
try
{
await Task.Run(() =>
{
using (var z = ZipFile.OpenRead(zip))
foreach (var e in z.Entries)
if (UnsafeName(e.FullName) is { } why)
throw new InvalidDataException($"The download holds {why} (\"{e.FullName}\"): it was not unpacked.");
ZipFile.ExtractToDirectory(zip, part);
});
}
catch (Exception)
{
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
throw;
}
var inner = Path.Combine(part, "HookshotBuilder");
if (Directory.Exists(target)) Directory.Delete(target, true);
Directory.Move(Directory.Exists(inner) ? inner : part, target);
var old = target + ".old";
if (Directory.Exists(old)) Directory.Delete(old, true);
if (Directory.Exists(target)) Directory.Move(target, old);
try { Directory.Move(Directory.Exists(inner) ? inner : part, target); }
catch (Exception)
{
try { if (!Directory.Exists(target) && Directory.Exists(old)) Directory.Move(old, target); } catch (Exception) { }
try { if (Directory.Exists(part)) Directory.Delete(part, true); } catch (Exception) { }
throw;
}
try { if (Directory.Exists(old)) Directory.Delete(old, true); } catch (Exception) { }
if (Directory.Exists(part)) Directory.Delete(part, true);
return target;
}

View File

@@ -11,6 +11,7 @@
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>

View File

@@ -232,16 +232,21 @@ def _kept_version(d):
return bool(cur) and _same(cur, d)
def freeable(after_build=False):
def freeable(after_build=False, installing=False):
"""What free lets go (measure counts it; nothing is changed here). (Triforce) Never an unfinished version that still holds
folders of the installed one (setup_parts.lent: its reused.txt): deleted, the installed version lost its Python or its
compiler for good. installing: another install holds the setup's folder now, and what it is putting together
(downloads\\, versions\\) stays"""
from . import setup_parts
for d in (("sa", "exefs", "probe") if after_build else ("objcache", "sa", "exefs", "probe")):
yield os.path.join(work(), d)
for d in ("downloads", "update"):
for d in ("update",) if installing else ("downloads", "update"):
yield os.path.join(paths.base(), d)
v = paths.versions()
if os.path.isdir(v):
if os.path.isdir(v) and not installing:
for name in os.listdir(v):
p = os.path.join(v, name)
if os.path.isdir(p) and not _kept_version(p):
if os.path.isdir(p) and not _kept_version(p) and not setup_parts.lent(p):
yield p
@@ -275,13 +280,24 @@ def measure():
def free(after_build=False):
"""Lets go of what measure counts as freeable; returns the bytes it could not delete (a file in use)"""
for d in list(freeable(after_build)):
_delete(d)
if not after_build:
_delete(os.path.join(work(), "system_headers.txt"))
return measure()[1]
seen = set()
return sum(_size(d, seen) for d in freeable(True))
from . import setup_parts
# ((Triforce) what a cut-off install moved from the installed version goes back first (setup_parts.undo_every_reuse), and
# then its <tag>.part is freeable; one whose folders could not all go back stays. With the setup's folder held: an install
# running now is not undone under it, and its folders are left alone)
lock = setup_parts.take_lock(0)
try:
if lock:
setup_parts.undo_every_reuse()
for d in list(freeable(after_build, installing=not lock)):
_delete(d)
if not after_build:
_delete(os.path.join(work(), "system_headers.txt"))
return measure()[1]
seen = set()
return sum(_size(d, seen) for d in freeable(True, installing=not lock))
finally:
if lock:
lock.release()
def gb(n):

View File

@@ -22,12 +22,80 @@ from . import REPO, paths
UA = "HookshotBuilder-Setup/2.0"
WAITS = (3, 6, 12, 20, 30, 45, 60) # (8 tries over ~3 minutes: GitHub's release downloads answered 504 for hours on 2026-11-08)
OWN = ("python", "emsdk", "cpm", "third_party", "wgpu-native")
MARGIN = 32 << 20 # ((Triforce) what a disk keeps free beyond what is about to be written to it: setup/Guard.cs Space.Margin)
REUSED = "reused.txt" # ((Triforce) in versions\<tag>.part: the folders moved over from the installed version, reuse_part)
DEVICES = {"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"}
LOCK_WAIT = 20 # ((Triforce) seconds an install waits for another one into the same folder before it says so: setup.c SETUP_LOCK_WAIT_MS)
class SetupError(Exception):
pass
def unsafe_member(name):
"""(Triforce) Why a zip's member must not be unpacked under its name, None when it may (setup/Mods.cs Unsafe, the same
rules): a path from the disk's root, a colon (a drive's letter, a hidden stream of another file), a path through "..", a
name Windows keeps for a device (CON, NUL, COM1, lpt2.txt: with or without an extension), a name that ends in a dot or a
space (Windows drops them, so the file would land under another name), a character Windows does not allow. zipfile's
extractall drops some of these quietly and writes the file under another name; a device's name it writes to the device"""
n = name.replace("\\", "/")
if not n.strip():
return "a member without a name"
if n.startswith("/"):
return "a path that starts at the disk's root"
if ":" in n:
return "a name with a colon or a drive's letter"
for p in n.split("/"):
if p in ("", "."):
continue
if p == "..":
return "a path that leaves its own folder (..)"
if p[-1] in ". ":
return "a name that ends in a dot or a space, which Windows drops"
stem = p.split(".", 1)[0].rstrip(" ").upper()
# (COM1 to COM9 and LPT1 to LPT9; Windows takes the raised digits 1, 2 and 3 for digits there too)
if stem in DEVICES or (len(stem) == 4 and stem[:3] in ("COM", "LPT") and stem[3] in "123456789\xb9\xb2\xb3"):
return "a name Windows keeps for a device (%s)" % p
if any(ord(c) < 32 or c in '<>"|?*' for c in p):
return "a name with a character Windows does not allow"
return None
def check_zip(z, dest, what):
"""(Triforce) Every member's name checked (unsafe_member) and the room for all of it asked before the first file is
written: such a zip is refused whole"""
need = 0
for info in z.infolist():
why = unsafe_member(info.filename)
if why:
raise SetupError("%s holds %s (\"%s\"): it was not unpacked." % (what, why, info.filename[:120]))
need += info.file_size + 4096 # (a file takes whole clusters)
room(dest, need, what)
def free_bytes(folder):
"""The free bytes of the disk that holds folder (asked of the nearest folder above it that is there); None when unknown"""
d = os.path.abspath(folder)
while not os.path.isdir(d):
up = os.path.dirname(d)
if up == d:
return None
d = up
try:
return shutil.disk_usage(d).free
except OSError:
return None
def room(folder, need, what):
"""(Triforce) SetupError before anything is written when the disk of folder has no room for need bytes and the margin"""
free = free_bytes(folder)
if free is not None and free < need + MARGIN:
raise SetupError("There is no room for %s on %s: it takes %d MB there, and %d MB are free. Make room and try again."
% (what, os.path.splitdrive(os.path.abspath(folder))[0] or folder, (need + MARGIN + (1 << 20) - 1) >> 20,
free >> 20))
class Part:
def __init__(self, sha, size, dest, frm, to, url):
self.sha, self.size, self.dest, self.frm, self.to, self.url = sha, int(size), dest, frm, to, url
@@ -182,6 +250,17 @@ def reuse_part(tag, p, install):
if not os.path.exists(src):
return False
os.makedirs(os.path.dirname(dst), exist_ok=True)
# ((Triforce) written down before it moves: the installed version is the rollback point, and a cancelled or failed install
# moves it back (undo_reuse). Before, a cancel left the installed version without the folders it lent and nothing ran)
try:
journal = os.path.join(install, REUSED)
new = not os.path.isfile(journal)
with open(journal, "a", encoding="utf-8") as f:
f.write(("%s\n" % was if new else "") + rel + "\n")
f.flush()
os.fsync(f.fileno())
except OSError:
return False
try:
os.replace(src, dst)
return True
@@ -189,6 +268,139 @@ def reuse_part(tag, p, install):
return False
def undo_reuse(work):
"""(Triforce) The folders reuse_part moved from the installed version into the unfinished one (work), moved back: what a
cancelled, failed or cut-off install leaves is the version that was installed, whole. Each goes back only where the
installed version has none; the list is removed once all went back"""
journal = os.path.join(work, REUSED)
try:
with open(journal, encoding="utf-8") as f:
lines = [l.rstrip("\n") for l in f if l.strip()]
except OSError:
return True
if not lines:
return True
was, ok = lines[0], True
for rel in lines[1:]:
if os.path.isabs(rel) or ".." in rel.replace("\\", "/").split("/"):
continue
src, back = os.path.join(work, rel), os.path.join(paths.versions(), was, rel)
if not os.path.exists(src) or os.path.exists(back):
continue
try:
os.makedirs(os.path.dirname(back), exist_ok=True)
os.replace(src, back)
except OSError:
ok = False
if ok:
try:
os.remove(journal)
except OSError:
pass
return ok
def undo_every_reuse():
"""(Triforce) undo_reuse for every unfinished version (versions\\*.part) that holds a reused.txt. Before, only the <tag>.part
of the release being installed now was undone: an install of another release cut off before left the installed version's
folders in its own <tag>.part, and the installed version ran without them. Returns the first such folder whose folders
could not all go back (each is tried), None when nothing is left to move back"""
v, left = paths.versions(), None
try:
names = sorted(os.listdir(v))
except OSError:
return None
for name in names:
work = os.path.join(v, name)
if name.lower().endswith(".part") and os.path.isfile(os.path.join(work, REUSED)) and not undo_reuse(work):
left = left or work
return left
def lent(folder):
"""(Triforce) True when folder is an unfinished version (a versions\\*.part) that still holds folders of another version
(its reused.txt): only undo_reuse may let it go, never a delete (core.freeable)"""
return os.path.basename(folder.rstrip("\\/")).lower().endswith(".part") and os.path.isfile(os.path.join(folder, REUSED))
def lock_name(base=None):
"""(Triforce) The name of the lock every install into base holds (setup.c setup_lock_name and Reuse.cs LockName, the same):
Local\\HookshotBuilder-Setup-<a 64-bit FNV-1a of the folder's full path with '\\' between its parts, none at its end, a to z
in upper case, taken a UTF-16 unit at a time>. Local\\: this user's session"""
full = os.path.abspath(base or paths.base()).replace("/", "\\").rstrip("\\")
data, h = full.encode("utf-16-le", "surrogatepass"), 14695981039346656037 # (a name, not a secret)
for i in range(0, len(data), 2):
c = data[i] | data[i + 1] << 8
h = ((h ^ (c - 32 if 97 <= c <= 122 else c)) * 1099511628211) & 0xFFFFFFFFFFFFFFFF
return "Local\\HookshotBuilder-Setup-%016x" % h
class Lock:
"""(Triforce) The lock of the setup's folder, held (release() lets go of it; one that holds nothing where no lock could be
made at all). Windows' named mutex belongs to the thread that took it: released on that thread"""
def __init__(self, handle=None, file=None):
self.handle, self.file = handle, file
def release(self):
if self.handle:
k = ctypes_kernel32()
k.ReleaseMutex(self.handle)
k.CloseHandle(self.handle)
self.handle = None
if self.file:
self.file.close() # (the flock goes with the file)
self.file = None
def ctypes_kernel32():
import ctypes
from ctypes import wintypes
k = ctypes.WinDLL("kernel32", use_last_error=True)
k.CreateMutexW.argtypes = [ctypes.c_void_p, wintypes.BOOL, wintypes.LPCWSTR]
k.CreateMutexW.restype = wintypes.HANDLE
k.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
k.WaitForSingleObject.restype = wintypes.DWORD
k.ReleaseMutex.argtypes = [wintypes.HANDLE]
k.CloseHandle.argtypes = [wintypes.HANDLE]
return k
def take_lock(wait=LOCK_WAIT, base=None):
"""(Triforce) The setup's folder for this install alone: Lock, or None when another install (this app's, or setup.c's)
held it for wait seconds. Before, two installs into one folder ran at once, and one's sweep (undo_every_reuse) gave back
the folders the other had just moved into its <tag>.part: that one then finished without its Python. Windows lets go of
the mutex when its holder ends, however it ends; elsewhere a lock file (setup.lock in the folder) is flock'ed. Where no
lock can be made at all nobody is refused"""
base = base or paths.base()
if os.name == "nt":
k = ctypes_kernel32()
h = k.CreateMutexW(None, False, lock_name(base))
if not h: # (5: it is there, and belongs to a setup run as administrator)
import ctypes
return None if ctypes.get_last_error() == 5 else Lock()
if k.WaitForSingleObject(h, int(max(0, wait) * 1000)) in (0, 0x80): # (0x80: its holder ended without letting go: ours)
return Lock(handle=h)
k.CloseHandle(h)
return None
try:
import fcntl
os.makedirs(base, exist_ok=True)
f = open(os.path.join(base, "setup.lock"), "a")
except (ImportError, OSError):
return Lock()
end = time.monotonic() + max(0, wait)
while True:
try:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
return Lock(file=f)
except OSError:
if time.monotonic() >= end:
f.close()
return None
time.sleep(0.2)
def rmtree(p):
shutil.rmtree(p, ignore_errors=True)
@@ -207,6 +419,29 @@ def current():
def install(status, progress=lambda f: None, tag=None, repair=False, cancel=None):
"""Installs the release (the latest, or tag) unless it is there already; returns (tag, its folder)"""
# ((Triforce) one install at a time into the setup's folder, its sweep included (take_lock): another one waits for it, a while)
lock = take_lock(0)
if lock is None:
status("Another Hookshot Builder setup is installing. Waiting for it to finish...")
lock = take_lock(LOCK_WAIT)
if lock is None:
raise SetupError("Another Hookshot Builder setup is installing into %s right now. Wait for it to finish (or close it), "
"then try again." % paths.base())
try:
return install_locked(status, progress, tag, repair, cancel)
finally:
lock.release()
def install_locked(status, progress, tag, repair, cancel):
"""install's work, with the setup's folder held"""
# ((Triforce) an install cut off before (the app closed), of this release or another: what it moved over from the installed
# version goes back first, before the installed version is looked at, and a part folder whose folders could not all go back
# is kept, not deleted with them)
left = undo_every_reuse()
if left:
raise SetupError("The last install could not be undone: %s still holds folders of the installed version. Close every "
"Hookshot window and try again." % left)
tag, parts = read_manifest(status, tag, cancel)
versions, downloads = paths.versions(), os.path.join(paths.base(), "downloads")
final = os.path.join(versions, tag)
@@ -216,39 +451,23 @@ def install(status, progress=lambda f: None, tag=None, repair=False, cancel=None
rmtree(final)
os.makedirs(work, exist_ok=True)
os.makedirs(downloads, exist_ok=True)
n = len(parts)
for i, p in enumerate(parts, 1):
if cancel and cancel():
raise SetupError("cancelled")
if reuse_part(tag, p, work):
status("Part %d of %d unchanged: kept from the installed version" % (i, n))
continue
zpath = os.path.join(downloads, p.sha + ".zip")
if not (os.path.isfile(zpath) and sha256_file(zpath) == p.sha):
download_part(status, progress, p, i, n, zpath, cancel)
status("Unpacking part %d of %d..." % (i, n))
progress(-1)
dest = work if p.dest == "." else os.path.join(work, p.dest.replace("/", os.sep))
os.makedirs(dest, exist_ok=True)
try:
with zipfile.ZipFile(zpath) as z:
z.extractall(dest)
except (OSError, zipfile.BadZipFile) as e:
raise SetupError("Unpacking part %d of %d failed: %s" % (i, n, e)) from None
if p.frm != "-" and p.to != "-": # (llvm-mingw-<version>-ucrt-x86_64 -> llvm-mingw)
src, dst = os.path.join(dest, p.frm), os.path.join(dest, p.to)
if not os.path.exists(dst):
try:
os.replace(src, dst)
except OSError:
raise SetupError("Could not set up part %d of %d (renaming %s)." % (i, n, p.frm)) from None
if not os.path.isfile(os.path.join(work, "HookshotBuilder", "tools", "nx2", "make_game.py")):
raise SetupError("The build tools are missing after unpacking. Your antivirus may have removed them: allow the folder %s "
"and try again." % paths.base())
try:
unpack_parts(status, progress, tag, parts, work, downloads, cancel)
except BaseException:
# ((Triforce) a cancel or a failure: the installed version gets back what was moved from it, and the partial goes)
if undo_reuse(work):
rmtree(work)
raise
try:
os.replace(work, final)
except OSError:
if undo_reuse(work):
rmtree(work)
raise SetupError("Could not finish installing into %s." % final) from None
try:
os.remove(os.path.join(final, REUSED))
except OSError:
pass
paths.write_small(os.path.join(final, "installed.txt"), tag)
write_parts(final, parts)
elif not os.path.isfile(os.path.join(final, "parts.txt")):
@@ -258,8 +477,45 @@ def install(status, progress=lambda f: None, tag=None, repair=False, cancel=None
return tag, final
def unpack_parts(status, progress, tag, parts, work, downloads, cancel):
"""Each part into work: moved over from the installed version, or downloaded (when not there already), checked and unpacked"""
n = len(parts)
for i, p in enumerate(parts, 1):
if cancel and cancel():
raise SetupError("cancelled")
if reuse_part(tag, p, work):
status("Part %d of %d unchanged: kept from the installed version" % (i, n))
continue
zpath = os.path.join(downloads, p.sha + ".zip")
if not (os.path.isfile(zpath) and sha256_file(zpath) == p.sha):
download_part(status, progress, p, i, n, zpath, cancel)
status("Unpacking part %d of %d..." % (i, n))
progress(-1)
dest = work if p.dest == "." else os.path.join(work, p.dest.replace("/", os.sep))
os.makedirs(dest, exist_ok=True)
try:
with zipfile.ZipFile(zpath) as z:
check_zip(z, dest, "Part %d of %d" % (i, n)) # ((Triforce) every name, and the room, before the first file)
z.extractall(dest)
except (OSError, zipfile.BadZipFile) as e:
raise SetupError("Unpacking part %d of %d failed: %s" % (i, n, e)) from None
if p.frm != "-" and p.to != "-": # (llvm-mingw-<version>-ucrt-x86_64 -> llvm-mingw)
src, dst = os.path.join(dest, p.frm), os.path.join(dest, p.to)
if not os.path.exists(dst):
try:
os.replace(src, dst)
except OSError:
raise SetupError("Could not set up part %d of %d (renaming %s)." % (i, n, p.frm)) from None
if not os.path.isfile(os.path.join(work, "HookshotBuilder", "tools", "nx2", "make_game.py")):
raise SetupError("The build tools are missing after unpacking. Your antivirus may have removed them: allow the folder %s "
"and try again." % paths.base())
def download_part(status, progress, p, i, n, zpath, cancel):
http, part = Http(), zpath + ".part"
# ((Triforce) room for the size the list names, asked before the first byte: a full disk stopped the download half way with
# Windows' own words for it. The part is written from its first byte at each try, so no address or mark is kept beside it)
room(os.path.dirname(zpath), p.size, "part %d of %d" % (i, n))
for attempt in range(len(WAITS) + 1):
if attempt:
status("Part %d of %d: GitHub didn't answer (%s). Trying again in %d s..." % (i, n, http.status or "no answer",

View File

@@ -89,12 +89,21 @@ static void status(const wchar_t *fmt, ...) {
PostMessageW(g_win, WM_STATUS, 0, 0);
}
/* (Triforce) the unfinished version's folder while one is put together, and the versions folder: what fail() undoes (undo_reuse) */
static wchar_t g_part_dir[MAX_PATH], g_versions_dir[MAX_PATH];
static int undo_reuse(const wchar_t *versions, const wchar_t *install);
static void rmtree(const wchar_t *dir);
static void setup_lock_release(void);
static void fail(const wchar_t *fmt, ...) {
wchar_t msg[1024];
va_list ap;
va_start(ap, fmt);
vswprintf(msg, 1024, fmt, ap);
va_end(ap);
/* ((Triforce) the installed version gets back the folders that were moved from it, and the unfinished one goes) */
if (g_part_dir[0] && undo_reuse(g_versions_dir, g_part_dir)) rmtree(g_part_dir);
setup_lock_release(); /* ((Triforce) undone: the next setup may begin) */
if (g_headless) say_error(msg), ExitProcess(1);
MessageBoxW(g_win, msg, L"Hookshot Builder setup", MB_OK | MB_ICONERROR);
PostMessageW(g_win, WM_DONE, 1, 0);
@@ -318,6 +327,29 @@ static int part_folder(const Part *p, wchar_t *rel, int n) {
return 1;
}
#define REUSED_NOTE L"reused.txt"
/* ((Triforce) undo_reuse's note: rel added to <install>\reused.txt, the installed version's tag first when it is new; written
through to the disk. 0: it could not be written (the folder is then not moved) */
static int reuse_note(const wchar_t *install, const char *was, const wchar_t *rel) {
wchar_t note[MAX_PATH];
char line[2 * MAX_PATH + 160];
swprintf(note, MAX_PATH, L"%ls\\" REUSED_NOTE, install);
const int fresh = GetFileAttributesW(note) == INVALID_FILE_ATTRIBUTES;
HANDLE f = CreateFileW(note, FILE_APPEND_DATA, 0, NULL, OPEN_ALWAYS, FILE_FLAG_WRITE_THROUGH, NULL);
if (f == INVALID_HANDLE_VALUE) return 0;
int n = fresh ? snprintf(line, sizeof line, "%s\n", was) : 0;
const int k = WideCharToMultiByte(CP_UTF8, 0, rel, -1, line + n, (int)sizeof line - n - 2, NULL, NULL);
DWORD put = 0;
int ok = k > 0;
if (ok) {
n += k - 1;
line[n++] = '\n';
ok = WriteFile(f, line, (DWORD)n, &put, NULL) && put == (DWORD)n && FlushFileBuffers(f);
}
CloseHandle(f);
return ok;
}
/* (players asked for less in %LOCALAPPDATA%: the downloaded zips are not kept beside the unpacked version any more. So that an update
still downloads only what changed, a part whose checksum the installed version lists in its parts.txt (and whose folder it has)
is moved over from it instead of downloaded: that version is deleted after the install anyway) */
@@ -343,9 +375,106 @@ static int reuse_part(const wchar_t *versions, const char *tag, const Part *p, c
wcscpy(parent, to);
wchar_t *slash = wcsrchr(parent, L'\\');
if (slash) *slash = 0, mkdirs(parent);
/* ((Triforce) written down before it moves: the installed version is the rollback point, undo_reuse) */
if (!reuse_note(install, was, rel)) return 0;
return MoveFileW(from, to) != 0;
}
/* (Triforce) The folders reuse_part moved from the installed version into the unfinished one (install), moved back: what a
failed, closed or cut-off setup leaves is the version that was installed, whole. Before, they stayed in <tag>.part, which
the next run deleted with them, and the version still installed had lost them. Each goes back only where the installed
version has none; the note (<tag>.part\reused.txt: the installed version's tag, then a folder a line) is removed once all
went back. 1: nothing is left to move back */
static int undo_reuse(const wchar_t *versions, const wchar_t *install) {
wchar_t note[MAX_PATH];
swprintf(note, MAX_PATH, L"%ls\\" REUSED_NOTE, install);
HANDLE f = CreateFileW(note, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (f == INVALID_HANDLE_VALUE) return 1;
char buf[8192];
DWORD got = 0;
ReadFile(f, buf, sizeof buf - 1, &got, NULL);
CloseHandle(f);
buf[got] = 0;
char *next = buf, *was = next_line(&next), *rel;
int ok = 1;
if (!was || !list_name_ok(was, 0)) return DeleteFileW(note), 1; /* (no version named: nothing was moved yet) */
while ((rel = next_line(&next)) != NULL) {
if (!list_name_ok(rel, 1)) continue;
wchar_t wrel[MAX_PATH], from[MAX_PATH], back[MAX_PATH], parent[MAX_PATH];
MultiByteToWideChar(CP_UTF8, 0, rel, -1, wrel, MAX_PATH);
swprintf(from, MAX_PATH, L"%ls\\%ls", install, wrel);
swprintf(back, MAX_PATH, L"%ls\\%hs\\%ls", versions, was, wrel);
if (GetFileAttributesW(from) == INVALID_FILE_ATTRIBUTES || GetFileAttributesW(back) != INVALID_FILE_ATTRIBUTES) continue;
wcscpy(parent, back);
wchar_t *slash = wcsrchr(parent, L'\\');
if (slash) *slash = 0, mkdirs(parent);
if (!MoveFileW(from, back)) ok = 0;
}
if (ok) DeleteFileW(note);
return ok;
}
/* (Triforce) undo_reuse for every unfinished version (versions\*.part) that holds a note. Before, only the <tag>.part of the
release being set up now was undone: a setup of another release cut off before left the installed version's folders in its
own <tag>.part, and the installed version ran without them. Each is tried; 1: nothing is left to move back, 0: left names the
first folder whose folders could not all go back */
static int undo_every_reuse(const wchar_t *versions, wchar_t *left, size_t cap) {
wchar_t pattern[MAX_PATH], dir[MAX_PATH], note[MAX_PATH];
WIN32_FIND_DATAW fd;
swprintf(pattern, MAX_PATH, L"%ls\\*", versions);
HANDLE h = FindFirstFileW(pattern, &fd);
if (h == INVALID_HANDLE_VALUE) return 1;
int ok = 1;
do {
const size_t n = wcslen(fd.cFileName);
if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || n < 6 || _wcsicmp(fd.cFileName + n - 5, L".part")) continue;
swprintf(dir, MAX_PATH, L"%ls\\%ls", versions, fd.cFileName);
swprintf(note, MAX_PATH, L"%ls\\" REUSED_NOTE, dir);
if (GetFileAttributesW(note) == INVALID_FILE_ATTRIBUTES || undo_reuse(versions, dir)) continue;
if (ok) wcsncpy(left, dir, cap - 1), left[cap - 1] = 0;
ok = 0;
} while (FindNextFileW(h, &fd));
FindClose(h);
return ok;
}
/* (Triforce) One setup at a time for a setup folder (base), its sweep (undo_every_reuse) included. Two at once each undid the
other's <tag>.part: the second one's sweep gave the installed version back the folders the first had just moved over, and
the first finished without its Python. The lock is a named mutex (Windows lets go of it when its holder ends, however it
ends), named as setup_parts.lock_name and Reuse.cs LockName name it: Local\HookshotBuilder-Setup-<a 64-bit FNV-1a of the
folder's full path with '\' between its parts, none at its end, a to z in upper case>. Local\: this user's session */
#define SETUP_LOCK_WAIT_MS 20000
static HANDLE g_setup_lock;
static void setup_lock_name(const wchar_t *base, wchar_t *name, size_t cap) {
wchar_t full[2 * MAX_PATH];
const DWORD got = GetFullPathNameW(base, 2 * MAX_PATH, full, NULL);
if (!got || got >= 2 * MAX_PATH) wcsncpy(full, base, 2 * MAX_PATH - 1), full[2 * MAX_PATH - 1] = 0;
size_t n = wcslen(full);
for (size_t i = 0; i < n; i++) if (full[i] == L'/') full[i] = L'\\';
while (n && full[n - 1] == L'\\') full[--n] = 0;
unsigned long long h = 14695981039346656037ULL; /* (a name, not a secret) */
for (size_t i = 0; i < n; i++) {
const unsigned c = full[i] >= L'a' && full[i] <= L'z' ? full[i] - 32u : full[i];
h = (h ^ c) * 1099511628211ULL;
}
swprintf(name, cap, L"Local\\HookshotBuilder-Setup-%016llx", h);
}
/* 1: this setup holds base (or no lock can be made at all: nobody is refused), 0: another setup held it for wait_ms */
static int setup_lock_take(const wchar_t *base, DWORD wait_ms) {
wchar_t name[96];
if (g_setup_lock) return 1;
setup_lock_name(base, name, 96);
HANDLE m = CreateMutexW(NULL, FALSE, name);
if (!m) return GetLastError() != ERROR_ACCESS_DENIED; /* (it is there, and belongs to a setup run as administrator) */
const DWORD r = WaitForSingleObject(m, wait_ms);
if (r == WAIT_OBJECT_0 || r == WAIT_ABANDONED) return g_setup_lock = m, 1; /* (abandoned: its holder ended, it is ours) */
CloseHandle(m);
return 0;
}
static void setup_lock_release(void) {
if (g_setup_lock) ReleaseMutex(g_setup_lock), CloseHandle(g_setup_lock), g_setup_lock = NULL;
}
/* The checksums of the parts this version holds in folders of their own (reuse_part reads them at the next update) */
static void write_parts(const wchar_t *install, const Part *parts, int nparts) {
wchar_t list[MAX_PATH], rel[MAX_PATH];
@@ -536,6 +665,14 @@ static DWORD WINAPI work(LPVOID unused) {
const wchar_t *tb = _wgetenv(L"HOOKSHOT_SETUP_BASE");
if (tb && *tb) wcsncpy(base, tb, MAX_PATH - 1), base[MAX_PATH - 1] = 0;
}
/* ((Triforce) this folder for this setup alone until the builder starts, its sweep included (setup_lock_take): another one
waits for it, a while) */
if (!setup_lock_take(base, 0)) {
status(L"Another Hookshot Builder setup is installing. Waiting for it to finish...");
if (!setup_lock_take(base, SETUP_LOCK_WAIT_MS))
fail(L"Another Hookshot Builder setup is installing into %ls right now. Wait for it to finish (or close it), then run the "
L"setup again.", base);
}
swprintf(downloads, MAX_PATH, L"%ls\\downloads", base);
mkdirs(downloads);
@@ -618,12 +755,21 @@ static DWORD WINAPI work(LPVOID unused) {
swprintf(exe, MAX_PATH, L"%ls\\%ls", install, wrun);
for (wchar_t *q = exe; *q; q++) if (*q == L'/') *q = L'\\';
{ /* ((Triforce) a setup cut off before, of this release or another: what it moved over from the installed version goes
back first, before the installed version is looked at; a part folder whose folders could not all go back is kept, not
deleted with them) */
wchar_t left[MAX_PATH];
if (!undo_every_reuse(versions, left, MAX_PATH))
fail(L"The last setup could not be undone: %ls still holds folders of the installed version. Close every Hookshot window "
L"and run the setup again.", left);
}
if (repair || GetFileAttributesW(marker) == INVALID_FILE_ATTRIBUTES || GetFileAttributesW(exe) == INVALID_FILE_ATTRIBUTES) {
/* (unpacked into <tag>.part and renamed once complete: a setup stopped half way never leaves a version that looks installed) */
swprintf(install, MAX_PATH, L"%ls\\%ls.part", versions, wtag);
rmtree(install);
rmtree(final_dir);
mkdirs(install);
wcscpy(g_versions_dir, versions), wcscpy(g_part_dir, install); /* (fail() undoes from here on) */
for (int i = 0; i < nparts; i++) {
Part *p = &parts[i];
wchar_t zip[MAX_PATH], wsha[65];
@@ -721,7 +867,13 @@ static DWORD WINAPI work(LPVOID unused) {
if (GetFileAttributesW(staged_exe) == INVALID_FILE_ATTRIBUTES)
fail(L"The builder is missing after unpacking (%ls). Your antivirus may have removed it: allow the folder %ls and run the setup again.", staged_exe, base);
if (!MoveFileW(install, final_dir)) fail(L"Could not finish installing into %ls.", final_dir);
g_part_dir[0] = 0; /* (installed: nothing to undo; the note goes) */
wcscpy(install, final_dir);
{
wchar_t note[MAX_PATH];
swprintf(note, MAX_PATH, L"%ls\\" REUSED_NOTE, final_dir);
DeleteFileW(note);
}
write_small(marker, tag);
write_parts(install, parts, nparts);
}
@@ -732,6 +884,7 @@ static DWORD WINAPI work(LPVOID unused) {
}
prune(versions, downloads, tag, parts, nparts);
rmtree(downloads); /* (installed: its zips are not kept; an update moves unchanged folders over instead, reuse_part) */
setup_lock_release(); /* ((Triforce) installed: the builder this starts may start a setup of its own) */
status(L"Starting the Hookshot Builder...");
wchar_t cmd[4096], dir[MAX_PATH];

View File

@@ -2,6 +2,6 @@
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity type="win32" name="Hookshot.BuilderSetup" version="1.0.0.0"/>
<dependency><dependentAssembly><assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/></dependentAssembly></dependency>
<application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware></windowsSettings></application>
<application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware><longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware></windowsSettings></application>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges><requestedExecutionLevel level="asInvoker" uiAccess="false"/></requestedPrivileges></security></trustInfo>
</assembly>