using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform.Storage; using UltraParadise.Shared; using Path = System.IO.Path; namespace UltraParadise.Linux { internal sealed class LProfile { public string Name; public HashSet On = new(); public Dictionary Vals = new(); public Dictionary Keys = new(); public string Hot = ""; public bool Chaos; } internal sealed class LMacro { public string Name = "", Cond = "always", Mode = "on", Key = ""; public List Ids = new(); } internal sealed class LRun { public DateTime Start; public double Secs; public int Deepest; public bool Died; public float BloodLost, BloodGained; public int LimbsLost, Spawned, Actions; public HashSet Cheats = new(); public float LastBlood = -1f; public int LastMissing = -1; public bool Cheated => Cheats.Count > 0 || Spawned > 0 || Actions > 0; public string Line() => string.Join("|", Start.Ticks.ToString(CultureInfo.InvariantCulture), ((int)Secs).ToString(CultureInfo.InvariantCulture), Deepest, Died ? 1 : 0, BloodLost.ToString("0.#", CultureInfo.InvariantCulture), BloodGained.ToString("0.#", CultureInfo.InvariantCulture), LimbsLost, Spawned, Actions, string.Join(";", Cheats).Replace("|", "/")); public static LRun Parse(string s) { string[] p = s.Split('|'); if (p.Length < 10 || !long.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out long ticks) || ticks <= 0 || ticks >= DateTime.MaxValue.Ticks) return null; LRun r = new() { Start = new DateTime(ticks), Died = p[3] == "1" }; if (int.TryParse(p[1], out int i)) r.Secs = i; if (int.TryParse(p[2], out i)) r.Deepest = i; if (float.TryParse(p[4], NumberStyles.Float, CultureInfo.InvariantCulture, out float f)) r.BloodLost = f; if (float.TryParse(p[5], NumberStyles.Float, CultureInfo.InvariantCulture, out f)) r.BloodGained = f; if (int.TryParse(p[6], out i)) r.LimbsLost = i; if (int.TryParse(p[7], out i)) r.Spawned = i; if (int.TryParse(p[8], out i)) r.Actions = i; foreach (string c in p[9].Split(';')) if (c.Length > 0) r.Cheats.Add(c); return r; } } internal sealed partial class MainWindow { private readonly List profiles = new(); private readonly List macros = new(); private readonly Dictionary timers = new(); private readonly HashSet neverRandom = new(); private readonly HashSet randOn = new(); private DateTime nextRandom = DateTime.MaxValue; private readonly List<(string name, float x, float y, int depth)> bookmarks = new(); private readonly List<(DateTime at, string text)> history = new(); private LRun run; private DateTime noRunSince = DateTime.MinValue, lastRunTick = DateTime.MinValue; private readonly List pastRuns = new(); private readonly List watched = new(); private readonly HashSet alerting = new(); private readonly Dictionary checkBad = new(); private readonly Dictionary originOf = new(); private string toolsSig = "", lastOvExtra = ""; private bool historyDirty; private readonly StackPanel profList = new() { Spacing = 6 }, macroList = new() { Spacing = 6 }, timerList = new() { Spacing = 6 }, bookList = new() { Spacing = 6 }, checkList = new() { Spacing = 4 }, watchList = new() { Spacing = 6 }, allValues = new() { Spacing = 4 }, runNow = new() { Spacing = 3 }, runPast = new() { Spacing = 3 }, histList = new() { Spacing = 2 }; private readonly List<(TextBlock tb, Func text)> liveText = new(); private readonly TextBlock randText = T("", 13, Ui.B(Ui.Text), false, true); private static readonly string[] DefaultNever = { "UnchippedChallenge", "HopelessStart", "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "FastRadiation", "ColdCaves", "MoreTraps", "LootScarcity", "FreeCamera", "Noclip", "FlyMode", "ClickTeleport", "MoodLock" }; private static readonly string[] CondIds = { "always", "run", "bleeding", "critical", "hurt", "hungry", "trader" }; 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" }; private static readonly string[] ModeIds = { "on", "off", "flip" }; private static readonly string[] ModeNames = { "Turn the cheats on", "Turn the cheats off", "Flip them (on to off, off to on)" }; private static readonly (string key, string name, string unit)[] WatchKeys = { ("blood", "Blood", "%"), ("bleed", "Bleeding", " L/min"), ("oxy", "Blood oxygen", "%"), ("consc", "Consciousness", "%"), ("brain", "Brain health", "%"), ("hr", "Heart rate", " bpm"), ("temp", "Body temperature", "°"), ("pain", "Pain", ""), ("hunger", "Food", ""), ("thirst", "Water", ""), ("energy", "Energy", ""), ("mood", "Mood", ""), ("sick", "Sickness", ""), ("rad", "Radiation", ""), ("venom", "Venom", ""), ("infect", "Infection", ""), ("broken", "Broken bones", ""), ("disloc", "Dislocations", ""), ("shrapnel", "Shrapnel", ""), ("missing", "Missing limbs", ""), }; private static string RunsFile => Path.Combine(Dirs.Config, "runs.txt"); private void SetupTools() { foreach (CTab t in tabs) foreach (CSection s in t.Sections) foreach (COpt o in s.Rows) originOf[o.Id] = t.Name; LoadProfiles(); LoadMacros(); string nv = Settings.Get("rand.never", null); if (nv != null) { foreach (string s in nv.Split(',')) if (s.Length > 0) neverRandom.Add(s); } else foreach (string s in DefaultNever) neverRandom.Add(s); foreach (string s in Settings.Get("watch", "").Split(',')) if (WatchIndex(s) >= 0 && !watched.Contains(s)) watched.Add(s); 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) { } link.Sent += s => Avalonia.Threading.Dispatcher.UIThread.Post(() => OnSent(s)); } private bool IsOn(string id) => lastState.TryGetValue(id, out string v) && v == "1"; private List CheatToggles() => tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows).Where(o => o.Kind == CKind.Toggle).ToList(); private List MacroPool() => tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows).Where(o => o.Kind is CKind.Toggle or CKind.Action).ToList(); private void SetCheat(string id, bool on) { if (!link.IsConnected || IsOn(id) == on) return; link.Send("SET " + id + (on ? " 1" : " 0")); NoteState(id, on ? "1" : "0"); if (stateSetters.TryGetValue(id, out Action set)) set(on ? "1" : "0"); if (!on) { timers.Remove(id); randOn.Remove(id); } } private static string PName(string s) { string r = new string((s ?? "").Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '_' or '\'' or '!').ToArray()).Trim(); return r.Length > 24 ? r[..24].Trim() : r; } private static float V(Dictionary d, string k, float def) => d != null && d.TryGetValue(k, out string s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float f) ? f : def; private static string Clock2(int s) => (s / 60).ToString(CultureInfo.InvariantCulture) + ":" + (s % 60).ToString("00", CultureInfo.InvariantCulture); private static string Long(double secs) { int s = (int)secs; return s >= 3600 ? (s / 3600) + "h " + ((s / 60) % 60).ToString("00") + "m" : Clock2(s); } private TextBlock Live(Func text, bool dim = false) { TextBlock tb = T(text() ?? "", 13, Ui.B(dim ? Ui.Dim : Ui.Text), false, true); liveText.Add((tb, text)); return tb; } private Grid LineRow(Func text, params Button[] bs) { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; TextBlock tb = Live(text); tb.VerticalAlignment = VerticalAlignment.Center; g.Children.Add(tb); StackPanel sp = new() { Orientation = Orientation.Horizontal, Spacing = 4 }; foreach (Button b in bs) { b.Padding = new Thickness(10, 3); b.MinHeight = 28; sp.Children.Add(b); } Grid.SetColumn(sp, 1); g.Children.Add(sp); return g; } private static StackPanel Col(int i) { StackPanel c = new() { Margin = new Thickness(i == 0 ? 0 : 7, 0, i == 2 ? 0 : 7, 0) }; Grid.SetColumn(c, i); return c; } private Control ProfilesPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2); Border a = Section("PROFILES", out StackPanel ab); 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)); ab.Children.Add(profList); ab.Children.Add(Row(Btn("New From Current Cheats", () => _ = NewProfile()), Btn("Import...", () => _ = ImportProfile()))); c0.Children.Add(a); Border b = Section("MACROS", out StackPanel bb); 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)); bb.Children.Add(macroList); bb.Children.Add(Row(Btn("New Macro...", () => _ = EditMacro(new LMacro())))); c1.Children.Add(b); Border c = Section("BACK UP EVERYTHING", out StackPanel cb); 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)); cb.Children.Add(Row(Btn("Back Up...", () => _ = BackupAll()), Btn("Restore...", () => _ = RestoreAll()))); c2.Children.Add(c); g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2); RebuildTools(true); return Scroll(g); } private Control ToolsPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2); Border a = Section("TIMED CHEATS", out StackPanel ab); 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)); ab.Children.Add(timerList); c0.Children.Add(a); Border r = Section("RANDOMIZER", out StackPanel rb); rb.Children.Add(Row(Btn("Random Cheat", RandomOne), Btn("Shuffle", () => Shuffle(RandCount())), Btn("Never List...", () => _ = EditNever()))); rb.Children.Add(randText); rb.Children.Add(Row(Btn("Shuffle 3", () => SetRand("rand.count", "3")), Btn("5", () => SetRand("rand.count", "5")), Btn("8", () => SetRand("rand.count", "8")))); 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")))); 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)); c0.Children.Add(r); Border b = Section("TELEPORT BOOKMARKS", out StackPanel bb); 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)); bb.Children.Add(Row(Btn("Save This Spot", () => _ = SaveSpot()))); bb.Children.Add(bookList); c1.Children.Add(b); Border c = Section("CHEAT CHECK", out StackPanel cb); 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)); cb.Children.Add(checkList); c2.Children.Add(c); g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2); return Scroll(g); } private Control WatchPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,2*") }; StackPanel c0 = Col(0), c1 = Col(2); Grid.SetColumn(c1, 1); Border a = Section("WATCHING", out StackPanel ab); 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)); ab.Children.Add(watchList); c0.Children.Add(a); Border b = Section("LIVE VALUES", out StackPanel bb); bb.Children.Add(allValues); c1.Children.Add(b); g.Children.Add(c0); g.Children.Add(c1); return Scroll(g); } private Control StatsPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; StackPanel c0 = Col(0), c1 = Col(1), c2 = Col(2); Border a = Section("THIS RUN", out StackPanel ab); ab.Children.Add(runNow); c0.Children.Add(a); Border b = Section("PAST RUNS", out StackPanel bb); bb.Children.Add(runPast); 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)); c1.Children.Add(b); Border c = Section("ACTIVITY HISTORY", out StackPanel cb); cb.Children.Add(Row(Btn("Save to File...", () => _ = SaveHistory()), Btn("Clear", () => { history.Clear(); historyDirty = true; RebuildTools(true); }))); cb.Children.Add(histList); c2.Children.Add(c); g.Children.Add(c0); g.Children.Add(c1); g.Children.Add(c2); return Scroll(g); } private void RebuildTools(bool force) { StringBuilder sig = new(); foreach (string k in timers.Keys) sig.Append(k).Append(','); sig.Append('|').Append(bookmarks.Count).Append('|').Append(watched.Count).Append('|').Append(pastRuns.Count).Append('|').Append(run != null).Append('|').Append(profiles.Count).Append(macros.Count); foreach (COpt o in CheatToggles()) if (IsOn(o.Id)) sig.Append(o.Id).Append(','); if (!force && sig.ToString() == toolsSig && !historyDirty) { RefreshLive(); return; } toolsSig = sig.ToString(); historyDirty = false; liveText.Clear(); profList.Children.Clear(); string active = Settings.Get("profile.active", ""); foreach (LProfile p in profiles) { LProfile pp = p; Button more = Btn("More", () => { }); more.ContextMenu = ProfileMenu(pp); more.Click += (_, _) => more.ContextMenu?.Open(more); profList.Children.Add(LineRow(() => (pp.Name == active ? "● " : "") + pp.Name + (pp.Chaos ? " (random)" : " (" + pp.On.Count + ")") + (pp.Hot.Length > 0 ? " " + Cheats.KeyLabel(pp.Hot) : ""), Btn("Load", () => LoadProfile(pp)), Btn("Save Here", () => _ = SaveHere(pp)), more)); } macroList.Children.Clear(); foreach (LMacro m in macros) { LMacro mm = m; macroList.Children.Add(LineRow(() => mm.Name + (mm.Key.Length > 0 ? " " + Cheats.KeyLabel(mm.Key) : ""), Btn("Run", () => RunMacro(mm)), Btn("Edit", () => _ = EditMacro(mm)), Btn("Delete", () => _ = DeleteMacro(mm)))); string names = string.Join(", ", mm.Ids.Select(i => byId.TryGetValue(i, out COpt o) ? o.Name : i)); if (mm.Cond != "always") names += " · " + CondNames[Math.Max(0, Array.IndexOf(CondIds, mm.Cond))].ToLowerInvariant(); macroList.Children.Add(T(names, 12, Ui.B(Ui.Dim), false, true)); } timerList.Children.Clear(); foreach (string id in timers.Keys.ToList()) { string iid = id; string nm = byId.TryGetValue(id, out COpt o) ? o.Name : id; timerList.Children.Add(LineRow(() => timers.TryGetValue(iid, out DateTime t) ? nm + " " + Clock2(Math.Max(0, (int)(t - DateTime.UtcNow).TotalSeconds)) : nm, 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); }))); } if (timers.Count == 0) timerList.Children.Add(T("No timers running.", 13, Ui.B(Ui.Text))); bookList.Children.Clear(); for (int i = 0; i < bookmarks.Count; i++) { int ii = i; var bm = bookmarks[i]; bookList.Children.Add(LineRow(() => bm.name + (bm.depth >= 0 ? " (layer " + (bm.depth + 1) + ")" : " (special area)"), Btn("Go", () => { if (Linked()) link.Send("ACT tpgo " + bm.x.ToString(CultureInfo.InvariantCulture) + " " + bm.y.ToString(CultureInfo.InvariantCulture) + " " + bm.depth); }), Btn("Delete", () => { if (ii < bookmarks.Count) bookmarks.RemoveAt(ii); RebuildTools(true); }))); } checkList.Children.Clear(); int n = 0; foreach (COpt o in CheatToggles()) { if (!IsOn(o.Id)) continue; COpt oo = o; checkList.Children.Add(Live(() => CheckLine(oo))); n++; } if (n == 0) checkList.Children.Add(T("No cheats are on.", 13, Ui.B(Ui.Text))); watchList.Children.Clear(); foreach (string k in watched) { string kk = k; watchList.Children.Add(LineRow(() => WatchKeys[WatchIndex(kk)].name + ": " + WatchValue(kk) + (AlertText(kk).Length > 0 ? " (" + AlertText(kk) + ")" : ""), Btn("Alert...", () => _ = EditAlert(kk)), Btn("Unpin", () => { watched.Remove(kk); alerting.Remove(kk); SaveWatch(); RebuildTools(true); }))); } if (watched.Count == 0) watchList.Children.Add(T("Nothing pinned yet. Pin values from the list.", 13, Ui.B(Ui.Text), false, true)); allValues.Children.Clear(); foreach (var w in WatchKeys) { string k = w.key; allValues.Children.Add(LineRow(() => w.name + ": " + WatchValue(k), Btn(watched.Contains(k) ? "Pinned" : "Pin", () => { if (!watched.Remove(k)) watched.Add(k); SaveWatch(); RebuildTools(true); }))); } runNow.Children.Clear(); runNow.Children.Add(Live(() => run == null ? "Not in a run." : "Time: " + Long(run.Secs) + (run.Died ? " (died)" : ""))); runNow.Children.Add(Live(() => run == null ? "" : "Deepest layer: " + Math.Max(1, run.Deepest))); runNow.Children.Add(Live(() => run == null ? "" : "Blood lost: " + run.BloodLost.ToString("0", CultureInfo.InvariantCulture) + " healed: " + run.BloodGained.ToString("0", CultureInfo.InvariantCulture))); runNow.Children.Add(Live(() => run == null ? "" : "Limbs lost: " + run.LimbsLost)); runNow.Children.Add(Live(() => run == null ? "" : "Items spawned: " + run.Spawned + " actions used: " + run.Actions)); 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")); runPast.Children.Clear(); double total = pastRuns.Sum(r => r.Secs); 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)); for (int i = pastRuns.Count - 1; i >= 0 && i >= pastRuns.Count - 12; i--) { LRun r = pastRuns[i]; 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)); } if (pastRuns.Count > 0) runPast.Children.Add(Row(Btn("Clear Run History", () => _ = ClearRuns()))); histList.Children.Clear(); if (history.Count == 0) histList.Children.Add(T("Nothing yet. Everything the trainer does shows up here.", 13, Ui.B(Ui.Text), false, true)); for (int i = history.Count - 1; i >= 0 && i >= history.Count - 40; i--) histList.Children.Add(T(history[i].at.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + history[i].text, 12.5, Ui.B(Ui.Text), false, true)); RefreshLive(); } private void RefreshLive() { foreach (var (tb, text) in liveText) tb.Text = text() ?? ""; int e = RandEvery(); randText.Text = "Shuffle turns on " + RandCount() + ". " + (e == 0 ? "Swapping is off." : "Swaps one every " + e + " min."); } private void LoadProfiles() { profiles.Clear(); string list = Settings.Get("profiles", null); if (list == null) { profiles.Add(new LProfile { Name = "Sandbox", On = new HashSet { "GodMode", "NoHunger", "NoThirst", "NoTiredness", "InfiniteStamina", "FreeCrafting", "NoCraftFail", "AllRecipes", "UnlimitedAmmo", "NoDegradation", "UnlimitedBattery", "UnlimitedCarry", "FullBright", "MasterLockpick" } }); profiles.Add(new LProfile { Name = "Survival", On = new HashSet { "NoFallDamage", "InfiniteStamina", "AllRecipes", "NoCraftFail", "FasterHealing" } }); profiles.Add(new LProfile { Name = "Chaos", Chaos = true }); profiles.Add(new LProfile { Name = "Hardcore", On = new HashSet { "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "LootScarcity", "ColdCaves", "MoreTraps" } }); foreach (LProfile p in profiles) p.On.RemoveWhere(id => !byId.ContainsKey(id)); SaveProfiles(); return; } foreach (string n in list.Split('|')) { if (n.Length == 0) continue; string k = "profile." + n + "."; LProfile p = new() { Name = n, Hot = Settings.Get(k + "hot", ""), Chaos = Settings.Get(k + "chaos", "0") == "1" }; foreach (string s in Settings.Get(k + "on", "").Split(',')) if (byId.ContainsKey(s)) p.On.Add(s); 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]; } 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]; } profiles.Add(p); } } private void SaveProfiles() { foreach (string k in Settings.Keys().Where(k => k.StartsWith("profile.", StringComparison.Ordinal) && k != "profile.active").ToList()) Settings.Set(k, null); foreach (LProfile p in profiles) { string k = "profile." + p.Name + "."; Settings.Set(k + "on", string.Join(",", p.On)); if (p.Vals.Count > 0) Settings.Set(k + "val", string.Join(",", p.Vals.Select(kv => kv.Key + ":" + kv.Value))); if (p.Keys.Count > 0) Settings.Set(k + "lkeys", string.Join(",", p.Keys.Select(kv => kv.Key + ":" + kv.Value))); if (p.Hot.Length > 0) Settings.Set(k + "hot", p.Hot); if (p.Chaos) Settings.Set(k + "chaos", "1"); } Settings.Set("profiles", string.Join("|", profiles.Select(p => p.Name))); } private LProfile FindProfile(string n) => profiles.FirstOrDefault(p => string.Equals(p.Name, n, StringComparison.OrdinalIgnoreCase)); private string UniqueName(string n) { n = PName(n); if (n.Length == 0) n = "Profile"; if (FindProfile(n) == null) return n; for (int i = 2; ; i++) if (FindProfile(n + " " + i) == null) return n + " " + i; } private void CaptureInto(LProfile p) { p.On.Clear(); p.Vals.Clear(); p.Keys.Clear(); foreach (COpt o in tabs.SelectMany(t => t.Sections).SelectMany(s => s.Rows)) { if (o.Kind == CKind.Toggle && IsOn(o.Id)) p.On.Add(o.Id); if (o.Kind == CKind.Slider && lastState.TryGetValue(o.Id, out string v)) p.Vals[o.Id] = v; 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; } } private void LoadProfile(LProfile p) { if (!Linked()) return; foreach (COpt o in CheatToggles()) SetCheat(o.Id, !p.Chaos && p.On.Contains(o.Id)); foreach (var kv in p.Vals) if (byId.TryGetValue(kv.Key, out COpt o) && o.Kind == CKind.Slider && float.TryParse(kv.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out float f)) { string v = Math.Clamp(f, o.Min, o.Max).ToString("0.###", CultureInfo.InvariantCulture); link.Send("VAL " + o.Id + " " + v); if (stateSetters.TryGetValue(o.Id, out Action set)) set(v); } if (p.Keys.Count > 0) foreach (COpt o in MacroPool()) { string v = p.Keys.TryGetValue(o.Id, out string k) ? k : "none"; binds[o.Id] = v; Settings.Set("bind." + o.Id, v); link.Send("BIND " + o.Id + " " + v); if (keyButtons.TryGetValue(o.Id, out Button b)) b.Content = Cheats.KeyLabel(v); } if (p.Chaos) Shuffle(RandCount()); Settings.Set("profile.active", p.Name); Message("Loaded the " + p.Name + " profile.", false); RebuildTools(true); } private async Task NewProfile() { string n = await AskText("New profile", "Name for the new profile (it starts with the cheats you have on now):", "My Profile"); if (n == null) return; LProfile p = new() { Name = UniqueName(n) }; CaptureInto(p); profiles.Add(p); SaveProfiles(); RebuildTools(true); } private async Task SaveHere(LProfile p) { if (!await Confirm("Save profile", "Replace the " + p.Name + " profile with the cheats, sliders and hotkeys you have now?")) return; CaptureInto(p); p.Chaos = false; SaveProfiles(); RebuildTools(true); Message("Saved the " + p.Name + " profile.", false); } private ContextMenu ProfileMenu(LProfile p) { ContextMenu m = new(); void Add(string h, Action a) { MenuItem i = new() { Header = h }; i.Click += (_, _) => a(); m.Items.Add(i); } Add("Rename...", async () => { string n = await AskText("Rename profile", "New name for " + p.Name + ":", p.Name); n = PName(n); if (string.IsNullOrEmpty(n)) return; LProfile o = FindProfile(n); if (o != null && o != p) { Message("There's already a profile called " + n + ".", true); return; } if (Settings.Get("profile.active", "") == p.Name) Settings.Set("profile.active", n); p.Name = n; SaveProfiles(); RebuildTools(true); }); Add("Duplicate", () => { LProfile c = new() { Name = UniqueName(p.Name + " copy"), Chaos = p.Chaos, On = new HashSet(p.On), Vals = new Dictionary(p.Vals), Keys = new Dictionary(p.Keys) }; profiles.Insert(profiles.IndexOf(p) + 1, c); SaveProfiles(); RebuildTools(true); }); Add("Set Hotkey...", async () => { string k = await AskKey("Profile hotkey", "Hotkey that loads the " + p.Name + " profile.", p.Hot); if (k == null) return; if (k.Length > 0 && KeyTaken(k, p)) { Message(Cheats.KeyLabel(k) + " is already used. Pick another key.", true); return; } p.Hot = k; SaveProfiles(); SendXBinds(); RebuildTools(true); }); Add(p.Chaos ? "Stop Randomizing on Load" : "Randomize on Load (Chaos)", () => { p.Chaos = !p.Chaos; SaveProfiles(); RebuildTools(true); }); Add("Export...", () => _ = ExportProfile(p)); Add("Delete", async () => { if (!await Confirm("Delete profile", "Delete the " + p.Name + " profile? This can't be undone.")) return; profiles.Remove(p); SaveProfiles(); SendXBinds(); RebuildTools(true); }); return m; } private async Task ExportProfile(LProfile p) { IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Export profile", SuggestedFileName = p.Name + ".upprofile" }); string path = f?.TryGetLocalPath(); if (path == null) return; List 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") }; try { File.WriteAllLines(path, l); Message("Exported " + p.Name + ".", false); } catch (Exception e) { Message("Couldn't save the file: " + e.Message, true); } } private async Task ImportProfile() { var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Import profile", AllowMultiple = false }); string path = files.Count > 0 ? files[0].TryGetLocalPath() : null; if (path == null) return; string[] lines; try { if (new FileInfo(path).Length > 65536) { Message("That file is too big to be a profile.", true); return; } lines = File.ReadAllLines(path); } catch (Exception e) { Message("Couldn't read the file: " + e.Message, true); return; } if (lines.Length == 0 || lines[0].Trim() != "UltraParadiseProfile 1") { Message("That isn't an Ultra Paradise profile file.", true); return; } Dictionary m = new(); foreach (string ln in lines) { int eq = ln.IndexOf('='); if (eq > 0) m[ln[..eq].Trim()] = ln[(eq + 1)..].Trim(); } LProfile p = new() { Name = UniqueName(m.GetValueOrDefault("name", Path.GetFileNameWithoutExtension(path))), Chaos = m.GetValueOrDefault("chaos", "0") == "1" }; foreach (string s in m.GetValueOrDefault("on", "").Split(',')) if (byId.TryGetValue(s, out COpt o) && o.Kind == CKind.Toggle) p.On.Add(s); 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]; } 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]; } profiles.Add(p); SaveProfiles(); RebuildTools(true); Message("Imported the " + p.Name + " profile.", false); } private static bool KeyLooksOk(string k) => k.Length > 0 && k.Length < 40 && k.All(c => char.IsLetterOrDigit(c) || c == '+'); private void LoadMacros() { macros.Clear(); for (int i = 0; i < 50; i++) { string v = Settings.Get("macro." + i, null); if (v == null) continue; string[] p = v.Split('|'); if (p.Length < 5) continue; 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" }; foreach (string s in p[4].Split(',')) if (byId.ContainsKey(s)) m.Ids.Add(s); if (m.Ids.Count > 0) macros.Add(m); } } private void SaveMacros() { for (int i = 0; i < 50; i++) Settings.Set("macro." + i, null); for (int i = 0; i < macros.Count && i < 50; i++) { LMacro m = macros[i]; Settings.Set("macro." + i, m.Name.Replace("|", "/") + "|" + m.Key + "|" + m.Cond + "|" + m.Mode + "|" + string.Join(",", m.Ids)); } } private bool KeyTaken(string k, object except) { if (binds.Values.Any(v => string.Equals(v, k, StringComparison.OrdinalIgnoreCase))) return true; if (macros.Any(m => m != except && string.Equals(m.Key, k, StringComparison.OrdinalIgnoreCase))) return true; return profiles.Any(p => p != except && string.Equals(p.Hot, k, StringComparison.OrdinalIgnoreCase)); } private void SendXBinds() { if (!link.IsConnected) return; List l = new(); for (int i = 0; i < macros.Count; i++) if (macros[i].Key.Length > 0) l.Add("m" + i + "=" + macros[i].Key); for (int i = 0; i < profiles.Count; i++) if (profiles[i].Hot.Length > 0) l.Add("p" + i + "=" + profiles[i].Hot); link.Send("XBINDS " + (l.Count > 0 ? string.Join(",", l) : "-")); } private void OnHotkey(string id) { if (id.Length < 2 || !int.TryParse(id[1..], out int i)) return; if (id[0] == 'm' && i < macros.Count) RunMacro(macros[i]); else if (id[0] == 'p' && i < profiles.Count) LoadProfile(profiles[i]); } private bool CondMet(string c) => c switch { "run" => vitals != null, "bleeding" => vitals != null && V(vitals, "bleed", 0f) > 0.02f, "critical" => vitals != null && (V(vitals, "crit", 0f) > 0 || V(vitals, "arrest", 0f) > 0), "hurt" => vitals != null && (V(vitals, "pain", 0f) > 20f || V(vitals, "broken", 0f) > 0 || V(vitals, "disloc", 0f) > 0), "hungry" => vitals != null && (V(vitals, "hunger", 100f) < 35f || V(vitals, "thirst", 100f) < 35f), "trader" => info != null && info.ContainsKey("trader"), _ => true, }; private void RunMacro(LMacro m) { if (!Linked()) return; if (!CondMet(m.Cond)) { Message(m.Name + " didn't run: it works " + CondNames[Math.Max(0, Array.IndexOf(CondIds, m.Cond))].ToLowerInvariant() + ".", false); return; } foreach (string id in m.Ids) { if (!byId.TryGetValue(id, out COpt o)) continue; if (o.Kind == CKind.Toggle) SetCheat(id, m.Mode == "on" || (m.Mode == "flip" && !IsOn(id))); else link.Send("ACT " + id); } Message("Ran " + m.Name + ".", false); RebuildTools(false); } private async Task DeleteMacro(LMacro m) { if (!await Confirm("Delete macro", "Delete the " + m.Name + " macro?")) return; macros.Remove(m); SaveMacros(); SendXBinds(); RebuildTools(true); } private ContextMenu CheatContext(COpt o) { ContextMenu m = new(); m.Opening += (_, _) => { m.Items.Clear(); bool on = IsOn(o.Id); foreach (int n in new[] { 1, 2, 5, 10, 30 }) { MenuItem i = new() { Header = (on ? "Turn off in " : "Turn on for ") + n + (n == 1 ? " minute" : " minutes") }; i.Click += (_, _) => StartTimer(o, n); m.Items.Add(i); } if (timers.ContainsKey(o.Id)) { MenuItem c = new() { Header = "Cancel the timer" }; c.Click += (_, _) => { timers.Remove(o.Id); RebuildTools(false); }; m.Items.Add(c); } MenuItem nv = new() { Header = (neverRandom.Contains(o.Id) ? "✔ " : "") + "Never randomise this" }; nv.Click += (_, _) => { if (!neverRandom.Remove(o.Id)) neverRandom.Add(o.Id); SaveNever(); }; m.Items.Add(nv); MenuItem mk = new() { Header = "New macro with this cheat..." }; mk.Click += (_, _) => { LMacro x = new() { Name = o.Name }; x.Ids.Add(o.Id); _ = EditMacro(x); }; m.Items.Add(mk); }; m.Items.Add(new MenuItem { Header = "..." }); return m; } private void StartTimer(COpt o, int minutes) { if (!Linked()) return; SetCheat(o.Id, true); timers[o.Id] = DateTime.UtcNow.AddMinutes(minutes); Message(o.Name + " turns off by itself in " + minutes + (minutes == 1 ? " minute." : " minutes."), false); RebuildTools(false); } private void SaveNever() => Settings.Set("rand.never", string.Join(",", neverRandom)); private static int RandCount() => int.TryParse(Settings.Get("rand.count", "5"), out int n) ? Math.Clamp(n, 1, 12) : 5; private static int RandEvery() => int.TryParse(Settings.Get("rand.every", "0"), out int n) ? Math.Clamp(n, 0, 60) : 0; private void SetRand(string k, string v) { Settings.Set(k, v); nextRandom = DateTime.MaxValue; RefreshLive(); } private COpt RandomOn() { List l = CheatToggles().Where(o => !neverRandom.Contains(o.Id) && !IsOn(o.Id)).ToList(); if (l.Count == 0) return null; COpt o = l[Random.Shared.Next(l.Count)]; SetCheat(o.Id, true); randOn.Add(o.Id); return o; } private void RandomOne() { if (!Linked()) return; COpt o = RandomOn(); Message(o == null ? "No cheats left to turn on." : "Randomizer: " + o.Name + " on.", false); } private void Shuffle(int n) { if (!Linked()) return; foreach (COpt o in CheatToggles()) if (!neverRandom.Contains(o.Id)) SetCheat(o.Id, false); randOn.Clear(); List got = new(); for (int i = 0; i < n; i++) { COpt o = RandomOn(); if (o != null) got.Add(o.Name); } Message(got.Count == 0 ? "Nothing to randomise: every cheat is on the never list." : "Randomizer: " + string.Join(", ", got) + ".", false); } private void RandomTick() { int every = RandEvery(); if (every <= 0 || !link.IsConnected) { nextRandom = DateTime.MaxValue; return; } if (nextRandom == DateTime.MaxValue) nextRandom = DateTime.UtcNow.AddMinutes(every); if (DateTime.UtcNow < nextRandom) return; nextRandom = DateTime.UtcNow.AddMinutes(every); List mine = randOn.ToList(); string offName = null; 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; } COpt on = RandomOn(); string s = (offName != null ? offName + " off" : "") + (on != null ? (offName != null ? ", " : "") + on.Name + " on" : ""); if (s.Length > 0) Message("Randomizer: " + s + ".", false); } private async Task EditNever() { HashSet pick = new(neverRandom); if (!await PickMany("Never randomise", "Tick the cheats the randomizer and the Chaos profile should never touch.", CheatToggles(), pick)) return; neverRandom.Clear(); neverRandom.UnionWith(pick); SaveNever(); } private static int WatchIndex(string k) => Array.FindIndex(WatchKeys, w => w.key == k); private string WatchValue(string k) { if (vitals == null || !vitals.TryGetValue(k, out string s)) return "-"; int i = WatchIndex(k); return s + (i >= 0 ? WatchKeys[i].unit : ""); } private void SaveWatch() => Settings.Set("watch", string.Join(",", watched)); private static string AlertText(string k) { string a = Settings.Get("watch.alert." + k, ""); return a.Length < 2 ? "" : (a[0] == '<' ? "alert below " : "alert above ") + a[1..]; } private void WatchTick() { foreach (string k in watched) { string a = Settings.Get("watch.alert." + k, ""); if (vitals == null || a.Length < 2 || !float.TryParse(a[1..], NumberStyles.Float, CultureInfo.InvariantCulture, out float thr)) { alerting.Remove(k); continue; } float cur = V(vitals, k, float.NaN); if (float.IsNaN(cur)) continue; bool hit = a[0] == '<' ? cur < thr : cur > thr; if (hit && alerting.Add(k)) { string msg = WatchKeys[WatchIndex(k)].name + " is " + WatchValue(k) + " (" + AlertText(k) + ")"; Message(msg + ".", true); if (link.IsConnected) link.Send("TOAST " + msg); } else if (!hit) alerting.Remove(k); } } private void OverlayTick() { if (!link.IsConnected) { lastOvExtra = ""; return; } List l = new(); 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"); 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) ? " !" : "")); } string s = string.Join("\u001c", l); if (s == lastOvExtra) return; lastOvExtra = s; link.Send("OVEXTRA " + (s.Length > 0 ? s : "-")); } private async Task EditAlert(string k) { string a = Settings.Get("watch.alert." + k, ""); Window w = Dialog("Alert for " + WatchKeys[WatchIndex(k)].name.ToLowerInvariant(), out StackPanel sp); sp.Children.Add(T("Pop up a warning when " + WatchKeys[WatchIndex(k)].name.ToLowerInvariant() + " goes:", 13, Ui.B(Ui.Text), false, true)); ComboBox c = new() { ItemsSource = new[] { "No alert", "Below", "Above" }, SelectedIndex = a.StartsWith("<") ? 1 : a.StartsWith(">") ? 2 : 0, Width = 140 }; 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 }; sp.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { c, n } }); if (!await OkCancel(w, sp, "Save")) return; if (c.SelectedIndex == 0) Settings.Set("watch.alert." + k, null); else Settings.Set("watch.alert." + k, (c.SelectedIndex == 1 ? "<" : ">") + ((float)(n.Value ?? 0)).ToString(CultureInfo.InvariantCulture)); alerting.Remove(k); RebuildTools(true); } private static string CheckRule(string id, Dictionary v, out bool ok) { ok = true; switch (id) { case "GodMode": ok = V(v, "alive", 1f) > 0 && V(v, "arrest", 0f) <= 0; return "you're alive and your heart is beating"; case "NoHunger": ok = V(v, "hunger", 100f) >= 80f; return "food stays full"; case "NoThirst": ok = V(v, "thirst", 100f) >= 80f; return "water stays full"; case "NoTiredness": ok = V(v, "energy", 100f) >= 80f; return "energy stays full"; case "NoBleeding": ok = V(v, "bleed", 0f) <= 0.02f; return "no bleeding"; case "NoPain": ok = V(v, "pain", 0f) <= 5f; return "no pain"; case "NoInfection": ok = V(v, "infect", 0f) <= 1f; return "no infection"; case "NoSickness": ok = V(v, "sick", 0f) <= 1f; return "no sickness"; case "NoRadiation": ok = V(v, "rad", 0f) <= 1f; return "no radiation sickness"; case "UnlimitedOxygen": ok = V(v, "oxy", 100f) >= 90f; return "blood oxygen stays high"; case "UnlimitedCarry": ok = V(v, "enc", 0f) <= 0f; return "you're not over-encumbered"; default: return null; } } private string CheckLine(COpt o) { if (vitals == null) return o.Name + ": start a run to check it"; string what = CheckRule(o.Id, vitals, out bool ok); if (what == null) return o.Name + ": on (can't be checked from here)"; if (ok) { checkBad.Remove(o.Id); return "✔ " + o.Name + ": working (" + what + ")"; } if (!checkBad.TryGetValue(o.Id, out DateTime since)) { checkBad[o.Id] = since = DateTime.UtcNow; } return (DateTime.UtcNow - since).TotalSeconds < 6 ? o.Name + ": checking..." : "⚠ " + o.Name + ": doesn't look like it's working"; } private async Task SaveSpot() { if (!Linked()) return; float x = V(info, "px", float.NaN), y = V(info, "py", float.NaN); int d = (int)V(info, "depth", -2f); 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; } string n = await AskText("Save spot", "Name for this spot:", "Spot " + (bookmarks.Count + 1)); if (n == null) return; bookmarks.Add((PName(n).Length > 0 ? PName(n) : "Spot", x, y, d)); if (bookmarks.Count > 20) bookmarks.RemoveAt(0); RebuildTools(true); } private void OnSent(string s) { string[] p = s.Split(' ', 3); string text; switch (p[0]) { case "SET": if (p.Length < 3 || !byId.TryGetValue(p[1], out COpt o)) return; text = o.Name + (p[2] == "1" ? " on" : " off"); if (p[2] == "1" && run != null) run.Cheats.Add(o.Id); break; case "VAL": if (p.Length < 3 || !byId.TryGetValue(p[1], out COpt v)) return; text = v.Name + " set to " + p[2]; if (history.Count > 0 && history[^1].text.StartsWith(v.Name + " set to ", StringComparison.Ordinal)) history.RemoveAt(history.Count - 1); break; case "ACT": if (p.Length < 2) return; text = p[1] == "tpgo" ? "Teleported to a bookmark" : byId.TryGetValue(p[1], out COpt a) ? a.Name : p[1]; if (run != null) run.Actions++; break; case "SPAWN": if (p.Length < 3) return; if (!int.TryParse(p[2], out int n)) n = 1; text = "Spawned " + n + " x " + p[1]; if (run != null) run.Spawned += n; break; case "MODACT": text = "My Mods: " + (p.Length >= 3 ? p[2] : ""); break; case "MUSICPLAY": text = "Music: " + (p.Length >= 3 ? p[2] : ""); break; default: return; } AddHistory(text); } private void AddHistory(string text) { history.Add((DateTime.Now, text)); if (history.Count > 300) history.RemoveRange(0, history.Count - 300); historyDirty = true; } private void ToolsLine(string cmd, string rest) { if (cmd == "MSG" && rest.Length > 0) AddHistory("Game: " + rest); else if (cmd == "HOTKEY") OnHotkey(rest.Trim()); } private void SaveRuns() { try { Directory.CreateDirectory(Dirs.Config); File.WriteAllLines(RunsFile, pastRuns.Select(r => r.Line())); } catch (Exception) { } } private void RunTick() { bool inRun = link.IsConnected && vitals != null; DateTime now = DateTime.UtcNow; if (inRun) { noRunSince = DateTime.MinValue; if (run == null) { run = new LRun { Start = DateTime.Now }; foreach (COpt o in CheatToggles()) if (IsOn(o.Id)) run.Cheats.Add(o.Id); bookmarks.Clear(); lastRunTick = now; } if (V(vitals, "alive", 1f) > 0) run.Secs += Math.Min(5.0, (now - lastRunTick).TotalSeconds); else run.Died = true; int depth = (int)V(info, "depth", -2f); if (depth >= 0) run.Deepest = Math.Max(run.Deepest, depth + 1); float blood = V(vitals, "blood", -1f); if (blood >= 0 && run.LastBlood >= 0) { float d = blood - run.LastBlood; if (d < 0) run.BloodLost -= d; else run.BloodGained += d; } if (blood >= 0) run.LastBlood = blood; int miss = (int)V(vitals, "missing", -1f); if (miss >= 0 && run.LastMissing >= 0 && miss > run.LastMissing) run.LimbsLost += miss - run.LastMissing; if (miss >= 0) run.LastMissing = miss; } else if (run != null) { if (noRunSince == DateTime.MinValue) noRunSince = now; else if ((now - noRunSince).TotalSeconds >= 4 || !link.IsConnected) { if (run.Secs >= 10) { pastRuns.Add(run); if (pastRuns.Count > 40) pastRuns.RemoveRange(0, pastRuns.Count - 40); SaveRuns(); } run = null; bookmarks.Clear(); } } lastRunTick = now; } private async Task ClearRuns() { if (!await Confirm("Clear run history", "Delete every saved run?")) return; pastRuns.Clear(); SaveRuns(); RebuildTools(true); } private async Task SaveHistory() { IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Save activity history", SuggestedFileName = "Ultra Paradise activity.txt" }); string path = f?.TryGetLocalPath(); if (path == null) return; 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); } } private static bool BackupName(string n) { string e = Path.GetExtension(n).ToLowerInvariant(); return n.IndexOfAny(new[] { '/', '\\', ':' }) < 0 && e is ".ini" or ".txt" or ".json" or ".cfg"; } private async Task BackupAll() { IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Back up everything", SuggestedFileName = "Ultra Paradise backup " + DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".zip" }); string path = f?.TryGetLocalPath(); if (path == null) return; try { int n = 0; using (ZipArchive z = ZipFile.Open(path, ZipArchiveMode.Create)) foreach (string file in Directory.GetFiles(Dirs.Config)) { string name = Path.GetFileName(file); if (!BackupName(name) || new FileInfo(file).Length > 4 * 1024 * 1024) continue; z.CreateEntryFromFile(file, name); n++; } Message("Backed up " + n + " files to " + Path.GetFileName(path) + ".", false); } catch (Exception e) { Message("Couldn't make the backup: " + e.Message, true); } } private async Task RestoreAll() { var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Restore a backup", AllowMultiple = false }); string path = files.Count > 0 ? files[0].TryGetLocalPath() : null; if (path == null) return; if (!await Confirm("Restore backup", "Replace your current settings, profiles, macros and theme with the ones in this backup? Restart the trainer afterwards.")) return; try { int n = 0; using (ZipArchive z = ZipFile.OpenRead(path)) { if (!z.Entries.Any(e => e.FullName == "settings.ini")) { Message("That zip isn't an Ultra Paradise backup.", true); return; } foreach (ZipArchiveEntry e in z.Entries) { if (!BackupName(e.FullName) || e.Length > 4 * 1024 * 1024) continue; e.ExtractToFile(Path.Combine(Dirs.Config, e.FullName), true); n++; } } Settings.Load(); Message("Restored " + n + " files. Close and reopen the trainer to finish.", false); } catch (Exception e) { Message("Couldn't restore the backup: " + e.Message, true); } } private void ToolsTick() { DateTime now = DateTime.UtcNow; foreach (string id in timers.Where(kv => now >= kv.Value).Select(kv => kv.Key).ToList()) { timers.Remove(id); SetCheat(id, false); Message((byId.TryGetValue(id, out COpt o) ? o.Name : id) + " turned itself off.", false); } RunTick(); WatchTick(); RandomTick(); OverlayTick(); RebuildTools(false); } private Window Dialog(string title, out StackPanel sp) { sp = new StackPanel { Margin = new Thickness(20), Spacing = 10 }; return new Window { Title = title, Width = 440, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = Ui.B(Ui.Back), Content = sp }; } private async Task OkCancel(Window w, StackPanel sp, string ok) { bool result = false; Button okB = new() { Content = ok, Padding = new Thickness(16, 6), Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent), IsDefault = true }; Button cancel = new() { Content = "Cancel", Padding = new Thickness(16, 6), IsCancel = true }; okB.Click += (_, _) => { result = true; w.Close(); }; cancel.Click += (_, _) => w.Close(); sp.Children.Add(new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right, Children = { cancel, okB } }); await w.ShowDialog(this); return result; } private async Task AskText(string title, string prompt, string def) { Window w = Dialog(title, out StackPanel sp); sp.Children.Add(T(prompt, 13, Ui.B(Ui.Text), false, true)); TextBox t = new() { Text = def ?? "", MaxLength = 32 }; sp.Children.Add(t); w.Opened += (_, _) => { t.Focus(); t.SelectAll(); }; return await OkCancel(w, sp, "OK") ? (t.Text ?? "").Trim() : null; } private async Task Confirm(string title, string text) { Window w = Dialog(title, out StackPanel sp); sp.Children.Add(T(text, 13, Ui.B(Ui.Text), false, true)); return await OkCancel(w, sp, "Yes"); } private Button KeyCatcher(string start, Action changed) { string cur = start ?? ""; Button b = new() { Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)", HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 32 }; bool listening = false; b.Click += (_, _) => { listening = true; b.Content = "Press a key..."; b.Focus(); }; b.KeyDown += (_, e) => { if (!listening) return; Key k = e.Key; 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; e.Handled = true; listening = false; if (k == Key.Escape) { b.Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)"; return; } if (k is Key.Delete or Key.Back) cur = ""; else { string u = KeyMap.Unity(k); if (u == null) { b.Content = "That key can't be used"; return; } cur = (e.KeyModifiers.HasFlag(KeyModifiers.Control) ? "Ctrl+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? "Shift+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Alt) ? "Alt+" : "") + u; } b.Content = cur.Length > 0 ? Cheats.KeyLabel(cur) : "No key (click to set)"; changed(cur); }; return b; } private async Task AskKey(string title, string what, string start) { Window w = Dialog(title, out StackPanel sp); sp.Children.Add(T(what + " Click the box, then press a key. Delete clears it.", 13, Ui.B(Ui.Text), false, true)); string got = start ?? ""; sp.Children.Add(KeyCatcher(got, k => got = k)); return await OkCancel(w, sp, "OK") ? got : null; } private async Task PickMany(string title, string text, List pool, HashSet picked) { Window w = Dialog(title, out StackPanel sp); sp.Children.Add(T(text, 13, Ui.B(Ui.Text), false, true)); StackPanel list = new() { Spacing = 2 }; List<(CheckBox cb, string id)> boxes = new(); foreach (COpt o in pool) { CheckBox cb = new() { Content = o.Name + " · " + originOf.GetValueOrDefault(o.Id, ""), IsChecked = picked.Contains(o.Id) }; boxes.Add((cb, o.Id)); list.Children.Add(cb); } sp.Children.Add(new ScrollViewer { Content = list, Height = 320 }); if (!await OkCancel(w, sp, "Save")) return false; picked.Clear(); foreach (var (cb, id) in boxes) if (cb.IsChecked == true) picked.Add(id); return true; } private async Task EditMacro(LMacro m) { Window w = Dialog("Macro", out StackPanel sp); w.Width = 480; sp.Children.Add(T("Name", 13, Ui.B(Ui.Text))); TextBox name = new() { Text = m.Name, MaxLength = 32 }; sp.Children.Add(name); sp.Children.Add(T("What it does with toggles (actions like Heal always just run)", 13, Ui.B(Ui.Text), false, true)); ComboBox mode = new() { ItemsSource = ModeNames, SelectedIndex = Math.Max(0, Array.IndexOf(ModeIds, m.Mode)), HorizontalAlignment = HorizontalAlignment.Stretch }; sp.Children.Add(mode); sp.Children.Add(T("When the hotkey works (contextual hotkey)", 13, Ui.B(Ui.Text))); ComboBox cond = new() { ItemsSource = CondNames, SelectedIndex = Math.Max(0, Array.IndexOf(CondIds, m.Cond)), HorizontalAlignment = HorizontalAlignment.Stretch }; sp.Children.Add(cond); sp.Children.Add(T("Cheats and actions in this macro", 13, Ui.B(Ui.Text))); StackPanel list = new() { Spacing = 2 }; List<(CheckBox cb, string id)> boxes = new(); foreach (COpt o in MacroPool()) { CheckBox cb = new() { Content = o.Name + (o.Kind == CKind.Action ? " (action)" : "") + " · " + originOf.GetValueOrDefault(o.Id, ""), IsChecked = m.Ids.Contains(o.Id) }; boxes.Add((cb, o.Id)); list.Children.Add(cb); } sp.Children.Add(new ScrollViewer { Content = list, Height = 240 }); sp.Children.Add(T("Hotkey", 13, Ui.B(Ui.Text))); string key = m.Key; sp.Children.Add(KeyCatcher(key, k => key = k)); if (!await OkCancel(w, sp, "Save")) return; string nm = (name.Text ?? "").Trim().Replace("|", "/"); List ids = boxes.Where(b => b.cb.IsChecked == true).Select(b => b.id).ToList(); if (nm.Length == 0 || ids.Count == 0) { Message("A macro needs a name and at least one cheat or action.", true); return; } m.Name = nm; m.Mode = ModeIds[Math.Max(0, mode.SelectedIndex)]; m.Cond = CondIds[Math.Max(0, cond.SelectedIndex)]; m.Ids = ids; m.Key = key; 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 = ""; } if (!macros.Contains(m)) macros.Add(m); SaveMacros(); SendXBinds(); RebuildTools(true); } } }