casualexpiesource

cu-trainer/Ultra Paradise Linux/app/Core.cs

1579 lines · 75.0 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Globalization;
5using System.IO;
6using System.IO.Compression;
7using System.Linq;
8using System.Net;
9using System.Net.Http;
10using System.Net.Sockets;
11using System.Reflection;
12using System.Security.Cryptography;
13using System.Text;
14using System.Text.Json;
15using System.Text.RegularExpressions;
16using System.Threading;
17using System.Threading.Tasks;
18using UltraParadise.Shared;
19
20namespace UltraParadise.Linux
21{
22 internal static class Dirs
23 {
24 public static string Home => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
25 public static string Config
26 {
27 get
28 {
29 if (OperatingSystem.IsMacOS()) return Path.Combine(Home, "Library", "Application Support", "UltraParadise");
30 string x = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
31 return Path.Combine(string.IsNullOrEmpty(x) ? Path.Combine(Home, ".config") : x, "UltraParadise");
32 }
33 }
34 public static string Cache
35 {
36 get
37 {
38 if (OperatingSystem.IsMacOS()) return Path.Combine(Home, "Library", "Caches", "UltraParadise");
39 string x = Environment.GetEnvironmentVariable("XDG_CACHE_HOME");
40 return Path.Combine(string.IsNullOrEmpty(x) ? Path.Combine(Home, ".cache") : x, "UltraParadise");
41 }
42 }
43 }
44
45 internal static class Private
46 {
47 private const UnixFileMode DirMode = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
48 private const UnixFileMode FileMode_ = UnixFileMode.UserRead | UnixFileMode.UserWrite;
49
50 public static void Dir(string d)
51 {
52 if (OperatingSystem.IsWindows()) { Directory.CreateDirectory(d); return; }
53 if (!Directory.Exists(d)) Directory.CreateDirectory(d, DirMode);
54 else File.SetUnixFileMode(d, DirMode);
55 }
56
57 public static void Write(string f, byte[] data)
58 {
59 if (OperatingSystem.IsWindows()) { File.WriteAllBytes(f, data); return; }
60 if (File.Exists(f) || new FileInfo(f).LinkTarget != null) File.Delete(f);
61 using FileStream fs = new(f, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = FileMode_ });
62 fs.Write(data, 0, data.Length);
63 }
64 }
65
66 internal static class Settings
67 {
68 private static readonly Dictionary<string, string> d = new();
69 private static string File => Path.Combine(Dirs.Config, "settings.ini");
70
71 public static void Load()
72 {
73 try
74 {
75 if (!System.IO.File.Exists(File)) return;
76 foreach (string line in System.IO.File.ReadAllLines(File))
77 {
78 int eq = line.IndexOf('=');
79 if (eq > 0) d[line[..eq].Trim()] = line[(eq + 1)..].Trim();
80 }
81 }
82 catch (Exception) { }
83 }
84
85 public static string Get(string k, string def) => d.TryGetValue(k, out string v) ? v : def;
86 public static bool On(string k, bool def) => Get(k, def ? "1" : "0") == "1";
87
88 public static IEnumerable<string> Keys() => d.Keys.ToList();
89
90 public static void Set(string k, string v)
91 {
92 if (v == null) d.Remove(k); else d[k] = v;
93 try
94 {
95 Directory.CreateDirectory(Dirs.Config);
96 System.IO.File.WriteAllLines(File, d.OrderBy(x => x.Key, StringComparer.Ordinal).Select(x => x.Key + "=" + x.Value));
97 }
98 catch (Exception) { }
99 }
100 }
101
102 internal static class Http
103 {
104 public static readonly HttpClient Client = Make();
105
106 private static HttpClient Make()
107 {
108 HttpClient c = new(new SocketsHttpHandler { AllowAutoRedirect = true, MaxAutomaticRedirections = 5, ConnectTimeout = TimeSpan.FromSeconds(15) });
109 c.Timeout = TimeSpan.FromSeconds(60);
110 c.DefaultRequestHeaders.UserAgent.ParseAdd("UltraParadiseCUTrainer-Linux/" + Program.Version);
111 return c;
112 }
113
114 public static string Sha(string file)
115 {
116 using SHA256 h = SHA256.Create();
117 using FileStream fs = System.IO.File.OpenRead(file);
118 return Convert.ToHexString(h.ComputeHash(fs)).ToLowerInvariant();
119 }
120
121 public static string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant();
122
123 public static async Task<string> Download(string url, string file, long max, long exact, Action<int> progress)
124 {
125 string err = null;
126 for (int attempt = 1; attempt <= 3; attempt++)
127 {
128 err = await DownloadOnce(url, file, max, exact, progress);
129 if (err == null) return null;
130 if (err.StartsWith("the download was bigger", StringComparison.Ordinal) || err.StartsWith("the server said 4", StringComparison.Ordinal)) return err;
131 if (attempt < 3) await Task.Delay(2000 * attempt);
132 }
133 return err + " (tried 3 times)";
134 }
135
136 private static async Task<string> DownloadOnce(string url, string file, long max, long exact, Action<int> progress)
137 {
138 using CancellationTokenSource cts = new();
139 try
140 {
141 cts.CancelAfter(TimeSpan.FromSeconds(90));
142 using HttpResponseMessage res = await Client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, cts.Token);
143 if (res.StatusCode != HttpStatusCode.OK) return "the server said " + (int)res.StatusCode;
144 await using Stream s = await res.Content.ReadAsStreamAsync(cts.Token);
145 await using FileStream fs = new(file, FileMode.Create, FileAccess.Write);
146 byte[] buf = new byte[65536];
147 long total = 0, size = exact > 0 ? exact : res.Content.Headers.ContentLength ?? 0;
148 int n, last = -1;
149 while (true)
150 {
151 cts.CancelAfter(TimeSpan.FromSeconds(20));
152 n = await s.ReadAsync(buf, cts.Token);
153 if (n <= 0) break;
154 total += n;
155 if (total > max || (exact > 0 && total > exact)) return "the download was bigger than expected";
156 await fs.WriteAsync(buf.AsMemory(0, n));
157 if (size > 0 && progress != null)
158 {
159 int pc = (int)(total * 100 / size);
160 if (pc != last) { last = pc; progress(pc); }
161 }
162 }
163 if (exact > 0 && total != exact) return "the download was cut short";
164 return null;
165 }
166 catch (OperationCanceledException) { return "the download stalled"; }
167 catch (HttpRequestException e) { return "the connection dropped (" + e.Message + ")"; }
168 catch (IOException e) { return "the connection dropped (" + e.Message + ")"; }
169 }
170 }
171
172 internal sealed class LinkServer
173 {
174 public const string CodeVersion = "L1";
175 private TcpListener listener;
176 private readonly string token = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
177 private readonly object gate = new();
178 private TcpClient client;
179 private Stream stream;
180 public int Port { get; private set; }
181 public volatile bool IsConnected;
182 public volatile string GameCode;
183 public event Action<string> Line;
184 public event Action Connected, Disconnected;
185 private string linkFile;
186
187 public void Start()
188 {
189 listener = new TcpListener(IPAddress.Loopback, 0);
190 listener.Start();
191 Port = ((IPEndPoint)listener.LocalEndpoint).Port;
192 Thread t = new(AcceptLoop) { IsBackground = true, Name = "link accept" };
193 t.Start();
194 }
195
196 public void WriteLinkFile(string gameDir)
197 {
198 try
199 {
200 string dir = Path.Combine(gameDir, "UltraParadise");
201 string f = Path.Combine(dir, "link.txt");
202 string want = Port + " " + token;
203 if (f == linkFile && System.IO.File.Exists(f) && System.IO.File.ReadAllText(f).Trim() == want) return;
204 if (!Directory.Exists(gameDir)) return;
205 Private.Dir(dir);
206 string tmp = f + ".tmp";
207 Private.Write(tmp, Encoding.ASCII.GetBytes(want));
208 System.IO.File.Move(tmp, f, true);
209 if (linkFile != null && linkFile != f) RemoveLinkFile();
210 linkFile = f;
211 }
212 catch (Exception) { }
213 }
214
215 public void RemoveLinkFile()
216 {
217 try { if (linkFile != null && System.IO.File.Exists(linkFile)) System.IO.File.Delete(linkFile); } catch (Exception) { }
218 }
219
220 private void AcceptLoop()
221 {
222 while (true)
223 {
224 TcpClient c;
225 try { c = listener.AcceptTcpClient(); }
226 catch (Exception) { return; }
227 Thread t = new(() => Session(c)) { IsBackground = true, Name = "link session" };
228 t.Start();
229 }
230 }
231
232 private static string ReadLine(Stream s, int max)
233 {
234 MemoryStream ms = new();
235 while (true)
236 {
237 int b = s.ReadByte();
238 if (b < 0) return ms.Length > 0 ? Encoding.UTF8.GetString(ms.ToArray()) : null;
239 if (b == '\n') return Encoding.UTF8.GetString(ms.ToArray()).TrimEnd('\r');
240 if (ms.Length >= max) throw new IOException("line too long");
241 ms.WriteByte((byte)b);
242 }
243 }
244
245 private void Session(TcpClient c)
246 {
247 bool mine = false;
248 try
249 {
250 c.NoDelay = true;
251 c.ReceiveTimeout = 5000;
252 Stream s = new BufferedStream(c.GetStream(), 65536);
253 string hello = ReadLine(s, 256);
254 string[] p = hello == null ? Array.Empty<string>() : hello.Split(' ');
255 if (p.Length < 3 || p[0] != "HELLO" || !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(p[1]), Encoding.ASCII.GetBytes(token))) return;
256 c.ReceiveTimeout = 0;
257 lock (gate)
258 {
259 try { client?.Close(); } catch (Exception) { }
260 client = c;
261 stream = c.GetStream();
262 mine = true;
263 }
264 GameCode = p[2];
265 Raw("OK");
266 IsConnected = true;
267 Connected?.Invoke();
268 while (true)
269 {
270 string line = ReadLine(s, 16 * 1024 * 1024);
271 if (line == null) break;
272 if (line.Length > 70000 && !line.StartsWith("SFX ", StringComparison.Ordinal) && !line.StartsWith("MICON ", StringComparison.Ordinal) && !line.StartsWith("MOODLES ", StringComparison.Ordinal) && !line.StartsWith("DLOG ", StringComparison.Ordinal) && !line.StartsWith("DSNAP ", StringComparison.Ordinal) && !line.StartsWith("DSYS ", StringComparison.Ordinal) && !line.StartsWith("MODS ", StringComparison.Ordinal) && !line.StartsWith("MUSICLIST ", StringComparison.Ordinal)) continue;
273 Line?.Invoke(line);
274 }
275 }
276 catch (Exception) { }
277 finally
278 {
279 bool drop = false;
280 lock (gate)
281 {
282 if (mine && client == c) { client = null; stream = null; drop = true; }
283 }
284 try { c.Close(); } catch (Exception) { }
285 if (drop)
286 {
287 IsConnected = false;
288 Disconnected?.Invoke();
289 }
290 }
291 }
292
293 private void Raw(string s)
294 {
295 lock (gate)
296 {
297 if (stream == null) return;
298 try
299 {
300 byte[] b = Encoding.UTF8.GetBytes(s.Replace('\n', ' ').Replace('\r', ' ') + "\n");
301 stream.Write(b, 0, b.Length);
302 }
303 catch (Exception) { try { client?.Close(); } catch (Exception) { } }
304 }
305 }
306
307 public event Action<string> Sent;
308
309 public void Send(string s)
310 {
311 if (!IsConnected) return;
312 Raw(s);
313 try { Sent?.Invoke(s); } catch (Exception) { }
314 }
315 }
316
317 internal sealed class VNode
318 {
319 public string Key, Value;
320 public List<VNode> Kids;
321
322 public VNode Child(string key) => Kids?.FirstOrDefault(k => string.Equals(k.Key, key, StringComparison.OrdinalIgnoreCase));
323
324 public VNode Ensure(string key)
325 {
326 VNode n = Child(key);
327 if (n != null && n.Kids != null) return n;
328 if (n != null) Kids.Remove(n);
329 n = new VNode { Key = key, Kids = new List<VNode>() };
330 Kids.Add(n);
331 return n;
332 }
333
334 public void SetValue(string key, string value)
335 {
336 VNode n = Child(key);
337 if (n == null || n.Kids != null)
338 {
339 if (n != null) Kids.Remove(n);
340 n = new VNode { Key = key };
341 Kids.Add(n);
342 }
343 n.Value = value;
344 }
345 }
346
347 internal static class Vdf
348 {
349 public static VNode Parse(string text)
350 {
351 int i = 0;
352 VNode root = new() { Key = "", Kids = new List<VNode>() };
353 Stack<VNode> st = new();
354 st.Push(root);
355 string pendingKey = null;
356 while (true)
357 {
358 string tok = Next(text, ref i, out bool quoted);
359 if (tok == null) break;
360 if (!quoted && tok == "{")
361 {
362 if (pendingKey == null) throw new FormatException("unexpected {");
363 VNode n = new() { Key = pendingKey, Kids = new List<VNode>() };
364 st.Peek().Kids.Add(n);
365 st.Push(n);
366 pendingKey = null;
367 }
368 else if (!quoted && tok == "}")
369 {
370 if (st.Count <= 1) throw new FormatException("unexpected }");
371 st.Pop();
372 }
373 else if (pendingKey == null) pendingKey = tok;
374 else
375 {
376 st.Peek().Kids.Add(new VNode { Key = pendingKey, Value = tok });
377 pendingKey = null;
378 }
379 }
380 if (st.Count != 1) throw new FormatException("unbalanced braces");
381 return root;
382 }
383
384 private static string Next(string t, ref int i, out bool quoted)
385 {
386 quoted = false;
387 while (i < t.Length)
388 {
389 char c = t[i];
390 if (char.IsWhiteSpace(c)) { i++; continue; }
391 if (c == '/' && i + 1 < t.Length && t[i + 1] == '/') { while (i < t.Length && t[i] != '\n') i++; continue; }
392 break;
393 }
394 if (i >= t.Length) return null;
395 if (t[i] == '{' || t[i] == '}') return t[i++].ToString();
396 StringBuilder sb = new();
397 if (t[i] == '"')
398 {
399 quoted = true;
400 i++;
401 while (i < t.Length && t[i] != '"')
402 {
403 if (t[i] == '\\' && i + 1 < t.Length)
404 {
405 char e = t[i + 1];
406 sb.Append(e == 'n' ? '\n' : e == 't' ? '\t' : e);
407 i += 2;
408 continue;
409 }
410 sb.Append(t[i++]);
411 }
412 if (i >= t.Length) throw new FormatException("unterminated string");
413 i++;
414 return sb.ToString();
415 }
416 while (i < t.Length && !char.IsWhiteSpace(t[i]) && t[i] != '{' && t[i] != '}' && t[i] != '"') sb.Append(t[i++]);
417 return sb.ToString();
418 }
419
420 private static string Q(string s) => "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\t", "\\t") + "\"";
421
422 public static string Write(VNode root)
423 {
424 StringBuilder sb = new();
425 foreach (VNode k in root.Kids) Write(sb, k, 0);
426 return sb.ToString();
427 }
428
429 private static void Write(StringBuilder sb, VNode n, int depth)
430 {
431 string ind = new('\t', depth);
432 if (n.Kids == null) { sb.Append(ind).Append(Q(n.Key)).Append("\t\t").Append(Q(n.Value ?? "")).Append('\n'); return; }
433 sb.Append(ind).Append(Q(n.Key)).Append('\n').Append(ind).Append("{\n");
434 foreach (VNode k in n.Kids) Write(sb, k, depth + 1);
435 sb.Append(ind).Append("}\n");
436 }
437 }
438
439 internal static class Game
440 {
441 public const string AppId = "4576490";
442 public const string Exe = "CasualtiesUnknown.exe";
443 public const string Overrides = "WINEDLLOVERRIDES=\"winhttp,version=n,b\"";
444 public const string LaunchOption = Overrides + " %command%";
445 public const string BepVersion = "5.4.23.6";
446 private const string BepZipUrl = "https://github.com/BepInEx/BepInEx/releases/download/v5.4.23.6/BepInEx_win_x64_5.4.23.6.zip";
447 private const string BepSha = "6c57a714a892efb4e9e1fef63d608a3391f30ec984031c465404e4ee381a0755";
448 public const string PluginFolder = "UltraParadise";
449 public const string PluginFile = "UltraParadise.CUTrainer.dll";
450
451 public static string Current;
452
453 public static bool IsGameDir(string d) => !string.IsNullOrEmpty(d) && File.Exists(Path.Combine(d, Exe));
454
455 public static List<string> SteamRoots()
456 {
457 List<string> c = new();
458 string h = Dirs.Home;
459 if (OperatingSystem.IsWindows())
460 {
461 c.Add(@"C:\Program Files (x86)\Steam");
462 c.Add(@"C:\Program Files\Steam");
463 }
464 else
465 {
466 c.Add(Path.Combine(h, ".steam", "steam"));
467 c.Add(Path.Combine(h, ".steam", "root"));
468 c.Add(Path.Combine(h, ".local", "share", "Steam"));
469 c.Add(Path.Combine(h, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam"));
470 c.Add(Path.Combine(h, ".var", "app", "com.valvesoftware.Steam", "data", "Steam"));
471 c.Add(Path.Combine(h, "snap", "steam", "common", ".local", "share", "Steam"));
472 }
473 List<string> o = new();
474 HashSet<string> seen = new(StringComparer.Ordinal);
475 foreach (string p in c)
476 {
477 try
478 {
479 if (!Directory.Exists(p)) continue;
480 string real = Real(p);
481 if (seen.Add(real)) o.Add(real);
482 }
483 catch (Exception) { }
484 }
485 return o;
486 }
487
488 private static string Real(string p)
489 {
490 try
491 {
492 FileSystemInfo t = new DirectoryInfo(p).ResolveLinkTarget(true);
493 return Path.GetFullPath(t != null ? t.FullName : p).TrimEnd('/', '\\');
494 }
495 catch (Exception) { return Path.GetFullPath(p).TrimEnd('/', '\\'); }
496 }
497
498 public static List<string> Libraries()
499 {
500 List<string> libs = new();
501 HashSet<string> seen = new(StringComparer.Ordinal);
502 foreach (string root in SteamRoots())
503 {
504 if (seen.Add(root)) libs.Add(root);
505 try
506 {
507 string f = Path.Combine(root, "steamapps", "libraryfolders.vdf");
508 if (!File.Exists(f)) continue;
509 VNode v = Vdf.Parse(File.ReadAllText(f));
510 VNode lf = v.Child("libraryfolders") ?? v;
511 foreach (VNode n in lf.Kids ?? new List<VNode>())
512 {
513 string p = n.Kids != null ? n.Child("path")?.Value : n.Value;
514 if (string.IsNullOrEmpty(p) || !Directory.Exists(p)) continue;
515 string real = Real(p);
516 if (seen.Add(real)) libs.Add(real);
517 }
518 }
519 catch (Exception) { }
520 }
521 return libs;
522 }
523
524 public static string Find()
525 {
526 if (Mac.On) return Mac.Find();
527 foreach (string lib in Libraries())
528 {
529 try
530 {
531 string acf = Path.Combine(lib, "steamapps", "appmanifest_" + AppId + ".acf");
532 if (File.Exists(acf))
533 {
534 string dir = Vdf.Parse(File.ReadAllText(acf)).Child("AppState")?.Child("installdir")?.Value;
535 if (!string.IsNullOrEmpty(dir))
536 {
537 string d = Path.Combine(lib, "steamapps", "common", dir);
538 if (IsGameDir(d)) return d;
539 }
540 }
541 string guess = Path.Combine(lib, "steamapps", "common", "Casualties Unknown");
542 if (IsGameDir(guess)) return guess;
543 }
544 catch (Exception) { }
545 }
546 return null;
547 }
548
549 public static bool BepInstalled(string d) => IsGameDir(d) && File.Exists(Path.Combine(d, "BepInEx", "core", "BepInEx.dll")) && File.Exists(Path.Combine(d, "winhttp.dll"));
550 public static bool BepRan(string d) => File.Exists(Path.Combine(d, "BepInEx", "LogOutput.log"));
551 public static string PluginPath(string d) => Path.Combine(d, "BepInEx", "plugins", PluginFolder, PluginFile);
552
553 public const string UpDll = "UltraPara.dll";
554 public const string UpStub = "version.dll";
555
556 private static bool StubOurs(string stub)
557 {
558 try
559 {
560 byte[] b = File.ReadAllBytes(stub);
561 byte[] mark = Encoding.Unicode.GetBytes("UltraPara");
562 return b.AsSpan().IndexOf(mark) >= 0;
563 }
564 catch (Exception) { return false; }
565 }
566
567 public static string PluginState(string d)
568 {
569 if (!IsGameDir(d)) return "nogame";
570 string dll = Path.Combine(d, UpDll), stub = Path.Combine(d, UpStub);
571 if (File.Exists(stub) && !StubOurs(stub)) return "foreign";
572 if (!File.Exists(dll) || !File.Exists(stub)) return "missing";
573 try { return Http.Sha(dll) == UltraParaInfo.DllSha && Http.Sha(stub) == UltraParaInfo.StubSha ? "ok" : "old"; }
574 catch (Exception) { return "old"; }
575 }
576
577 public static string LoaderLog(string d)
578 {
579 try
580 {
581 string f = Path.Combine(d, "UltraParadise", "UltraPara.log");
582 if (!File.Exists(f)) return null;
583 using FileStream fs = new(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
584 using StreamReader r = new(fs);
585 string[] lines = r.ReadToEnd().Replace("\r", "").Split('\n', StringSplitOptions.RemoveEmptyEntries);
586 return lines.Length > 0 ? lines[^1] : null;
587 }
588 catch (Exception) { return null; }
589 }
590
591 private static byte[] ZipEntry(ZipArchive z, string name, string sha)
592 {
593 ZipArchiveEntry e = z.GetEntry(name) ?? throw new InvalidDataException(name + " is missing from the download");
594 using Stream s = e.Open();
595 using MemoryStream ms = new();
596 s.CopyTo(ms);
597 byte[] b = ms.ToArray();
598 if (Http.Sha(b) != sha) throw new InvalidDataException(name + " didn't match its fingerprint");
599 return b;
600 }
601
602 public static async Task<string> InstallPlugin(string d, Action<int> progress = null)
603 {
604 if (!IsGameDir(d)) return "the game folder wasn't found";
605 if (GameRunning()) return "close the game first";
606 string st = PluginState(d);
607 if (st == "foreign") return "your game folder already has a version.dll from another program or mod. Move it out of the game folder, then try again";
608 try
609 {
610 string cacheDir = Path.Combine(Dirs.Cache, "ultrapara");
611 Directory.CreateDirectory(cacheDir);
612 string zip = Path.Combine(cacheDir, UltraParaInfo.ZipName);
613 if (!File.Exists(zip) || Http.Sha(zip) != UltraParaInfo.ZipSha)
614 {
615 string tmp = zip + ".part";
616 string err = await Http.Download("https://updates.smellypawz.com/v1/download?app=ultrapara&version=" + UltraParaInfo.Version, tmp, 30L * 1024 * 1024, 0, progress);
617 if (err != null) { try { File.Delete(tmp); } catch (Exception) { } return "couldn't download UltraPara.dll from the update server (" + err + "). You can also get it from updates.smellypawz.com and put UltraPara.dll and version.dll in the game folder yourself"; }
618 if (Http.Sha(tmp) != UltraParaInfo.ZipSha) { File.Delete(tmp); return "the download didn't match the fingerprint built into the trainer, so nothing was installed"; }
619 File.Move(tmp, zip, true);
620 }
621 byte[] dll, stub;
622 using (ZipArchive z = ZipFile.OpenRead(zip))
623 {
624 dll = ZipEntry(z, UpDll, UltraParaInfo.DllSha);
625 stub = ZipEntry(z, UpStub, UltraParaInfo.StubSha);
626 }
627 foreach ((string name, byte[] b) in new[] { (UpDll, dll), (UpStub, stub) })
628 {
629 string p = Path.Combine(d, name);
630 File.WriteAllBytes(p + ".new", b);
631 File.Move(p + ".new", p, true);
632 }
633 string old = Path.GetDirectoryName(PluginPath(d));
634 if (Directory.Exists(old)) Directory.Delete(old, true);
635 return PluginState(d) == "ok" ? null : "UltraPara.dll was written but doesn't check out. Try again";
636 }
637 catch (Exception e) { return e.Message; }
638 }
639
640 public static string RemovePlugin(string d)
641 {
642 if (GameRunning()) return "close the game first";
643 try
644 {
645 string dll = Path.Combine(d, UpDll), stub = Path.Combine(d, UpStub);
646 if (File.Exists(stub) && StubOurs(stub)) File.Delete(stub);
647 if (File.Exists(dll)) File.Delete(dll);
648 string dir = Path.GetDirectoryName(PluginPath(d));
649 if (Directory.Exists(dir)) Directory.Delete(dir, true);
650 return null;
651 }
652 catch (Exception e) { return e.Message; }
653 }
654
655 public static string OtherCheats(string d)
656 {
657 try
658 {
659 string pl = Path.Combine(d, "BepInEx", "plugins");
660 if (!Directory.Exists(pl)) return null;
661 foreach (string f in Directory.EnumerateFiles(pl, "*.dll", SearchOption.AllDirectories))
662 if (string.Equals(Path.GetFileName(f), "CUCheats.dll", StringComparison.OrdinalIgnoreCase)) return f;
663 }
664 catch (Exception) { }
665 return null;
666 }
667
668 public static async Task<string> InstallBepInEx(string d, Action<int> progress)
669 {
670 if (!IsGameDir(d)) return "the game folder wasn't found";
671 if (GameRunning()) return "close the game first";
672 string dir = Path.Combine(Dirs.Cache, "download");
673 Directory.CreateDirectory(dir);
674 string zip = Path.Combine(dir, "BepInEx_win_x64_" + BepVersion + ".zip");
675 try
676 {
677 string err = await Http.Download(BepZipUrl, zip, 20L * 1024 * 1024, 0, progress);
678 if (err != null) return "couldn't download BepInEx: " + err;
679 if (Http.Sha(zip) != BepSha) return "the BepInEx download didn't match its official fingerprint, so nothing was installed";
680 string root = Path.GetFullPath(d).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
681 using (ZipArchive a = ZipFile.OpenRead(zip))
682 {
683 foreach (ZipArchiveEntry e in a.Entries)
684 {
685 string name = e.FullName.Replace('\\', '/');
686 if (name.Length == 0) continue;
687 string dest = Path.GetFullPath(Path.Combine(d, name));
688 if (!dest.StartsWith(root, StringComparison.Ordinal)) return "the BepInEx download had an unsafe path in it";
689 if (name.EndsWith('/')) { Directory.CreateDirectory(dest); continue; }
690 Directory.CreateDirectory(Path.GetDirectoryName(dest));
691 e.ExtractToFile(dest, true);
692 }
693 }
694 Directory.CreateDirectory(Path.Combine(d, "BepInEx", "plugins"));
695 return BepInstalled(d) ? null : "BepInEx didn't end up in the game folder";
696 }
697 catch (Exception e) { return e.Message; }
698 finally { try { File.Delete(zip); } catch (Exception) { } }
699 }
700
701 private static IEnumerable<(int pid, string comm, string cmd)> Procs()
702 {
703 if (OperatingSystem.IsWindows()) yield break;
704 string[] dirs;
705 try { dirs = Directory.GetDirectories("/proc"); } catch (Exception) { yield break; }
706 foreach (string p in dirs)
707 {
708 if (!int.TryParse(Path.GetFileName(p), out int pid)) continue;
709 string comm = "", cmd = "";
710 try { comm = File.ReadAllText(Path.Combine(p, "comm")).Trim(); } catch (Exception) { }
711 try { cmd = File.ReadAllText(Path.Combine(p, "cmdline")).Replace('\0', ' '); } catch (Exception) { }
712 yield return (pid, comm, cmd);
713 }
714 }
715
716 public static bool GameRunning()
717 {
718 if (OperatingSystem.IsWindows()) return Process.GetProcessesByName("CasualtiesUnknown").Length > 0;
719 if (Mac.On) return Mac.GameRunning();
720 foreach (var p in Procs())
721 if (p.cmd.Contains(Exe, StringComparison.OrdinalIgnoreCase) && !p.cmd.Contains("UltraParadise", StringComparison.Ordinal)) return true;
722 return false;
723 }
724
725 public static bool SteamRunning()
726 {
727 if (OperatingSystem.IsWindows()) return Process.GetProcessesByName("steam").Length > 0;
728 foreach (var p in Procs())
729 if (p.comm == "steam" || p.cmd.Contains("/ubuntu12_32/steam ", StringComparison.Ordinal) || p.cmd.EndsWith("/ubuntu12_32/steam", StringComparison.Ordinal)) return true;
730 return false;
731 }
732
733 public static List<string> LocalConfigs()
734 {
735 List<string> o = new();
736 foreach (string root in SteamRoots())
737 {
738 string ud = Path.Combine(root, "userdata");
739 if (!Directory.Exists(ud)) continue;
740 try
741 {
742 foreach (string u in Directory.GetDirectories(ud))
743 {
744 string f = Path.Combine(u, "config", "localconfig.vdf");
745 if (File.Exists(f)) o.Add(f);
746 }
747 }
748 catch (Exception) { }
749 }
750 return o;
751 }
752
753 private static VNode AppNode(VNode root, bool create)
754 {
755 VNode n = root.Child("UserLocalConfigStore");
756 if (n == null) return null;
757 foreach (string k in new[] { "Software", "Valve", "Steam", "apps", AppId })
758 {
759 VNode c = n.Child(k);
760 if (c == null || c.Kids == null)
761 {
762 if (!create) return null;
763 c = n.Ensure(k);
764 }
765 n = c;
766 }
767 return n;
768 }
769
770 public static bool HasOverride(string opts) => opts != null && System.Text.RegularExpressions.Regex.IsMatch(opts, "WINEDLLOVERRIDES=\"[^\"]*\\bversion\\b[^\"]*=n,b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
771
772 public static string LaunchOptionState()
773 {
774 if (Mac.On) return Current == null ? "unknown" : Mac.OverrideState(Current);
775 List<string> files = LocalConfigs();
776 if (files.Count == 0) return "unknown";
777 bool any = false;
778 foreach (string f in files)
779 {
780 try
781 {
782 VNode a = AppNode(Vdf.Parse(File.ReadAllText(f)), false);
783 if (HasOverride(a?.Child("LaunchOptions")?.Value)) return "set";
784 any = true;
785 }
786 catch (Exception) { }
787 }
788 return any ? "unset" : "unknown";
789 }
790
791 public static string SetLaunchOption()
792 {
793 if (Mac.On) return Current == null ? "find the game first" : Mac.SetOverride(Current);
794 if (SteamRunning()) return "Steam is running. Quit Steam fully (Steam menu > Exit), then try again. Or paste the line into the game's Properties > Launch Options yourself.";
795 List<string> files = LocalConfigs();
796 if (files.Count == 0) return "couldn't find Steam's settings. Paste the line into the game's Properties > Launch Options yourself.";
797 int done = 0;
798 string last = null;
799 foreach (string f in files)
800 {
801 try
802 {
803 string text = File.ReadAllText(f);
804 VNode root = Vdf.Parse(text);
805 VNode a = AppNode(root, true);
806 if (a == null) continue;
807 string cur = a.Child("LaunchOptions")?.Value ?? "";
808 if (HasOverride(cur)) { done++; continue; }
809 string v;
810 if (cur.Trim().Length == 0) v = LaunchOption;
811 else if (System.Text.RegularExpressions.Regex.IsMatch(cur, "WINEDLLOVERRIDES=\"[^\"]*\"")) v = System.Text.RegularExpressions.Regex.Replace(cur.Trim(), "WINEDLLOVERRIDES=\"[^\"]*\"", Overrides);
812 else if (cur.Contains("%command%", StringComparison.Ordinal)) v = Overrides + " " + cur.Trim();
813 else v = LaunchOption + " " + cur.Trim();
814 a.SetValue("LaunchOptions", v);
815 string bak = f + ".ultraparadise.bak";
816 if (!File.Exists(bak)) File.Copy(f, bak);
817 string tmp = f + ".tmp";
818 File.WriteAllText(tmp, Vdf.Write(root));
819 Vdf.Parse(File.ReadAllText(tmp));
820 File.Move(tmp, f, true);
821 done++;
822 }
823 catch (Exception e) { last = e.Message; }
824 }
825 if (done == 0) return "couldn't change Steam's settings" + (last != null ? " (" + last + ")" : "") + ". Paste the line into the game's Properties > Launch Options yourself.";
826 return null;
827 }
828
829 public static string Which(string exe)
830 {
831 foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(':').Concat(new[] { "/usr/bin", "/usr/local/bin", "/bin", "/usr/games", "/opt/homebrew/bin" }))
832 {
833 if (dir.Length == 0) continue;
834 string f = Path.Combine(dir, exe);
835 if (File.Exists(f)) return f;
836 }
837 return null;
838 }
839
840 private static async Task<bool> Try(string exe, params string[] args)
841 {
842 try
843 {
844 ProcessStartInfo si = new(exe) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true };
845 foreach (string a in args) si.ArgumentList.Add(a);
846 Process p = Process.Start(si);
847 if (p == null) return false;
848 _ = p.StandardOutput.ReadToEndAsync();
849 _ = p.StandardError.ReadToEndAsync();
850 Task done = p.WaitForExitAsync();
851 if (await Task.WhenAny(done, Task.Delay(4000)) != done) return true;
852 return p.ExitCode == 0;
853 }
854 catch (Exception) { return false; }
855 }
856
857 public static async Task<string> Start()
858 {
859 if (Mac.On) return Current == null ? "find the game first" : await Mac.Start(Current);
860 string url = "steam://rungameid/" + AppId;
861 if (OperatingSystem.IsWindows())
862 {
863 try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); return null; }
864 catch (Exception e) { return e.Message; }
865 }
866 string steam = Which("steam");
867 if (steam != null && await Try(steam, "-applaunch", AppId)) return null;
868 string flatpak = Which("flatpak");
869 if (flatpak != null && Directory.Exists(Path.Combine(Dirs.Home, ".var", "app", "com.valvesoftware.Steam")) && await Try(flatpak, "run", "com.valvesoftware.Steam", "-applaunch", AppId)) return null;
870 string snap = Which("snap");
871 if (snap != null && Directory.Exists(Path.Combine(Dirs.Home, "snap", "steam")) && await Try(snap, "run", "steam", "-applaunch", AppId)) return null;
872 string xdg = Which("xdg-open");
873 if (xdg != null && await Try(xdg, url)) return null;
874 string gio = Which("gio");
875 if (gio != null && await Try(gio, "open", url)) return null;
876 return "couldn't ask Steam to start the game. Start it from your Steam library instead.";
877 }
878
879 public static void Open(string target)
880 {
881 try
882 {
883 if (OperatingSystem.IsWindows()) Process.Start(new ProcessStartInfo(target) { UseShellExecute = true });
884 else
885 {
886 ProcessStartInfo si = new(Mac.On ? "/usr/bin/open" : "xdg-open") { UseShellExecute = false };
887 si.ArgumentList.Add(target);
888 Process.Start(si);
889 }
890 }
891 catch (Exception) { }
892 }
893 }
894
895 internal static class Nexus
896 {
897 private const string MemberId = "94954933";
898 private const string GameDomain = "scavprototype";
899 public const int TrainerModId = 1203;
900 public static string PageUrl => "https://www.nexusmods.com/" + GameDomain + "/mods/" + TrainerModId;
901
902 public static async Task<int> HashListed(string hash)
903 {
904 if (hash == null || !Regex.IsMatch(hash, "^[0-9a-f]{64}$")) return -1;
905 string q = "{ mods(filter:{ uploaderId:{ value:\"" + MemberId + "\" } }, count: 60) { nodes { modId description status game { domainName } } } }";
906 string body = JsonSerializer.Serialize(new Dictionary<string, string> { ["query"] = q });
907 using HttpRequestMessage req = new(HttpMethod.Post, "https://api.nexusmods.com/v2/graphql") { Content = new StringContent(body, Encoding.UTF8, "application/json") };
908 using HttpResponseMessage res = await Http.Client.SendAsync(req);
909 if (!res.IsSuccessStatusCode) return 0;
910 using JsonDocument doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
911 if (!doc.RootElement.TryGetProperty("data", out JsonElement data) || !data.TryGetProperty("mods", out JsonElement mods) || !mods.TryGetProperty("nodes", out JsonElement nodes)) return 0;
912 bool page = false;
913 foreach (JsonElement n in nodes.EnumerateArray())
914 {
915 if (!n.TryGetProperty("modId", out JsonElement id) || id.ValueKind != JsonValueKind.Number || id.GetInt32() != TrainerModId) continue;
916 if (!n.TryGetProperty("game", out JsonElement g) || !g.TryGetProperty("domainName", out JsonElement dn) || dn.GetString() != GameDomain) continue;
917 if (!n.TryGetProperty("status", out JsonElement st) || st.GetString() != "published") continue;
918 page = true;
919 string desc = n.TryGetProperty("description", out JsonElement de) ? de.GetString() ?? "" : "";
920 if (desc.ToLowerInvariant().Contains(hash)) return 1;
921 }
922 return page ? -1 : 0;
923 }
924 }
925
926 internal sealed class UpdateInfo
927 {
928 public string Version, Sha, Notes;
929 public long Size;
930 public VtResult Vt;
931
932 public bool VtClean => Vt != null && Vt.Clean;
933 public bool VtFlagged => Vt != null && Vt.Status == "done" && Vt.Flagged > 0;
934 public string VtLine => Vt != null ? Vt.Line : "VirusTotal: couldn't get a result right now.";
935 }
936
937 internal sealed class VtResult
938 {
939 public string Status = "unknown", Link, Sha;
940 public int Flagged, Total, Malicious, Suspicious, Undetected, Harmless;
941 public long Scanned;
942
943 public string Detail => Status != "done" ? "Engine breakdown: not ready yet." : "Malicious " + Malicious + " \u00b7 Suspicious " + Suspicious + " \u00b7 Clean " + (Undetected + Harmless) + " \u00b7 " + Total + " engines";
944
945 public bool Clean => Status == "done" && Flagged == 0 && Total > 0;
946
947 private string When => Scanned <= 0 ? "" : " Scanned " + DateTimeOffset.FromUnixTimeMilliseconds(Scanned).LocalDateTime.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + ".";
948
949 public string Line => Status switch
950 {
951 "done" => "VirusTotal: " + Flagged + " of " + Total + " antivirus engines flagged it." + When,
952 "queued" => "VirusTotal: it's being scanned right now. The result shows up within about 30 minutes.",
953 "not_official" => "VirusTotal: this copy isn't an official release, so it has no report. Get the trainer from the official Nexus page.",
954 _ => "VirusTotal: no result yet. The update server checks again every 30 minutes.",
955 };
956 }
957
958 internal static class VirusTotal
959 {
960 private const string Base = "https://updates.smellypawz.com";
961 public static VtResult Self;
962
963 public static async Task<VtResult> Lookup(string query)
964 {
965 string json = await Http.Client.GetStringAsync(Base + "/v1/vt?" + query);
966 using JsonDocument doc = JsonDocument.Parse(json);
967 JsonElement r = doc.RootElement;
968 int N(string k) => r.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.Number ? e.GetInt32() : 0;
969 VtResult v = new()
970 {
971 Status = r.TryGetProperty("status", out JsonElement s) && s.ValueKind == JsonValueKind.String ? s.GetString() : "unknown",
972 Flagged = N("malicious") + N("suspicious"),
973 Total = N("total"),
974 Malicious = N("malicious"),
975 Suspicious = N("suspicious"),
976 Undetected = N("undetected"),
977 Harmless = N("harmless"),
978 Scanned = r.TryGetProperty("scanned", out JsonElement sc) && sc.ValueKind == JsonValueKind.Number ? sc.GetInt64() : 0,
979 };
980 if (r.TryGetProperty("sha256", out JsonElement h) && h.ValueKind == JsonValueKind.String && Regex.IsMatch(h.GetString(), "^[0-9a-f]{64}$"))
981 {
982 v.Sha = h.GetString();
983 v.Link = "https://www.virustotal.com/gui/file/" + v.Sha;
984 }
985 return v;
986 }
987
988 public static Task<VtResult> ForSha(string sha) => Lookup("sha=" + sha);
989
990 public static Task<VtResult> ForThisVersion() => Lookup("app=" + (Mac.On ? "trainermac" : "trainerlinux") + "&version=" + Program.Version);
991 }
992
993 internal static class Usage
994 {
995 private const string Base = "https://updates.smellypawz.com";
996 public static string Status = "Not counted yet.";
997
998 public static long Day => (long)Math.Floor((DateTime.UtcNow - DateTime.UnixEpoch).TotalDays);
999
1000 public static string NewId() => Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLowerInvariant();
1001
1002 public static bool ValidId(string id) => id != null && Regex.IsMatch(id, "^[0-9a-f]{32}$");
1003
1004 public static async Task<bool> Ping(string id)
1005 {
1006 if (!ValidId(id)) return false;
1007 string s = await Http.Client.GetStringAsync(Base + "/v1/ping?app=trainerlinux&id=" + id + "&v=" + Program.Version + "&os=" + (Mac.On ? "mac" : "linux"));
1008 return s.Contains("\"ok\":true");
1009 }
1010
1011 public static async Task<bool> Forget(string id)
1012 {
1013 if (!ValidId(id)) return true;
1014 string s = await Http.Client.GetStringAsync(Base + "/v1/forget?app=trainerlinux&id=" + id);
1015 return s.Contains("\"ok\":true");
1016 }
1017
1018 public static async Task<string> Stats()
1019 {
1020 string json = await Http.Client.GetStringAsync(Base + "/v1/users");
1021 using JsonDocument doc = JsonDocument.Parse(json);
1022 JsonElement r = doc.RootElement;
1023 static int N(JsonElement o, string k) => o.ValueKind == JsonValueKind.Object && o.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.Number ? e.GetInt32() : 0;
1024 if (!r.TryGetProperty("week", out _)) return null;
1025 JsonElement p = r.TryGetProperty("platforms30d", out JsonElement pe) ? pe : default;
1026 CultureInfo c = CultureInfo.InvariantCulture;
1027 int mac = N(p, "mac");
1028 return "Today: " + N(r, "today").ToString("N0", c) + "\nThis week: " + N(r, "week").ToString("N0", c) + "\nThis month: " + N(r, "month").ToString("N0", c) + "\nLast 90 days: " + N(r, "last90days").ToString("N0", c)
1029 + "\n\nLast 30 days: Windows " + N(p, "win").ToString("N0", c) + " · Linux / Steam Deck " + N(p, "linux").ToString("N0", c) + (mac > 0 ? " · macOS " + mac.ToString("N0", c) : "");
1030 }
1031
1032 public static async Task<string> Count()
1033 {
1034 string json = await Http.Client.GetStringAsync(Base + "/v1/users");
1035 using JsonDocument doc = JsonDocument.Parse(json);
1036 JsonElement r = doc.RootElement;
1037 int week = r.TryGetProperty("week", out JsonElement w) && w.ValueKind == JsonValueKind.Number ? w.GetInt32() : 0;
1038 int month = r.TryGetProperty("month", out JsonElement m) && m.ValueKind == JsonValueKind.Number ? m.GetInt32() : week;
1039 return week.ToString("N0", CultureInfo.InvariantCulture) + (week == 1 ? " person" : " people") + " used the trainer this week, " + month.ToString("N0", CultureInfo.InvariantCulture) + " this month.";
1040 }
1041 }
1042
1043 internal static class Updater
1044 {
1045 private const string Base = "https://updates.smellypawz.com";
1046 private static string AppName => Mac.On ? "trainermac" : "trainerlinux";
1047 public static bool Manual => Mac.On;
1048 public static string ManualPage => Nexus.PageUrl + "?tab=files";
1049 private const long MaxBytes = 120L * 1024 * 1024;
1050 public static string Status = "Not checked yet.";
1051 public static UpdateInfo Ready;
1052
1053 public static int Compare(string a, string b)
1054 {
1055 string[] x = a.Split('.'), y = b.Split('.');
1056 for (int i = 0; i < 3; i++)
1057 {
1058 int p = i < x.Length && int.TryParse(x[i], out int px) ? px : 0;
1059 int q = i < y.Length && int.TryParse(y[i], out int qy) ? qy : 0;
1060 if (p != q) return p.CompareTo(q);
1061 }
1062 return 0;
1063 }
1064
1065 public static async Task<UpdateInfo> Check()
1066 {
1067 string json = await Http.Client.GetStringAsync(Base + "/v1/latest?app=" + AppName + "&have=" + Program.Version);
1068 using JsonDocument doc = JsonDocument.Parse(json);
1069 JsonElement r = doc.RootElement;
1070 string S(string k) => r.TryGetProperty(k, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() : null;
1071 string ver = S("version");
1072 if (ver == null || !Regex.IsMatch(ver, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$") || Compare(ver, Program.Version) <= 0) return null;
1073 if (Manual)
1074 {
1075 string mn = S("notes") ?? "";
1076 mn = mn.Replace("\\n", "\n").Replace("\r\n", "\n").Trim();
1077 return new UpdateInfo { Version = ver, Notes = mn.Length > 4000 ? mn[..4000] : mn };
1078 }
1079 string sha = S("sha256")?.ToLowerInvariant();
1080 if (sha == null || !Regex.IsMatch(sha, "^[0-9a-f]{64}$")) return null;
1081 long size = r.TryGetProperty("size", out JsonElement se) && se.ValueKind == JsonValueKind.Number ? se.GetInt64() : 0;
1082 if (size <= 0 || size > MaxBytes) return null;
1083 string notes = S("notes") ?? "";
1084 notes = notes.Replace("\\n", "\n").Replace("\r\n", "\n").Trim();
1085 if (notes.Length > 4000) notes = notes[..4000];
1086 UpdateInfo info = new() { Version = ver, Sha = sha, Size = size, Notes = notes };
1087 try { info.Vt = await VirusTotal.ForSha(sha); } catch (Exception) { info.Vt = null; }
1088 return info;
1089 }
1090
1091 public static async Task<string> Install(UpdateInfo u, Action<int> progress)
1092 {
1093 if (OperatingSystem.IsWindows()) return "updates install on Linux only";
1094 string cur = Environment.ProcessPath;
1095 if (string.IsNullOrEmpty(cur)) return "couldn't find where the trainer is";
1096 string dir = Path.Combine(Dirs.Cache, "update");
1097 try { if (Directory.Exists(dir)) Directory.Delete(dir, true); } catch (Exception) { }
1098 Private.Dir(Dirs.Cache);
1099 Private.Dir(dir);
1100 string tgz = Path.Combine(dir, "update.tar.gz");
1101 string err = await Http.Download(Base + "/v1/download?app=" + AppName + "&version=" + u.Version, tgz, MaxBytes, u.Size, progress);
1102 if (err != null) return err;
1103 if (Http.Sha(tgz) != u.Sha) return "the download didn't match its fingerprint, so it was thrown away";
1104 int listed;
1105 try { listed = await Nexus.HashListed(u.Sha); } catch (Exception) { listed = 0; }
1106 if (listed == 0) return "couldn't reach Nexus Mods to double-check the update. Try again later";
1107 if (listed < 0) return "this update isn't listed on the official Nexus page yet, so it wasn't installed";
1108 string x = Path.Combine(dir, "x");
1109 Private.Dir(x);
1110 ProcessStartInfo list = new("tar") { RedirectStandardOutput = true, UseShellExecute = false };
1111 list.ArgumentList.Add("-tzf"); list.ArgumentList.Add(tgz);
1112 using (Process p = Process.Start(list))
1113 {
1114 string names = await p.StandardOutput.ReadToEndAsync();
1115 await p.WaitForExitAsync();
1116 if (p.ExitCode != 0) return "couldn't read the update";
1117 foreach (string n in names.Split('\n', StringSplitOptions.RemoveEmptyEntries))
1118 if (n.StartsWith('/') || n.Split('/').Contains("..")) return "the update had an unsafe path in it";
1119 }
1120 ProcessStartInfo kinds = new("tar") { RedirectStandardOutput = true, UseShellExecute = false };
1121 kinds.ArgumentList.Add("-tvzf"); kinds.ArgumentList.Add(tgz);
1122 using (Process p = Process.Start(kinds))
1123 {
1124 string rows = await p.StandardOutput.ReadToEndAsync();
1125 await p.WaitForExitAsync();
1126 if (p.ExitCode != 0) return "couldn't read the update";
1127 foreach (string r in rows.Split('\n', StringSplitOptions.RemoveEmptyEntries))
1128 if (r[0] != '-' && r[0] != 'd') return "the update had a link or special file in it, so it was thrown away";
1129 }
1130 ProcessStartInfo ex = new("tar") { UseShellExecute = false };
1131 ex.ArgumentList.Add("-xzf"); ex.ArgumentList.Add(tgz); ex.ArgumentList.Add("--no-same-owner"); ex.ArgumentList.Add("-C"); ex.ArgumentList.Add(x);
1132 using (Process p = Process.Start(ex))
1133 {
1134 await p.WaitForExitAsync();
1135 if (p.ExitCode != 0) return "couldn't unpack the update";
1136 }
1137 string exe = Directory.EnumerateFiles(x, "UltraParadiseCUTrainer", SearchOption.AllDirectories).FirstOrDefault();
1138 if (exe == null || new FileInfo(exe).LinkTarget != null) return "the update didn't have the trainer in it";
1139 try
1140 {
1141 string tmp = cur + ".new";
1142 File.Copy(exe, tmp, true);
1143 File.SetUnixFileMode(tmp, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute | UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
1144 File.Move(tmp, cur, true);
1145 string icon = Path.Combine(Path.GetDirectoryName(exe), "icon.png");
1146 if (File.Exists(icon)) File.Copy(icon, Path.Combine(Path.GetDirectoryName(cur), "icon.png"), true);
1147 }
1148 catch (Exception e) { return "couldn't install the update: " + e.Message; }
1149 try { Directory.Delete(dir, true); } catch (Exception) { }
1150 try { Process.Start(new ProcessStartInfo(cur, "--updated") { UseShellExecute = false }); }
1151 catch (Exception e) { return "the update is installed, but the trainer couldn't restart itself (" + e.Message + "). Open it again."; }
1152 return null;
1153 }
1154 }
1155
1156 internal static class Bark
1157 {
1158 private static string Folder => Path.Combine(Dirs.Cache, "sounds");
1159 private static readonly Random rng = new();
1160 public static float Pitch = 1f;
1161 public static List<string> Names = new();
1162 private static string player;
1163 private static int plays;
1164 private static DateTime last = DateTime.MinValue;
1165
1166 public static void LoadSaved()
1167 {
1168 string s = Settings.Get("barkset", "");
1169 if (s.Length > 0) Parse(s);
1170 }
1171
1172 private static bool Parse(string rest)
1173 {
1174 int sp = rest.IndexOf(' ');
1175 if (sp <= 0) return false;
1176 if (!float.TryParse(rest[..sp], NumberStyles.Float, CultureInfo.InvariantCulture, out float p)) return false;
1177 List<string> names = rest[(sp + 1)..].Split(',', StringSplitOptions.RemoveEmptyEntries).Where(Ok).Take(16).ToList();
1178 if (names.Count == 0) return false;
1179 Pitch = Math.Clamp(p, 0.5f, 2f);
1180 Names = names;
1181 return true;
1182 }
1183
1184 private static bool Ok(string n) => n.Length is > 0 and <= 40 && n.All(c => char.IsAsciiLetterOrDigit(c) || c == '_' || c == '-');
1185
1186 public static List<string> OnSet(string rest)
1187 {
1188 List<string> want = new();
1189 if (!Parse(rest)) return want;
1190 Settings.Set("barkset", rest);
1191 foreach (string n in Names) if (!File.Exists(Path.Combine(Folder, n + ".wav"))) want.Add(n);
1192 return want;
1193 }
1194
1195 public static void OnSfx(string rest)
1196 {
1197 int sp = rest.IndexOf(' ');
1198 if (sp <= 0) return;
1199 string name = rest[..sp];
1200 if (!Ok(name)) return;
1201 byte[] b;
1202 try { b = Convert.FromBase64String(rest[(sp + 1)..]); } catch (Exception) { return; }
1203 if (b.Length < 44 || b.Length > 12 * 1024 * 1024 || b[0] != 'R' || b[1] != 'I' || b[2] != 'F' || b[3] != 'F' || b[8] != 'W' || b[9] != 'A' || b[10] != 'V' || b[11] != 'E') return;
1204 try
1205 {
1206 Directory.CreateDirectory(Folder);
1207 File.WriteAllBytes(Path.Combine(Folder, name + ".wav"), b);
1208 }
1209 catch (Exception) { }
1210 }
1211
1212 private static string Player()
1213 {
1214 if (player != null) return player.Length > 0 ? player : null;
1215 player = "";
1216 if (OperatingSystem.IsWindows()) return null;
1217 if (Mac.On) { player = File.Exists("/usr/bin/afplay") ? "/usr/bin/afplay" : ""; return player.Length > 0 ? player : null; }
1218 foreach (string exe in new[] { "pw-play", "paplay", "aplay" })
1219 foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "/usr/bin:/bin").Split(':'))
1220 {
1221 if (dir.Length == 0) continue;
1222 string f = Path.Combine(dir, exe);
1223 if (File.Exists(f)) { player = f; return player; }
1224 }
1225 return null;
1226 }
1227
1228 public static void Play() => Play(false);
1229
1230 public static string Play(bool test)
1231 {
1232 if (!test && (DateTime.UtcNow - last).TotalMilliseconds < 400) return null;
1233 try
1234 {
1235 List<string> have = Names.Where(n => File.Exists(Path.Combine(Folder, n + ".wav"))).ToList();
1236 if (have.Count == 0) return "No bark sounds yet. Start a run with the trainer attached once, and it picks your runner's barks up from the game.";
1237 string p = Player();
1238 if (p == null) return "No sound player found. Install pipewire (pw-play), pulseaudio-utils (paplay) or alsa-utils (aplay).";
1239 last = DateTime.UtcNow;
1240 byte[] b = File.ReadAllBytes(Path.Combine(Folder, have[rng.Next(have.Count)] + ".wav"));
1241 float pitch = Pitch * (0.92f + (float)rng.NextDouble() * 0.16f);
1242 int rate = BitConverter.ToInt32(b, 24), ch = b[22], bits = b[34];
1243 int nr = Math.Clamp((int)(rate * pitch), 8000, 192000);
1244 BitConverter.GetBytes(nr).CopyTo(b, 24);
1245 BitConverter.GetBytes(nr * ch * (bits / 8)).CopyTo(b, 28);
1246 string playDir = Path.Combine(Dirs.Cache, "play");
1247 Private.Dir(Dirs.Cache);
1248 Private.Dir(playDir);
1249 string tmp = Path.Combine(playDir, "bark-" + (++plays % 4) + ".wav");
1250 Private.Write(tmp, b);
1251 ProcessStartInfo si = new(p) { UseShellExecute = false, RedirectStandardError = false, RedirectStandardOutput = false };
1252 si.ArgumentList.Add(tmp);
1253 using Process pr = Process.Start(si);
1254 return null;
1255 }
1256 catch (Exception e) { return "The bark couldn't play: " + e.Message; }
1257 }
1258 }
1259
1260 internal sealed class Fix
1261 {
1262 public string Label, Act;
1263 public COpt Opt;
1264 }
1265
1266 internal sealed class Issue
1267 {
1268 public string Title, Detail;
1269 public bool Danger;
1270 public readonly List<Fix> Fixes = new();
1271 }
1272
1273 internal static class Advisor
1274 {
1275 public static float F(Dictionary<string, string> d, string k, float def) =>
1276 d != null && d.TryGetValue(k, out string v) && float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out float f) ? f : def;
1277
1278 private static void Add(List<Issue> list, Dictionary<string, COpt> byId, bool danger, string title, string detail, params string[] fixes)
1279 {
1280 Issue i = new() { Danger = danger, Title = title, Detail = detail };
1281 foreach (string f in fixes)
1282 {
1283 if (f.StartsWith("act:", StringComparison.Ordinal))
1284 {
1285 string[] p = f[4..].Split('|');
1286 i.Fixes.Add(new Fix { Act = p[0], Label = p.Length > 1 ? p[1] : p[0] });
1287 }
1288 else if (byId.TryGetValue(f, out COpt o)) i.Fixes.Add(new Fix { Opt = o, Label = o.Name });
1289 }
1290 list.Add(i);
1291 }
1292
1293 public static List<Issue> Check(Dictionary<string, string> d, Dictionary<string, COpt> byId)
1294 {
1295 List<Issue> list = new();
1296 if (d == null) return list;
1297 CultureInfo ci = CultureInfo.InvariantCulture;
1298 if (F(d, "alive", 1) < 0.5f)
1299 {
1300 Add(list, byId, true, "Your character is dead", "Nothing can save this run now.");
1301 return list;
1302 }
1303 if (F(d, "arrest", 0) > 0.5f) Add(list, byId, true, "Your heart has stopped", "Cardiac arrest. Heal right away or you won't come back.", "heal", "GodMode");
1304 else if (F(d, "crit", 0) > 0.5f) Add(list, byId, true, "You're dying", "Your body is failing. Heal now, and God Mode keeps you alive.", "heal", "GodMode");
1305 float bleed = F(d, "bleed", 0);
1306 if (bleed > 0.01f) Add(list, byId, bleed > 0.25f, bleed > 0.25f ? "Bleeding badly" : "Bleeding", "Losing " + bleed.ToString("0.00", ci) + " litres of blood a minute.", "NoBleeding", "heal");
1307 float blood = F(d, "blood", 100);
1308 if (blood < 70f) Add(list, byId, blood < 45f, "Low blood", "Blood is at " + blood.ToString("0", ci) + "%. Under 25% gets very dangerous.", "heal", "FasterHealing");
1309 float oxy = F(d, "oxy", 100);
1310 if (oxy < 85f) Add(list, byId, oxy < 70f, "Low oxygen", "Blood oxygen is at " + oxy.ToString("0", ci) + "%.", "UnlimitedOxygen", "heal");
1311 float brain = F(d, "brain", 100);
1312 if (brain < 80f) Add(list, byId, brain < 50f, "Brain damage", "Brain health is " + brain.ToString("0", ci) + ". At 0 you die.", "heal", "GodMode");
1313 float consc = F(d, "consc", 100);
1314 if (consc < 60f) Add(list, byId, consc < 40f, "Losing consciousness", "Consciousness is at " + consc.ToString("0", ci) + "%.", "heal", "NoPain");
1315 float pain = F(d, "pain", 0);
1316 if (pain > 50f) Add(list, byId, pain > 75f, "In a lot of pain", "Pain is at " + pain.ToString("0", ci) + "%. It knocks you out and drags your mood down.", "NoPain");
1317 float temp = F(d, "temp", 37);
1318 if (temp < 34f || temp > 39.5f) Add(list, byId, temp < 30f || temp > 41f, temp < 34f ? "Too cold" : "Overheating", "Body temperature is " + temp.ToString("0.0", ci) + " °C.", "StableTemperature");
1319 float hunger = F(d, "hunger", 100);
1320 if (hunger < 25f) Add(list, byId, hunger < 10f, "Starving", "Hunger is at " + hunger.ToString("0", ci) + ".", "NoHunger");
1321 float thirst = F(d, "thirst", 100);
1322 if (thirst < 25f) Add(list, byId, thirst < 10f, "Dehydrated", "Thirst is at " + thirst.ToString("0", ci) + ".", "NoThirst");
1323 float energy = F(d, "energy", 100);
1324 if (energy < 20f) Add(list, byId, energy < 5f, "Exhausted", "Energy is at " + energy.ToString("0", ci) + "%.", "NoTiredness");
1325 float infect = F(d, "infect", 0);
1326 if (infect >= 25f) Add(list, byId, infect >= 60f, "Infected wound", "Worst infection is at " + infect.ToString("0", ci) + ".", "NoInfection", "heal");
1327 float sick = F(d, "sick", 0);
1328 if (sick > 40f) Add(list, byId, sick > 70f, "Sick", "Sickness is at " + sick.ToString("0", ci) + "%.", "NoSickness");
1329 float venom = F(d, "venom", 0);
1330 if (venom > 0.5f) Add(list, byId, venom > 300f, "Poisoned", "Toxin at " + (venom * 0.1f).ToString("0.0", ci) + " ppm.", "NoSickness");
1331 float rad = F(d, "rad", 0);
1332 if (rad > 3f) Add(list, byId, rad > 7.5f, "Radiation sickness", "Radiation dose is " + rad.ToString("0.0", ci) + " gy.", "NoRadiation");
1333 int broken = (int)F(d, "broken", 0), disloc = (int)F(d, "disloc", 0), shrap = (int)F(d, "shrapnel", 0), missing = (int)F(d, "missing", 0);
1334 if (broken + disloc > 0)
1335 {
1336 List<string> parts = new();
1337 if (broken > 0) parts.Add(broken + " broken");
1338 if (disloc > 0) parts.Add(disloc + " dislocated");
1339 Add(list, byId, false, "Injured limbs", string.Join(", ", parts) + ".", "heal");
1340 }
1341 if (shrap > 0) Add(list, byId, false, "Shrapnel", shrap + " limb" + (shrap == 1 ? " has" : "s have") + " shrapnel in it.", "heal");
1342 if (missing > 0) Add(list, byId, false, "Missing limbs", missing + " limb" + (missing == 1 ? " is" : "s are") + " gone.", "limbs");
1343 float mood = F(d, "mood", 0);
1344 if (mood < -40f) Add(list, byId, mood <= -75f, "Very low mood", "Mood is " + mood.ToString("0", ci) + ". This low, your character may hurt themselves.", "act:moodmax|Max Mood", "MoodLock");
1345 if (F(d, "radline", 0) > 0.5f) Add(list, byId, true, "The radiation line is here", "Get out of this layer or stop the line.", "PauseRadiation", "exit");
1346 if (F(d, "enc", 0) > 0.5f) Add(list, byId, false, "Carrying too much", "Over-encumbered: slower, and tiring faster.", "UnlimitedCarry");
1347 return list.Where(i => i.Danger).Concat(list.Where(i => !i.Danger)).ToList();
1348 }
1349 }
1350
1351 internal sealed class KnownMod
1352 {
1353 public int Id;
1354 public string Dll, Name, Ts;
1355 public KnownMod(int id, string dll, string name, string ts) { Id = id; Dll = dll; Name = name; Ts = ts; }
1356 public string Page => "https://www.nexusmods.com/scavprototype/mods/" + Id;
1357 }
1358
1359 internal static class Mods
1360 {
1361 public static readonly KnownMod[] All =
1362 {
1363 new(874, "CUCheats.dll", "CU Cheats - Ultra Paradise", "CUCheats"),
1364 new(885, "SaveAnywhere.dll", "Save Anywhere", "SaveAnywhere"),
1365 new(894, "NoDurability.dll", "No Durability", "NoDurability"),
1366 new(915, "PickYourNumber.dll", "Pick Your Number, Age and Height", "PickYourNumber"),
1367 new(897, "GetStinky.dll", "Get Stinky", "GetStinky"),
1368 new(1183, "ThighHighsRevamped.dll", "Thigh Highs Revamped", "ThighHighsRevamped"),
1369 new(1059, "AlwaysGivenAChance.dll", "Always Given A Chance", "AlwaysGivenAChance"),
1370 new(999, "CustomDeathScreen.dll", "Custom Death Screen", null),
1371 new(998, "NoMoreSoundCannons.dll", "No More Sound Cannons", "NoMoreSoundCannons"),
1372 new(1190, "ControllerSupport.dll", "Controller Support", "ControllerSupport"),
1373 new(1200, "HatsHatsHats.dll", "Hats Hats Hats", "HatsHatsHats"),
1374 new(1204, "SpeedrunCU.dll", "Speed Run CU", "SpeedRunCU"),
1375 new(1214, "IRegretNothing.dll", "I Regret Nothing", "IRegretNothing"),
1376 new(1233, "Interpretation.dll", "Interpretation - Expie and Milky Reskin", "Interpretation"),
1377 };
1378
1379 public static string Plugins(string game) => Path.Combine(game, "BepInEx", "plugins");
1380
1381 public static readonly (int id, string why)[] Recommended =
1382 {
1383 (885, "Save your run anywhere, not just at the usual spots"),
1384 (1190, "Play with an Xbox or PlayStation controller"),
1385 (894, "Your gear and tools stop wearing out"),
1386 (915, "Pick your experiment number, age and height"),
1387 (1059, "Your last stand always gets its chance"),
1388 (1200, "A Santa hat on new runs, and a traffic cone to find"),
1389 };
1390
1391 public static bool SteamDeck
1392 {
1393 get
1394 {
1395 try
1396 {
1397 foreach (string f in new[] { "/sys/devices/virtual/dmi/id/board_vendor", "/sys/devices/virtual/dmi/id/sys_vendor" })
1398 if (File.Exists(f) && File.ReadAllText(f).Trim() == "Valve") return true;
1399 }
1400 catch (Exception) { }
1401 return false;
1402 }
1403 }
1404
1405 public static string Why(int id)
1406 {
1407 if (id == 1190 && SteamDeck) return "Recommended for the Steam Deck: full controller support in game";
1408 foreach (var r in Recommended) if (r.id == id) return r.why;
1409 return null;
1410 }
1411
1412 public static string Downloads
1413 {
1414 get
1415 {
1416 string d = null;
1417 try
1418 {
1419 string f = Path.Combine(Dirs.Home, ".config", "user-dirs.dirs");
1420 if (File.Exists(f))
1421 foreach (string line in File.ReadAllLines(f))
1422 {
1423 Match m = Regex.Match(line, "^XDG_DOWNLOAD_DIR=\"(.+)\"$");
1424 if (m.Success) d = m.Groups[1].Value.Replace("$HOME", Dirs.Home);
1425 }
1426 }
1427 catch (Exception) { }
1428 if (d == null || !Directory.Exists(d)) d = Path.Combine(Dirs.Home, "Downloads");
1429 return Directory.Exists(d) ? d : null;
1430 }
1431 }
1432
1433 private static IEnumerable<string> Find(string game, string dll)
1434 {
1435 string p = Plugins(game);
1436 if (!Directory.Exists(p)) return Enumerable.Empty<string>();
1437 return Directory.EnumerateFiles(p, "*.dll", SearchOption.AllDirectories).Where(f => string.Equals(Path.GetFileName(f), dll, StringComparison.OrdinalIgnoreCase));
1438 }
1439
1440 public static bool Installed(string game, KnownMod m)
1441 {
1442 try { return Game.IsGameDir(game) && Find(game, m.Dll).Any(); } catch (Exception) { return false; }
1443 }
1444
1445 public static KnownMod Identify(string zip)
1446 {
1447 try
1448 {
1449 FileInfo fi = new(zip);
1450 if (!fi.Exists || fi.Length > 200L * 1024 * 1024) return null;
1451 using ZipArchive za = ZipFile.OpenRead(zip);
1452 KnownMod hit = null;
1453 foreach (ZipArchiveEntry e in za.Entries)
1454 {
1455 if (e.FullName.Replace('\\', '/').Contains("ModLoader/", StringComparison.OrdinalIgnoreCase)) return null;
1456 foreach (KnownMod m in All)
1457 if (string.Equals(e.Name, m.Dll, StringComparison.OrdinalIgnoreCase)) hit = m;
1458 }
1459 return hit;
1460 }
1461 catch (Exception) { return null; }
1462 }
1463
1464 public static bool SameAsInstalled(string game, string zip, KnownMod m)
1465 {
1466 try
1467 {
1468 using ZipArchive za = ZipFile.OpenRead(zip);
1469 ZipArchiveEntry e = za.Entries.FirstOrDefault(x => string.Equals(x.Name, m.Dll, StringComparison.OrdinalIgnoreCase));
1470 if (e == null) return false;
1471 using Stream s = e.Open();
1472 using MemoryStream ms = new();
1473 s.CopyTo(ms);
1474 string h = Http.Sha(ms.ToArray());
1475 return Find(game, m.Dll).Any(f => Http.Sha(f) == h);
1476 }
1477 catch (Exception) { return false; }
1478 }
1479
1480 private static int Segment(string p, string seg)
1481 {
1482 if (p.StartsWith(seg, StringComparison.OrdinalIgnoreCase)) return 0;
1483 int i = p.IndexOf("/" + seg, StringComparison.OrdinalIgnoreCase);
1484 return i < 0 ? -1 : i + 1;
1485 }
1486
1487 public static string Install(string zip, string game, out KnownMod mod)
1488 {
1489 mod = Identify(zip);
1490 if (mod == null) return "that zip isn't one of casualexpie's BepInEx mods";
1491 if (!Game.IsGameDir(game)) return "the game folder wasn't found";
1492 if (!Game.BepInstalled(game)) return "install BepInEx first (Game Setup tab)";
1493 if (Game.GameRunning()) return "close the game first";
1494 string root = Path.GetFullPath(Plugins(game)).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
1495 List<(ZipArchiveEntry e, string target)> plan = new();
1496 using (ZipArchive za = ZipFile.OpenRead(zip))
1497 {
1498 bool tsZip = za.GetEntry("manifest.json") != null;
1499 string tsDir = Thunderstore.Owner + "-" + (mod.Ts ?? Path.GetFileNameWithoutExtension(mod.Dll)) + "/";
1500 foreach (ZipArchiveEntry e in za.Entries)
1501 {
1502 if (string.IsNullOrEmpty(e.Name)) continue;
1503 string p = e.FullName.Replace('\\', '/');
1504 if (p.Contains("../") || p.StartsWith('/') || p.Contains(':')) return "that zip has unsafe file paths, so it wasn't installed";
1505 if (e.Name.StartsWith("README", StringComparison.OrdinalIgnoreCase) && e.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) continue;
1506 int bi = Segment(p, "BepInEx/plugins/");
1507 string rel;
1508 if (bi >= 0) rel = p[(bi + "BepInEx/plugins/".Length)..];
1509 else if (Segment(p, "BepInEx/") >= 0) continue;
1510 else if (tsZip) rel = tsDir + p;
1511 else rel = e.Name;
1512 string target = Path.GetFullPath(Path.Combine(root, rel));
1513 if (!target.StartsWith(root, StringComparison.Ordinal)) continue;
1514 plan.Add((e, target));
1515 }
1516 if (plan.Count == 0) return "there was nothing to install in that zip";
1517 foreach (var (e, target) in plan)
1518 {
1519 Directory.CreateDirectory(Path.GetDirectoryName(target));
1520 e.ExtractToFile(target, true);
1521 }
1522 }
1523 foreach (string f in Find(game, mod.Dll).ToList())
1524 if (!plan.Any(x => string.Equals(Path.GetFullPath(f), x.target, StringComparison.Ordinal))) { try { File.Delete(f); } catch (Exception) { } }
1525 return null;
1526 }
1527
1528 public static string Remove(string game, KnownMod m)
1529 {
1530 if (Game.GameRunning()) return "close the game first";
1531 int n = 0;
1532 foreach (string f in Find(game, m.Dll).ToList()) { File.Delete(f); n++; }
1533 return n == 0 ? m.Name + " wasn't installed" : null;
1534 }
1535 }
1536
1537 internal static class KeyMap
1538 {
1539 public static string Unity(Avalonia.Input.Key k)
1540 {
1541 if (k >= Avalonia.Input.Key.NumPad0 && k <= Avalonia.Input.Key.NumPad9) return "Keypad" + (k - Avalonia.Input.Key.NumPad0);
1542 if (k >= Avalonia.Input.Key.D0 && k <= Avalonia.Input.Key.D9) return "Alpha" + (k - Avalonia.Input.Key.D0);
1543 if (k >= Avalonia.Input.Key.A && k <= Avalonia.Input.Key.Z) return k.ToString();
1544 if (k >= Avalonia.Input.Key.F1 && k <= Avalonia.Input.Key.F15) return k.ToString();
1545 return k switch
1546 {
1547 Avalonia.Input.Key.Insert => "Insert",
1548 Avalonia.Input.Key.Home => "Home",
1549 Avalonia.Input.Key.End => "End",
1550 Avalonia.Input.Key.PageUp => "PageUp",
1551 Avalonia.Input.Key.PageDown => "PageDown",
1552 Avalonia.Input.Key.Up => "UpArrow",
1553 Avalonia.Input.Key.Down => "DownArrow",
1554 Avalonia.Input.Key.Left => "LeftArrow",
1555 Avalonia.Input.Key.Right => "RightArrow",
1556 Avalonia.Input.Key.Decimal => "KeypadPeriod",
1557 Avalonia.Input.Key.Add => "KeypadPlus",
1558 Avalonia.Input.Key.Subtract => "KeypadMinus",
1559 Avalonia.Input.Key.Multiply => "KeypadMultiply",
1560 Avalonia.Input.Key.Divide => "KeypadDivide",
1561 Avalonia.Input.Key.Space => "Space",
1562 Avalonia.Input.Key.Tab => "Tab",
1563 Avalonia.Input.Key.Enter => "Return",
1564 Avalonia.Input.Key.OemTilde => "BackQuote",
1565 Avalonia.Input.Key.OemMinus => "Minus",
1566 Avalonia.Input.Key.OemPlus => "Equals",
1567 Avalonia.Input.Key.OemOpenBrackets => "LeftBracket",
1568 Avalonia.Input.Key.OemCloseBrackets => "RightBracket",
1569 Avalonia.Input.Key.OemSemicolon => "Semicolon",
1570 Avalonia.Input.Key.OemQuotes => "Quote",
1571 Avalonia.Input.Key.OemComma => "Comma",
1572 Avalonia.Input.Key.OemPeriod => "Period",
1573 Avalonia.Input.Key.OemQuestion => "Slash",
1574 Avalonia.Input.Key.OemPipe => "Backslash",
1575 _ => null,
1576 };
1577 }
1578 }
1579}