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:
252
launcher/Logic/Mods/GameBanana.cs
Normal file
252
launcher/Logic/Mods/GameBanana.cs
Normal file
@@ -0,0 +1,252 @@
|
||||
// GameBanana's mods for this game (ported from the game's own Mods menu, gpu/vk/vk_mods.cpp; research/02 7.3):
|
||||
// the section https://gamebanana.com/apiv11/Game/26242/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=<n>
|
||||
// a search .../apiv11/Util/Search/Results?_sModelName=Mod&_idGameRow=26242&_sOrder=best_match&_nPage=<n>&_sSearchString=<q>
|
||||
// (+ the WiPs' first page, _sModelName=Wip: GameBanana's search takes one kind a request), and when the
|
||||
// whole-word search finds nothing, the section's name filter: Subfeed...&_nPage=<n>&_sName=<q> (3 letters at least)
|
||||
// the details .../apiv11/<Mod|Wip>/<id>/ProfilePage (_aFiles[]: _idRow, _sFile, _sDescription, _sDownloadUrl, _nFilesize,
|
||||
// _tsDateAdded; _sText the description as HTML; _nDownloadCount)
|
||||
// Mods and WiPs: a WiP with files is often a mod all the same, and the online co-op kit is posted as one. A WiP with nothing to
|
||||
// download (_bHasFiles false) is left out; a record of another game (_aGame._idRow) too. A page that fails with cards already
|
||||
// listed is tried again after 2, 4 and 8 s (the first page's failure is shown at once, as in the game).
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A card: one mod or WiP of the section.</summary>
|
||||
public sealed record GbMod(int Id, bool Wip, string Name, string Author, string Category, string? Page, int Likes, int Views, long Updated, string? ThumbUrl)
|
||||
{
|
||||
/// <summary>A program of its own (Kits): installed into kits\<folder> and started, not put in mods.</summary>
|
||||
public bool IsKit => Kits.Find(Wip, Id) != null;
|
||||
}
|
||||
|
||||
public sealed record GbFile(int Id, string Name, string Description, string Url, long Bytes, long Added);
|
||||
|
||||
public sealed record GbDetails(int Id, bool Wip, string Text, int Downloads, IReadOnlyList<GbFile> Files)
|
||||
{
|
||||
/// <summary>The file to offer first: a kit's Windows file (Squadala posts a -windows and a -linux zip), else the first.</summary>
|
||||
public int DefaultFile(bool isKit)
|
||||
{
|
||||
if (isKit)
|
||||
for (var k = 0; k < Files.Count; k++)
|
||||
if (Files[k].Name.Contains(OperatingSystem.IsWindows() ? "windows" : "linux", StringComparison.OrdinalIgnoreCase)) return k;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public sealed record GbPage(IReadOnlyList<GbMod> Mods, int Page, int Total, bool Complete, bool NameFilter);
|
||||
|
||||
public sealed class GameBanana
|
||||
{
|
||||
/// <summary>GameBanana's game: The Legend of Zelda: Ocarina of Time (Switch 2).</summary>
|
||||
public const int GameId = 26242;
|
||||
const string Api = "https://gamebanana.com/apiv11";
|
||||
|
||||
readonly HttpClient http;
|
||||
public GameBanana(HttpClient? http = null)
|
||||
{
|
||||
this.http = http ?? Create();
|
||||
}
|
||||
|
||||
/// <summary>The waits before a failed page is asked again (old: 2, 4, 8 s).</summary>
|
||||
public TimeSpan[] RetryDelays { get; set; } = { TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(4), TimeSpan.FromSeconds(8) };
|
||||
|
||||
public static HttpClient Create()
|
||||
{
|
||||
// (GameBanana's /dl/ links send to its file server: redirects followed. 15 s to connect, 60 s for an answer as WinHTTP had)
|
||||
var h = new HttpClient(new SocketsHttpHandler { AllowAutoRedirect = true, ConnectTimeout = TimeSpan.FromSeconds(15), AutomaticDecompression = System.Net.DecompressionMethods.All })
|
||||
{ Timeout = Timeout.InfiniteTimeSpan };
|
||||
h.DefaultRequestHeaders.UserAgent.ParseAdd("Triforce-mod-browser/" + BuildInfo.Version);
|
||||
h.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
h.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*", 0.8));
|
||||
return h;
|
||||
}
|
||||
|
||||
public static string ListUrl(int page) => Api + "/Game/" + GameId + "/Subfeed?_sSort=default&_csvModelInclusions=Mod,Wip&_nPage=" + page;
|
||||
public static string SearchUrl(bool wip, int page, string query) =>
|
||||
Api + "/Util/Search/Results?_sModelName=" + (wip ? "Wip" : "Mod") + "&_idGameRow=" + GameId + "&_sOrder=best_match&_nPage=" + page + "&_sSearchString=" + UrlEncode(query);
|
||||
public static string NameFilterUrl(int page, string query) => ListUrl(page) + "&_sName=" + UrlEncode(query);
|
||||
public static string ProfileUrl(bool wip, int id) => Api + "/" + (wip ? "Wip" : "Mod") + "/" + id + "/ProfilePage";
|
||||
|
||||
/// <summary>A search's text in a URL: its UTF-8 bytes, letters, digits and - _ . ~ as they are, the rest %XX (sent in another
|
||||
/// code page GameBanana drops every filter, and & or + cut or change the query).</summary>
|
||||
public static string UrlEncode(string s)
|
||||
{
|
||||
var o = new StringBuilder();
|
||||
foreach (var b in Encoding.UTF8.GetBytes(s))
|
||||
{
|
||||
var c = (char)b;
|
||||
if (c is >= '0' and <= '9' or >= 'A' and <= 'Z' or >= 'a' and <= 'z' or '-' or '_' or '.' or '~') o.Append(c);
|
||||
else o.Append('%').Append(b.ToString("X2"));
|
||||
}
|
||||
return o.ToString();
|
||||
}
|
||||
|
||||
async Task<string> GetTextAsync(string url, CancellationToken token)
|
||||
{
|
||||
using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
|
||||
if (!r.IsSuccessStatusCode) throw new HttpRequestException("GameBanana answered " + (int)r.StatusCode, null, r.StatusCode);
|
||||
return await r.Content.ReadAsStringAsync(token).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
async Task<string> GetWithRetriesAsync(string url, bool retry, CancellationToken token)
|
||||
{
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try { return await GetTextAsync(url, token).ConfigureAwait(false); }
|
||||
catch (Exception) when (retry && attempt < RetryDelays.Length && !token.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(RetryDelays[attempt], token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One page of the section (15 records a page), newest activity first.</summary>
|
||||
public async Task<GbPage> ListAsync(int page, CancellationToken token = default) =>
|
||||
ParsePage(await GetWithRetriesAsync(ListUrl(page), page > 1, token).ConfigureAwait(false), null, page, false);
|
||||
|
||||
/// <summary>A search: GameBanana's own (whole words, best matches first, the WiPs' first page with the mods' first); when that
|
||||
/// finds nothing on its first page and the text has 3 letters or more, the section's name filter (a part of a name: "majora",
|
||||
/// "zeld"). nameFilter: ask the name filter's page directly (the next pages of a search that went there).</summary>
|
||||
public async Task<GbPage> SearchAsync(string query, int page, bool nameFilter = false, CancellationToken token = default)
|
||||
{
|
||||
query = query.Trim();
|
||||
if (nameFilter) return ParsePage(await GetWithRetriesAsync(NameFilterUrl(page, query), page > 1, token).ConfigureAwait(false), null, page, true);
|
||||
var mods = await GetWithRetriesAsync(SearchUrl(false, page, query), page > 1, token).ConfigureAwait(false);
|
||||
string? wips = null;
|
||||
if (page == 1)
|
||||
try { wips = await GetTextAsync(SearchUrl(true, 1, query), token).ConfigureAwait(false); }
|
||||
catch (Exception) when (!token.IsCancellationRequested) { } // (the WiPs could not be read: the mods alone)
|
||||
var got = ParsePage(mods, wips, page, false);
|
||||
if (page == 1 && got.Mods.Count == 0 && got.Complete && query.Length >= 3)
|
||||
return ParsePage(await GetWithRetriesAsync(NameFilterUrl(1, query), false, token).ConfigureAwait(false), null, 1, true);
|
||||
return got;
|
||||
}
|
||||
|
||||
/// <summary>A page's records as cards: mods and WiPs only, a WiP with nothing to download left out, another game's records
|
||||
/// left out, the same mod once. Total and Complete from _aMetadata.</summary>
|
||||
public static GbPage ParsePage(string json, string? wipJson, int page, bool nameFilter)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json);
|
||||
using var wdoc = wipJson != null ? TryParse(wipJson) : null;
|
||||
var j = doc.RootElement;
|
||||
var meta = Get(j, "_aMetadata");
|
||||
var total = (int)Num(meta, "_nRecordCount") + (wdoc != null ? (int)Num(Get(wdoc.RootElement, "_aMetadata"), "_nRecordCount") : 0);
|
||||
var complete = meta.ValueKind == JsonValueKind.Object && meta.TryGetProperty("_bIsComplete", out var c) && c.ValueKind == JsonValueKind.True;
|
||||
var list = new List<GbMod>();
|
||||
var records = new List<JsonElement>();
|
||||
if (Get(j, "_aRecords") is { ValueKind: JsonValueKind.Array } a) records.AddRange(a.EnumerateArray());
|
||||
if (wdoc != null && Get(wdoc.RootElement, "_aRecords") is { ValueKind: JsonValueKind.Array } w) records.AddRange(w.EnumerateArray());
|
||||
foreach (var r in records)
|
||||
{
|
||||
if (r.ValueKind != JsonValueKind.Object) continue;
|
||||
var model = Str(r, "_sModelName");
|
||||
if (model != "Mod" && model != "Wip") continue; // (the section's requests, questions and tools: not mods)
|
||||
if (model == "Wip" && r.TryGetProperty("_bHasFiles", out var hf) && hf.ValueKind == JsonValueKind.False) continue;
|
||||
if (Get(r, "_aGame") is { ValueKind: JsonValueKind.Object } g && Num(g, "_idRow") != GameId) continue;
|
||||
var id = (int)Num(r, "_idRow");
|
||||
var wip = model == "Wip";
|
||||
if (list.Any(o => o.Id == id && o.Wip == wip)) continue;
|
||||
string? thumb = null;
|
||||
if (Get(Get(r, "_aPreviewMedia"), "_aImages") is { ValueKind: JsonValueKind.Array } imgs && imgs.GetArrayLength() > 0 && imgs[0] is { ValueKind: JsonValueKind.Object } img)
|
||||
{
|
||||
// (530 wide when GameBanana made that size: sharp in the details; the cards draw it smaller)
|
||||
var file = Str(img, "_sFile530") is { Length: > 0 } f530 ? f530 : Str(img, "_sFile220") is { Length: > 0 } f220 ? f220 : Str(img, "_sFile");
|
||||
thumb = Str(img, "_sBaseUrl") + "/" + file;
|
||||
}
|
||||
var updated = Num(r, "_tsDateModified") is var m && m != 0 ? m : Num(r, "_tsDateAdded");
|
||||
list.Add(new GbMod(id, wip, Str(r, "_sName"), Str(Get(r, "_aSubmitter"), "_sName"), Str(Get(r, "_aRootCategory"), "_sName"), Str(r, "_sProfileUrl") is { Length: > 0 } p ? p : null,
|
||||
(int)Num(r, "_nLikeCount"), (int)Num(r, "_nViewCount"), updated, thumb));
|
||||
}
|
||||
return new GbPage(list, page, total, complete, nameFilter);
|
||||
}
|
||||
|
||||
static JsonDocument? TryParse(string s) { try { return JsonDocument.Parse(s); } catch (Exception) { return null; } }
|
||||
static JsonElement Get(JsonElement o, string name) => o.ValueKind == JsonValueKind.Object && o.TryGetProperty(name, out var v) ? v : default;
|
||||
static string Str(JsonElement o, string name) => Get(o, name) is var v && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : v.ValueKind == JsonValueKind.Number ? v.GetRawText() : "";
|
||||
static long Num(JsonElement o, string name) => Get(o, name) is var v && v.ValueKind == JsonValueKind.Number ? (v.TryGetInt64(out var n) ? n : (long)v.GetDouble())
|
||||
: v.ValueKind == JsonValueKind.String && long.TryParse(v.GetString(), out var s) ? s : 0;
|
||||
|
||||
/// <summary>A mod's details: its files (those with a download link), its description as plain text, its downloads.</summary>
|
||||
public async Task<GbDetails> DetailsAsync(int id, bool wip, CancellationToken token = default)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(await GetTextAsync(ProfileUrl(wip, id), token).ConfigureAwait(false));
|
||||
return ParseDetails(doc.RootElement, id, wip);
|
||||
}
|
||||
|
||||
public static GbDetails ParseDetails(JsonElement j, int id, bool wip)
|
||||
{
|
||||
var files = new List<GbFile>();
|
||||
if (Get(j, "_aFiles") is { ValueKind: JsonValueKind.Array } a)
|
||||
foreach (var f in a.EnumerateArray())
|
||||
{
|
||||
var url = Str(f, "_sDownloadUrl");
|
||||
if (url.Length > 0) files.Add(new GbFile((int)Num(f, "_idRow"), Str(f, "_sFile"), Str(f, "_sDescription"), url, Num(f, "_nFilesize"), Num(f, "_tsDateAdded")));
|
||||
}
|
||||
return new GbDetails(id, wip, Plain(Str(j, "_sText")), (int)Num(j, "_nDownloadCount"), files);
|
||||
}
|
||||
|
||||
/// <summary>A card's picture's bytes (at most 8 MB); the App decodes it.</summary>
|
||||
public async Task<byte[]> ThumbnailAsync(string url, CancellationToken token = default)
|
||||
{
|
||||
if (!url.StartsWith("https://", StringComparison.Ordinal)) throw new ArgumentException("not an https link");
|
||||
using var r = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
|
||||
r.EnsureSuccessStatusCode();
|
||||
await using var s = await r.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
|
||||
using var m = new MemoryStream();
|
||||
var buf = new byte[1 << 16];
|
||||
for (int n; (n = await s.ReadAsync(buf, token).ConfigureAwait(false)) > 0;)
|
||||
{
|
||||
m.Write(buf, 0, n);
|
||||
if (m.Length > 8 << 20) throw new InvalidDataException("the picture is larger than 8 MB");
|
||||
}
|
||||
return m.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>GameBanana's descriptions are HTML: the text alone, a line where a paragraph or a break was (vk_mods.cpp plain).</summary>
|
||||
public static string Plain(string html)
|
||||
{
|
||||
var o = new StringBuilder();
|
||||
string[][] ents =
|
||||
{
|
||||
new[] { "&", "&" }, new[] { "<", "<" }, new[] { ">", ">" }, new[] { """, "\"" }, new[] { "'", "'" }, new[] { "'", "'" },
|
||||
new[] { " ", " " }, new[] { "’", "’" }, new[] { "‘", "‘" }, new[] { "“", "“" }, new[] { "”", "”" },
|
||||
new[] { "…", "..." }, new[] { "—", "—" }, new[] { "–", "–" },
|
||||
};
|
||||
for (var i = 0; i < html.Length;)
|
||||
{
|
||||
if (html[i] == '<')
|
||||
{
|
||||
var end = html.IndexOf('>', i);
|
||||
if (end < 0) break;
|
||||
var tag = html.Substring(i + 1, end - i - 1).ToLowerInvariant();
|
||||
if (tag.StartsWith("br") || tag.StartsWith("/p") || tag.StartsWith("/li") || tag.StartsWith("/h") || tag.StartsWith("/div")) o.Append('\n');
|
||||
else if (tag.StartsWith("li")) o.Append("- ");
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
if (html[i] == '&')
|
||||
{
|
||||
var hit = ents.FirstOrDefault(e => string.CompareOrdinal(html, i, e[0], 0, e[0].Length) == 0);
|
||||
if (hit != null) { o.Append(hit[1]); i += hit[0].Length; continue; }
|
||||
}
|
||||
o.Append(html[i++]);
|
||||
}
|
||||
// (runs of blank lines and spaces: one each)
|
||||
var tidy = new StringBuilder();
|
||||
var newlines = 0;
|
||||
var space = false;
|
||||
foreach (var ch in o.ToString())
|
||||
{
|
||||
var c = ch == '\r' || ch == '\t' ? ' ' : ch;
|
||||
if (c == '\n') { if (++newlines <= 2 && tidy.Length > 0) tidy.Append('\n'); space = false; continue; }
|
||||
if (c == ' ') { if (!space && tidy.Length > 0 && tidy[^1] != '\n') tidy.Append(' '); space = true; continue; }
|
||||
newlines = 0;
|
||||
space = false;
|
||||
tidy.Append(c);
|
||||
}
|
||||
var s = tidy.ToString().TrimEnd('\n', ' ');
|
||||
return s.Length > 1400 ? s.Substring(0, 1400) + "..." : s;
|
||||
}
|
||||
}
|
||||
287
launcher/Logic/Mods/GameBananaInstaller.cs
Normal file
287
launcher/Logic/Mods/GameBananaInstaller.cs
Normal file
@@ -0,0 +1,287 @@
|
||||
// Installing what GameBanana offers (vk_mods.cpp run_install / run_kit), with the launcher's own checked unpacking (ModManager:
|
||||
// names, links, sizes, room) where the game used tar.exe as is.
|
||||
// a mod downloaded into mods\.triforce-download, unpacked there, each folder holding romfs (or exefs) found (five levels down;
|
||||
// a folder of the game's own RomFS folders with no romfs above them is wrapped in one), then moved into mods\NN-<name>
|
||||
// with triforce_mod.json beside it. A reinstall or an update replaces the folders this mod had and keeps the first one's
|
||||
// place in the order and its on/off; several roots are the mod's options: the first on, the others off (_).
|
||||
// a kit (Kits: an allow-list, never what a download holds) unpacked into kits\<folder>, its start file found (three levels
|
||||
// down), its files moved over what is there (the kit's own settings stay), triforce_kit.json written, then its start file
|
||||
// run in a console of its own. Windows only, as in the game.
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A program of its own posted in the section, not a romfs mod.</summary>
|
||||
public sealed record Kit(bool Wip, int Id, string Folder, string Start);
|
||||
|
||||
public static class Kits
|
||||
{
|
||||
/// <summary>((Triforce) 11-18, "make sure the multiplayer mod is included": daurosk's Squadala!, online co-op,
|
||||
/// github.com/daurosk/oot-remake-multiplayer.) Only the ones named here: a download is never started because of what it holds.</summary>
|
||||
public static readonly IReadOnlyList<Kit> All = new[] { new Kit(true, 105323, "Squadala", "Start Squadala.bat") };
|
||||
|
||||
public static Kit? Find(bool wip, int id) => All.FirstOrDefault(k => k.Wip == wip && k.Id == id);
|
||||
}
|
||||
|
||||
/// <summary>A mod or kit that came from GameBanana, as its json says (id, WiP or Mod, the file's date).</summary>
|
||||
public sealed record InstalledMod(int Id, bool Wip, long FileDate, string Folder);
|
||||
|
||||
public sealed class GameBananaInstaller
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
readonly ModManager mods;
|
||||
public GameBananaInstaller(TriforceContext ctx, ModManager? mods = null)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
this.mods = mods ?? new ModManager(ctx);
|
||||
}
|
||||
|
||||
static readonly string[] RomfsDirs = { "Model", "UI", "Tex", "Pack", "Sound", "Event", "Banc", "Effect", "Mals", "Font2", "Logic", "Phive", "Scene", "System", "GameData", "Voice", "Movie", "AS", "AI", "Game", "Env" };
|
||||
|
||||
/// <summary>What came from GameBanana into this game folder: mods (triforce_mod.json) and kits (triforce_kit.json).</summary>
|
||||
public IReadOnlyList<InstalledMod> Installed(string game)
|
||||
{
|
||||
var o = new List<InstalledMod>();
|
||||
var root = Mods.FolderOf(game);
|
||||
if (Directory.Exists(root))
|
||||
foreach (var d in Directory.GetDirectories(root))
|
||||
{
|
||||
if (Path.GetFileName(d).StartsWith('.')) continue;
|
||||
if (ModManager.ReadInfo(d) is { GameBananaId: > 0 } i) o.Add(new InstalledMod((int)i.GameBananaId, i.Wip, i.FileDate, d));
|
||||
}
|
||||
foreach (var k in Kits.All)
|
||||
{
|
||||
var dir = Path.Combine(game, "kits", k.Folder);
|
||||
if (ReadJson(Path.Combine(dir, "triforce_kit.json")) is { } j && j.Id == k.Id) o.Add(new InstalledMod(k.Id, k.Wip, j.Date, dir));
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
/// <summary>Installed, and is there a newer file (an "Update" mark): newest file date > the one installed.</summary>
|
||||
public (bool Installed, bool Update) State(string game, GbMod m, GbDetails? d)
|
||||
{
|
||||
var hit = Installed(game).FirstOrDefault(i => i.Id == m.Id && i.Wip == m.Wip);
|
||||
if (hit == null) return (false, false);
|
||||
var newest = d?.Files.Count > 0 ? d.Files.Max(f => f.Added) : 0;
|
||||
return (true, newest > hit.FileDate && hit.FileDate > 0);
|
||||
}
|
||||
|
||||
static (long Id, long Date)? ReadJson(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var r = doc.RootElement;
|
||||
long N(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var x) ? x : 0;
|
||||
return (N("gamebanana_id"), N("file_date"));
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>A folder name: no characters Windows refuses, never "off" by its name, at most 60 characters (vk_mods.cpp safe_name).</summary>
|
||||
public static string SafeName(string name)
|
||||
{
|
||||
var s = new string(name.Where(c => c >= 32 && "<>:\"/\\|?*".IndexOf(c) < 0).ToArray());
|
||||
s = s.TrimEnd('.', ' ').TrimStart('_', '-', '.', ' ');
|
||||
if (s.Length > 60) s = s.Substring(0, 60);
|
||||
s = s.TrimEnd('.', ' ');
|
||||
return s.Length == 0 ? "mod" : s;
|
||||
}
|
||||
|
||||
static string InfoJson(string name, GbMod m, GbFile f, bool kit) => JsonSerializer.Serialize(new Dictionary<string, object?>
|
||||
{
|
||||
["name"] = name, ["author"] = m.Author, ["page"] = m.Page, ["gamebanana_id"] = m.Id,
|
||||
["gamebanana_model"] = kit || m.Wip ? (m.Wip ? "Wip" : "Mod") : null,
|
||||
["file"] = f.Name, ["file_date"] = f.Added, ["installed_by"] = "Triforce's launcher",
|
||||
}.Where(kv => kv.Value != null).ToDictionary(kv => kv.Key, kv => kv.Value), new JsonSerializerOptions { WriteIndented = true }) + "\n";
|
||||
|
||||
/// <summary>Downloads and installs one of a mod's files; a kit goes to kits and is started. Returns the sentence the App shows.
|
||||
/// Refused while the game runs.</summary>
|
||||
public async Task<string> InstallAsync(HttpClient http, GbMod m, GbFile f, string game, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
if (Kits.Find(m.Wip, m.Id) is { } kit) return await InstallKitAsync(http, m, f, game, kit, progress, token).ConfigureAwait(false);
|
||||
if (mods.GameRuns(game)) throw new ModsException("Close the game first. Mods are added, switched, ordered and removed only while it is not running.");
|
||||
var root = Mods.FolderOf(game);
|
||||
var stage = Path.Combine(root, ".triforce-download");
|
||||
ctx.Require(stage);
|
||||
var unpacked = await DownloadUnpackAsync(http, m, f, root, stage, progress, token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var (roots, bare) = FindRoots(unpacked);
|
||||
if (roots.Count == 0 && bare.Count > 0) // (packed without a romfs folder: one made around the game's folders)
|
||||
{
|
||||
var made = Path.Combine(stage, "wrapped");
|
||||
Directory.CreateDirectory(made);
|
||||
Directory.Move(bare[0], Path.Combine(made, "romfs"));
|
||||
roots.Add(made);
|
||||
}
|
||||
if (roots.Count == 0)
|
||||
throw new ModsException("This download has no romfs folder in it, so it is not a mod Triforce can load (it may need its own installer, or be for another version of the game).");
|
||||
// (a reinstall or an update: the folders this mod had go, and the new one takes the first one's place and its on or off)
|
||||
var number = 0;
|
||||
var wasOff = false;
|
||||
var old = new List<string>();
|
||||
foreach (var d in Directory.GetDirectories(root).OrderBy(x => x, StringComparer.Ordinal))
|
||||
{
|
||||
var name = Path.GetFileName(d);
|
||||
if (name.StartsWith('.')) continue;
|
||||
if (ModManager.ReadInfo(d) is not { } info || info.GameBananaId != m.Id) continue;
|
||||
if (old.Count == 0)
|
||||
{
|
||||
var (off, num, _) = Mods.Parse(name);
|
||||
wasOff = off;
|
||||
number = num ?? 0;
|
||||
}
|
||||
old.Add(d);
|
||||
}
|
||||
var aside = new List<(string Was, string Gone)>();
|
||||
for (var k = 0; k < old.Count; k++) // (out of the way first: removed once the new one is in, put back if it fails)
|
||||
{
|
||||
var gone = Path.Combine(stage, "old-" + k);
|
||||
try { Directory.Move(old[k], gone); aside.Add((old[k], gone)); } catch (Exception e) { ctx.Log.Write("mods: the old " + old[k] + " could not be moved aside: " + e.Message); }
|
||||
}
|
||||
var label0 = SafeName(m.Name);
|
||||
if (number == 0) number = NextNumber(root);
|
||||
var placed = new List<string>();
|
||||
string? err = null;
|
||||
for (var i = 0; i < roots.Count; i++)
|
||||
{
|
||||
var label = label0;
|
||||
if (roots.Count > 1 && !TriforceContext.SamePath(roots[i], unpacked)) label += " - " + SafeName(Path.GetFileName(roots[i]));
|
||||
var prefix = (i > 0 || wasOff ? "_" : "") + (number++).ToString("00") + "-";
|
||||
var target = Path.Combine(root, prefix + label);
|
||||
for (var k = 2; Directory.Exists(target); k++) target = Path.Combine(root, prefix + label + " (" + k + ")");
|
||||
try { ctx.Require(target); Directory.Move(roots[i], target); }
|
||||
catch (Exception e) { err = "could not move it into " + target + " (" + e.Message + ")"; break; }
|
||||
File.WriteAllText(Path.Combine(target, "triforce_mod.json"), InfoJson(roots.Count > 1 ? label : m.Name, m, f, false));
|
||||
placed.Add(target);
|
||||
}
|
||||
if (placed.Count == 0)
|
||||
{
|
||||
foreach (var (was, gone) in aside) try { Directory.Move(gone, was); } catch (Exception) { }
|
||||
throw new ModsException("It could not be installed: " + err + "." + (aside.Count == 0 ? "" : " The one installed before is kept."));
|
||||
}
|
||||
if (placed.Select(p => mods.List(root).FirstOrDefault(x => TriforceContext.SamePath(x.Path, p))).Any(x => x is { Built: true }) && mods.BuiltMark(game) == null)
|
||||
mods.MarkChanged(game);
|
||||
ctx.Log.Write("mods: installed " + m.Name + " (" + m.Id + ") into " + placed.Count + " folder(s), the first " + placed[0]);
|
||||
var msg = "Installed into mods" + Path.DirectorySeparatorChar + Path.GetFileName(placed[0]) + ".";
|
||||
if (placed.Count > 1) msg += " It came with " + placed.Count + " options: the first is on, the others are off. Choose on the Mods page.";
|
||||
return msg;
|
||||
}
|
||||
finally { Partial.Remove(stage); }
|
||||
}
|
||||
|
||||
/// <summary>The file downloaded into stage (made anew) and unpacked into stage\unpacked with the checked unpacking.</summary>
|
||||
async Task<string> DownloadUnpackAsync(HttpClient http, GbMod m, GbFile f, string within, string stage, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
Partial.Remove(stage);
|
||||
Directory.CreateDirectory(stage);
|
||||
try { File.SetAttributes(stage, File.GetAttributes(stage) | FileAttributes.Hidden); } catch (Exception) { }
|
||||
var name = SafeName(f.Name.Length == 0 ? "mod.zip" : f.Name);
|
||||
var archive = Path.Combine(stage, name);
|
||||
ctx.Log.Write("mods: installing " + m.Name + " (" + m.Id + "), file " + f.Name + " (" + f.Bytes + " bytes) from " + f.Url);
|
||||
try
|
||||
{
|
||||
// (the size the server names: GameBanana's listed size is not trusted to the byte)
|
||||
await new Downloader(ctx).ToFileAsync(http, f.Url, archive, 0, progress, token).ConfigureAwait(false);
|
||||
var unpacked = Path.Combine(stage, "unpacked");
|
||||
await Task.Run(() => mods.Unpack(within, archive, unpacked, null), token).ConfigureAwait(false);
|
||||
return unpacked;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Partial.Remove(stage);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The folders holding romfs (or exefs) under dir, five levels down; a folder of the game's RomFS folders with no romfs
|
||||
/// above them counts as a romfs itself (bare).</summary>
|
||||
static (List<string> Roots, List<string> Bare) FindRoots(string dir)
|
||||
{
|
||||
var roots = new List<string>();
|
||||
var bare = new List<string>();
|
||||
void Look(string d, int depth)
|
||||
{
|
||||
if (Directory.Exists(Path.Combine(d, "romfs")) || Directory.Exists(Path.Combine(d, "exefs"))) { roots.Add(d); return; }
|
||||
var subs = Directory.GetDirectories(d).OrderBy(x => x, StringComparer.Ordinal).ToList();
|
||||
if (subs.Any(s => RomfsDirs.Any(r => string.Equals(Path.GetFileName(s), r, StringComparison.OrdinalIgnoreCase)))) { bare.Add(d); return; }
|
||||
if (depth >= 5) return;
|
||||
foreach (var s in subs) Look(s, depth + 1);
|
||||
}
|
||||
Look(dir, 0);
|
||||
return (roots, bare);
|
||||
}
|
||||
|
||||
/// <summary>After the highest "NN-" there: a new mod wins over those installed before.</summary>
|
||||
static int NextNumber(string root)
|
||||
{
|
||||
var hi = 0;
|
||||
foreach (var d in Directory.GetDirectories(root))
|
||||
if (Mods.Parse(Path.GetFileName(d)).Number is { } n) hi = Math.Max(hi, n);
|
||||
return hi + 1;
|
||||
}
|
||||
|
||||
async Task<string> InstallKitAsync(HttpClient http, GbMod m, GbFile f, string game, Kit k, Action<DownloadProgress>? progress, CancellationToken token)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) throw new ModsException(m.Name + " is not available on Linux from the launcher yet: download it from its page and follow its own steps.");
|
||||
var kits = Path.Combine(game, "kits");
|
||||
var dir = Path.Combine(kits, k.Folder);
|
||||
var stage = Path.Combine(kits, ".triforce-download");
|
||||
ctx.Require(stage);
|
||||
// (this file installed already, and its start file there: started again, nothing downloaded)
|
||||
var have = ReadJson(Path.Combine(dir, "triforce_kit.json")) is { } j && j.Id == k.Id && j.Date >= f.Added && File.Exists(Path.Combine(dir, k.Start));
|
||||
if (!have)
|
||||
{
|
||||
ctx.Log.Write("mods: " + m.Name + " is a kit: into " + dir);
|
||||
var unpacked = await DownloadUnpackAsync(http, m, f, kits, stage, progress, token).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var top = FindKitTop(unpacked, k.Start, 0)
|
||||
?? throw new ModsException("This download has no \"" + k.Start + "\" in it: GameBanana's file may have changed. Nothing was installed.");
|
||||
try { MoveOver(top, dir); }
|
||||
catch (Exception e) { throw new ModsException("It could not be put into kits\\" + k.Folder + ": " + e.Message + ". If " + m.Name + " is running, close it and try again."); }
|
||||
File.WriteAllText(Path.Combine(dir, "triforce_kit.json"), InfoJson(m.Name, m, f, true));
|
||||
}
|
||||
finally { Partial.Remove(stage); }
|
||||
}
|
||||
if (!ctx.Allowed(dir)) throw new ModsException(ctx.TestOnly);
|
||||
try
|
||||
{
|
||||
// (the kit's start file run in a console of its own, from its folder: cmd /c, a .bat or any start file Windows runs)
|
||||
var cmd = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe");
|
||||
Process.Start(new ProcessStartInfo(cmd, "/c \"\"" + Path.Combine(dir, k.Start) + "\"\"") { UseShellExecute = false, CreateNoWindow = false, WorkingDirectory = dir })?.Dispose();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
throw new ModsException(k.Start + " could not be started (" + e.Message + "). It is in kits\\" + k.Folder + " beside the game: start it from there.");
|
||||
}
|
||||
ctx.Log.Write("mods: kit " + m.Name + " " + (have ? "installed already" : "installed") + ", started: " + Path.Combine(dir, k.Start));
|
||||
return (have ? "Started" : "Installed into kits\\" + k.Folder + " and started") + " in a window of its own. Follow its steps there.";
|
||||
}
|
||||
|
||||
/// <summary>The folder under dir (dir itself, or 3 levels down at most) whose files hold the kit's start file.</summary>
|
||||
static string? FindKitTop(string dir, string start, int depth)
|
||||
{
|
||||
if (Directory.GetFiles(dir).Any(f => string.Equals(Path.GetFileName(f), start, StringComparison.OrdinalIgnoreCase))) return dir;
|
||||
if (depth >= 3) return null;
|
||||
foreach (var d in Directory.GetDirectories(dir).OrderBy(x => x, StringComparer.Ordinal))
|
||||
if (FindKitTop(d, start, depth + 1) is { } t) return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>from's files moved over into's (folders made, files there replaced; what into has more stays: the kit's own settings).</summary>
|
||||
static void MoveOver(string from, string into)
|
||||
{
|
||||
Directory.CreateDirectory(into);
|
||||
foreach (var f in Directory.GetFiles(from))
|
||||
{
|
||||
var to = Path.Combine(into, Path.GetFileName(f));
|
||||
if (File.Exists(to)) File.SetAttributes(to, FileAttributes.Normal);
|
||||
File.Move(f, to, true);
|
||||
}
|
||||
foreach (var d in Directory.GetDirectories(from)) MoveOver(d, Path.Combine(into, Path.GetFileName(d)));
|
||||
}
|
||||
}
|
||||
640
launcher/Logic/Mods/ModManager.cs
Normal file
640
launcher/Logic/Mods/ModManager.cs
Normal file
@@ -0,0 +1,640 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A game folder's mods folder: list, on/off, order, remove, add from an archive, and the "Build again to apply" mark
|
||||
/// (old Mods.cs and Shell.Mods.cs, with their hooks as instance settings rather than statics).</summary>
|
||||
public sealed class ModManager
|
||||
{
|
||||
readonly TriforceContext ctx;
|
||||
public ModManager(TriforceContext ctx)
|
||||
{
|
||||
this.ctx = ctx;
|
||||
GameRuns = folder => new Game(ctx).IsRunning(folder);
|
||||
Tar = DefaultTar;
|
||||
}
|
||||
|
||||
/// <summary>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).</summary>
|
||||
public long MaxBytes { get; set; } = 32L << 30;
|
||||
public int MaxFiles { get; set; } = 200000;
|
||||
/// <summary>Does the game of this game folder run? Asked before every change (a test puts its own answer here).</summary>
|
||||
public Func<string, bool> GameRuns { get; set; }
|
||||
/// <summary>The tar that reads .7z and .rar: Windows' own System32\tar.exe (bsdtar), never whatever "tar" the PATH names; Linux
|
||||
/// bsdtar (libarchive) when installed: GNU tar reads neither. Null: none.</summary>
|
||||
public Func<string?> Tar { get; set; }
|
||||
|
||||
static string? DefaultTar()
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var tar = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "tar.exe");
|
||||
return File.Exists(tar) ? tar : null;
|
||||
}
|
||||
foreach (var p in new[] { "/usr/bin/bsdtar", "/bin/bsdtar", "/usr/local/bin/bsdtar" })
|
||||
if (File.Exists(p)) return p;
|
||||
return null;
|
||||
}
|
||||
|
||||
static StringComparison PathCase => OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
static bool Same(string a, string b) => string.Equals(a, b, PathCase);
|
||||
static string Hex8() => Guid.NewGuid().ToString("N").Substring(0, 8);
|
||||
static string Full(string path) => Path.GetFullPath(path).TrimEnd('\\', '/');
|
||||
static char Sep => Path.DirectorySeparatorChar;
|
||||
|
||||
// ---- only inside the mods folder ----
|
||||
|
||||
/// <summary>Is the path the mods folder or inside it? Every folder made, renamed or written to is asked this first.</summary>
|
||||
public static bool Inside(string mods, string path) => TriforceContext.Inside(mods, path);
|
||||
|
||||
void Within(string mods, string path)
|
||||
{
|
||||
if (!Inside(mods, path)) throw new InvalidOperationException("The launcher would have written outside the mods folder (" + path + "), and did not.");
|
||||
ctx.Require(path);
|
||||
}
|
||||
|
||||
void MakeFolder(string mods, string dir)
|
||||
{
|
||||
Within(mods, dir);
|
||||
Directory.CreateDirectory(dir);
|
||||
}
|
||||
|
||||
void MoveFolder(string mods, string from, string to)
|
||||
{
|
||||
Within(mods, from);
|
||||
Within(mods, to);
|
||||
Directory.Move(from, to);
|
||||
}
|
||||
|
||||
void Refuse(string mods)
|
||||
{
|
||||
if (GameRuns(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 Array.Empty<string>(); }
|
||||
}
|
||||
|
||||
// ---- the list ----
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public 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 = Mods.Compare(Mods.Place(a.Rel), Mods.Place(b.Rel));
|
||||
return c != 0 ? c : string.CompareOrdinal(a.Rel, b.Rel);
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>The mods of a game folder.</summary>
|
||||
public List<Mod> ListGame(string game, bool carried = true) => List(Mods.FolderOf(game), carried);
|
||||
|
||||
static void Walk(string dir, string rel, int depth, string? offAbove, List<Mod> found, bool carried)
|
||||
{
|
||||
var folder = depth > 0 ? Path.GetFileName(dir) : "";
|
||||
var (isOff, number, name) = Mods.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(Path.Combine(dir, part)) || part != "cheats" && File.Exists(Path.Combine(dir, part));
|
||||
if (depth > 0 && Mods.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, Info = ReadInfo(dir),
|
||||
};
|
||||
if (carried) Fill(m);
|
||||
found.Add(m);
|
||||
return;
|
||||
}
|
||||
if (depth >= 4) return;
|
||||
foreach (var sub in Folders(dir))
|
||||
{
|
||||
var child = 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>triforce_mod.json beside a mod, when it came from GameBanana (the old Setup did not read it: vk_mods.h's mismatch).</summary>
|
||||
public static ModInfo? ReadInfo(string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(dir, "triforce_mod.json");
|
||||
if (!File.Exists(file)) return null;
|
||||
using var doc = JsonDocument.Parse(File.ReadAllText(file));
|
||||
var r = doc.RootElement;
|
||||
string? S(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
|
||||
long N(string n) => r.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out var x) ? x : 0;
|
||||
return new ModInfo(S("name"), S("author"), S("page"), N("gamebanana_id"), S("gamebanana_model") == "Wip", S("file"), N("file_date"));
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>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 (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 the game's own sounds and music the App plays.)</summary>
|
||||
public 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) || Mods.IsLink(at)) return null;
|
||||
at = Path.Combine(at, parts[i]);
|
||||
if (i == parts.Length - 1) return File.Exists(at) ? at : null;
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
foreach (var m in Enumerable.Reverse(List(Mods.FolderOf(game), false)).Where(m => m.On))
|
||||
if (In(Path.Combine(m.Path, "romfs")) is { } theirs) return theirs;
|
||||
var own = Path.Combine(new[] { game, "romfs" }.Concat(parts).ToArray());
|
||||
return File.Exists(own) ? own : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>What a mod carries: its RomFS files as the game indexes them (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.</summary>
|
||||
static void Fill(Mod m)
|
||||
{
|
||||
var romfs = Path.Combine(m.Path, "romfs");
|
||||
if (Directory.Exists(romfs))
|
||||
{
|
||||
if (Mods.IsLink(romfs)) m.RomfsIsLink = true;
|
||||
else Index(m, romfs, "", 0);
|
||||
}
|
||||
m.Files.Sort(string.CompareOrdinal);
|
||||
m.Patches = Count(Path.Combine(m.Path, "exefs"));
|
||||
m.Cheats = Count(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(Mods.Key(path));
|
||||
try { m.Bytes += ((FileInfo)e).Length; } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int Count(string dir)
|
||||
{
|
||||
try { return Directory.Exists(dir) && !Mods.IsLink(dir) ? Directory.GetFiles(dir, "*", SearchOption.AllDirectories).Length : 0; }
|
||||
catch (Exception) { return 0; }
|
||||
}
|
||||
|
||||
// ---- what the game must be built again for ----
|
||||
|
||||
/// <summary>The mark of the mods' code the game folder was last built with (ModsBuilt "<game>|<mark>"), null when none is kept for it.</summary>
|
||||
public string? BuiltMark(string game) =>
|
||||
ctx.Settings.ModsBuilt is { } kept && kept.StartsWith(game + "|", StringComparison.OrdinalIgnoreCase) ? kept.Substring(game.Length + 1) : null;
|
||||
|
||||
/// <summary>A build of this game folder ended well: its mods' code patches are in it as they are now.</summary>
|
||||
public void MarkBuilt(string game) => ctx.Settings.ModsBuilt = game + "|" + Mods.CodeState(ListGame(game));
|
||||
|
||||
/// <summary>A mod with code patches changed before any build was marked: built in or not, the game is not as its mods are.</summary>
|
||||
public void MarkChanged(string game)
|
||||
{
|
||||
if (BuiltMark(game) == null) ctx.Settings.ModsBuilt = game + "|changed";
|
||||
}
|
||||
|
||||
/// <summary>"Build again to apply" (old Shell.Mods.cs ModsRefresh): the code patches of the mods that are on are not the ones of the
|
||||
/// last build. Then BuildRunner with BuildRequest.Update(game) (refused while the game runs).</summary>
|
||||
public bool NeedsRebuild(string game) => Mods.NeedsBuild(Mods.CodeState(ListGame(game)), BuiltMark(game));
|
||||
|
||||
// ---- on and off ----
|
||||
|
||||
/// <summary>Switches a mod on or off by its folder's name: "-" in front of it, or no - and _ there. Returns its folder now.</summary>
|
||||
public 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, _, _) = Mods.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 target = Path.Combine(Path.GetDirectoryName(mod.Path)!, 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.");
|
||||
}
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: " + mod.Name + " switched " + (on ? "on" : "off"));
|
||||
return target;
|
||||
}
|
||||
|
||||
// ---- the order ----
|
||||
|
||||
/// <summary>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 moves with the folder of the mods
|
||||
/// folder it is in. False when it is at that end already.</summary>
|
||||
public bool Move(string mods, Mod mod, bool later)
|
||||
{
|
||||
Refuse(mods);
|
||||
var tops = Mods.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);
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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) = Mods.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 = 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 = Mods.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, Path.Combine(mods, from), 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, Path.Combine(mods, done[i].To), 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 ----
|
||||
|
||||
/// <summary>Takes a mod out of the game's sight: its folder moves into mods\.removed (under a free name). Nothing is deleted.</summary>
|
||||
public 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 = Path.Combine(mods, Mods.Removed);
|
||||
try
|
||||
{
|
||||
MakeFolder(mods, bin);
|
||||
var target = Free(bin, mod.Folder.TrimStart('-', '_') is { Length: > 0 } n ? n : "mod");
|
||||
MoveFolder(mods, mod.Path, target);
|
||||
if (mod.Built) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: " + mod.Name + " removed to " + 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.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>dir\name, or the first of "name (2)", "name (3)" ... that is not there.</summary>
|
||||
internal static string Free(string dir, string name)
|
||||
{
|
||||
for (var k = 1; ; k++)
|
||||
{
|
||||
var path = Path.Combine(dir, k == 1 ? name : name + " (" + k + ")");
|
||||
if (!Directory.Exists(path) && !File.Exists(path)) return path;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- adding from an archive ----
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public Mod Add(string mods, string archive, Action<double>? progress = null)
|
||||
{
|
||||
Refuse(mods);
|
||||
var kind = 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 = Path.Combine(mods, 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 = Path.Combine(temp, "x");
|
||||
Unpack(mods, archive, into, progress);
|
||||
var root = FindRoot(into);
|
||||
// (the mod's name: its own folder's in the archive, else the archive's)
|
||||
var given = Same(Full(root), Full(into)) || Mods.Generic(Path.GetFileName(root)) ? Path.GetFileNameWithoutExtension(archive) : Path.GetFileName(root);
|
||||
var name = Mods.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 = Mods.Tops(List(mods)).Select(t => Mods.Parse(t).Number).Where(n => n != null).Select(n => n!.Value).ToList();
|
||||
if (numbers.Count > 0 && Mods.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);
|
||||
var mod = 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.");
|
||||
if (mod.Code) MarkChanged(Path.GetDirectoryName(Full(mods))!);
|
||||
ctx.Log.Write("mods: added " + mod.Rel + " from " + Path.GetFileName(archive));
|
||||
return mod;
|
||||
}
|
||||
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(ctx.Platform.IsDiskFull(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); }
|
||||
}
|
||||
|
||||
/// <summary>The archive unpacked into a folder and checked there (names, links, sizes, counts), before anything moves.</summary>
|
||||
internal void Unpack(string mods, string archive, string into, Action<double>? progress)
|
||||
{
|
||||
var kind = Path.GetExtension(archive).ToLowerInvariant();
|
||||
if (kind == ".zip") UnpackZip(mods, archive, into, progress);
|
||||
else UnpackWithTar(mods, archive, into, kind);
|
||||
Check(into, kind != ".zip");
|
||||
}
|
||||
|
||||
/// <summary>What an adding that was cut off left in the mods folder a day ago or longer.</summary>
|
||||
void Sweep(string mods)
|
||||
{
|
||||
foreach (var d in Folders(mods))
|
||||
try
|
||||
{
|
||||
if (Regex.IsMatch(Path.GetFileName(d), "^" + Regex.Escape(Mods.Adding) + "[0-9a-f]{8}$") && DateTime.UtcNow - Directory.GetLastWriteTimeUtc(d) > TimeSpan.FromDays(1))
|
||||
Delete(mods, d);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>Removes the folder an archive was unpacked into, with what is left in it. A link in it is removed as a link.</summary>
|
||||
void Delete(string mods, string dir)
|
||||
{
|
||||
try
|
||||
{
|
||||
Within(mods, dir);
|
||||
if (!Same(Path.GetDirectoryName(Full(dir)) ?? "", Full(mods)) || !Path.GetFileName(Full(dir)).StartsWith(Mods.Adding, StringComparison.Ordinal)) return;
|
||||
Empty(dir);
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
internal 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) { }
|
||||
}
|
||||
|
||||
/// <summary>A zip, with .NET's own reader. 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.</summary>
|
||||
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 the launcher can read (" + e.Message + "). Nothing was added.");
|
||||
}
|
||||
using (zip)
|
||||
{
|
||||
System.Collections.ObjectModel.ReadOnlyCollection<ZipArchiveEntry> entries;
|
||||
try { entries = zip.Entries; }
|
||||
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 the launcher 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 (Mods.Unsafe(e.FullName, true) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Mods.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 (\"" + Mods.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 (\"" + Mods.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 (\"" + Mods.Short(e.FullName) + "\"). Nothing was unpacked.");
|
||||
if (e.Length < 0 || e.Length > MaxBytes || (total += e.Length) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (ctx.SpaceProblem("this mod", total + entries.Count * 4096L, mods) is { } none) throw new ModsException(none);
|
||||
MakeFolder(mods, into);
|
||||
var root = Full(into) + Sep;
|
||||
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 = Path.GetFullPath(Path.Combine(into, name.Replace('/', Sep)));
|
||||
if (!(dest + Sep).StartsWith(root, PathCase)) throw new ModsException("The archive holds a path that leaves its own folder: \"" + Mods.Short(e.FullName) + "\".");
|
||||
Within(mods, dest);
|
||||
if (name.EndsWith('/')) { Directory.CreateDirectory(dest); continue; }
|
||||
Directory.CreateDirectory(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 (\"" + Mods.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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.";
|
||||
|
||||
/// <summary>A .7z or .rar, with the system's bsdtar (Windows' own tar.exe). Its list is asked for first, twice: the names
|
||||
/// (checked as a zip's are) 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).</summary>
|
||||
void UnpackWithTar(string mods, string archive, string into, string kind)
|
||||
{
|
||||
var tar = Tar();
|
||||
if (tar == null)
|
||||
throw new ModsException(OperatingSystem.IsWindows()
|
||||
? "This PC has no tar.exe in its System32 folder (Windows 10 and 11 bring one), and the launcher opens " + kind + " files with nothing else." + ByHand(kind)
|
||||
: "This PC has no bsdtar (libarchive's tar; GNU tar does not read " + kind + " files)." + ByHand(kind));
|
||||
MakeFolder(mods, into);
|
||||
var (code, names, error) = Run(tar, new[] { "-tf", archive }, into, MaxFiles + 1);
|
||||
if (code != 0) throw new ModsException("This PC's tar 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 (Mods.Unsafe(n, false) is { } why) throw new ModsException("The archive holds " + why + ": \"" + Mods.Short(n) + "\". Nothing was unpacked.");
|
||||
var (code2, lines, error2) = Run(tar, new[] { "-tvf", archive }, into, MaxFiles + 1);
|
||||
if (code2 != 0 || lines.Count != names.Count) throw new ModsException("This PC's tar 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 lists the " + kind + " file in a way the launcher 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 (\"" + Mods.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 (\"" + Mods.Short(names[i]) + "\"). Nothing was unpacked.");
|
||||
if (size > MaxBytes || (total += size) > MaxBytes) throw new ModsException(TooBig());
|
||||
}
|
||||
if (ctx.SpaceProblem("this mod", total + names.Count * 4096L, mods) is { } none) throw new ModsException(none);
|
||||
Within(mods, into);
|
||||
var (code3, _, error3) = Run(tar, new[] { "-xf", archive, "-C", into }, into, 0);
|
||||
if (code3 != 0) throw new ModsException("This PC's tar 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 ? Mods.Short(line) : "exit code " + code;
|
||||
}
|
||||
|
||||
/// <summary>tar with these words, its lines (at most so many: one more and it is stopped) and what it said of errors.</summary>
|
||||
static (int Code, List<string> Lines, string Error) Run(string exe, string[] arguments, string dir, int most)
|
||||
{
|
||||
var si = new ProcessStartInfo(exe)
|
||||
{
|
||||
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = dir,
|
||||
};
|
||||
foreach (var a in arguments) si.ArgumentList.Add(a);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
void Check(string into, bool links)
|
||||
{
|
||||
var files = 0;
|
||||
long bytes = 0;
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (depth > Mods.MaxDepth) throw new ModsException("The archive's folders go more than " + Mods.MaxDepth + " deep. Nothing was added.");
|
||||
foreach (var e in new DirectoryInfo(dir).GetFileSystemInfos())
|
||||
{
|
||||
var shown = Mods.Short(e.FullName.Substring(Full(into).Length + 1));
|
||||
if ((e.Attributes & FileAttributes.ReparsePoint) != 0 || e.LinkTarget != null) throw new ModsException("The archive holds a link (\"" + shown + "\"), which could point anywhere on this PC. Nothing was added.");
|
||||
if (Mods.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 && ctx.Platform.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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
static string FindRoot(string into)
|
||||
{
|
||||
var found = new List<string>();
|
||||
void Look(string dir, int depth)
|
||||
{
|
||||
if (Mods.Parts.Any(p => Directory.Exists(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 the launcher 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 => 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 = Path.GetFileName(found[0]);
|
||||
if (!Same(Full(found[0]), Full(into)) && Regex.IsMatch(title, "^[0-9A-Fa-f]{16}$") && !string.Equals(title, Mods.TitleId, StringComparison.OrdinalIgnoreCase))
|
||||
throw new ModsException("The archive holds a mod for another game (title " + title.ToUpperInvariant() + "), not for this one (" + Mods.TitleId + "). Nothing was added.");
|
||||
return found[0];
|
||||
}
|
||||
}
|
||||
245
launcher/Logic/Mods/Mods.cs
Normal file
245
launcher/Logic/Mods/Mods.cs
Normal file
@@ -0,0 +1,245 @@
|
||||
// (Triforce) The mods of a game folder as they lie on the disk (old setup/Mods.cs, Shell.Mods.cs). 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 launcher 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-"), 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.Diagnostics;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What the Mods page tells the player when something cannot be done: a whole sentence, in plain words.</summary>
|
||||
public sealed class ModsException : Exception
|
||||
{
|
||||
public ModsException(string message) : base(message) { }
|
||||
}
|
||||
|
||||
/// <summary>One mod as the game would find it.</summary>
|
||||
public sealed class Mod
|
||||
{
|
||||
public string Path { get; set; } = ""; // (its folder, in full)
|
||||
public string Rel { get; set; } = ""; // (its place under the mods folder, "/" between folders: what the game sorts by)
|
||||
public string Top { get; set; } = ""; // (the folder of the mods folder it is, or is in)
|
||||
public string Folder { get; set; } = ""; // (its folder's name as it is on the disk)
|
||||
public string Name { get; set; } = ""; // (its own name: the folder's without the switch and the number)
|
||||
public int? Number { get; set; } // (the number its folder's name starts with, "01-", when it has one)
|
||||
public bool On { get; set; }
|
||||
public string? OffAbove { get; set; } // (the folder above it whose name switches it off, when it is not its own name that does)
|
||||
public List<string> Files { get; } = new(); // (its RomFS files as the game looks them up: lower case, "/" between folders)
|
||||
public long Bytes { get; set; }
|
||||
public int Patches { get; set; } // (the files in its exefs)
|
||||
public int Cheats { get; set; } // (the files in its cheats folder)
|
||||
public bool RomfsIsLink { get; set; } // (its romfs folder is a link, which the game leaves out)
|
||||
/// <summary>What GameBanana said of it (triforce_mod.json beside it), when it came from there.</summary>
|
||||
public ModInfo? Info { get; set; }
|
||||
|
||||
public bool Deep => Rel.IndexOf('/') >= 0;
|
||||
public bool Code => Patches > 0 || Cheats > 0;
|
||||
/// <summary>It carries code patches: what is built into the game (its cheats are read when the game starts: host/mod_cheats.c).</summary>
|
||||
public bool Built => Patches > 0;
|
||||
public override string ToString() => Rel;
|
||||
}
|
||||
|
||||
/// <summary>triforce_mod.json (written by the game's Mods menu and the launcher's GameBanana install): name, author, page, id.</summary>
|
||||
public sealed record ModInfo(string? Name, string? Author, string? Page, long GameBananaId, bool Wip, string? File, long FileDate);
|
||||
|
||||
/// <summary>A file more than one of the mods that are on carry: the last of them, in the order the game loads them, wins.</summary>
|
||||
public sealed class Conflict
|
||||
{
|
||||
public string File { get; set; } = "";
|
||||
public List<Mod> Mods { get; } = new();
|
||||
public Mod Winner => Mods[Mods.Count - 1];
|
||||
}
|
||||
|
||||
/// <summary>The rules that need no folder: names, order, the safety of an archive's names, the build mark.</summary>
|
||||
public static class Mods
|
||||
{
|
||||
/// <summary>The game this is built for: a mod in an emulator's layout names the game it is made for by this number.</summary>
|
||||
public const string TitleId = "0400486024DEC000";
|
||||
public const string BuildAgain = "Build again to apply";
|
||||
/// <summary>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).</summary>
|
||||
public const string Removed = ".removed", Adding = ".adding-", Moving = ".moving-";
|
||||
internal static readonly string[] Parts = { "romfs", "exefs", "cheats" };
|
||||
/// <summary>How deep a path in an archive may go (the game follows a RomFS 32 folders down).</summary>
|
||||
public const int MaxDepth = 40;
|
||||
|
||||
public static string FolderOf(string game) => Path.Combine(game, "mods");
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>As the game compares names (host/mods.c mod_cmp, _stricmp): byte by byte, the letters A to Z without case.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A RomFS path as the game looks it up (host/mods.c lower_slash): "/" between folders, A to Z in lower case.</summary>
|
||||
internal 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();
|
||||
}
|
||||
|
||||
/// <summary>A mod's place in the list: its path as the game sorts it, read without the switches.</summary>
|
||||
internal static string Place(string rel) => string.Join("/", rel.Split('/').Select(p => p.TrimStart('-', '_')));
|
||||
|
||||
/// <summary>What a mod carries, in words: "1,204 game files, 2 code patch files, 1 cheat file".</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The files more than one of the mods that are on carry, each with its mods in the order the game loads them.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>For one mod: each other mod it shares files with, how many, and whether this one wins them (it loads later).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Every conflict as text, for the clipboard: the file, the mods that carry it, and which one the game takes.</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>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. FNV-1a 64 over the UTF-16 units of the lines joined by \n, as 16 hex digits.</summary>
|
||||
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 = 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);
|
||||
// (the relative path as the old Setup wrote it, with \ on Windows: a mark kept by an old Setup still matches)
|
||||
lines.Add(part + f.Substring(dir.Length).ToLowerInvariant() + "|" + info.Length + "|" + info.LastWriteTimeUtc.Ticks);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (lines.Count == 0) return "";
|
||||
return InstanceLock.Fnv1a64(string.Join("\n", lines)).ToString("x16");
|
||||
}
|
||||
|
||||
/// <summary>Is the game to be built again for its mods? built is the mark kept at the last build: null when none (then any code
|
||||
/// a mod that is on carries is news), and anything that is no mark ("changed") never matches.</summary>
|
||||
public static bool NeedsBuild(string state, string? built) => built == null ? state.Length > 0 : state != built;
|
||||
|
||||
/// <summary>The folders of the mods folder that are mods or hold them, in the order the game loads them.</summary>
|
||||
public static List<string> Tops(IEnumerable<Mod> mods) => mods.Select(m => m.Top).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
|
||||
|
||||
internal static bool IsLink(string path)
|
||||
{
|
||||
try { return (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0; } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
static readonly HashSet<string> Devices = new(StringComparer.OrdinalIgnoreCase) { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
|
||||
|
||||
/// <summary>Is this a name Windows keeps for a device, with or without an extension (NUL, con.txt)? Kept on Linux too: mods and
|
||||
/// saves move between systems.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A folder's name in an archive that says nothing about the mod: an emulator's layout, or the part itself.</summary>
|
||||
internal static bool Generic(string name) =>
|
||||
Regex.IsMatch(name, "^[0-9A-Fa-f]{16}$") || new[] { "contents", "atmosphere", "mods", "mod" }.Any(g => string.Equals(g, name, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
internal static string Short(string name) => name.Length > 120 ? name.Substring(0, 117) + "..." : name;
|
||||
}
|
||||
Reference in New Issue
Block a user