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:
89
launcher/Logic/Platform/IPlatform.cs
Normal file
89
launcher/Logic/Platform/IPlatform.cs
Normal file
@@ -0,0 +1,89 @@
|
||||
// What differs between Windows and Linux, behind one face (DESIGN.md 8: "the Windows-only parts behind an IPlatform";
|
||||
// research/02 section 11 lists each Windows mechanism and its Linux equivalent). Everything else in Triforce.Logic is
|
||||
// plain .NET and the same on both.
|
||||
//
|
||||
// TRIFORCE_TEST_ROOT=<folder> (old Setup.cs Install.TestRoot) keeps a whole install inside one folder on both systems: the
|
||||
// settings are <root>\registry.txt, the shortcuts, the build's work folder, the default game folder, the emulators' saves
|
||||
// and Steam are folders inside it, and nothing outside it is written (TriforceContext.Allowed). A test run never reads or
|
||||
// writes the real registry, the real shortcuts, the real Steam or the real game.
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>Where a shortcut to the launcher goes.</summary>
|
||||
public enum ShortcutPlace
|
||||
{
|
||||
/// <summary>Windows: the desktop's Triforce.lnk. Linux: ~/Desktop/triforce-launcher.desktop when there is a desktop folder.</summary>
|
||||
Desktop,
|
||||
/// <summary>Windows: Start menu\Programs\Triforce\Triforce.lnk. Linux: ~/.local/share/applications/triforce-launcher.desktop.</summary>
|
||||
StartMenu,
|
||||
}
|
||||
|
||||
/// <summary>A shortcut's contents.</summary>
|
||||
public sealed record Shortcut(string Target, string Arguments, string WorkingDirectory, string Icon, string Description, string Name = "Triforce");
|
||||
|
||||
/// <summary>Something the App shows as a system notification (a build finished while the window was not in front, DESIGN 6).</summary>
|
||||
public sealed record LauncherNotification(string Title, string Text);
|
||||
|
||||
/// <summary>A running program: its process id, name and, when it can be read, the full path of its executable.</summary>
|
||||
public sealed record RunningProcess(int Id, string Name, string? Exe);
|
||||
|
||||
public interface IPlatform
|
||||
{
|
||||
bool IsWindows { get; }
|
||||
/// <summary>TRIFORCE_TEST_ROOT, as a full path, or null.</summary>
|
||||
string? TestRoot { get; }
|
||||
/// <summary>An environment variable as this context sees it (a test's own values first).</summary>
|
||||
string? Env(string name);
|
||||
/// <summary>The settings: HKCU\Software\Triforce (Windows), ~/.config/triforce/builder.ini (Linux), registry.txt (test run).</summary>
|
||||
ISettingsStore Settings { get; }
|
||||
|
||||
// ---- paths ----
|
||||
/// <summary>Windows %LOCALAPPDATA%\Programs\Triforce; Linux the self-update root ${XDG_DATA_HOME}/triforce/builder.</summary>
|
||||
string DefaultInstallDir { get; }
|
||||
/// <summary>make_game.py's work folder (its default --work): build_times.json, objcache, sa... (research/02 1.1, 12 section 2).</summary>
|
||||
string WorkFolder { get; }
|
||||
string DefaultGameFolder { get; }
|
||||
/// <summary>Where setup.log is written for an install folder (Windows: the folder itself; Linux ${XDG_STATE_HOME}/triforce).</summary>
|
||||
string LogFolder(string home);
|
||||
/// <summary>Where NVIDIA's DLSS SDK is fetched to: beside the tools, never inside them (an update replaces those whole).</summary>
|
||||
string NgxSdkFolder(string home);
|
||||
/// <summary>The save folder of a game folder: Windows <game>\user\save\<uid>; Linux ${XDG_DATA_HOME}/hookshot/save/<uid>.</summary>
|
||||
string SaveFolder(string game, string uid);
|
||||
/// <summary>The folders emulators keep their data in: (Roaming, Local) on Windows; (data, config) on Linux.</summary>
|
||||
(string Roaming, string Local) EmulatorDataRoots { get; }
|
||||
/// <summary>Steam folders to look in, in order (test run: <root>\Steam only).</summary>
|
||||
IReadOnlyList<string> SteamRoots();
|
||||
|
||||
// ---- shortcuts and the shell ----
|
||||
string ShortcutPath(ShortcutPlace place);
|
||||
void CreateShortcut(ShortcutPlace place, Shortcut shortcut);
|
||||
/// <summary>Removes the launcher's shortcuts (both places); quietly when one cannot be.</summary>
|
||||
void RemoveShortcuts();
|
||||
/// <summary>Explorer / xdg-open on a folder. Not in a test run (nothing opens a window there).</summary>
|
||||
void OpenFolder(string folder);
|
||||
/// <summary>The App listens and shows it (a toast, a desktop notification).</summary>
|
||||
event EventHandler<LauncherNotification>? NotificationRequested;
|
||||
void Notify(string title, string text);
|
||||
|
||||
// ---- processes ----
|
||||
/// <summary>Starts a program so that it and every program it starts can be stopped together (KillTree). Linux: setsid, its
|
||||
/// own process group; Windows: as is (taskkill /T walks the tree).</summary>
|
||||
Process StartTree(ProcessStartInfo info);
|
||||
/// <summary>Stops a program and its children, waiting up to 5 s: taskkill /PID n /T /F; kill(-pgid, SIGTERM) then SIGKILL.</summary>
|
||||
void KillTree(Process process);
|
||||
/// <summary>The running programs of these names (case-insensitive), with their executables where they can be read.</summary>
|
||||
IReadOnlyList<RunningProcess> FindProcesses(params string[] names);
|
||||
|
||||
// ---- disks ----
|
||||
/// <summary>Free bytes for this user on the disk of a folder (the nearest existing folder above it); null when unknown.</summary>
|
||||
long? FreeBytes(string folder);
|
||||
/// <summary>The disk as the player knows it: C:\ on Windows, the mount point on Linux.</summary>
|
||||
string Disk(string folder);
|
||||
/// <summary>Is this the error of a disk that filled while it was written to? (ERROR_DISK_FULL / ENOSPC)</summary>
|
||||
bool IsDiskFull(Exception? e);
|
||||
/// <summary>from over to in one step (MoveFileExW REPLACE_EXISTING|WRITE_THROUGH; rename(2)).</summary>
|
||||
void ReplaceFile(string from, string to);
|
||||
/// <summary>Does a file have a second name (a hard link)? Writing one writes the other.</summary>
|
||||
bool HasOtherName(string file);
|
||||
}
|
||||
256
launcher/Logic/Platform/LinuxPlatform.cs
Normal file
256
launcher/Logic/Platform/LinuxPlatform.cs
Normal file
@@ -0,0 +1,256 @@
|
||||
// Linux (the AppImage, the Steam Deck): the Tk builder's layout (research/12 section 2) and the equivalents research/02
|
||||
// section 11 names for each Windows mechanism. NOT run on this PC (Windows): every Linux path here is ported from the
|
||||
// Python/shell it replaces and should be checked on a real Linux machine or a Deck before release.
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
public sealed class LinuxPlatform : PlatformBase
|
||||
{
|
||||
public LinuxPlatform(IReadOnlyDictionary<string, string?>? env = null) : base(env)
|
||||
{
|
||||
Settings = TestRoot != null ? new TestRootSettingsStore(TestRoot) : new IniSettingsStore(Path.Combine(ConfigHome, "triforce", "builder.ini"));
|
||||
}
|
||||
|
||||
public override bool IsWindows => false;
|
||||
public override ISettingsStore Settings { get; }
|
||||
|
||||
string HomeDir => TestRoot ?? Env("HOME") ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||
|
||||
// (XDG, honoured as the Tk builder does: config, data, cache; the game's own saves_dir takes XDG_DATA_HOME only when absolute)
|
||||
string Xdg(string name, string fallback, string testSub)
|
||||
{
|
||||
if (TestRoot != null) return Path.Combine(TestRoot, testSub);
|
||||
return Env(name) is { Length: > 0 } v && v.StartsWith('/') ? v : Path.Combine(HomeDir, fallback);
|
||||
}
|
||||
|
||||
public string ConfigHome => Xdg("XDG_CONFIG_HOME", ".config", "config");
|
||||
public string DataHome => Xdg("XDG_DATA_HOME", Path.Combine(".local", "share"), "data");
|
||||
string CacheHome => Xdg("XDG_CACHE_HOME", ".cache", "cache");
|
||||
string StateHome => Xdg("XDG_STATE_HOME", Path.Combine(".local", "state"), "state");
|
||||
|
||||
/// <summary>linux_update.data_root(): ${HOOKSHOT_BUILDER_HOME:-${XDG_DATA_HOME:-~/.local/share}}/triforce/builder: the self-update
|
||||
/// root (current, versions/<tag>), read by the game (host/hos_update.c) and the folder launcher (hookshot-folder).</summary>
|
||||
public override string DefaultInstallDir =>
|
||||
Path.Combine(TestRoot == null && Env("HOOKSHOT_BUILDER_HOME") is { Length: > 0 } b ? b : DataHome, "triforce", "builder");
|
||||
|
||||
public override string WorkFolder => Path.Combine(CacheHome, "triforce-build");
|
||||
public override string DefaultGameFolder => Path.Combine(HomeDir, "Games", "Triforce");
|
||||
public override string LogFolder(string home) => Path.Combine(StateHome, "triforce");
|
||||
// (hookshot_builder.py ngx_sdk_dir: beside the builder's versions, kept across updates)
|
||||
public override string NgxSdkFolder(string home) => Path.Combine(DefaultInstallDir, "ngx-sdk");
|
||||
// (host/hos_main.c saves_dir: $XDG_DATA_HOME/hookshot, outside the game folder so a rebuild keeps them)
|
||||
public override string SaveFolder(string game, string uid) => Path.Combine(DataHome, "hookshot", "save", uid);
|
||||
public override (string Roaming, string Local) EmulatorDataRoots => (DataHome, ConfigHome);
|
||||
|
||||
public override IReadOnlyList<string> SteamRoots()
|
||||
{
|
||||
if (TestRoot != null) return new[] { Path.Combine(TestRoot, "Steam") };
|
||||
// (research/12 section 6, guess-level: verify on a Deck. ~/.steam/steam is a link to the real folder)
|
||||
return new[]
|
||||
{
|
||||
Path.Combine(HomeDir, ".steam", "steam"), Path.Combine(HomeDir, ".local", "share", "Steam"),
|
||||
Path.Combine(HomeDir, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam"),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- shortcuts: .desktop files ----
|
||||
|
||||
public override string ShortcutPath(ShortcutPlace place) => place == ShortcutPlace.Desktop
|
||||
? Path.Combine(HomeDir, "Desktop", "triforce-launcher.desktop")
|
||||
: Path.Combine(DataHome, "applications", "triforce-launcher.desktop");
|
||||
|
||||
public override void CreateShortcut(ShortcutPlace place, Shortcut s)
|
||||
{
|
||||
var file = ShortcutPath(place);
|
||||
if (place == ShortcutPlace.Desktop && !Directory.Exists(Path.GetDirectoryName(file))) return; // (no desktop folder: none made)
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
File.WriteAllText(file, DesktopEntry(s.Name, s.Description, s.Target, s.Arguments, s.WorkingDirectory, s.Icon), new UTF8Encoding(false));
|
||||
if (!OperatingSystem.IsWindows()) try { File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.OtherRead); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A desktop entry. Refuses CR, LF and NUL in any value (a line break would start another key: hookshot_builder.py add_to_menu).</summary>
|
||||
public static string DesktopEntry(string name, string comment, string target, string arguments, string workDir, string icon, string? wmClass = null)
|
||||
{
|
||||
foreach (var v in new[] { name, comment, target, arguments, workDir, icon, wmClass ?? "" })
|
||||
if (v.IndexOfAny(new[] { '\r', '\n', '\0' }) >= 0) throw new ArgumentException("A path or name with a line break cannot go into a menu entry.");
|
||||
var exec = DesktopExec(target) + (arguments.Length > 0 ? " " + arguments : "");
|
||||
return "[Desktop Entry]\nType=Application\nName=" + name + "\nComment=" + comment + "\nExec=" + exec + "\nPath=" + workDir + "\nIcon=" + icon +
|
||||
"\nCategories=Game;\nTerminal=false\n" + (wmClass != null ? "StartupWMClass=" + wmClass + "\n" : "");
|
||||
}
|
||||
|
||||
/// <summary>One Exec argument (hookshot_builder.py desktop_exec): a % is a field code, so it is doubled; inside the quotes the
|
||||
/// Desktop Entry spec wants " ` $ \ each preceded by a backslash, and every backslash written twice because the file's string
|
||||
/// escaping is applied first (so a literal backslash is four, and a dollar two backslashes and the dollar).</summary>
|
||||
public static string DesktopExec(string path)
|
||||
{
|
||||
var escaped = path.Replace("\\", "\\\\\\\\");
|
||||
foreach (var c in new[] { "\"", "`", "$" }) escaped = escaped.Replace(c, "\\\\" + c);
|
||||
return "\"" + escaped.Replace("%", "%%") + "\"";
|
||||
}
|
||||
|
||||
public override void RemoveShortcuts()
|
||||
{
|
||||
foreach (var p in new[] { ShortcutPlace.Desktop, ShortcutPlace.StartMenu })
|
||||
try { var f = ShortcutPath(p); if (File.Exists(f)) File.Delete(f); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected override void OpenFolderNow(string folder) =>
|
||||
Process.Start(new ProcessStartInfo("xdg-open") { ArgumentList = { folder }, UseShellExecute = false })?.Dispose();
|
||||
|
||||
// ---- processes ----
|
||||
|
||||
[DllImport("libc", SetLastError = true)]
|
||||
static extern int kill(int pid, int sig);
|
||||
const int SIGTERM = 15, SIGKILL = 9;
|
||||
|
||||
static string? Which(string name)
|
||||
{
|
||||
foreach (var dir in (Environment.GetEnvironmentVariable("PATH") ?? "/usr/bin:/bin").Split(':'))
|
||||
if (dir.Length > 0 && File.Exists(Path.Combine(dir, name))) return Path.Combine(dir, name);
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Through setsid, so the program leads a process group of its own and Stop reaches the clang and lift workers too
|
||||
/// (research/12 4.6: Process cannot start a child in a new session). A child .NET starts is no group leader, so setsid
|
||||
/// calls setsid() and execs in place: the process id is the group's id. -w: should it have to fork, it waits.</summary>
|
||||
public override Process StartTree(ProcessStartInfo info)
|
||||
{
|
||||
if (Which("setsid") is { } setsid)
|
||||
{
|
||||
var wrapped = new ProcessStartInfo(setsid)
|
||||
{
|
||||
UseShellExecute = false, WorkingDirectory = info.WorkingDirectory, CreateNoWindow = info.CreateNoWindow,
|
||||
RedirectStandardOutput = info.RedirectStandardOutput, RedirectStandardError = info.RedirectStandardError,
|
||||
RedirectStandardInput = info.RedirectStandardInput,
|
||||
StandardOutputEncoding = info.StandardOutputEncoding, StandardErrorEncoding = info.StandardErrorEncoding,
|
||||
};
|
||||
wrapped.ArgumentList.Add("-w");
|
||||
wrapped.ArgumentList.Add(info.FileName);
|
||||
foreach (var a in info.ArgumentList) wrapped.ArgumentList.Add(a);
|
||||
wrapped.Environment.Clear();
|
||||
foreach (var kv in info.Environment) wrapped.Environment[kv.Key] = kv.Value;
|
||||
return Process.Start(wrapped) ?? throw new InvalidOperationException("setsid did not start.");
|
||||
}
|
||||
return Process.Start(info) ?? throw new InvalidOperationException(info.FileName + " did not start.");
|
||||
}
|
||||
|
||||
/// <summary>kill(-pgid, SIGTERM), then SIGKILL after 5 s (the Tk builder's killpg; make_game reports an outside SIGTERM as
|
||||
/// "out of memory", but a Stop is told apart by the runner, which knows it asked).</summary>
|
||||
public override void KillTree(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (process.HasExited) return;
|
||||
if (kill(-process.Id, SIGTERM) != 0) kill(process.Id, SIGTERM);
|
||||
if (!process.WaitForExit(5000))
|
||||
{
|
||||
kill(-process.Id, SIGKILL);
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/proc/<pid>/comm (the first 15 characters of the name) and /proc/<pid>/exe.</summary>
|
||||
public override IReadOnlyList<RunningProcess> FindProcesses(params string[] names)
|
||||
{
|
||||
var found = new List<RunningProcess>();
|
||||
string[] dirs;
|
||||
try { dirs = Directory.GetDirectories("/proc"); } catch (Exception) { return found; }
|
||||
foreach (var d in dirs)
|
||||
{
|
||||
if (!int.TryParse(Path.GetFileName(d), out var pid)) continue;
|
||||
string comm;
|
||||
try { comm = File.ReadAllText(Path.Combine(d, "comm")).Trim(); } catch (Exception) { continue; }
|
||||
string? exe = null;
|
||||
try { exe = new FileInfo(Path.Combine(d, "exe")).LinkTarget; } catch (Exception) { }
|
||||
var exeName = exe != null ? Path.GetFileName(exe) : null;
|
||||
foreach (var n in names)
|
||||
if (string.Equals(comm, n.Length > 15 ? n.Substring(0, 15) : n, StringComparison.OrdinalIgnoreCase) ||
|
||||
exeName != null && string.Equals(exeName, n, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
found.Add(new RunningProcess(pid, n, exe));
|
||||
break;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- disks ----
|
||||
|
||||
// (struct statvfs, x86_64 and aarch64 glibc: eleven unsigned longs then six ints of padding)
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct StatVfs
|
||||
{
|
||||
public ulong bsize, frsize, blocks, bfree, bavail, files, ffree, favail, fsid, flag, namemax;
|
||||
public int s0, s1, s2, s3, s4, s5;
|
||||
}
|
||||
|
||||
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
|
||||
static extern int statvfs(string path, out StatVfs buf);
|
||||
|
||||
public override long? FreeBytes(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var d = Path.GetFullPath(folder); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
|
||||
if (Directory.Exists(d))
|
||||
return statvfs(d, out var s) == 0 ? (long)Math.Min(s.bavail * s.frsize, (ulong)long.MaxValue) : null;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The mount point that holds the folder (the longest one that is a prefix of it).</summary>
|
||||
public override string Disk(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var full = Path.GetFullPath(folder);
|
||||
var best = "/";
|
||||
foreach (var d in DriveInfo.GetDrives())
|
||||
{
|
||||
var root = d.RootDirectory.FullName.TrimEnd('/') + "/";
|
||||
if ((full + "/").StartsWith(root, StringComparison.Ordinal) && root.Length > best.Length) best = d.RootDirectory.FullName;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
catch (Exception) { return folder; }
|
||||
}
|
||||
|
||||
public override bool IsDiskFull(Exception? e)
|
||||
{
|
||||
for (; e != null; e = e.InnerException)
|
||||
if (e is IOException)
|
||||
{
|
||||
var code = e.HResult & 0xFFFF;
|
||||
if (code == 28 || code == 122 || code == 112 || code == 39) return true; // (ENOSPC, EDQUOT, and the Windows codes .NET may map them to)
|
||||
if (e.Message.Contains("No space left", StringComparison.OrdinalIgnoreCase) || e.Message.Contains("quota", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public override void ReplaceFile(string from, string to) => File.Move(from, to, true); // (rename(2): one step)
|
||||
|
||||
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
|
||||
static extern int lstat(string path, byte[] buf);
|
||||
|
||||
/// <summary>st_nlink > 1 (x86_64 glibc layout: st_dev 8, st_ino 8, st_nlink 8 at offset 16; the AppImage is x86_64 only).
|
||||
/// Elsewhere unknown: false.</summary>
|
||||
public override bool HasOtherName(string file)
|
||||
{
|
||||
if (RuntimeInformation.ProcessArchitecture != Architecture.X64) return false;
|
||||
try
|
||||
{
|
||||
var buf = new byte[256];
|
||||
return lstat(file, buf) == 0 && BitConverter.ToUInt64(buf, 16) > 1;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
}
|
||||
60
launcher/Logic/Platform/PlatformBase.cs
Normal file
60
launcher/Logic/Platform/PlatformBase.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>What both platforms share: the environment (with a test's own values first), TRIFORCE_TEST_ROOT, notifications.</summary>
|
||||
public abstract class PlatformBase : IPlatform
|
||||
{
|
||||
readonly IReadOnlyDictionary<string, string?>? env;
|
||||
|
||||
protected PlatformBase(IReadOnlyDictionary<string, string?>? env)
|
||||
{
|
||||
this.env = env;
|
||||
// (old Setup.cs Install.TestRoot: TRIFORCE_TEST_ROOT=<folder> keeps a whole install inside that folder)
|
||||
TestRoot = Env("TRIFORCE_TEST_ROOT") is { Length: > 0 } t ? Path.GetFullPath(t) : null;
|
||||
}
|
||||
|
||||
public string? TestRoot { get; }
|
||||
|
||||
public string? Env(string name) =>
|
||||
env != null && env.TryGetValue(name, out var v) ? v : Environment.GetEnvironmentVariable(name);
|
||||
|
||||
public abstract bool IsWindows { get; }
|
||||
public abstract ISettingsStore Settings { get; }
|
||||
public abstract string DefaultInstallDir { get; }
|
||||
public abstract string WorkFolder { get; }
|
||||
public abstract string DefaultGameFolder { get; }
|
||||
public abstract string LogFolder(string home);
|
||||
public abstract string NgxSdkFolder(string home);
|
||||
public abstract string SaveFolder(string game, string uid);
|
||||
public abstract (string Roaming, string Local) EmulatorDataRoots { get; }
|
||||
public abstract IReadOnlyList<string> SteamRoots();
|
||||
public abstract string ShortcutPath(ShortcutPlace place);
|
||||
public abstract void CreateShortcut(ShortcutPlace place, Shortcut shortcut);
|
||||
public abstract void RemoveShortcuts();
|
||||
|
||||
public void OpenFolder(string folder)
|
||||
{
|
||||
// (a test run opens no window: the old Setup skipped Explorer under a UI script too)
|
||||
if (TestRoot != null) return;
|
||||
try { OpenFolderNow(folder); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected abstract void OpenFolderNow(string folder);
|
||||
|
||||
public event EventHandler<LauncherNotification>? NotificationRequested;
|
||||
public void Notify(string title, string text) => NotificationRequested?.Invoke(this, new LauncherNotification(title, text));
|
||||
|
||||
public abstract Process StartTree(ProcessStartInfo info);
|
||||
public abstract void KillTree(Process process);
|
||||
public abstract IReadOnlyList<RunningProcess> FindProcesses(params string[] names);
|
||||
public abstract long? FreeBytes(string folder);
|
||||
public abstract string Disk(string folder);
|
||||
public abstract bool IsDiskFull(Exception? e);
|
||||
public abstract void ReplaceFile(string from, string to);
|
||||
public abstract bool HasOtherName(string file);
|
||||
|
||||
/// <summary>The platform this program runs on.</summary>
|
||||
public static IPlatform Create(IReadOnlyDictionary<string, string?>? env = null) =>
|
||||
OperatingSystem.IsWindows() ? new WindowsPlatform(env) : new LinuxPlatform(env);
|
||||
}
|
||||
226
launcher/Logic/Platform/Settings.cs
Normal file
226
launcher/Logic/Platform/Settings.cs
Normal file
@@ -0,0 +1,226 @@
|
||||
// The launcher's small settings, and the Apps-list entry that says where it is installed.
|
||||
// Windows HKCU\Software\Triforce (REG_SZ strings) and HKCU\...\Uninstall\Triforce (old Setup.cs:219-259)
|
||||
// test run <TRIFORCE_TEST_ROOT>\registry.txt: one line per value, "<key>\<name>=<value>", the last line for a name wins.
|
||||
// The same file the old Setup's test runs write, on every system
|
||||
// Linux ${XDG_CONFIG_HOME:-~/.config}/triforce/builder.ini: flat key=value lines, rewritten whole (the Tk builder's file,
|
||||
// builder/linux/hookshot_builder.py load_config/save_config, which keeps keys it does not know). The names the
|
||||
// Tk builder and hookshot-launch read are written under their names there (out, language, dlss)
|
||||
using System.Runtime.Versioning;
|
||||
using System.Text;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>The values the launcher keeps between runs (old research/02 1.2 names).</summary>
|
||||
public static class SettingNames
|
||||
{
|
||||
public const string Desktop = "Desktop", StartMenu = "StartMenu", Language = "Language", GameFolder = "GameFolder", Dlss = "Dlss",
|
||||
SetupSkip = "SetupSkip", Sounds = "Sounds", ModsBuilt = "ModsBuilt";
|
||||
// (DESIGN 10: kept per user)
|
||||
public const string MusicVolume = "MusicVolume", SoundVolume = "SoundVolume", Muted = "Muted";
|
||||
}
|
||||
|
||||
/// <summary>Where the settings are kept. Get/Set work on the settings; the Uninstall* calls on the Apps-list entry (Windows,
|
||||
/// and a test run's registry.txt; nothing elsewhere).</summary>
|
||||
public interface ISettingsStore
|
||||
{
|
||||
string? Get(string name);
|
||||
void Set(string name, string value);
|
||||
/// <summary>Every setting gone (uninstall).</summary>
|
||||
void RemoveAll();
|
||||
string? GetUninstall(string name);
|
||||
void SetUninstall(string name, string value);
|
||||
void SetUninstallNumber(string name, int value);
|
||||
void RemoveUninstall();
|
||||
}
|
||||
|
||||
/// <summary>The keys as the old Setup named them.</summary>
|
||||
static class Keys
|
||||
{
|
||||
public const string Uninstall = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Triforce";
|
||||
public const string Settings = @"Software\Triforce";
|
||||
}
|
||||
|
||||
/// <summary>HKCU, as the old Setup kept it. Only HKCU: no admin rights, nothing in HKLM.</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
sealed class RegistrySettingsStore : ISettingsStore
|
||||
{
|
||||
static string? Read(string key, string name)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(key);
|
||||
return k?.GetValue(name) as string;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
static void Write(string key, string name, object value)
|
||||
{
|
||||
using var k = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(key);
|
||||
if (value is int n) k.SetValue(name, n, Microsoft.Win32.RegistryValueKind.DWord); else k.SetValue(name, value);
|
||||
}
|
||||
|
||||
static void Remove(string key)
|
||||
{
|
||||
try { Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree(key, false); } catch (Exception) { }
|
||||
}
|
||||
|
||||
public string? Get(string name) => Read(Keys.Settings, name);
|
||||
public void Set(string name, string value) => Write(Keys.Settings, name, value);
|
||||
public void RemoveAll() => Remove(Keys.Settings);
|
||||
public string? GetUninstall(string name) => Read(Keys.Uninstall, name);
|
||||
public void SetUninstall(string name, string value) => Write(Keys.Uninstall, name, value);
|
||||
public void SetUninstallNumber(string name, int value) => Write(Keys.Uninstall, name, value);
|
||||
public void RemoveUninstall() => Remove(Keys.Uninstall);
|
||||
}
|
||||
|
||||
/// <summary>(testing: TRIFORCE_TEST_ROOT) what would go to the registry, as a text file in the test folder (old Setup.cs:228-259):
|
||||
/// "<key>\<name>=<value>", the last line for a name wins, a write rewrites the file without the name's older lines.</summary>
|
||||
sealed class TestRootSettingsStore : ISettingsStore
|
||||
{
|
||||
readonly string root, file;
|
||||
readonly object gate = new();
|
||||
public TestRootSettingsStore(string root) { this.root = root; file = Path.Combine(root, "registry.txt"); }
|
||||
|
||||
string? Read(string key, string name)
|
||||
{
|
||||
var start = key + "\\" + name + "=";
|
||||
lock (gate)
|
||||
return File.Exists(file) ? File.ReadAllLines(file).LastOrDefault(l => l.StartsWith(start, StringComparison.Ordinal))?.Substring(start.Length) : null;
|
||||
}
|
||||
|
||||
void Write(string key, string name, string value)
|
||||
{
|
||||
lock (gate)
|
||||
{
|
||||
Directory.CreateDirectory(root);
|
||||
var start = key + "\\" + name + "=";
|
||||
var lines = File.Exists(file) ? File.ReadAllLines(file).Where(l => !l.StartsWith(start, StringComparison.Ordinal)).ToList() : new List<string>();
|
||||
lines.Add(start + value);
|
||||
File.WriteAllLines(file, lines);
|
||||
}
|
||||
}
|
||||
|
||||
void Remove(string key)
|
||||
{
|
||||
lock (gate)
|
||||
if (File.Exists(file)) File.WriteAllLines(file, File.ReadAllLines(file).Where(l => !l.StartsWith(key + "\\", StringComparison.Ordinal)).ToList());
|
||||
}
|
||||
|
||||
public string? Get(string name) => Read(Keys.Settings, name);
|
||||
public void Set(string name, string value) => Write(Keys.Settings, name, value);
|
||||
public void RemoveAll() => Remove(Keys.Settings);
|
||||
public string? GetUninstall(string name) => Read(Keys.Uninstall, name);
|
||||
public void SetUninstall(string name, string value) => Write(Keys.Uninstall, name, value);
|
||||
public void SetUninstallNumber(string name, int value) => Write(Keys.Uninstall, name, value.ToString());
|
||||
public void RemoveUninstall() => Remove(Keys.Uninstall);
|
||||
}
|
||||
|
||||
/// <summary>Linux: builder.ini, the Tk builder's own file (flat key=value, split on the first =, rewritten whole). The values
|
||||
/// both read share a name: GameFolder is "out" (hookshot-launch starts the last out= line's game), Language "language",
|
||||
/// Dlss "dlss". Other keys are kept as they are, the Tk builder's too (kind, nup, romfs, exefs, prepare).</summary>
|
||||
sealed class IniSettingsStore : ISettingsStore
|
||||
{
|
||||
readonly string file;
|
||||
readonly object gate = new();
|
||||
public IniSettingsStore(string file) { this.file = file; }
|
||||
public string FilePath => file;
|
||||
|
||||
static string KeyOf(string name) => name switch
|
||||
{
|
||||
SettingNames.GameFolder => "out",
|
||||
SettingNames.Language => "language",
|
||||
SettingNames.Dlss => "dlss",
|
||||
_ => name,
|
||||
};
|
||||
|
||||
List<(string Key, string Value)> Load()
|
||||
{
|
||||
var all = new List<(string, string)>();
|
||||
try
|
||||
{
|
||||
foreach (var line in File.ReadAllLines(file, Encoding.UTF8))
|
||||
{
|
||||
var eq = line.IndexOf('=');
|
||||
if (eq < 0) continue;
|
||||
var key = line.Substring(0, eq);
|
||||
all.RemoveAll(kv => kv.Item1 == key); // (a dict in the Tk builder: the last line for a key wins)
|
||||
all.Add((key, line.Substring(eq + 1)));
|
||||
}
|
||||
}
|
||||
catch (Exception) { }
|
||||
return all;
|
||||
}
|
||||
|
||||
void Save(List<(string Key, string Value)> all)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(file)!);
|
||||
var tmp = file + ".new";
|
||||
File.WriteAllText(tmp, string.Concat(all.Select(kv => kv.Key + "=" + kv.Value + "\n")), new UTF8Encoding(false));
|
||||
File.Move(tmp, file, true);
|
||||
}
|
||||
|
||||
public string? Get(string name)
|
||||
{
|
||||
lock (gate) { var key = KeyOf(name); var hit = Load().LastOrDefault(kv => kv.Key == key); return hit.Key == null ? null : hit.Value; }
|
||||
}
|
||||
|
||||
public void Set(string name, string value)
|
||||
{
|
||||
if (value.IndexOfAny(new[] { '\n', '\r' }) >= 0) throw new ArgumentException("A setting cannot hold a line break.");
|
||||
lock (gate)
|
||||
{
|
||||
var key = KeyOf(name);
|
||||
var all = Load();
|
||||
var at = all.FindIndex(kv => kv.Key == key);
|
||||
if (at >= 0) all[at] = (key, value); else all.Add((key, value));
|
||||
Save(all);
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveAll()
|
||||
{
|
||||
lock (gate) try { if (File.Exists(file)) File.Delete(file); } catch (Exception) { }
|
||||
}
|
||||
|
||||
// (no Apps list on Linux: the launcher is the AppImage the player keeps where they like)
|
||||
public string? GetUninstall(string name) => null;
|
||||
public void SetUninstall(string name, string value) { }
|
||||
public void SetUninstallNumber(string name, int value) { }
|
||||
public void RemoveUninstall() { }
|
||||
}
|
||||
|
||||
/// <summary>The settings with their names and meanings. Writes are dropped while the context says NoWrites (old --snapshot).</summary>
|
||||
public sealed class Settings
|
||||
{
|
||||
readonly ISettingsStore store;
|
||||
readonly Func<bool> noWrites;
|
||||
internal Settings(ISettingsStore store, Func<bool> noWrites) { this.store = store; this.noWrites = noWrites; }
|
||||
|
||||
public ISettingsStore Store => store;
|
||||
public string? Get(string name) => store.Get(name);
|
||||
public void Set(string name, string value) { if (!noWrites()) store.Set(name, value); }
|
||||
|
||||
/// <summary>The game folder the last good build wrote (its @@done line).</summary>
|
||||
public string? GameFolder { get => Get(SettingNames.GameFolder) is { Length: > 0 } g ? g : null; set => Set(SettingNames.GameFolder, value ?? ""); }
|
||||
/// <summary>The game's language code (Languages.All), null when never chosen.</summary>
|
||||
public string? Language { get => Get(SettingNames.Language); set => Set(SettingNames.Language, value ?? ""); }
|
||||
/// <summary>NVIDIA DLSS chosen, its licence accepted ("1").</summary>
|
||||
public bool Dlss { get => Get(SettingNames.Dlss) == "1"; set => Set(SettingNames.Dlss, value ? "1" : "0"); }
|
||||
/// <summary>A release tag whose launcher could not start on this PC: never fetched again (research/02 2.4a).</summary>
|
||||
public string? SetupSkip { get => Get(SettingNames.SetupSkip); set => Set(SettingNames.SetupSkip, value ?? ""); }
|
||||
/// <summary>Shortcut choices, re-used when a downloaded copy reinstalls over an install (default on).</summary>
|
||||
public bool Desktop { get => Get(SettingNames.Desktop) != "0"; set => Set(SettingNames.Desktop, value ? "1" : "0"); }
|
||||
public bool StartMenu { get => Get(SettingNames.StartMenu) != "0"; set => Set(SettingNames.StartMenu, value ? "1" : "0"); }
|
||||
/// <summary>"<gameFolder>|<16 hex CodeState>" or "<gameFolder>|changed" (Mods.CodeState).</summary>
|
||||
public string? ModsBuilt { get => Get(SettingNames.ModsBuilt); set => Set(SettingNames.ModsBuilt, value ?? ""); }
|
||||
/// <summary>The old sound level: off / low / medium / high.</summary>
|
||||
public string? Sounds { get => Get(SettingNames.Sounds); set => Set(SettingNames.Sounds, value ?? ""); }
|
||||
/// <summary>DESIGN 10: 0..100, default 40.</summary>
|
||||
public int MusicVolume { get => Percent(SettingNames.MusicVolume, 40); set => Set(SettingNames.MusicVolume, Math.Clamp(value, 0, 100).ToString()); }
|
||||
/// <summary>DESIGN 10: 0..100, default 70.</summary>
|
||||
public int SoundVolume { get => Percent(SettingNames.SoundVolume, 70); set => Set(SettingNames.SoundVolume, Math.Clamp(value, 0, 100).ToString()); }
|
||||
public bool Muted { get => Get(SettingNames.Muted) == "1"; set => Set(SettingNames.Muted, value ? "1" : "0"); }
|
||||
|
||||
int Percent(string name, int fallback) => int.TryParse(Get(name), out var v) && v >= 0 && v <= 100 ? v : fallback;
|
||||
}
|
||||
199
launcher/Logic/Platform/WindowsPlatform.cs
Normal file
199
launcher/Logic/Platform/WindowsPlatform.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
// Windows: what the old WPF Setup did, without its window (research/02 sections 1, 5, 11).
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
[SupportedOSPlatform("windows")]
|
||||
public sealed class WindowsPlatform : PlatformBase
|
||||
{
|
||||
public WindowsPlatform(IReadOnlyDictionary<string, string?>? env = null) : base(env)
|
||||
{
|
||||
Settings = TestRoot != null ? new TestRootSettingsStore(TestRoot) : new RegistrySettingsStore();
|
||||
}
|
||||
|
||||
public override bool IsWindows => true;
|
||||
public override ISettingsStore Settings { get; }
|
||||
|
||||
/// <summary>%LOCALAPPDATA%, or the test folder (old Setup.cs Install.LocalData).</summary>
|
||||
string LocalData => TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
||||
|
||||
public override string DefaultInstallDir => Path.Combine(LocalData, "Programs", "Triforce");
|
||||
// (make_game.py's own default --work is %LOCALAPPDATA%\Triforce\build; a test run passes --work <root>\build)
|
||||
public override string WorkFolder => TestRoot != null ? Path.Combine(TestRoot, "build") : Path.Combine(LocalData, "Triforce", "build");
|
||||
public override string DefaultGameFolder => Path.Combine(TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Games", "Triforce");
|
||||
public override string LogFolder(string home) => home;
|
||||
public override string NgxSdkFolder(string home) => Path.Combine(home, "ngx-sdk");
|
||||
public override string SaveFolder(string game, string uid) => Path.Combine(game, "user", "save", uid);
|
||||
public override (string Roaming, string Local) EmulatorDataRoots => TestRoot != null
|
||||
? (Path.Combine(TestRoot, "Roaming"), Path.Combine(TestRoot, "Local"))
|
||||
: (Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
|
||||
|
||||
public override IReadOnlyList<string> SteamRoots()
|
||||
{
|
||||
if (TestRoot != null) return new[] { Path.Combine(TestRoot, "Steam") };
|
||||
// (Steam's folder as Steam wrote it into the registry (read, never written), else the usual one: old Steam.cs FromRegistry)
|
||||
string? folder = null;
|
||||
try
|
||||
{
|
||||
using var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Valve\Steam", false);
|
||||
folder = key?.GetValue("SteamPath") as string;
|
||||
}
|
||||
catch (Exception) { }
|
||||
var list = new List<string>();
|
||||
if (!string.IsNullOrWhiteSpace(folder)) try { list.Add(Path.GetFullPath(folder.Replace('/', '\\'))); } catch (Exception) { }
|
||||
list.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Steam"));
|
||||
return list;
|
||||
}
|
||||
|
||||
// ---- shortcuts ----
|
||||
|
||||
public override string ShortcutPath(ShortcutPlace place) => place == ShortcutPlace.Desktop
|
||||
? Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Desktop") : Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Triforce.lnk")
|
||||
: Path.Combine(StartFolder, "Triforce.lnk");
|
||||
|
||||
string StartFolder => Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Start Menu") : Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Triforce");
|
||||
|
||||
/// <summary>A .lnk through the WScript.Shell COM object (old Setup.cs Shortcut).</summary>
|
||||
public override void CreateShortcut(ShortcutPlace place, Shortcut s)
|
||||
{
|
||||
var link = ShortcutPath(place);
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(link)!);
|
||||
var type = Type.GetTypeFromProgID("WScript.Shell") ?? throw new InvalidOperationException("WScript.Shell is not on this PC.");
|
||||
var shell = Activator.CreateInstance(type)!;
|
||||
try
|
||||
{
|
||||
var lnk = type.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[] { link })!;
|
||||
var t = lnk.GetType();
|
||||
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[] { s.Target });
|
||||
t.InvokeMember("Arguments", BindingFlags.SetProperty, null, lnk, new object[] { s.Arguments });
|
||||
t.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, lnk, new object[] { s.WorkingDirectory });
|
||||
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[] { s.Icon + ",0" });
|
||||
t.InvokeMember("Description", BindingFlags.SetProperty, null, lnk, new object[] { s.Description });
|
||||
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
|
||||
Marshal.FinalReleaseComObject(lnk);
|
||||
}
|
||||
finally { Marshal.FinalReleaseComObject(shell); }
|
||||
}
|
||||
|
||||
public override void RemoveShortcuts()
|
||||
{
|
||||
try { var f = ShortcutPath(ShortcutPlace.Desktop); if (File.Exists(f)) File.Delete(f); } catch (Exception) { }
|
||||
try { if (Directory.Exists(StartFolder)) Directory.Delete(StartFolder, true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
protected override void OpenFolderNow(string folder) =>
|
||||
Process.Start(new ProcessStartInfo("explorer.exe", "\"" + folder + "\"") { UseShellExecute = true })?.Dispose();
|
||||
|
||||
// ---- processes ----
|
||||
|
||||
public override Process StartTree(ProcessStartInfo info) => Process.Start(info) ?? throw new InvalidOperationException(info.FileName + " did not start.");
|
||||
|
||||
/// <summary>taskkill /PID n /T /F, waiting up to 5 s (old Setup.cs Runner.Cancel).</summary>
|
||||
public override void KillTree(Process process)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (process.HasExited) return;
|
||||
using var k = Process.Start(new ProcessStartInfo("taskkill", "/PID " + process.Id + " /T /F") { CreateNoWindow = true, UseShellExecute = false });
|
||||
k?.WaitForExit(5000);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
try { process.Kill(entireProcessTree: true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
public override IReadOnlyList<RunningProcess> FindProcesses(params string[] names)
|
||||
{
|
||||
var found = new List<RunningProcess>();
|
||||
foreach (var n in names)
|
||||
foreach (var p in Process.GetProcessesByName(n))
|
||||
using (p)
|
||||
{
|
||||
string? exe = null;
|
||||
try { exe = p.MainModule?.FileName; } catch (Exception) { }
|
||||
found.Add(new RunningProcess(p.Id, n, exe));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// ---- disks ----
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool GetDiskFreeSpaceExW(string folder, out ulong forCaller, out ulong total, out ulong free);
|
||||
|
||||
public override long? FreeBytes(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
for (var d = Path.GetFullPath(folder); !string.IsNullOrEmpty(d); d = Path.GetDirectoryName(d))
|
||||
if (Directory.Exists(d))
|
||||
return GetDiskFreeSpaceExW(d, out var mine, out _, out _) ? (long)Math.Min(mine, (ulong)long.MaxValue) : null;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return null;
|
||||
}
|
||||
|
||||
public override string Disk(string folder)
|
||||
{
|
||||
try { return Path.GetPathRoot(Path.GetFullPath(folder)) is { Length: > 0 } root ? root : folder; }
|
||||
catch (Exception) { return folder; }
|
||||
}
|
||||
|
||||
public override bool IsDiskFull(Exception? e)
|
||||
{
|
||||
for (; e != null; e = e.InnerException)
|
||||
if (e is IOException && (uint)e.HResult >> 16 == 0x8007 && ((e.HResult & 0xFFFF) == 112 || (e.HResult & 0xFFFF) == 39))
|
||||
return true; // (ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL)
|
||||
return false;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
static extern bool MoveFileExW(string from, string to, int flags);
|
||||
|
||||
public override void ReplaceFile(string from, string to)
|
||||
{
|
||||
if (!MoveFileExW(from, to, 1 | 8)) // (MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)
|
||||
throw new IOException("Could not put " + to + " in place (Windows error " + Marshal.GetLastWin32Error() + ").");
|
||||
}
|
||||
|
||||
// (BY_HANDLE_FILE_INFORMATION: its three times are pairs of 32-bit numbers, so nothing in it is aligned to 8 bytes)
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
struct FileInformation
|
||||
{
|
||||
public uint Attributes;
|
||||
public long Created, Accessed, Written;
|
||||
public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
static extern bool GetFileInformationByHandle(Microsoft.Win32.SafeHandles.SafeFileHandle file, out FileInformation information);
|
||||
|
||||
public override bool HasOtherName(string file)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var f = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return GetFileInformationByHandle(f.SafeFileHandle, out var information) && information.Links > 1;
|
||||
}
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
static extern uint GetShortPathNameW(string path, System.Text.StringBuilder into, uint size);
|
||||
|
||||
/// <summary>A folder's short name (C:\Users\LONGNA~1), which programs print for temporary files, when it has another one.</summary>
|
||||
public static string? ShortName(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var into = new System.Text.StringBuilder(1024);
|
||||
var n = GetShortPathNameW(folder, into, (uint)into.Capacity);
|
||||
return n > 0 && n < into.Capacity && !string.Equals(into.ToString(), folder, StringComparison.OrdinalIgnoreCase) ? into.ToString() : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user