casualexpiesource

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

1131 lines · 62.5 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Globalization;
4using System.IO;
5using System.IO.Compression;
6using System.Linq;
7using System.Text;
8using System.Threading.Tasks;
9using Avalonia;
10using Avalonia.Controls;
11using Avalonia.Input;
12using Avalonia.Layout;
13using Avalonia.Media;
14using Avalonia.Platform.Storage;
15using UltraParadise.Shared;
16using Path = System.IO.Path;
17
18namespace UltraParadise.Linux
19{
20 internal sealed class LProfile
21 {
22 public string Name;
23 public HashSet<string> On = new();
24 public Dictionary<string, string> Vals = new();
25 public Dictionary<string, string> Keys = new();
26 public string Hot = "";
27 public bool Chaos;
28 }
29
30 internal sealed class LMacro
31 {
32 public string Name = "", Cond = "always", Mode = "on", Key = "";
33 public List<string> Ids = new();
34 }
35
36 internal sealed class LRun
37 {
38 public DateTime Start;
39 public double Secs;
40 public int Deepest;
41 public bool Died;
42 public float BloodLost, BloodGained;
43 public int LimbsLost, Spawned, Actions;
44 public HashSet<string> Cheats = new();
45 public float LastBlood = -1f;
46 public int LastMissing = -1;
47 public bool Cheated => Cheats.Count > 0 || Spawned > 0 || Actions > 0;
48
49 public string Line() => string.Join("|", Start.Ticks.ToString(CultureInfo.InvariantCulture), ((int)Secs).ToString(CultureInfo.InvariantCulture), Deepest, Died ? 1 : 0,
50 BloodLost.ToString("0.#", CultureInfo.InvariantCulture), BloodGained.ToString("0.#", CultureInfo.InvariantCulture), LimbsLost, Spawned, Actions, string.Join(";", Cheats).Replace("|", "/"));
51
52 public static LRun Parse(string s)
53 {
54 string[] p = s.Split('|');
55 if (p.Length < 10 || !long.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out long ticks) || ticks <= 0 || ticks >= DateTime.MaxValue.Ticks) return null;
56 LRun r = new() { Start = new DateTime(ticks), Died = p[3] == "1" };
57 if (int.TryParse(p[1], out int i)) r.Secs = i;
58 if (int.TryParse(p[2], out i)) r.Deepest = i;
59 if (float.TryParse(p[4], NumberStyles.Float, CultureInfo.InvariantCulture, out float f)) r.BloodLost = f;
60 if (float.TryParse(p[5], NumberStyles.Float, CultureInfo.InvariantCulture, out f)) r.BloodGained = f;
61 if (int.TryParse(p[6], out i)) r.LimbsLost = i;
62 if (int.TryParse(p[7], out i)) r.Spawned = i;
63 if (int.TryParse(p[8], out i)) r.Actions = i;
64 foreach (string c in p[9].Split(';')) if (c.Length > 0) r.Cheats.Add(c);
65 return r;
66 }
67 }
68
69 internal sealed partial class MainWindow
70 {
71 private readonly List<LProfile> profiles = new();
72 private readonly List<LMacro> macros = new();
73 private readonly Dictionary<string, DateTime> timers = new();
74 private readonly HashSet<string> neverRandom = new();
75 private readonly HashSet<string> randOn = new();
76 private DateTime nextRandom = DateTime.MaxValue;
77 private readonly List<(string name, float x, float y, int depth)> bookmarks = new();
78 private readonly List<(DateTime at, string text)> history = new();
79 private LRun run;
80 private DateTime noRunSince = DateTime.MinValue, lastRunTick = DateTime.MinValue;
81 private readonly List<LRun> pastRuns = new();
82 private readonly List<string> watched = new();
83 private readonly HashSet<string> alerting = new();
84 private readonly Dictionary<string, DateTime> checkBad = new();
85 private readonly Dictionary<string, string> originOf = new();
86 private string toolsSig = "", lastOvExtra = "";
87 private bool historyDirty;
88 private readonly StackPanel profList = new() { Spacing = 6 }, macroList = new() { Spacing = 6 }, timerList = new() { Spacing = 6 }, bookList = new() { Spacing = 6 },
89 checkList = new() { Spacing = 4 }, watchList = new() { Spacing = 6 }, allValues = new() { Spacing = 4 }, runNow = new() { Spacing = 3 }, runPast = new() { Spacing = 3 }, histList = new() { Spacing = 2 };
90 private readonly List<(TextBlock tb, Func<string> text)> liveText = new();
91 private readonly TextBlock randText = T("", 13, Ui.B(Ui.Text), false, true);
92
93 private static readonly string[] DefaultNever = { "UnchippedChallenge", "HopelessStart", "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "FastRadiation", "ColdCaves", "MoreTraps", "LootScarcity", "FreeCamera", "Noclip", "FlyMode", "ClickTeleport", "MoodLock" };
94 private static readonly string[] CondIds = { "always", "run", "bleeding", "critical", "hurt", "hungry", "trader" };
95 private static readonly string[] CondNames = { "Always", "Only in a run", "Only when bleeding", "Only when dying or in cardiac arrest", "Only when hurt (pain, broken or dislocated)", "Only when hungry or thirsty", "Only next to a survivor" };
96 private static readonly string[] ModeIds = { "on", "off", "flip" };
97 private static readonly string[] ModeNames = { "Turn the cheats on", "Turn the cheats off", "Flip them (on to off, off to on)" };
98 private static readonly (string key, string name, string unit)[] WatchKeys =
99 {
100 ("blood", "Blood", "%"), ("bleed", "Bleeding", " L/min"), ("oxy", "Blood oxygen", "%"), ("consc", "Consciousness", "%"), ("brain", "Brain health", "%"),
101 ("hr", "Heart rate", " bpm"), ("temp", "Body temperature", "°"), ("pain", "Pain", ""), ("hunger", "Food", ""), ("thirst", "Water", ""),
102 ("energy", "Energy", ""), ("mood", "Mood", ""), ("sick", "Sickness", ""), ("rad", "Radiation", ""), ("venom", "Venom", ""),
103 ("infect", "Infection", ""), ("broken", "Broken bones", ""), ("disloc", "Dislocations", ""), ("shrapnel", "Shrapnel", ""), ("missing", "Missing limbs", ""),
104 };
105
106 private static string RunsFile => Path.Combine(Dirs.Config, "runs.txt");
107
108 private void SetupTools()
109 {
110 foreach (CTab t in tabs) foreach (CSection s in t.Sections) foreach (COpt o in s.Rows) originOf[o.Id] = t.Name;
111 LoadProfiles();
112 LoadMacros();
113 string nv = Settings.Get("rand.never", null);
114 if (nv != null) { foreach (string s in nv.Split(',')) if (s.Length > 0) neverRandom.Add(s); }
115 else foreach (string s in DefaultNever) neverRandom.Add(s);
116 foreach (string s in Settings.Get("watch", "").Split(',')) if (WatchIndex(s) >= 0 && !watched.Contains(s)) watched.Add(s);
117 try { if (File.Exists(RunsFile)) foreach (string l in File.ReadAllLines(RunsFile)) { LRun r = LRun.Parse(l); if (r != null) pastRuns.Add(r); } } catch (Exception) { }
118 link.Sent += s => Avalonia.Threading.Dispatcher.UIThread.Post(() => OnSent(s));
119 }
120
121 private bool IsOn(string id) => lastState.TryGetValue(id, out string v) && v == "1";
122
123 private List<COpt> CheatToggles() => tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows).Where(o => o.Kind == CKind.Toggle).ToList();
124
125 private List<COpt> MacroPool() => tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows).Where(o => o.Kind is CKind.Toggle or CKind.Action).ToList();
126
127 private void SetCheat(string id, bool on)
128 {
129 if (!link.IsConnected || IsOn(id) == on) return;
130 link.Send("SET " + id + (on ? " 1" : " 0"));
131 NoteState(id, on ? "1" : "0");
132 if (stateSetters.TryGetValue(id, out Action<string> set)) set(on ? "1" : "0");
133 if (!on) { timers.Remove(id); randOn.Remove(id); }
134 }
135
136 private static string PName(string s)
137 {
138 string r = new string((s ?? "").Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '_' or '\'' or '!').ToArray()).Trim();
139 return r.Length > 24 ? r[..24].Trim() : r;
140 }
141
142 private static float V(Dictionary<string, string> d, string k, float def) =>
143 d != null && d.TryGetValue(k, out string s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float f) ? f : def;
144
145 private static string Clock2(int s) => (s / 60).ToString(CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture);
146
147 private static string Long(double secs)
148 {
149 int s = (int)secs;
150 return s >= 3600 ? (s / 3600) + "h " + ((s / 60) % 60).ToString("00") + "m" : Clock2(s);
151 }
152
153 private TextBlock Live(Func<string> text, bool dim = false)
154 {
155 TextBlock tb = T(text() ?? "", 13, Ui.B(dim ? Ui.Dim : Ui.Text), false, true);
156 liveText.Add((tb, text));
157 return tb;
158 }
159
160 private Grid LineRow(Func<string> text, params Button[] bs)
161 {
162 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
163 TextBlock tb = Live(text);
164 tb.VerticalAlignment = VerticalAlignment.Center;
165 g.Children.Add(tb);
166 StackPanel sp = new() { Orientation = Orientation.Horizontal, Spacing = 4 };
167 foreach (Button b in bs) { b.Padding = new Thickness(10, 3); b.MinHeight = 28; sp.Children.Add(b); }
168 Grid.SetColumn(sp, 1);
169 g.Children.Add(sp);
170 return g;
171 }
172
173 private static StackPanel Col(int i)
174 {
175 StackPanel c = new() { Margin = new Thickness(i == 0 ? 0 : 7, 0, i == 2 ? 0 : 7, 0) };
176 Grid.SetColumn(c, i);
177 return c;
178 }
179
180 private Control ProfilesPage()
181 {
182 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
183 StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2);
184 Border a = Section("PROFILES", out StackPanel ab);
185 ab.Children.Add(T("A profile is a set of cheats, sliders and hotkeys. Load one to switch everything at once.", 12, Ui.B(Ui.Dim), false, true));
186 ab.Children.Add(profList);
187 ab.Children.Add(Row(Btn("New From Current Cheats", () => _ = NewProfile()), Btn("Import...", () => _ = ImportProfile())));
188 c0.Children.Add(a);
189 Border b = Section("MACROS", out StackPanel bb);
190 bb.Children.Add(T("A macro switches several cheats or runs several actions with one click or hotkey. Pick a condition to make it a contextual hotkey, like one that only works while you're bleeding. Macro hotkeys work while the game is in front.", 12, Ui.B(Ui.Dim), false, true));
191 bb.Children.Add(macroList);
192 bb.Children.Add(Row(Btn("New Macro...", () => _ = EditMacro(new LMacro()))));
193 c1.Children.Add(b);
194 Border c = Section("BACK UP EVERYTHING", out StackPanel cb);
195 cb.Children.Add(T("Saves your settings, hotkeys, theme, profiles, macros, favorites and run history to one .zip file.", 12, Ui.B(Ui.Dim), false, true));
196 cb.Children.Add(Row(Btn("Back Up...", () => _ = BackupAll()), Btn("Restore...", () => _ = RestoreAll())));
197 c2.Children.Add(c);
198 g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2);
199 RebuildTools(true);
200 return Scroll(g);
201 }
202
203 private Control ToolsPage()
204 {
205 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
206 StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2);
207 Border a = Section("TIMED CHEATS", out StackPanel ab);
208 ab.Children.Add(T("Right-click any cheat and pick a time. It turns itself off when the time is up. The in-game overlay shows the time left.", 12, Ui.B(Ui.Dim), false, true));
209 ab.Children.Add(timerList);
210 c0.Children.Add(a);
211 Border r = Section("RANDOMIZER", out StackPanel rb);
212 rb.Children.Add(Row(Btn("Random Cheat", RandomOne), Btn("Shuffle", () => Shuffle(RandCount())), Btn("Never List...", () => _ = EditNever())));
213 rb.Children.Add(randText);
214 rb.Children.Add(Row(Btn("Shuffle 3", () => SetRand("rand.count", "3")), Btn("5", () => SetRand("rand.count", "5")), Btn("8", () => SetRand("rand.count", "8"))));
215 rb.Children.Add(Row(Btn("Swap off", () => SetRand("rand.every", "0")), Btn("1 min", () => SetRand("rand.every", "1")), Btn("2", () => SetRand("rand.every", "2")), Btn("5", () => SetRand("rand.every", "5")), Btn("10", () => SetRand("rand.every", "10"))));
216 rb.Children.Add(T("The randomizer skips cheats on the never list (challenges, noclip and free camera start on it). Every N minutes it swaps one of its own cheats for a new one.", 12, Ui.B(Ui.Dim), false, true));
217 c0.Children.Add(r);
218 Border b = Section("TELEPORT BOOKMARKS", out StackPanel bb);
219 bb.Children.Add(T("Save where you're standing and jump back later on the same layer. Bookmarks clear when the run ends.", 12, Ui.B(Ui.Dim), false, true));
220 bb.Children.Add(Row(Btn("Save This Spot", () => _ = SaveSpot())));
221 bb.Children.Add(bookList);
222 c1.Children.Add(b);
223 Border c = Section("CHEAT CHECK", out StackPanel cb);
224 cb.Children.Add(T("Checks that the cheats you have on are really doing their job, using your character's live health.", 12, Ui.B(Ui.Dim), false, true));
225 cb.Children.Add(checkList);
226 c2.Children.Add(c);
227 g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2);
228 return Scroll(g);
229 }
230
231 private Control WatchPage()
232 {
233 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,2*") };
234 StackPanel c0 = Col(0), c1 = Col(2);
235 Grid.SetColumn(c1, 1);
236 Border a = Section("WATCHING", out StackPanel ab);
237 ab.Children.Add(T("Pinned values also show on the in-game overlay. Set an alert to get a warning when one crosses a line, like blood below 60.", 12, Ui.B(Ui.Dim), false, true));
238 ab.Children.Add(watchList);
239 c0.Children.Add(a);
240 Border b = Section("LIVE VALUES", out StackPanel bb);
241 bb.Children.Add(allValues);
242 c1.Children.Add(b);
243 g.Children.Add(c0); g.Children.Add(c1);
244 return Scroll(g);
245 }
246
247 private Control StatsPage()
248 {
249 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
250 StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2);
251 Border a = Section("THIS RUN", out StackPanel ab);
252 ab.Children.Add(runNow);
253 c0.Children.Add(a);
254 Border b = Section("PAST RUNS", out StackPanel bb);
255 bb.Children.Add(runPast);
256 bb.Children.Add(T("Runs shorter than 10 seconds aren't saved. A run shows 'cheats used' if any cheat was on, or you spawned items or used an action. That's only the trainer's own record: the game's save isn't marked as cheated.", 12, Ui.B(Ui.Dim), false, true));
257 c1.Children.Add(b);
258 Border c = Section("ACTIVITY HISTORY", out StackPanel cb);
259 cb.Children.Add(Row(Btn("Save to File...", () => _ = SaveHistory()), Btn("Clear", () => { history.Clear(); historyDirty = true; RebuildTools(true); })));
260 cb.Children.Add(histList);
261 c2.Children.Add(c);
262 g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2);
263 return Scroll(g);
264 }
265
266 private void RebuildTools(bool force)
267 {
268 StringBuilder sig = new();
269 foreach (string k in timers.Keys) sig.Append(k).Append(',');
270 sig.Append('|').Append(bookmarks.Count).Append('|').Append(watched.Count).Append('|').Append(pastRuns.Count).Append('|').Append(run != null).Append('|').Append(profiles.Count).Append(macros.Count);
271 foreach (COpt o in CheatToggles()) if (IsOn(o.Id)) sig.Append(o.Id).Append(',');
272 if (!force && sig.ToString() == toolsSig && !historyDirty) { RefreshLive(); return; }
273 toolsSig = sig.ToString();
274 historyDirty = false;
275 liveText.Clear();
276
277 profList.Children.Clear();
278 string active = Settings.Get("profile.active", "");
279 foreach (LProfile p in profiles)
280 {
281 LProfile pp = p;
282 Button more = Btn("More", () => { });
283 more.ContextMenu = ProfileMenu(pp);
284 more.Click += (_, _) => more.ContextMenu?.Open(more);
285 profList.Children.Add(LineRow(() => (pp.Name == active ? "● " : "") + pp.Name + (pp.Chaos ? " (random)" : " (" + pp.On.Count + ")") + (pp.Hot.Length > 0 ? " " + Cheats.KeyLabel(pp.Hot) : ""),
286 Btn("Load", () => LoadProfile(pp)), Btn("Save Here", () => _ = SaveHere(pp)), more));
287 }
288
289 macroList.Children.Clear();
290 foreach (LMacro m in macros)
291 {
292 LMacro mm = m;
293 macroList.Children.Add(LineRow(() => mm.Name + (mm.Key.Length > 0 ? " " + Cheats.KeyLabel(mm.Key) : ""),
294 Btn("Run", () => RunMacro(mm)), Btn("Edit", () => _ = EditMacro(mm)), Btn("Delete", () => _ = DeleteMacro(mm))));
295 string names = string.Join(", ", mm.Ids.Select(i => byId.TryGetValue(i, out COpt o) ? o.Name : i));
296 if (mm.Cond != "always") names += " · " + CondNames[Math.Max(0, Array.IndexOf(CondIds, mm.Cond))].ToLowerInvariant();
297 macroList.Children.Add(T(names, 12, Ui.B(Ui.Dim), false, true));
298 }
299
300 timerList.Children.Clear();
301 foreach (string id in timers.Keys.ToList())
302 {
303 string iid = id;
304 string nm = byId.TryGetValue(id, out COpt o) ? o.Name : id;
305 timerList.Children.Add(LineRow(() => timers.TryGetValue(iid, out DateTime t) ? nm + " " + Clock2(Math.Max(0, (int)(t - DateTime.UtcNow).TotalSeconds)) : nm,
306 Btn("+5 min", () => { if (timers.TryGetValue(iid, out DateTime t)) timers[iid] = t.AddMinutes(5); }), Btn("Keep On", () => { timers.Remove(iid); RebuildTools(false); }), Btn("Off Now", () => { SetCheat(iid, false); RebuildTools(false); })));
307 }
308 if (timers.Count == 0) timerList.Children.Add(T("No timers running.", 13, Ui.B(Ui.Text)));
309
310 bookList.Children.Clear();
311 for (int i = 0; i < bookmarks.Count; i++)
312 {
313 int ii = i;
314 var bm = bookmarks[i];
315 bookList.Children.Add(LineRow(() => bm.name + (bm.depth >= 0 ? " (layer " + (bm.depth + 1) + ")" : " (special area)"),
316 Btn("Go", () => { if (Linked()) link.Send("ACT tpgo " + bm.x.ToString(CultureInfo.InvariantCulture) + " " + bm.y.ToString(CultureInfo.InvariantCulture) + " " + bm.depth); }),
317 Btn("Delete", () => { if (ii < bookmarks.Count) bookmarks.RemoveAt(ii); RebuildTools(true); })));
318 }
319
320 checkList.Children.Clear();
321 int n = 0;
322 foreach (COpt o in CheatToggles())
323 {
324 if (!IsOn(o.Id)) continue;
325 COpt oo = o;
326 checkList.Children.Add(Live(() => CheckLine(oo)));
327 n++;
328 }
329 if (n == 0) checkList.Children.Add(T("No cheats are on.", 13, Ui.B(Ui.Text)));
330
331 watchList.Children.Clear();
332 foreach (string k in watched)
333 {
334 string kk = k;
335 watchList.Children.Add(LineRow(() => WatchKeys[WatchIndex(kk)].name + ": " + WatchValue(kk) + (AlertText(kk).Length > 0 ? " (" + AlertText(kk) + ")" : ""),
336 Btn("Alert...", () => _ = EditAlert(kk)), Btn("Unpin", () => { watched.Remove(kk); alerting.Remove(kk); SaveWatch(); RebuildTools(true); })));
337 }
338 if (watched.Count == 0) watchList.Children.Add(T("Nothing pinned yet. Pin values from the list.", 13, Ui.B(Ui.Text), false, true));
339 allValues.Children.Clear();
340 foreach (var w in WatchKeys)
341 {
342 string k = w.key;
343 allValues.Children.Add(LineRow(() => w.name + ": " + WatchValue(k), Btn(watched.Contains(k) ? "Pinned" : "Pin", () =>
344 {
345 if (!watched.Remove(k)) watched.Add(k);
346 SaveWatch(); RebuildTools(true);
347 })));
348 }
349
350 runNow.Children.Clear();
351 runNow.Children.Add(Live(() => run == null ? "Not in a run." : "Time: " + Long(run.Secs) + (run.Died ? " (died)" : "")));
352 runNow.Children.Add(Live(() => run == null ? "" : "Deepest layer: " + Math.Max(1, run.Deepest)));
353 runNow.Children.Add(Live(() => run == null ? "" : "Blood lost: " + run.BloodLost.ToString("0", CultureInfo.InvariantCulture) + " healed: " + run.BloodGained.ToString("0", CultureInfo.InvariantCulture)));
354 runNow.Children.Add(Live(() => run == null ? "" : "Limbs lost: " + run.LimbsLost));
355 runNow.Children.Add(Live(() => run == null ? "" : "Items spawned: " + run.Spawned + " actions used: " + run.Actions));
356 runNow.Children.Add(Live(() => run == null ? "" : run.Cheated ? "Cheats used this run: " + run.Cheats.Count + " (just for these stats; your save isn't marked)" : "No cheats used so far"));
357
358 runPast.Children.Clear();
359 double total = pastRuns.Sum(r => r.Secs);
360 runPast.Children.Add(T(pastRuns.Count + " runs · " + Long(total) + " played · " + pastRuns.Count(r => r.Died) + " deaths · " + pastRuns.Count(r => !r.Cheated) + " without cheats", 13, Ui.B(Ui.Text), true, true));
361 for (int i = pastRuns.Count - 1; i >= 0 && i >= pastRuns.Count - 12; i--)
362 {
363 LRun r = pastRuns[i];
364 runPast.Children.Add(T(r.Start.ToString("MMM d, HH:mm", CultureInfo.InvariantCulture) + " · " + Long(r.Secs) + " · layer " + Math.Max(1, r.Deepest) + (r.Died ? " · died" : "") + " · " + (r.Cheated ? "cheats used (" + r.Cheats.Count + ")" : "no cheats"), 13, Ui.B(Ui.Text), false, true));
365 }
366 if (pastRuns.Count > 0) runPast.Children.Add(Row(Btn("Clear Run History", () => _ = ClearRuns())));
367
368 histList.Children.Clear();
369 if (history.Count == 0) histList.Children.Add(T("Nothing yet. Everything the trainer does shows up here.", 13, Ui.B(Ui.Text), false, true));
370 for (int i = history.Count - 1; i >= 0 && i >= history.Count - 40; i--)
371 histList.Children.Add(T(history[i].at.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + history[i].text, 12.5, Ui.B(Ui.Text), false, true));
372 RefreshLive();
373 }
374
375 private void RefreshLive()
376 {
377 foreach (var (tb, text) in liveText) tb.Text = text() ?? "";
378 int e = RandEvery();
379 randText.Text = "Shuffle turns on " + RandCount() + ". " + (e == 0 ? "Swapping is off." : "Swaps one every " + e + " min.");
380 }
381
382 private void LoadProfiles()
383 {
384 profiles.Clear();
385 string list = Settings.Get("profiles", null);
386 if (list == null)
387 {
388 profiles.Add(new LProfile { Name = "Sandbox", On = new HashSet<string> { "GodMode", "NoHunger", "NoThirst", "NoTiredness", "InfiniteStamina", "FreeCrafting", "NoCraftFail", "AllRecipes", "UnlimitedAmmo", "NoDegradation", "UnlimitedBattery", "UnlimitedCarry", "FullBright", "MasterLockpick" } });
389 profiles.Add(new LProfile { Name = "Survival", On = new HashSet<string> { "NoFallDamage", "InfiniteStamina", "AllRecipes", "NoCraftFail", "FasterHealing" } });
390 profiles.Add(new LProfile { Name = "Chaos", Chaos = true });
391 profiles.Add(new LProfile { Name = "Hardcore", On = new HashSet<string> { "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "LootScarcity", "ColdCaves", "MoreTraps" } });
392 foreach (LProfile p in profiles) p.On.RemoveWhere(id => !byId.ContainsKey(id));
393 SaveProfiles();
394 return;
395 }
396 foreach (string n in list.Split('|'))
397 {
398 if (n.Length == 0) continue;
399 string k = "profile." + n + ".";
400 LProfile p = new() { Name = n, Hot = Settings.Get(k + "hot", ""), Chaos = Settings.Get(k + "chaos", "0") == "1" };
401 foreach (string s in Settings.Get(k + "on", "").Split(',')) if (byId.ContainsKey(s)) p.On.Add(s);
402 foreach (string s in Settings.Get(k + "val", "").Split(',')) { string[] kv = s.Split(':'); if (kv.Length == 2 && byId.ContainsKey(kv[0])) p.Vals[kv[0]] = kv[1]; }
403 foreach (string s in Settings.Get(k + "lkeys", "").Split(',')) { string[] kv = s.Split(':'); if (kv.Length == 2 && byId.ContainsKey(kv[0])) p.Keys[kv[0]] = kv[1]; }
404 profiles.Add(p);
405 }
406 }
407
408 private void SaveProfiles()
409 {
410 foreach (string k in Settings.Keys().Where(k => k.StartsWith("profile.", StringComparison.Ordinal) && k != "profile.active").ToList()) Settings.Set(k, null);
411 foreach (LProfile p in profiles)
412 {
413 string k = "profile." + p.Name + ".";
414 Settings.Set(k + "on", string.Join(",", p.On));
415 if (p.Vals.Count > 0) Settings.Set(k + "val", string.Join(",", p.Vals.Select(kv => kv.Key + ":" + kv.Value)));
416 if (p.Keys.Count > 0) Settings.Set(k + "lkeys", string.Join(",", p.Keys.Select(kv => kv.Key + ":" + kv.Value)));
417 if (p.Hot.Length > 0) Settings.Set(k + "hot", p.Hot);
418 if (p.Chaos) Settings.Set(k + "chaos", "1");
419 }
420 Settings.Set("profiles", string.Join("|", profiles.Select(p => p.Name)));
421 }
422
423 private LProfile FindProfile(string n) => profiles.FirstOrDefault(p => string.Equals(p.Name, n, StringComparison.OrdinalIgnoreCase));
424
425 private string UniqueName(string n)
426 {
427 n = PName(n);
428 if (n.Length == 0) n = "Profile";
429 if (FindProfile(n) == null) return n;
430 for (int i = 2; ; i++) if (FindProfile(n + " " + i) == null) return n + " " + i;
431 }
432
433 private void CaptureInto(LProfile p)
434 {
435 p.On.Clear(); p.Vals.Clear(); p.Keys.Clear();
436 foreach (COpt o in tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows))
437 {
438 if (o.Kind == CKind.Toggle && IsOn(o.Id)) p.On.Add(o.Id);
439 if (o.Kind == CKind.Slider && lastState.TryGetValue(o.Id, out string v)) p.Vals[o.Id] = v;
440 if (o.Kind is CKind.Toggle or CKind.Action && binds.TryGetValue(o.Id, out string k) && k.Length > 0 && k != "none") p.Keys[o.Id] = k;
441 }
442 }
443
444 private void LoadProfile(LProfile p)
445 {
446 if (!Linked()) return;
447 foreach (COpt o in CheatToggles()) SetCheat(o.Id, !p.Chaos && p.On.Contains(o.Id));
448 foreach (var kv in p.Vals)
449 if (byId.TryGetValue(kv.Key, out COpt o) && o.Kind == CKind.Slider && float.TryParse(kv.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float f))
450 {
451 string v = Math.Clamp(f, o.Min, o.Max).ToString("0.###", CultureInfo.InvariantCulture);
452 link.Send("VAL " + o.Id + " " + v);
453 if (stateSetters.TryGetValue(o.Id, out Action<string> set)) set(v);
454 }
455 if (p.Keys.Count > 0)
456 foreach (COpt o in MacroPool())
457 {
458 string v = p.Keys.TryGetValue(o.Id, out string k) ? k : "none";
459 binds[o.Id] = v;
460 Settings.Set("bind." + o.Id, v);
461 link.Send("BIND " + o.Id + " " + v);
462 if (keyButtons.TryGetValue(o.Id, out Button b)) b.Content = Cheats.KeyLabel(v);
463 }
464 if (p.Chaos) Shuffle(RandCount());
465 Settings.Set("profile.active", p.Name);
466 Message("Loaded the " + p.Name + " profile.", false);
467 RebuildTools(true);
468 }
469
470 private async Task NewProfile()
471 {
472 string n = await AskText("New profile", "Name for the new profile (it starts with the cheats you have on now):", "My Profile");
473 if (n == null) return;
474 LProfile p = new() { Name = UniqueName(n) };
475 CaptureInto(p);
476 profiles.Add(p); SaveProfiles(); RebuildTools(true);
477 }
478
479 private async Task SaveHere(LProfile p)
480 {
481 if (!await Confirm("Save profile", "Replace the " + p.Name + " profile with the cheats, sliders and hotkeys you have now?")) return;
482 CaptureInto(p); p.Chaos = false; SaveProfiles(); RebuildTools(true);
483 Message("Saved the " + p.Name + " profile.", false);
484 }
485
486 private ContextMenu ProfileMenu(LProfile p)
487 {
488 ContextMenu m = new();
489 void Add(string h, Action a) { MenuItem i = new() { Header = h }; i.Click += (_, _) => a(); m.Items.Add(i); }
490 Add("Rename...", async () =>
491 {
492 string n = await AskText("Rename profile", "New name for " + p.Name + ":", p.Name);
493 n = PName(n);
494 if (string.IsNullOrEmpty(n)) return;
495 LProfile o = FindProfile(n);
496 if (o != null && o != p) { Message("There's already a profile called " + n + ".", true); return; }
497 if (Settings.Get("profile.active", "") == p.Name) Settings.Set("profile.active", n);
498 p.Name = n; SaveProfiles(); RebuildTools(true);
499 });
500 Add("Duplicate", () =>
501 {
502 LProfile c = new() { Name = UniqueName(p.Name + " copy"), Chaos = p.Chaos, On = new HashSet<string>(p.On), Vals = new Dictionary<string, string>(p.Vals), Keys = new Dictionary<string, string>(p.Keys) };
503 profiles.Insert(profiles.IndexOf(p) + 1, c); SaveProfiles(); RebuildTools(true);
504 });
505 Add("Set Hotkey...", async () =>
506 {
507 string k = await AskKey("Profile hotkey", "Hotkey that loads the " + p.Name + " profile.", p.Hot);
508 if (k == null) return;
509 if (k.Length > 0 && KeyTaken(k, p)) { Message(Cheats.KeyLabel(k) + " is already used. Pick another key.", true); return; }
510 p.Hot = k; SaveProfiles(); SendXBinds(); RebuildTools(true);
511 });
512 Add(p.Chaos ? "Stop Randomizing on Load" : "Randomize on Load (Chaos)", () => { p.Chaos = !p.Chaos; SaveProfiles(); RebuildTools(true); });
513 Add("Export...", () => _ = ExportProfile(p));
514 Add("Delete", async () =>
515 {
516 if (!await Confirm("Delete profile", "Delete the " + p.Name + " profile? This can't be undone.")) return;
517 profiles.Remove(p); SaveProfiles(); SendXBinds(); RebuildTools(true);
518 });
519 return m;
520 }
521
522 private async Task ExportProfile(LProfile p)
523 {
524 IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Export profile", SuggestedFileName = p.Name + ".upprofile" });
525 string path = f?.TryGetLocalPath();
526 if (path == null) return;
527 List<string> l = new() { "UltraParadiseProfile 1", "name=" + p.Name, "on=" + string.Join(",", p.On), "val=" + string.Join(",", p.Vals.Select(kv => kv.Key + ":" + kv.Value)), "lkeys=" + string.Join(",", p.Keys.Select(kv => kv.Key + ":" + kv.Value)), "chaos=" + (p.Chaos ? "1" : "0") };
528 try { File.WriteAllLines(path, l); Message("Exported " + p.Name + ".", false); } catch (Exception e) { Message("Couldn't save the file: " + e.Message, true); }
529 }
530
531 private async Task ImportProfile()
532 {
533 var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Import profile", AllowMultiple = false });
534 string path = files.Count > 0 ? files[0].TryGetLocalPath() : null;
535 if (path == null) return;
536 string[] lines;
537 try
538 {
539 if (new FileInfo(path).Length > 65536) { Message("That file is too big to be a profile.", true); return; }
540 lines = File.ReadAllLines(path);
541 }
542 catch (Exception e) { Message("Couldn't read the file: " + e.Message, true); return; }
543 if (lines.Length == 0 || lines[0].Trim() != "UltraParadiseProfile 1") { Message("That isn't an Ultra Paradise profile file.", true); return; }
544 Dictionary<string, string> m = new();
545 foreach (string ln in lines) { int eq = ln.IndexOf('='); if (eq > 0) m[ln[..eq].Trim()] = ln[(eq + 1)..].Trim(); }
546 LProfile p = new() { Name = UniqueName(m.GetValueOrDefault("name", Path.GetFileNameWithoutExtension(path))), Chaos = m.GetValueOrDefault("chaos", "0") == "1" };
547 foreach (string s in m.GetValueOrDefault("on", "").Split(',')) if (byId.TryGetValue(s, out COpt o) && o.Kind == CKind.Toggle) p.On.Add(s);
548 foreach (string s in m.GetValueOrDefault("val", "").Split(',')) { string[] kv = s.Split(':'); if (kv.Length == 2 && byId.TryGetValue(kv[0], out COpt o) && o.Kind == CKind.Slider && float.TryParse(kv[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float f) && !float.IsNaN(f)) p.Vals[kv[0]] = kv[1]; }
549 foreach (string s in m.GetValueOrDefault("lkeys", "").Split(',')) { string[] kv = s.Split(':'); if (kv.Length == 2 && byId.ContainsKey(kv[0]) && KeyLooksOk(kv[1])) p.Keys[kv[0]] = kv[1]; }
550 profiles.Add(p); SaveProfiles(); RebuildTools(true);
551 Message("Imported the " + p.Name + " profile.", false);
552 }
553
554 private static bool KeyLooksOk(string k) => k.Length > 0 && k.Length < 40 && k.All(c => char.IsLetterOrDigit(c) || c == '+');
555
556 private void LoadMacros()
557 {
558 macros.Clear();
559 for (int i = 0; i < 50; i++)
560 {
561 string v = Settings.Get("macro." + i, null);
562 if (v == null) continue;
563 string[] p = v.Split('|');
564 if (p.Length < 5) continue;
565 LMacro m = new() { Name = p[0], Key = KeyLooksOk(p[1]) ? p[1] : "", Cond = Array.IndexOf(CondIds, p[2]) >= 0 ? p[2] : "always", Mode = p[3] is "off" or "flip" ? p[3] : "on" };
566 foreach (string s in p[4].Split(',')) if (byId.ContainsKey(s)) m.Ids.Add(s);
567 if (m.Ids.Count > 0) macros.Add(m);
568 }
569 }
570
571 private void SaveMacros()
572 {
573 for (int i = 0; i < 50; i++) Settings.Set("macro." + i, null);
574 for (int i = 0; i < macros.Count && i < 50; i++)
575 {
576 LMacro m = macros[i];
577 Settings.Set("macro." + i, m.Name.Replace("|", "/") + "|" + m.Key + "|" + m.Cond + "|" + m.Mode + "|" + string.Join(",", m.Ids));
578 }
579 }
580
581 private bool KeyTaken(string k, object except)
582 {
583 if (binds.Values.Any(v => string.Equals(v, k, StringComparison.OrdinalIgnoreCase))) return true;
584 if (macros.Any(m => m != except && string.Equals(m.Key, k, StringComparison.OrdinalIgnoreCase))) return true;
585 return profiles.Any(p => p != except && string.Equals(p.Hot, k, StringComparison.OrdinalIgnoreCase));
586 }
587
588 private void SendXBinds()
589 {
590 if (!link.IsConnected) return;
591 List<string> l = new();
592 for (int i = 0; i < macros.Count; i++) if (macros[i].Key.Length > 0) l.Add("m" + i + "=" + macros[i].Key);
593 for (int i = 0; i < profiles.Count; i++) if (profiles[i].Hot.Length > 0) l.Add("p" + i + "=" + profiles[i].Hot);
594 link.Send("XBINDS " + (l.Count > 0 ? string.Join(",", l) : "-"));
595 }
596
597 private void OnHotkey(string id)
598 {
599 if (id.Length < 2 || !int.TryParse(id[1..], out int i)) return;
600 if (id[0] == 'm' && i < macros.Count) RunMacro(macros[i]);
601 else if (id[0] == 'p' && i < profiles.Count) LoadProfile(profiles[i]);
602 }
603
604 private bool CondMet(string c) => c switch
605 {
606 "run" => vitals != null,
607 "bleeding" => vitals != null && V(vitals, "bleed", 0f) > 0.02f,
608 "critical" => vitals != null && (V(vitals, "crit", 0f) > 0 || V(vitals, "arrest", 0f) > 0),
609 "hurt" => vitals != null && (V(vitals, "pain", 0f) > 20f || V(vitals, "broken", 0f) > 0 || V(vitals, "disloc", 0f) > 0),
610 "hungry" => vitals != null && (V(vitals, "hunger", 100f) < 35f || V(vitals, "thirst", 100f) < 35f),
611 "trader" => info != null && info.ContainsKey("trader"),
612 _ => true,
613 };
614
615 private void RunMacro(LMacro m)
616 {
617 if (!Linked()) return;
618 if (!CondMet(m.Cond)) { Message(m.Name + " didn't run: it works " + CondNames[Math.Max(0, Array.IndexOf(CondIds, m.Cond))].ToLowerInvariant() + ".", false); return; }
619 foreach (string id in m.Ids)
620 {
621 if (!byId.TryGetValue(id, out COpt o)) continue;
622 if (o.Kind == CKind.Toggle) SetCheat(id, m.Mode == "on" || (m.Mode == "flip" && !IsOn(id)));
623 else link.Send("ACT " + id);
624 }
625 Message("Ran " + m.Name + ".", false);
626 RebuildTools(false);
627 }
628
629 private async Task DeleteMacro(LMacro m)
630 {
631 if (!await Confirm("Delete macro", "Delete the " + m.Name + " macro?")) return;
632 macros.Remove(m); SaveMacros(); SendXBinds(); RebuildTools(true);
633 }
634
635 private ContextMenu CheatContext(COpt o)
636 {
637 ContextMenu m = new();
638 m.Opening += (_, _) =>
639 {
640 m.Items.Clear();
641 bool on = IsOn(o.Id);
642 foreach (int n in new[] { 1, 2, 5, 10, 30 })
643 {
644 MenuItem i = new() { Header = (on ? "Turn off in " : "Turn on for ") + n + (n == 1 ? " minute" : " minutes") };
645 i.Click += (_, _) => StartTimer(o, n);
646 m.Items.Add(i);
647 }
648 if (timers.ContainsKey(o.Id)) { MenuItem c = new() { Header = "Cancel the timer" }; c.Click += (_, _) => { timers.Remove(o.Id); RebuildTools(false); }; m.Items.Add(c); }
649 MenuItem nv = new() { Header = (neverRandom.Contains(o.Id) ? "✔ " : "") + "Never randomise this" };
650 nv.Click += (_, _) => { if (!neverRandom.Remove(o.Id)) neverRandom.Add(o.Id); SaveNever(); };
651 m.Items.Add(nv);
652 MenuItem mk = new() { Header = "New macro with this cheat..." };
653 mk.Click += (_, _) => { LMacro x = new() { Name = o.Name }; x.Ids.Add(o.Id); _ = EditMacro(x); };
654 m.Items.Add(mk);
655 };
656 m.Items.Add(new MenuItem { Header = "..." });
657 return m;
658 }
659
660 private void StartTimer(COpt o, int minutes)
661 {
662 if (!Linked()) return;
663 SetCheat(o.Id, true);
664 timers[o.Id] = DateTime.UtcNow.AddMinutes(minutes);
665 Message(o.Name + " turns off by itself in " + minutes + (minutes == 1 ? " minute." : " minutes."), false);
666 RebuildTools(false);
667 }
668
669 private void SaveNever() => Settings.Set("rand.never", string.Join(",", neverRandom));
670 private static int RandCount() => int.TryParse(Settings.Get("rand.count", "5"), out int n) ? Math.Clamp(n, 1, 12) : 5;
671 private static int RandEvery() => int.TryParse(Settings.Get("rand.every", "0"), out int n) ? Math.Clamp(n, 0, 60) : 0;
672 private void SetRand(string k, string v) { Settings.Set(k, v); nextRandom = DateTime.MaxValue; RefreshLive(); }
673
674 private COpt RandomOn()
675 {
676 List<COpt> l = CheatToggles().Where(o => !neverRandom.Contains(o.Id) && !IsOn(o.Id)).ToList();
677 if (l.Count == 0) return null;
678 COpt o = l[Random.Shared.Next(l.Count)];
679 SetCheat(o.Id, true);
680 randOn.Add(o.Id);
681 return o;
682 }
683
684 private void RandomOne()
685 {
686 if (!Linked()) return;
687 COpt o = RandomOn();
688 Message(o == null ? "No cheats left to turn on." : "Randomizer: " + o.Name + " on.", false);
689 }
690
691 private void Shuffle(int n)
692 {
693 if (!Linked()) return;
694 foreach (COpt o in CheatToggles()) if (!neverRandom.Contains(o.Id)) SetCheat(o.Id, false);
695 randOn.Clear();
696 List<string> got = new();
697 for (int i = 0; i < n; i++) { COpt o = RandomOn(); if (o != null) got.Add(o.Name); }
698 Message(got.Count == 0 ? "Nothing to randomise: every cheat is on the never list." : "Randomizer: " + string.Join(", ", got) + ".", false);
699 }
700
701 private void RandomTick()
702 {
703 int every = RandEvery();
704 if (every <= 0 || !link.IsConnected) { nextRandom = DateTime.MaxValue; return; }
705 if (nextRandom == DateTime.MaxValue) nextRandom = DateTime.UtcNow.AddMinutes(every);
706 if (DateTime.UtcNow < nextRandom) return;
707 nextRandom = DateTime.UtcNow.AddMinutes(every);
708 List<string> mine = randOn.ToList();
709 string offName = null;
710 if (mine.Count > 0) { string id = mine[Random.Shared.Next(mine.Count)]; SetCheat(id, false); offName = byId.TryGetValue(id, out COpt o) ? o.Name : id; }
711 COpt on = RandomOn();
712 string s = (offName != null ? offName + " off" : "") + (on != null ? (offName != null ? ", " : "") + on.Name + " on" : "");
713 if (s.Length > 0) Message("Randomizer: " + s + ".", false);
714 }
715
716 private async Task EditNever()
717 {
718 HashSet<string> pick = new(neverRandom);
719 if (!await PickMany("Never randomise", "Tick the cheats the randomizer and the Chaos profile should never touch.", CheatToggles(), pick)) return;
720 neverRandom.Clear(); neverRandom.UnionWith(pick); SaveNever();
721 }
722
723 private static int WatchIndex(string k) => Array.FindIndex(WatchKeys, w => w.key == k);
724
725 private string WatchValue(string k)
726 {
727 if (vitals == null || !vitals.TryGetValue(k, out string s)) return "-";
728 int i = WatchIndex(k);
729 return s + (i >= 0 ? WatchKeys[i].unit : "");
730 }
731
732 private void SaveWatch() => Settings.Set("watch", string.Join(",", watched));
733
734 private static string AlertText(string k)
735 {
736 string a = Settings.Get("watch.alert." + k, "");
737 return a.Length < 2 ? "" : (a[0] == '<' ? "alert below " : "alert above ") + a[1..];
738 }
739
740 private void WatchTick()
741 {
742 foreach (string k in watched)
743 {
744 string a = Settings.Get("watch.alert." + k, "");
745 if (vitals == null || a.Length < 2 || !float.TryParse(a[1..], NumberStyles.Float, CultureInfo.InvariantCulture, out float thr)) { alerting.Remove(k); continue; }
746 float cur = V(vitals, k, float.NaN);
747 if (float.IsNaN(cur)) continue;
748 bool hit = a[0] == '<' ? cur < thr : cur > thr;
749 if (hit && alerting.Add(k))
750 {
751 string msg = WatchKeys[WatchIndex(k)].name + " is " + WatchValue(k) + " (" + AlertText(k) + ")";
752 Message(msg + ".", true);
753 if (link.IsConnected) link.Send("TOAST " + msg);
754 }
755 else if (!hit) alerting.Remove(k);
756 }
757 }
758
759 private void OverlayTick()
760 {
761 if (!link.IsConnected) { lastOvExtra = ""; return; }
762 List<string> l = new();
763 foreach (var kv in timers) l.Add((byId.TryGetValue(kv.Key, out COpt o) ? o.Name : kv.Key) + " " + Clock2(Math.Max(0, (int)(kv.Value - DateTime.UtcNow).TotalSeconds)) + " left");
764 if (vitals != null) foreach (string k in watched) { int i = WatchIndex(k); if (i >= 0) l.Add(WatchKeys[i].name + ": " + WatchValue(k) + (alerting.Contains(k) ? " !" : "")); }
765 string s = string.Join("\u001c", l);
766 if (s == lastOvExtra) return;
767 lastOvExtra = s;
768 link.Send("OVEXTRA " + (s.Length > 0 ? s : "-"));
769 }
770
771 private async Task EditAlert(string k)
772 {
773 string a = Settings.Get("watch.alert." + k, "");
774 Window w = Dialog("Alert for " + WatchKeys[WatchIndex(k)].name.ToLowerInvariant(), out StackPanel sp);
775 sp.Children.Add(T("Pop up a warning when " + WatchKeys[WatchIndex(k)].name.ToLowerInvariant() + " goes:", 13, Ui.B(Ui.Text), false, true));
776 ComboBox c = new() { ItemsSource = new[] { "No alert", "Below", "Above" }, SelectedIndex = a.StartsWith("<") ? 1 : a.StartsWith(">") ? 2 : 0, Width = 140 };
777 NumericUpDown n = new() { Minimum = -1000, Maximum = 100000, Increment = 1, FormatString = "0.#", Value = a.Length > 1 && decimal.TryParse(a[1..], NumberStyles.Float, CultureInfo.InvariantCulture, out decimal d) ? d : 50, Width = 160 };
778 sp.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { c, n } });
779 if (!await OkCancel(w, sp, "Save")) return;
780 if (c.SelectedIndex == 0) Settings.Set("watch.alert." + k, null);
781 else Settings.Set("watch.alert." + k, (c.SelectedIndex == 1 ? "<" : ">") + ((float)(n.Value ?? 0)).ToString(CultureInfo.InvariantCulture));
782 alerting.Remove(k);
783 RebuildTools(true);
784 }
785
786 private static string CheckRule(string id, Dictionary<string, string> v, out bool ok)
787 {
788 ok = true;
789 switch (id)
790 {
791 case "GodMode": ok = V(v, "alive", 1f) > 0 && V(v, "arrest", 0f) <= 0; return "you're alive and your heart is beating";
792 case "NoHunger": ok = V(v, "hunger", 100f) >= 80f; return "food stays full";
793 case "NoThirst": ok = V(v, "thirst", 100f) >= 80f; return "water stays full";
794 case "NoTiredness": ok = V(v, "energy", 100f) >= 80f; return "energy stays full";
795 case "NoBleeding": ok = V(v, "bleed", 0f) <= 0.02f; return "no bleeding";
796 case "NoPain": ok = V(v, "pain", 0f) <= 5f; return "no pain";
797 case "NoInfection": ok = V(v, "infect", 0f) <= 1f; return "no infection";
798 case "NoSickness": ok = V(v, "sick", 0f) <= 1f; return "no sickness";
799 case "NoRadiation": ok = V(v, "rad", 0f) <= 1f; return "no radiation sickness";
800 case "UnlimitedOxygen": ok = V(v, "oxy", 100f) >= 90f; return "blood oxygen stays high";
801 case "UnlimitedCarry": ok = V(v, "enc", 0f) <= 0f; return "you're not over-encumbered";
802 default: return null;
803 }
804 }
805
806 private string CheckLine(COpt o)
807 {
808 if (vitals == null) return o.Name + ": start a run to check it";
809 string what = CheckRule(o.Id, vitals, out bool ok);
810 if (what == null) return o.Name + ": on (can't be checked from here)";
811 if (ok) { checkBad.Remove(o.Id); return "✔ " + o.Name + ": working (" + what + ")"; }
812 if (!checkBad.TryGetValue(o.Id, out DateTime since)) { checkBad[o.Id] = since = DateTime.UtcNow; }
813 return (DateTime.UtcNow - since).TotalSeconds < 6 ? o.Name + ": checking..." : "⚠ " + o.Name + ": doesn't look like it's working";
814 }
815
816 private async Task SaveSpot()
817 {
818 if (!Linked()) return;
819 float x = V(info, "px", float.NaN), y = V(info, "py", float.NaN);
820 int d = (int)V(info, "depth", -2f);
821 if (vitals == null || float.IsNaN(x) || float.IsNaN(y) || d < -1) { Message("Start a run first. If you're in one, update UltraPara.dll in Game Setup.", true); return; }
822 string n = await AskText("Save spot", "Name for this spot:", "Spot " + (bookmarks.Count + 1));
823 if (n == null) return;
824 bookmarks.Add((PName(n).Length > 0 ? PName(n) : "Spot", x, y, d));
825 if (bookmarks.Count > 20) bookmarks.RemoveAt(0);
826 RebuildTools(true);
827 }
828
829 private void OnSent(string s)
830 {
831 string[] p = s.Split(' ', 3);
832 string text;
833 switch (p[0])
834 {
835 case "SET":
836 if (p.Length < 3 || !byId.TryGetValue(p[1], out COpt o)) return;
837 text = o.Name + (p[2] == "1" ? " on" : " off");
838 if (p[2] == "1" && run != null) run.Cheats.Add(o.Id);
839 break;
840 case "VAL":
841 if (p.Length < 3 || !byId.TryGetValue(p[1], out COpt v)) return;
842 text = v.Name + " set to " + p[2];
843 if (history.Count > 0 && history[^1].text.StartsWith(v.Name + " set to ", StringComparison.Ordinal)) history.RemoveAt(history.Count - 1);
844 break;
845 case "ACT":
846 if (p.Length < 2) return;
847 text = p[1] == "tpgo" ? "Teleported to a bookmark" : byId.TryGetValue(p[1], out COpt a) ? a.Name : p[1];
848 if (run != null) run.Actions++;
849 break;
850 case "SPAWN":
851 if (p.Length < 3) return;
852 if (!int.TryParse(p[2], out int n)) n = 1;
853 text = "Spawned " + n + " x " + p[1];
854 if (run != null) run.Spawned += n;
855 break;
856 case "MODACT": text = "My Mods: " + (p.Length >= 3 ? p[2] : ""); break;
857 case "MUSICPLAY": text = "Music: " + (p.Length >= 3 ? p[2] : ""); break;
858 default: return;
859 }
860 AddHistory(text);
861 }
862
863 private void AddHistory(string text)
864 {
865 history.Add((DateTime.Now, text));
866 if (history.Count > 300) history.RemoveRange(0, history.Count - 300);
867 historyDirty = true;
868 }
869
870 private void ToolsLine(string cmd, string rest)
871 {
872 if (cmd == "MSG" && rest.Length > 0) AddHistory("Game: " + rest);
873 else if (cmd == "HOTKEY") OnHotkey(rest.Trim());
874 }
875
876 private void SaveRuns()
877 {
878 try { Directory.CreateDirectory(Dirs.Config); File.WriteAllLines(RunsFile, pastRuns.Select(r => r.Line())); } catch (Exception) { }
879 }
880
881 private void RunTick()
882 {
883 bool inRun = link.IsConnected && vitals != null;
884 DateTime now = DateTime.UtcNow;
885 if (inRun)
886 {
887 noRunSince = DateTime.MinValue;
888 if (run == null)
889 {
890 run = new LRun { Start = DateTime.Now };
891 foreach (COpt o in CheatToggles()) if (IsOn(o.Id)) run.Cheats.Add(o.Id);
892 bookmarks.Clear();
893 lastRunTick = now;
894 }
895 if (V(vitals, "alive", 1f) > 0) run.Secs += Math.Min(5.0, (now - lastRunTick).TotalSeconds);
896 else run.Died = true;
897 int depth = (int)V(info, "depth", -2f);
898 if (depth >= 0) run.Deepest = Math.Max(run.Deepest, depth + 1);
899 float blood = V(vitals, "blood", -1f);
900 if (blood >= 0 && run.LastBlood >= 0) { float d = blood - run.LastBlood; if (d < 0) run.BloodLost -= d; else run.BloodGained += d; }
901 if (blood >= 0) run.LastBlood = blood;
902 int miss = (int)V(vitals, "missing", -1f);
903 if (miss >= 0 && run.LastMissing >= 0 && miss > run.LastMissing) run.LimbsLost += miss - run.LastMissing;
904 if (miss >= 0) run.LastMissing = miss;
905 }
906 else if (run != null)
907 {
908 if (noRunSince == DateTime.MinValue) noRunSince = now;
909 else if ((now - noRunSince).TotalSeconds >= 4 || !link.IsConnected)
910 {
911 if (run.Secs >= 10) { pastRuns.Add(run); if (pastRuns.Count > 40) pastRuns.RemoveRange(0, pastRuns.Count - 40); SaveRuns(); }
912 run = null;
913 bookmarks.Clear();
914 }
915 }
916 lastRunTick = now;
917 }
918
919 private async Task ClearRuns()
920 {
921 if (!await Confirm("Clear run history", "Delete every saved run?")) return;
922 pastRuns.Clear(); SaveRuns(); RebuildTools(true);
923 }
924
925 private async Task SaveHistory()
926 {
927 IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Save activity history", SuggestedFileName = "Ultra Paradise activity.txt" });
928 string path = f?.TryGetLocalPath();
929 if (path == null) return;
930 try { File.WriteAllLines(path, history.Select(h => h.at.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " " + h.text)); } catch (Exception e) { Message("Couldn't save: " + e.Message, true); }
931 }
932
933 private static bool BackupName(string n)
934 {
935 string e = Path.GetExtension(n).ToLowerInvariant();
936 return n.IndexOfAny(new[] { '/', '\\', ':' }) < 0 && e is ".ini" or ".txt" or ".json" or ".cfg";
937 }
938
939 private async Task BackupAll()
940 {
941 IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Back up everything", SuggestedFileName = "Ultra Paradise backup " + DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".zip" });
942 string path = f?.TryGetLocalPath();
943 if (path == null) return;
944 try
945 {
946 int n = 0;
947 using (ZipArchive z = ZipFile.Open(path, ZipArchiveMode.Create))
948 foreach (string file in Directory.GetFiles(Dirs.Config))
949 {
950 string name = Path.GetFileName(file);
951 if (!BackupName(name) || new FileInfo(file).Length > 4 * 1024 * 1024) continue;
952 z.CreateEntryFromFile(file, name);
953 n++;
954 }
955 Message("Backed up " + n + " files to " + Path.GetFileName(path) + ".", false);
956 }
957 catch (Exception e) { Message("Couldn't make the backup: " + e.Message, true); }
958 }
959
960 private async Task RestoreAll()
961 {
962 var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Restore a backup", AllowMultiple = false });
963 string path = files.Count > 0 ? files[0].TryGetLocalPath() : null;
964 if (path == null) return;
965 if (!await Confirm("Restore backup", "Replace your current settings, profiles, macros and theme with the ones in this backup? Restart the trainer afterwards.")) return;
966 try
967 {
968 int n = 0;
969 using (ZipArchive z = ZipFile.OpenRead(path))
970 {
971 if (!z.Entries.Any(e => e.FullName == "settings.ini")) { Message("That zip isn't an Ultra Paradise backup.", true); return; }
972 foreach (ZipArchiveEntry e in z.Entries)
973 {
974 if (!BackupName(e.FullName) || e.Length > 4 * 1024 * 1024) continue;
975 e.ExtractToFile(Path.Combine(Dirs.Config, e.FullName), true);
976 n++;
977 }
978 }
979 Settings.Load();
980 Message("Restored " + n + " files. Close and reopen the trainer to finish.", false);
981 }
982 catch (Exception e) { Message("Couldn't restore the backup: " + e.Message, true); }
983 }
984
985 private void ToolsTick()
986 {
987 DateTime now = DateTime.UtcNow;
988 foreach (string id in timers.Where(kv => now >= kv.Value).Select(kv => kv.Key).ToList())
989 {
990 timers.Remove(id);
991 SetCheat(id, false);
992 Message((byId.TryGetValue(id, out COpt o) ? o.Name : id) + " turned itself off.", false);
993 }
994 RunTick();
995 WatchTick();
996 RandomTick();
997 OverlayTick();
998 RebuildTools(false);
999 }
1000
1001 private Window Dialog(string title, out StackPanel sp)
1002 {
1003 sp = new StackPanel { Margin = new Thickness(20), Spacing = 10 };
1004 return new Window { Title = title, Width = 440, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = Ui.B(Ui.Back), Content = sp };
1005 }
1006
1007 private async Task<bool> OkCancel(Window w, StackPanel sp, string ok)
1008 {
1009 bool result = false;
1010 Button okB = new() { Content = ok, Padding = new Thickness(16, 6), Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent), IsDefault = true };
1011 Button cancel = new() { Content = "Cancel", Padding = new Thickness(16, 6), IsCancel = true };
1012 okB.Click += (_, _) => { result = true; w.Close(); };
1013 cancel.Click += (_, _) => w.Close();
1014 sp.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right, Children = { cancel, okB } });
1015 await w.ShowDialog(this);
1016 return result;
1017 }
1018
1019 private async Task<string> AskText(string title, string prompt, string def)
1020 {
1021 Window w = Dialog(title, out StackPanel sp);
1022 sp.Children.Add(T(prompt, 13, Ui.B(Ui.Text), false, true));
1023 TextBox t = new() { Text = def ?? "", MaxLength = 32 };
1024 sp.Children.Add(t);
1025 w.Opened += (_, _) => { t.Focus(); t.SelectAll(); };
1026 return await OkCancel(w, sp, "OK") ? (t.Text ?? "").Trim() : null;
1027 }
1028
1029 private async Task<bool> Confirm(string title, string text)
1030 {
1031 Window w = Dialog(title, out StackPanel sp);
1032 sp.Children.Add(T(text, 13, Ui.B(Ui.Text), false, true));
1033 return await OkCancel(w, sp, "Yes");
1034 }
1035
1036 private Button KeyCatcher(string start, Action<string> changed)
1037 {
1038 string cur = start ?? "";
1039 Button b = new() { Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)", HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 32 };
1040 bool listening = false;
1041 b.Click += (_, _) => { listening = true; b.Content = "Press a key..."; b.Focus(); };
1042 b.KeyDown += (_, e) =>
1043 {
1044 if (!listening) return;
1045 Key k = e.Key;
1046 if (k is Key.LeftCtrl or Key.RightCtrl or Key.LeftShift or Key.RightShift or Key.LeftAlt or Key.RightAlt or Key.LWin or Key.RWin) return;
1047 e.Handled = true;
1048 listening = false;
1049 if (k == Key.Escape) { b.Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)"; return; }
1050 if (k is Key.Delete or Key.Back) cur = "";
1051 else
1052 {
1053 string u = KeyMap.Unity(k);
1054 if (u == null) { b.Content = "That key can't be used"; return; }
1055 cur = (e.KeyModifiers.HasFlag(KeyModifiers.Control) ? "Ctrl+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? "Shift+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Alt) ? "Alt+" : "") + u;
1056 }
1057 b.Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)";
1058 changed(cur);
1059 };
1060 return b;
1061 }
1062
1063 private async Task<string> AskKey(string title, string what, string start)
1064 {
1065 Window w = Dialog(title, out StackPanel sp);
1066 sp.Children.Add(T(what + " Click the box, then press a key. Delete clears it.", 13, Ui.B(Ui.Text), false, true));
1067 string got = start ?? "";
1068 sp.Children.Add(KeyCatcher(got, k => got = k));
1069 return await OkCancel(w, sp, "OK") ? got : null;
1070 }
1071
1072 private async Task<bool> PickMany(string title, string text, List<COpt> pool, HashSet<string> picked)
1073 {
1074 Window w = Dialog(title, out StackPanel sp);
1075 sp.Children.Add(T(text, 13, Ui.B(Ui.Text), false, true));
1076 StackPanel list = new() { Spacing = 2 };
1077 List<(CheckBox cb, string id)> boxes = new();
1078 foreach (COpt o in pool)
1079 {
1080 CheckBox cb = new() { Content = o.Name + " · " + originOf.GetValueOrDefault(o.Id, ""), IsChecked = picked.Contains(o.Id) };
1081 boxes.Add((cb, o.Id));
1082 list.Children.Add(cb);
1083 }
1084 sp.Children.Add(new ScrollViewer { Content = list, Height = 320 });
1085 if (!await OkCancel(w, sp, "Save")) return false;
1086 picked.Clear();
1087 foreach (var (cb, id) in boxes) if (cb.IsChecked == true) picked.Add(id);
1088 return true;
1089 }
1090
1091 private async Task EditMacro(LMacro m)
1092 {
1093 Window w = Dialog("Macro", out StackPanel sp);
1094 w.Width = 480;
1095 sp.Children.Add(T("Name", 13, Ui.B(Ui.Text)));
1096 TextBox name = new() { Text = m.Name, MaxLength = 32 };
1097 sp.Children.Add(name);
1098 sp.Children.Add(T("What it does with toggles (actions like Heal always just run)", 13, Ui.B(Ui.Text), false, true));
1099 ComboBox mode = new() { ItemsSource = ModeNames, SelectedIndex = Math.Max(0, Array.IndexOf(ModeIds, m.Mode)), HorizontalAlignment = HorizontalAlignment.Stretch };
1100 sp.Children.Add(mode);
1101 sp.Children.Add(T("When the hotkey works (contextual hotkey)", 13, Ui.B(Ui.Text)));
1102 ComboBox cond = new() { ItemsSource = CondNames, SelectedIndex = Math.Max(0, Array.IndexOf(CondIds, m.Cond)), HorizontalAlignment = HorizontalAlignment.Stretch };
1103 sp.Children.Add(cond);
1104 sp.Children.Add(T("Cheats and actions in this macro", 13, Ui.B(Ui.Text)));
1105 StackPanel list = new() { Spacing = 2 };
1106 List<(CheckBox cb, string id)> boxes = new();
1107 foreach (COpt o in MacroPool())
1108 {
1109 CheckBox cb = new() { Content = o.Name + (o.Kind == CKind.Action ? " (action)" : "") + " · " + originOf.GetValueOrDefault(o.Id, ""), IsChecked = m.Ids.Contains(o.Id) };
1110 boxes.Add((cb, o.Id));
1111 list.Children.Add(cb);
1112 }
1113 sp.Children.Add(new ScrollViewer { Content = list, Height = 240 });
1114 sp.Children.Add(T("Hotkey", 13, Ui.B(Ui.Text)));
1115 string key = m.Key;
1116 sp.Children.Add(KeyCatcher(key, k => key = k));
1117 if (!await OkCancel(w, sp, "Save")) return;
1118 string nm = (name.Text ?? "").Trim().Replace("|", "/");
1119 List<string> ids = boxes.Where(b => b.cb.IsChecked == true).Select(b => b.id).ToList();
1120 if (nm.Length == 0 || ids.Count == 0) { Message("A macro needs a name and at least one cheat or action.", true); return; }
1121 m.Name = nm;
1122 m.Mode = ModeIds[Math.Max(0, mode.SelectedIndex)];
1123 m.Cond = CondIds[Math.Max(0, cond.SelectedIndex)];
1124 m.Ids = ids;
1125 m.Key = key;
1126 if (m.Key.Length > 0 && KeyTaken(m.Key, m)) { Message(Cheats.KeyLabel(m.Key) + " is already used, so the macro was saved without a hotkey.", true); m.Key = ""; }
1127 if (!macros.Contains(m)) macros.Add(m);
1128 SaveMacros(); SendXBinds(); RebuildTools(true);
1129 }
1130 }
1131}