casualexpiesource

cu-trainer/Ultra Paradise Application/src/Tools.cs

1536 lines · 79.0 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Drawing;
4using System.Globalization;
5using System.IO;
6using System.IO.Compression;
7using System.Text;
8using System.Windows.Forms;
9
10namespace UltraParadise
11{
12 internal class Profile
13 {
14 public string Name;
15 public readonly HashSet<string> On = new HashSet<string>();
16 public readonly Dictionary<string, float> Vals = new Dictionary<string, float>();
17 public readonly Dictionary<string, Keys> KeyMap = new Dictionary<string, Keys>();
18 public Keys Hot;
19 public bool Chaos;
20 }
21
22 internal class Macro
23 {
24 public string Name = "", Cond = "always", Mode = "on";
25 public Keys Key;
26 public readonly List<string> Ids = new List<string>();
27 }
28
29 internal class RunStat
30 {
31 public DateTime Start;
32 public double Secs;
33 public int Deepest;
34 public bool Died;
35 public float BloodLost, BloodGained;
36 public int LimbsLost, Spawned, Actions;
37 public readonly HashSet<string> Cheats = new HashSet<string>();
38 public float LastBlood = -1f;
39 public int LastMissing = -1;
40
41 public bool Cheated { get { return Cheats.Count > 0 || Spawned > 0 || Actions > 0; } }
42
43 public string Line()
44 {
45 List<string> c = new List<string>(Cheats);
46 return Start.Ticks.ToString(CultureInfo.InvariantCulture) + "|" + ((int)Secs).ToString(CultureInfo.InvariantCulture) + "|" + Deepest + "|" + (Died ? 1 : 0) + "|" +
47 BloodLost.ToString("0.#", CultureInfo.InvariantCulture) + "|" + BloodGained.ToString("0.#", CultureInfo.InvariantCulture) + "|" + LimbsLost + "|" + Spawned + "|" + Actions + "|" + string.Join(";", c.ToArray()).Replace("|", "/");
48 }
49
50 public static RunStat Parse(string s)
51 {
52 string[] p = s.Split('|');
53 if (p.Length < 10) return null;
54 RunStat r = new RunStat();
55 long ticks; int i; float f;
56 if (!long.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out ticks) || ticks <= 0 || ticks >= DateTime.MaxValue.Ticks) return null;
57 r.Start = new DateTime(ticks);
58 if (int.TryParse(p[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) r.Secs = i;
59 if (int.TryParse(p[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) r.Deepest = i;
60 r.Died = p[3] == "1";
61 if (float.TryParse(p[4], NumberStyles.Float, CultureInfo.InvariantCulture, out f)) r.BloodLost = f;
62 if (float.TryParse(p[5], NumberStyles.Float, CultureInfo.InvariantCulture, out f)) r.BloodGained = f;
63 if (int.TryParse(p[6], NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) r.LimbsLost = i;
64 if (int.TryParse(p[7], NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) r.Spawned = i;
65 if (int.TryParse(p[8], NumberStyles.Integer, CultureInfo.InvariantCulture, out i)) r.Actions = i;
66 foreach (string c in p[9].Split(';')) if (c.Length > 0) r.Cheats.Add(c);
67 return r;
68 }
69 }
70
71 internal static class SaveCheck
72 {
73 public static string Line(Dictionary<string, string> d)
74 {
75 string v;
76 if (d == null || !d.TryGetValue("savecheat", out v)) return "Save file marked as cheated: unknown (update UltraPara.dll)";
77 switch (v)
78 {
79 case "cheated": return "Save file marked as cheated: TRUE";
80 case "clean": return "Save file marked as cheated: FALSE";
81 case "none": return "Save file marked as cheated: no save file right now";
82 case "error": return "Save file marked as cheated: couldn't read the save";
83 default: return "Save file marked as cheated: unknown";
84 }
85 }
86
87 public static string Ach(Dictionary<string, string> d)
88 {
89 string v;
90 if (d == null || !d.TryGetValue("achoff", out v)) return "";
91 return v == "1" ? "Achievements right now: OFF" : "Achievements right now: on";
92 }
93 }
94
95 internal class Bookmark
96 {
97 public string Name;
98 public float X, Y;
99 public int Depth;
100 }
101
102 internal static partial class Dialogs
103 {
104 public static Form Shell(string title, int w)
105 {
106 Form f = new Form();
107 f.Text = title;
108 f.FormBorderStyle = FormBorderStyle.FixedDialog;
109 f.MaximizeBox = false;
110 f.MinimizeBox = false;
111 f.ShowInTaskbar = false;
112 f.StartPosition = FormStartPosition.CenterParent;
113 f.BackColor = Theme.Back;
114 f.ForeColor = Theme.Text;
115 f.Font = Theme.F("Segoe UI", 9.5f);
116 f.ClientSize = new Size(Theme.S(w), Theme.S(100));
117 return f;
118 }
119
120 public static Button MakeButton(string text, DialogResult r)
121 {
122 Button b = new Button();
123 b.Text = text;
124 b.DialogResult = r;
125 b.FlatStyle = FlatStyle.Flat;
126 b.FlatAppearance.BorderColor = Theme.Line;
127 b.BackColor = r == DialogResult.OK ? Theme.Orange : Theme.Panel;
128 b.ForeColor = r == DialogResult.OK ? (Theme.Lum(Theme.Orange) > 0.55 ? Color.Black : Color.White) : Theme.Text;
129 b.AutoSize = true;
130 b.Padding = new Padding(Theme.S(8), Theme.S(2), Theme.S(8), Theme.S(2));
131 return b;
132 }
133
134 public static Label Text(string s, int w)
135 {
136 Label l = new Label();
137 l.Text = s;
138 l.ForeColor = Theme.Text;
139 l.MaximumSize = new Size(Theme.S(w), 0);
140 l.AutoSize = true;
141 return l;
142 }
143
144 private static void Finish(Form f, Control last, Button ok, Button cancel)
145 {
146 int y = last.Bottom + Theme.S(14);
147 if (cancel != null) { cancel.Location = new Point(f.ClientSize.Width - Theme.S(16) - cancel.PreferredSize.Width, y); f.Controls.Add(cancel); f.CancelButton = cancel; }
148 ok.Location = new Point((cancel != null ? cancel.Left - Theme.S(8) : f.ClientSize.Width - Theme.S(16)) - ok.PreferredSize.Width, y);
149 f.Controls.Add(ok);
150 f.AcceptButton = ok;
151 f.ClientSize = new Size(f.ClientSize.Width, y + ok.PreferredSize.Height + Theme.S(14));
152 }
153
154 public static string Ask(IWin32Window owner, string title, string prompt, string def)
155 {
156 using (Form f = Shell(title, 380))
157 {
158 Label l = Text(prompt, 350); l.Location = new Point(Theme.S(16), Theme.S(14)); f.Controls.Add(l);
159 TextBox t = new TextBox();
160 t.Text = def ?? "";
161 t.BackColor = Theme.Panel; t.ForeColor = Theme.Text; t.BorderStyle = BorderStyle.FixedSingle;
162 t.Bounds = new Rectangle(Theme.S(16), l.Bottom + Theme.S(8), f.ClientSize.Width - Theme.S(32), t.PreferredHeight);
163 t.MaxLength = 32;
164 f.Controls.Add(t);
165 Finish(f, t, MakeButton("OK", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
166 t.SelectAll();
167 return f.ShowDialog(owner) == DialogResult.OK ? t.Text.Trim() : null;
168 }
169 }
170
171 public static bool Confirm(IWin32Window owner, string title, string text)
172 {
173 using (Form f = Shell(title, 380))
174 {
175 Label l = Text(text, 350); l.Location = new Point(Theme.S(16), Theme.S(14)); f.Controls.Add(l);
176 Finish(f, l, MakeButton("Yes", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
177 return f.ShowDialog(owner) == DialogResult.OK;
178 }
179 }
180
181 private class KeyBox : Label
182 {
183 public Keys Value;
184 public KeyBox()
185 {
186 SetStyle(ControlStyles.Selectable, true);
187 TabStop = true;
188 BorderStyle = BorderStyle.FixedSingle;
189 BackColor = Theme.Panel;
190 ForeColor = Theme.Text;
191 TextAlign = ContentAlignment.MiddleCenter;
192 }
193 protected override bool IsInputKey(Keys k) { return true; }
194 protected override void OnClick(EventArgs e) { Focus(); base.OnClick(e); }
195 protected override void OnGotFocus(EventArgs e) { Text = "Press a key..."; base.OnGotFocus(e); }
196 protected override void OnLostFocus(EventArgs e) { ShowKey(); base.OnLostFocus(e); }
197 public void ShowKey() { Text = Value == Keys.None ? "No key (click to set)" : KeyText.Of(Value); }
198 protected override void OnKeyDown(KeyEventArgs e)
199 {
200 Keys c = e.KeyCode;
201 e.Handled = true; e.SuppressKeyPress = true;
202 if (c == Keys.ControlKey || c == Keys.ShiftKey || c == Keys.Menu || c == Keys.LWin || c == Keys.RWin) return;
203 if (c == Keys.Escape) { Parent.SelectNextControl(this, true, true, true, true); return; }
204 Value = c == Keys.Delete || c == Keys.Back ? Keys.None : e.KeyData;
205 ShowKey();
206 Parent.SelectNextControl(this, true, true, true, true);
207 }
208 }
209
210 private static ComboBox Combo(string[] items, int sel)
211 {
212 ComboBox c = new ComboBox();
213 c.DropDownStyle = ComboBoxStyle.DropDownList;
214 c.FlatStyle = FlatStyle.Flat;
215 c.BackColor = Theme.Panel; c.ForeColor = Theme.Text;
216 c.Items.AddRange(items);
217 c.SelectedIndex = Math.Max(0, Math.Min(items.Length - 1, sel));
218 return c;
219 }
220
221 public static bool PickKey(IWin32Window owner, string title, string what, ref Keys key)
222 {
223 using (Form f = Shell(title, 340))
224 {
225 Label l = Text(what + "\n\nClick the box, then press a key (with Ctrl, Shift or Alt if you like). Delete clears it.", 310); l.Location = new Point(Theme.S(16), Theme.S(14)); f.Controls.Add(l);
226 KeyBox kb = new KeyBox(); kb.Value = key; kb.ShowKey();
227 kb.Bounds = new Rectangle(Theme.S(16), l.Bottom + Theme.S(10), f.ClientSize.Width - Theme.S(32), Theme.S(30));
228 f.Controls.Add(kb);
229 Finish(f, kb, MakeButton("OK", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
230 if (f.ShowDialog(owner) != DialogResult.OK) return false;
231 key = kb.Value;
232 return true;
233 }
234 }
235
236 public static readonly string[] CondIds = { "always", "run", "bleeding", "critical", "hurt", "hungry", "trader" };
237 public 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" };
238 private static readonly string[] ModeIds = { "on", "off", "flip" };
239 private static readonly string[] ModeNames = { "Turn the cheats on", "Turn the cheats off", "Flip them (on to off, off to on)" };
240
241 public static bool EditMacro(IWin32Window owner, Macro m, List<Option> pool)
242 {
243 using (Form f = Shell("Macro", 460))
244 {
245 int x = Theme.S(16), w = f.ClientSize.Width - Theme.S(32);
246 Label l1 = Text("Name", 400); l1.Location = new Point(x, Theme.S(12)); f.Controls.Add(l1);
247 TextBox name = new TextBox(); name.Text = m.Name; name.MaxLength = 32; name.BackColor = Theme.Panel; name.ForeColor = Theme.Text; name.BorderStyle = BorderStyle.FixedSingle;
248 name.Bounds = new Rectangle(x, l1.Bottom + Theme.S(4), w, name.PreferredHeight); f.Controls.Add(name);
249 Label l2 = Text("What it does with toggles (actions like Heal always just run)", 420); l2.Location = new Point(x, name.Bottom + Theme.S(10)); f.Controls.Add(l2);
250 ComboBox mode = Combo(ModeNames, Array.IndexOf(ModeIds, m.Mode)); mode.Bounds = new Rectangle(x, l2.Bottom + Theme.S(4), w, Theme.S(24)); f.Controls.Add(mode);
251 Label l3 = Text("When the hotkey works (contextual hotkey)", 420); l3.Location = new Point(x, mode.Bottom + Theme.S(10)); f.Controls.Add(l3);
252 ComboBox cond = Combo(CondNames, Array.IndexOf(CondIds, m.Cond)); cond.Bounds = new Rectangle(x, l3.Bottom + Theme.S(4), w, Theme.S(24)); f.Controls.Add(cond);
253 Label l4 = Text("Cheats and actions in this macro", 420); l4.Location = new Point(x, cond.Bottom + Theme.S(10)); f.Controls.Add(l4);
254 CheckedListBox list = new CheckedListBox();
255 list.CheckOnClick = true; list.BorderStyle = BorderStyle.FixedSingle; list.BackColor = Theme.Panel; list.ForeColor = Theme.Text; list.IntegralHeight = false;
256 list.Bounds = new Rectangle(x, l4.Bottom + Theme.S(4), w, Theme.S(220));
257 foreach (Option o in pool) list.Items.Add(o.Name + (o.Kind == Kind.Action ? " (action)" : "") + " · " + o.Origin, m.Ids.Contains(o.Id));
258 f.Controls.Add(list);
259 Label l5 = Text("Hotkey", 420); l5.Location = new Point(x, list.Bottom + Theme.S(10)); f.Controls.Add(l5);
260 KeyBox kb = new KeyBox(); kb.Value = m.Key; kb.ShowKey(); kb.Bounds = new Rectangle(x, l5.Bottom + Theme.S(4), w, Theme.S(28)); f.Controls.Add(kb);
261 Finish(f, kb, MakeButton("Save", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
262 while (true)
263 {
264 if (f.ShowDialog(owner) != DialogResult.OK) return false;
265 if (name.Text.Trim().Length == 0) { MessageBox.Show(f, "Give the macro a name.", "Macro"); continue; }
266 if (list.CheckedIndices.Count == 0) { MessageBox.Show(f, "Tick at least one cheat or action.", "Macro"); continue; }
267 break;
268 }
269 m.Name = name.Text.Trim().Replace("|", "/");
270 m.Mode = ModeIds[Math.Max(0, mode.SelectedIndex)];
271 m.Cond = CondIds[Math.Max(0, cond.SelectedIndex)];
272 m.Key = kb.Value;
273 m.Ids.Clear();
274 foreach (int i in list.CheckedIndices) m.Ids.Add(pool[i].Id);
275 return true;
276 }
277 }
278
279 public static bool PickMany(IWin32Window owner, string title, string text, List<Option> pool, HashSet<string> picked)
280 {
281 using (Form f = Shell(title, 420))
282 {
283 int x = Theme.S(16), w = f.ClientSize.Width - Theme.S(32);
284 Label l = Text(text, 390); l.Location = new Point(x, Theme.S(12)); f.Controls.Add(l);
285 CheckedListBox list = new CheckedListBox();
286 list.CheckOnClick = true; list.BorderStyle = BorderStyle.FixedSingle; list.BackColor = Theme.Panel; list.ForeColor = Theme.Text; list.IntegralHeight = false;
287 list.Bounds = new Rectangle(x, l.Bottom + Theme.S(8), w, Theme.S(300));
288 foreach (Option o in pool) list.Items.Add(o.Name + " · " + o.Origin, picked.Contains(o.Id));
289 f.Controls.Add(list);
290 Finish(f, list, MakeButton("Save", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
291 if (f.ShowDialog(owner) != DialogResult.OK) return false;
292 picked.Clear();
293 foreach (int i in list.CheckedIndices) picked.Add(pool[i].Id);
294 return true;
295 }
296 }
297
298 public static bool AskAlert(IWin32Window owner, string what, ref string op, ref float thr)
299 {
300 using (Form f = Shell("Alert for " + what, 340))
301 {
302 int x = Theme.S(16), w = f.ClientSize.Width - Theme.S(32);
303 Label l = Text("Pop up a warning when " + what + " goes:", 310); l.Location = new Point(x, Theme.S(12)); f.Controls.Add(l);
304 ComboBox c = Combo(new string[] { "No alert", "Below", "Above" }, op == "<" ? 1 : op == ">" ? 2 : 0);
305 c.Bounds = new Rectangle(x, l.Bottom + Theme.S(6), Theme.S(120), Theme.S(24)); f.Controls.Add(c);
306 NumericUpDown n = new NumericUpDown();
307 n.Minimum = -1000; n.Maximum = 100000; n.DecimalPlaces = 1; n.Increment = 1;
308 n.Value = (decimal)Math.Max(-1000f, Math.Min(100000f, thr));
309 n.BackColor = Theme.Panel; n.ForeColor = Theme.Text; n.BorderStyle = BorderStyle.FixedSingle;
310 n.Bounds = new Rectangle(c.Right + Theme.S(8), c.Top, w - Theme.S(128), Theme.S(24)); f.Controls.Add(n);
311 Finish(f, c, MakeButton("Save", DialogResult.OK), MakeButton("Cancel", DialogResult.Cancel));
312 if (f.ShowDialog(owner) != DialogResult.OK) return false;
313 op = c.SelectedIndex == 1 ? "<" : c.SelectedIndex == 2 ? ">" : "";
314 thr = (float)n.Value;
315 return true;
316 }
317 }
318 }
319
320 internal partial class MainForm
321 {
322 private Tab profTab, toolsTab, watchTab, statsTab;
323 private readonly List<Profile> profiles = new List<Profile>();
324 private readonly List<Macro> macros = new List<Macro>();
325 private readonly Dictionary<int, Action> toolKeys = new Dictionary<int, Action>();
326 private readonly Dictionary<string, DateTime> timers = new Dictionary<string, DateTime>();
327 private readonly HashSet<string> neverRandom = new HashSet<string>();
328 private readonly HashSet<string> randOn = new HashSet<string>();
329 private DateTime nextRandom = DateTime.MaxValue;
330 private readonly List<Bookmark> bookmarks = new List<Bookmark>();
331 private readonly List<KeyValuePair<DateTime, string>> history = new List<KeyValuePair<DateTime, string>>();
332 private bool historyDirty;
333 private RunStat run;
334 private DateTime noRunSince = DateTime.MinValue, lastRunTick = DateTime.MinValue, nextToolsSecond = DateTime.MinValue;
335 private readonly List<RunStat> pastRuns = new List<RunStat>();
336 private readonly List<string> watched = new List<string>();
337 private readonly HashSet<string> alerting = new HashSet<string>();
338 private readonly Dictionary<string, DateTime> checkBad = new Dictionary<string, DateTime>();
339 private string toolsSig = "";
340 private Option hoverOpt;
341
342 private static readonly string[] DefaultNever = { "UnchippedChallenge", "HopelessStart", "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "FastRadiation", "ColdCaves", "MoreTraps", "LootScarcity", "FreeCamera", "Noclip", "FlyMode", "ClickTeleport", "MoodLock" };
343 private static readonly string[] CheatTabs = { "Player", "Health", "Movement", "Items", "Combat", "World", "Traders", "Challenges" };
344
345 private static readonly string[][] WatchKeys =
346 {
347 new string[] { "blood", "Blood", "%" }, new string[] { "bleed", "Bleeding", " L/min" }, new string[] { "oxy", "Blood oxygen", "%" },
348 new string[] { "consc", "Consciousness", "%" }, new string[] { "brain", "Brain health", "%" }, new string[] { "hr", "Heart rate", " bpm" },
349 new string[] { "temp", "Body temperature", "°" }, new string[] { "pain", "Pain", "" }, new string[] { "hunger", "Food", "" },
350 new string[] { "thirst", "Water", "" }, new string[] { "energy", "Energy", "" }, new string[] { "mood", "Mood", "" },
351 new string[] { "sick", "Sickness", "" }, new string[] { "rad", "Radiation", "" }, new string[] { "venom", "Venom", "" },
352 new string[] { "infect", "Infection", "" }, new string[] { "broken", "Broken bones", "" }, new string[] { "disloc", "Dislocations", "" },
353 new string[] { "shrapnel", "Shrapnel", "" }, new string[] { "missing", "Missing limbs", "" }
354 };
355
356 private static string AppFolder { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"); } }
357 private static string RunsFile { get { return Path.Combine(AppFolder, "runs.txt"); } }
358
359 private void SetupTools()
360 {
361 foreach (Tab x in tabs)
362 {
363 if (x.Name == "Profiles") profTab = x;
364 else if (x.Name == "Tools") toolsTab = x;
365 else if (x.Name == "Watchlist") watchTab = x;
366 else if (x.Name == "Run Stats") statsTab = x;
367 }
368 LoadProfiles();
369 LoadMacros();
370 string nv;
371 if (settings.TryGetValue("rand.never", out nv)) { foreach (string s in nv.Split(',')) if (s.Length > 0) neverRandom.Add(s); }
372 else foreach (string s in DefaultNever) neverRandom.Add(s);
373 if (settings.TryGetValue("watch", out nv)) foreach (string s in nv.Split(',')) if (WatchIndex(s) >= 0 && !watched.Contains(s)) watched.Add(s);
374 LoadRuns();
375 link.Sent += delegate (string s) { Ui(delegate { OnSent(s); }); };
376 view.HoverChanged += delegate (Option o) { if (o != null) hoverOpt = o; };
377 view.MouseLeave += delegate { hoverOpt = null; };
378 view.MouseUp += delegate (object s, MouseEventArgs e) { if (e.Button == MouseButtons.Right) CheatMenu(e.Location); };
379 overlay.Suffix = delegate (Option o)
380 {
381 DateTime t;
382 if (!timers.TryGetValue(o.Id, out t)) return null;
383 return Clock(Math.Max(0, (int)(t - DateTime.UtcNow).TotalSeconds));
384 };
385 spawner.Favs.Clear();
386 if (settings.TryGetValue("items.fav", out nv)) foreach (string s in nv.Split(',')) if (s.Length > 0) spawner.Favs.Add(s);
387 if (settings.TryGetValue("items.recent", out nv)) foreach (string s in nv.Split(',')) if (s.Length > 0 && spawner.Recent.Count < 12) spawner.Recent.Add(s);
388 spawner.ListsChanged += delegate
389 {
390 settings["items.fav"] = string.Join(",", new List<string>(spawner.Favs).ToArray());
391 settings["items.recent"] = string.Join(",", spawner.Recent.ToArray());
392 Settings.Save(settings);
393 };
394 RebuildTools(true);
395 }
396
397 private static Option XInfo(Func<string> text)
398 {
399 Option o = new Option(); o.Kind = Kind.Info; o.Id = "x:info"; o.Local = true;
400 o.Text = delegate (Dictionary<string, string> d) { return text(); };
401 return o;
402 }
403
404 private static Option XBtns(string label, Func<string> text, params Btn[] b)
405 {
406 Option o = new Option(); o.Kind = Kind.Buttons; o.Id = "x:btn"; o.Name = label; o.Local = true;
407 if (text != null) o.Text = delegate (Dictionary<string, string> d) { return text(); };
408 o.Buttons = new List<Btn>(b);
409 return o;
410 }
411
412 private bool InCheatTab(Option o)
413 {
414 return o.Origin != null && Array.IndexOf(CheatTabs, o.Origin) >= 0;
415 }
416
417 private List<Option> CheatToggles()
418 {
419 List<Option> l = new List<Option>();
420 foreach (Option o in options) if (o.Kind == Kind.Toggle && !o.Local && InCheatTab(o)) l.Add(o);
421 return l;
422 }
423
424 private List<Option> MacroPool()
425 {
426 List<Option> l = new List<Option>();
427 foreach (Option o in options)
428 if ((o.Kind == Kind.Toggle || o.Kind == Kind.Action) && !o.Local && InCheatTab(o)) l.Add(o);
429 return l;
430 }
431
432 private void SetCheat(Option o, bool on)
433 {
434 if (o == null || o.Kind != Kind.Toggle || o.Local || o.On == on) return;
435 o.On = on;
436 if (link.IsConnected && blocked == null) link.Send("SET " + o.Id + " " + (on ? "1" : "0"));
437 if (!on) { timers.Remove(o.Id); randOn.Remove(o.Id); }
438 }
439
440 private void CheatsChanged()
441 {
442 SaveCheats();
443 view.Invalidate();
444 side.Invalidate();
445 overlay.Invalidate();
446 }
447
448 private static string ProfileName(string s)
449 {
450 StringBuilder sb = new StringBuilder();
451 foreach (char c in s ?? "") if (char.IsLetterOrDigit(c) || c == ' ' || c == '-' || c == '_' || c == '\'' || c == '!') sb.Append(c);
452 string r = sb.ToString().Trim();
453 return r.Length > 24 ? r.Substring(0, 24).Trim() : r;
454 }
455
456 private Profile Builtin(string name, bool chaos, params string[] on)
457 {
458 Profile p = new Profile(); p.Name = name; p.Chaos = chaos;
459 foreach (string s in on) if (byId.ContainsKey(s)) p.On.Add(s);
460 return p;
461 }
462
463 private void LoadProfiles()
464 {
465 profiles.Clear();
466 string list;
467 if (!settings.TryGetValue("profiles", out list))
468 {
469 profiles.Add(Builtin("Sandbox", false, "GodMode", "NoHunger", "NoThirst", "NoTiredness", "InfiniteStamina", "FreeCrafting", "NoCraftFail", "AllRecipes", "UnlimitedAmmo", "NoDegradation", "UnlimitedBattery", "UnlimitedCarry", "FullBright", "MasterLockpick"));
470 profiles.Add(Builtin("Survival", false, "NoFallDamage", "InfiniteStamina", "AllRecipes", "NoCraftFail", "FasterHealing"));
471 profiles.Add(Builtin("Chaos", true));
472 profiles.Add(Builtin("Hardcore", false, "FragileBody", "FastMetabolism", "BrittleGear", "StrongerEnemies", "LootScarcity", "ColdCaves", "MoreTraps"));
473 SaveProfiles();
474 return;
475 }
476 foreach (string n in list.Split('|'))
477 {
478 if (n.Length == 0) continue;
479 Profile p = new Profile(); p.Name = n;
480 string k = "profile." + n + ".";
481 string v;
482 if (settings.TryGetValue(k + "on", out v)) foreach (string s in v.Split(',')) if (byId.ContainsKey(s)) p.On.Add(s);
483 if (settings.TryGetValue(k + "val", out v))
484 foreach (string s in v.Split(','))
485 {
486 string[] kv = s.Split(':'); float f;
487 if (kv.Length == 2 && byId.ContainsKey(kv[0]) && float.TryParse(kv[1], NumberStyles.Float, CultureInfo.InvariantCulture, out f)) p.Vals[kv[0]] = f;
488 }
489 if (settings.TryGetValue(k + "keys", out v))
490 foreach (string s in v.Split(','))
491 {
492 string[] kv = s.Split(':'); int ki;
493 if (kv.Length == 2 && byId.ContainsKey(kv[0]) && int.TryParse(kv[1], out ki)) p.KeyMap[kv[0]] = (Keys)ki;
494 }
495 int hk;
496 if (settings.TryGetValue(k + "hot", out v) && int.TryParse(v, out hk)) p.Hot = (Keys)hk;
497 p.Chaos = settings.TryGetValue(k + "chaos", out v) && v == "1";
498 profiles.Add(p);
499 }
500 }
501
502 private void SaveProfiles()
503 {
504 List<string> drop = new List<string>();
505 foreach (string k in settings.Keys) if (k.StartsWith("profile.", StringComparison.Ordinal) && k != "profile.active") drop.Add(k);
506 foreach (string k in drop) settings.Remove(k);
507 List<string> names = new List<string>();
508 foreach (Profile p in profiles)
509 {
510 names.Add(p.Name);
511 string k = "profile." + p.Name + ".";
512 settings[k + "on"] = string.Join(",", new List<string>(p.On).ToArray());
513 List<string> vals = new List<string>();
514 foreach (KeyValuePair<string, float> kv in p.Vals) vals.Add(kv.Key + ":" + kv.Value.ToString(CultureInfo.InvariantCulture));
515 if (vals.Count > 0) settings[k + "val"] = string.Join(",", vals.ToArray());
516 List<string> keys = new List<string>();
517 foreach (KeyValuePair<string, Keys> kv in p.KeyMap) keys.Add(kv.Key + ":" + ((int)kv.Value).ToString(CultureInfo.InvariantCulture));
518 if (keys.Count > 0) settings[k + "keys"] = string.Join(",", keys.ToArray());
519 if (p.Hot != Keys.None) settings[k + "hot"] = ((int)p.Hot).ToString(CultureInfo.InvariantCulture);
520 if (p.Chaos) settings[k + "chaos"] = "1";
521 }
522 settings["profiles"] = string.Join("|", names.ToArray());
523 Settings.Save(settings);
524 }
525
526 private Profile FindProfile(string n)
527 {
528 foreach (Profile p in profiles) if (string.Equals(p.Name, n, StringComparison.OrdinalIgnoreCase)) return p;
529 return null;
530 }
531
532 private string UniqueName(string n)
533 {
534 n = ProfileName(n);
535 if (n.Length == 0) n = "Profile";
536 if (FindProfile(n) == null) return n;
537 for (int i = 2; ; i++) if (FindProfile(n + " " + i) == null) return n + " " + i;
538 }
539
540 private void CaptureInto(Profile p)
541 {
542 p.On.Clear(); p.Vals.Clear(); p.KeyMap.Clear();
543 foreach (Option o in options)
544 {
545 if (o.Kind == Kind.Toggle && !o.Local && o.On) p.On.Add(o.Id);
546 if (o.Kind == Kind.Slider && !o.Id.StartsWith("theme.", StringComparison.Ordinal)) p.Vals[o.Id] = o.Value;
547 if (o.Bindable && o.Key != Keys.None) p.KeyMap[o.Id] = o.Key;
548 }
549 }
550
551 private void LoadProfile(Profile p)
552 {
553 foreach (Option o in CheatToggles()) SetCheat(o, !p.Chaos && p.On.Contains(o.Id));
554 foreach (KeyValuePair<string, float> kv in p.Vals)
555 {
556 Option o;
557 if (byId.TryGetValue(kv.Key, out o) && o.Kind == Kind.Slider) SetSlider(o, Math.Max(o.Min, Math.Min(o.Max, kv.Value)));
558 }
559 if (p.KeyMap.Count > 0)
560 {
561 foreach (Option o in options)
562 {
563 if (!o.Bindable) continue;
564 Keys k;
565 o.Key = p.KeyMap.TryGetValue(o.Id, out k) ? k : Keys.None;
566 settings["key." + o.Id] = ((int)o.Key).ToString(CultureInfo.InvariantCulture);
567 }
568 if (hotkeysOn) { UnregisterKeys(); RegisterKeys(); }
569 }
570 if (p.Chaos) Shuffle(RandCount());
571 settings["profile.active"] = p.Name;
572 Settings.Save(settings);
573 CheatsChanged();
574 overlay.Toast("Profile: " + p.Name, true);
575 SetMessage("Loaded the " + p.Name + " profile." + (link.IsConnected ? "" : " It kicks in once the trainer is attached."), false);
576 RebuildTools(true);
577 }
578
579 private void ExportProfile(Profile p)
580 {
581 using (SaveFileDialog d = new SaveFileDialog())
582 {
583 d.Title = "Export profile";
584 d.Filter = "Ultra Paradise profile (*.upprofile)|*.upprofile";
585 d.FileName = p.Name + ".upprofile";
586 if (d.ShowDialog(this) != DialogResult.OK) return;
587 List<string> l = new List<string>();
588 l.Add("UltraParadiseProfile 1");
589 l.Add("name=" + p.Name);
590 l.Add("on=" + string.Join(",", new List<string>(p.On).ToArray()));
591 List<string> vals = new List<string>();
592 foreach (KeyValuePair<string, float> kv in p.Vals) vals.Add(kv.Key + ":" + kv.Value.ToString(CultureInfo.InvariantCulture));
593 l.Add("val=" + string.Join(",", vals.ToArray()));
594 List<string> keys = new List<string>();
595 foreach (KeyValuePair<string, Keys> kv in p.KeyMap) keys.Add(kv.Key + ":" + ((int)kv.Value).ToString(CultureInfo.InvariantCulture));
596 l.Add("keys=" + string.Join(",", keys.ToArray()));
597 l.Add("chaos=" + (p.Chaos ? "1" : "0"));
598 try { File.WriteAllLines(d.FileName, l.ToArray()); SetMessage("Exported " + p.Name + ".", false); }
599 catch (Exception e) { SetMessage("Couldn't save the file: " + e.Message, true); }
600 }
601 }
602
603 private void ImportProfile()
604 {
605 using (OpenFileDialog d = new OpenFileDialog())
606 {
607 d.Title = "Import profile";
608 d.Filter = "Ultra Paradise profile (*.upprofile)|*.upprofile|All files (*.*)|*.*";
609 if (d.ShowDialog(this) != DialogResult.OK) return;
610 string[] lines;
611 try
612 {
613 if (new FileInfo(d.FileName).Length > 65536) { SetMessage("That file is too big to be a profile.", true); return; }
614 lines = File.ReadAllLines(d.FileName);
615 }
616 catch (Exception e) { SetMessage("Couldn't read the file: " + e.Message, true); return; }
617 if (lines.Length == 0 || lines[0].Trim() != "UltraParadiseProfile 1") { SetMessage("That isn't an Ultra Paradise profile file.", true); return; }
618 Dictionary<string, string> m = new Dictionary<string, string>();
619 foreach (string ln in lines) { int eq = ln.IndexOf('='); if (eq > 0) m[ln.Substring(0, eq).Trim()] = ln.Substring(eq + 1).Trim(); }
620 Profile p = new Profile();
621 string v;
622 p.Name = UniqueName(m.TryGetValue("name", out v) ? v : Path.GetFileNameWithoutExtension(d.FileName));
623 if (m.TryGetValue("on", out v)) foreach (string s in v.Split(',')) { Option o; if (byId.TryGetValue(s, out o) && o.Kind == Kind.Toggle && !o.Local) p.On.Add(s); }
624 if (m.TryGetValue("val", out v))
625 foreach (string s in v.Split(','))
626 {
627 string[] kv = s.Split(':'); float f; Option o;
628 if (kv.Length == 2 && byId.TryGetValue(kv[0], out o) && o.Kind == Kind.Slider && float.TryParse(kv[1], NumberStyles.Float, CultureInfo.InvariantCulture, out f) && !float.IsNaN(f)) p.Vals[kv[0]] = f;
629 }
630 if (m.TryGetValue("keys", out v))
631 foreach (string s in v.Split(','))
632 {
633 string[] kv = s.Split(':'); int ki; Option o;
634 if (kv.Length == 2 && byId.TryGetValue(kv[0], out o) && o.Bindable && int.TryParse(kv[1], out ki)) p.KeyMap[kv[0]] = (Keys)ki;
635 }
636 p.Chaos = m.TryGetValue("chaos", out v) && v == "1";
637 profiles.Add(p);
638 SaveProfiles();
639 RebuildTools(true);
640 SetMessage("Imported the " + p.Name + " profile.", false);
641 }
642 }
643
644 private void ProfileMenu(Profile p)
645 {
646 ContextMenuStrip m = new ContextMenuStrip();
647 m.Items.Add("Rename...", null, delegate
648 {
649 string n = Dialogs.Ask(this, "Rename profile", "New name for " + p.Name + ":", p.Name);
650 if (n == null) return;
651 n = ProfileName(n);
652 if (n.Length == 0) return;
653 Profile o = FindProfile(n);
654 if (o != null && o != p) { SetMessage("There's already a profile called " + n + ".", true); return; }
655 if (Get("profile.active", "") == p.Name) settings["profile.active"] = n;
656 p.Name = n; SaveProfiles(); RebuildTools(true);
657 });
658 m.Items.Add("Duplicate", null, delegate
659 {
660 Profile c = new Profile(); c.Name = UniqueName(p.Name + " copy"); c.Chaos = p.Chaos;
661 foreach (string s in p.On) c.On.Add(s);
662 foreach (KeyValuePair<string, float> kv in p.Vals) c.Vals[kv.Key] = kv.Value;
663 foreach (KeyValuePair<string, Keys> kv in p.KeyMap) c.KeyMap[kv.Key] = kv.Value;
664 profiles.Insert(profiles.IndexOf(p) + 1, c); SaveProfiles(); RebuildTools(true);
665 });
666 m.Items.Add("Set Hotkey...", null, delegate
667 {
668 Keys k = p.Hot;
669 if (!Dialogs.PickKey(this, "Profile hotkey", "Hotkey that loads the " + p.Name + " profile.", ref k)) return;
670 if (k != Keys.None && KeyTaken(k, p)) { SetMessage(KeyText.Of(k) + " is already used. Pick another key.", true); return; }
671 p.Hot = k; SaveProfiles(); ReRegister(); RebuildTools(true);
672 });
673 m.Items.Add(p.Chaos ? "Stop Randomizing on Load" : "Randomize on Load (Chaos)", null, delegate { p.Chaos = !p.Chaos; SaveProfiles(); RebuildTools(true); });
674 m.Items.Add("Export...", null, delegate { ExportProfile(p); });
675 m.Items.Add(new ToolStripSeparator());
676 m.Items.Add("Delete", null, delegate
677 {
678 if (!Dialogs.Confirm(this, "Delete profile", "Delete the " + p.Name + " profile? This can't be undone.")) return;
679 profiles.Remove(p); SaveProfiles(); ReRegister(); RebuildTools(true);
680 });
681 m.Show(Cursor.Position);
682 }
683
684 private void LoadMacros()
685 {
686 macros.Clear();
687 for (int i = 0; i < 50; i++)
688 {
689 string v;
690 if (!settings.TryGetValue("macro." + i, out v)) continue;
691 string[] p = v.Split('|');
692 if (p.Length < 5) continue;
693 Macro m = new Macro(); m.Name = p[0];
694 int k; if (int.TryParse(p[1], out k)) m.Key = (Keys)k;
695 m.Cond = Array.IndexOf(Dialogs.CondIds, p[2]) >= 0 ? p[2] : "always";
696 m.Mode = p[3] == "off" || p[3] == "flip" ? p[3] : "on";
697 foreach (string s in p[4].Split(',')) if (byId.ContainsKey(s)) m.Ids.Add(s);
698 if (m.Ids.Count > 0) macros.Add(m);
699 }
700 }
701
702 private void SaveMacros()
703 {
704 for (int i = 0; i < 50; i++) settings.Remove("macro." + i);
705 for (int i = 0; i < macros.Count && i < 50; i++)
706 {
707 Macro m = macros[i];
708 settings["macro." + i] = m.Name.Replace("|", "/") + "|" + ((int)m.Key).ToString(CultureInfo.InvariantCulture) + "|" + m.Cond + "|" + m.Mode + "|" + string.Join(",", m.Ids.ToArray());
709 }
710 Settings.Save(settings);
711 }
712
713 private static float V(Dictionary<string, string> d, string k, float def)
714 {
715 string s; float f;
716 return d != null && d.TryGetValue(k, out s) && float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out f) ? f : def;
717 }
718
719 private bool CondMet(string c)
720 {
721 Dictionary<string, string> v = health.Vitals;
722 switch (c)
723 {
724 case "run": return v != null;
725 case "bleeding": return v != null && V(v, "bleed", 0f) > 0.02f;
726 case "critical": return v != null && (V(v, "crit", 0f) > 0 || V(v, "arrest", 0f) > 0);
727 case "hurt": return v != null && (V(v, "pain", 0f) > 20f || V(v, "broken", 0f) > 0 || V(v, "disloc", 0f) > 0);
728 case "hungry": return v != null && (V(v, "hunger", 100f) < 35f || V(v, "thirst", 100f) < 35f);
729 case "trader": return view.Info != null && view.Info.ContainsKey("trader");
730 default: return true;
731 }
732 }
733
734 private void RunMacro(Macro m)
735 {
736 if (!CondMet(m.Cond))
737 {
738 string why = Dialogs.CondNames[Math.Max(0, Array.IndexOf(Dialogs.CondIds, m.Cond))].ToLowerInvariant();
739 overlay.Toast(m.Name + ": " + why, false);
740 SetMessage(m.Name + " didn't run: it works " + why + ".", false);
741 return;
742 }
743 bool needLink = false;
744 foreach (string id in m.Ids)
745 {
746 Option o;
747 if (!byId.TryGetValue(id, out o)) continue;
748 if (o.Kind == Kind.Toggle) SetCheat(o, m.Mode == "on" ? true : m.Mode == "off" ? false : !o.On);
749 else if (o.Kind == Kind.Action)
750 {
751 if (!link.IsConnected) { needLink = true; continue; }
752 link.Send("ACT " + o.Id);
753 }
754 }
755 CheatsChanged();
756 overlay.Toast("Macro: " + m.Name, true);
757 SetMessage("Ran " + m.Name + "." + (needLink ? " Its actions need the trainer to be attached." : ""), needLink);
758 }
759
760 private string MacroText(Macro m)
761 {
762 List<string> n = new List<string>();
763 foreach (string id in m.Ids) { Option o; if (byId.TryGetValue(id, out o)) n.Add(o.Name); }
764 string s = string.Join(", ", n.ToArray());
765 return s.Length > 60 ? s.Substring(0, 59) + "…" : s;
766 }
767
768 private bool KeyTaken(Keys k, object except)
769 {
770 foreach (Option o in options) if (o.Bindable && o.Key == k) return true;
771 foreach (Macro m in macros) if (m != except && m.Key == k) return true;
772 foreach (Profile p in profiles) if (p != except && p.Hot == k) return true;
773 return false;
774 }
775
776 private void ReRegister()
777 {
778 if (hotkeysOn) { UnregisterKeys(); RegisterKeys(); }
779 }
780
781 private void RegisterToolKeys()
782 {
783 toolKeys.Clear();
784 int id = 0x5800;
785 foreach (Macro m in macros)
786 {
787 if (m.Key == Keys.None) continue;
788 Macro mm = m;
789 if (RegKey(id, m.Key)) toolKeys[id] = delegate { RunMacro(mm); };
790 id++;
791 }
792 foreach (Profile p in profiles)
793 {
794 if (p.Hot == Keys.None) continue;
795 Profile pp = p;
796 if (RegKey(id, p.Hot)) toolKeys[id] = delegate { LoadProfile(pp); };
797 id++;
798 }
799 }
800
801 private bool RegKey(int id, Keys k)
802 {
803 uint mods = 0x4000;
804 if ((k & Keys.Alt) != 0) mods |= 1;
805 if ((k & Keys.Control) != 0) mods |= 2;
806 if ((k & Keys.Shift) != 0) mods |= 4;
807 return Native.RegisterHotKey(Handle, id, mods, (uint)(k & Keys.KeyCode));
808 }
809
810 private void UnregisterToolKeys()
811 {
812 foreach (int id in toolKeys.Keys) Native.UnregisterHotKey(Handle, id);
813 toolKeys.Clear();
814 }
815
816 private bool ToolHotkey(int id)
817 {
818 Action a;
819 if (!toolKeys.TryGetValue(id, out a)) return false;
820 a();
821 return true;
822 }
823
824 private void CheatMenu(Point at)
825 {
826 Option o = hoverOpt;
827 if (o == null || o.Kind != Kind.Toggle || o.Local || !InCheatTab(o)) return;
828 ContextMenuStrip m = new ContextMenuStrip();
829 ToolStripMenuItem head = new ToolStripMenuItem(o.Name); head.Enabled = false; m.Items.Add(head);
830 int[] mins = { 1, 2, 5, 10, 30 };
831 foreach (int n in mins)
832 {
833 int nn = n;
834 m.Items.Add((o.On ? "Turn off in " : "Turn on for ") + n + (n == 1 ? " minute" : " minutes"), null, delegate { StartTimer(o, nn); });
835 }
836 if (timers.ContainsKey(o.Id)) m.Items.Add("Cancel the timer", null, delegate { timers.Remove(o.Id); overlay.Invalidate(); RebuildTools(false); });
837 m.Items.Add(new ToolStripSeparator());
838 ToolStripMenuItem nv = new ToolStripMenuItem("Never randomise this");
839 nv.Checked = neverRandom.Contains(o.Id);
840 nv.Click += delegate
841 {
842 if (!neverRandom.Remove(o.Id)) neverRandom.Add(o.Id);
843 SaveNever();
844 };
845 m.Items.Add(nv);
846 m.Items.Add("New macro with this cheat...", null, delegate { Macro mc = new Macro(); mc.Name = o.Name; mc.Ids.Add(o.Id); NewMacro(mc); });
847 m.Show(view, at);
848 }
849
850 private void StartTimer(Option o, int minutes)
851 {
852 SetCheat(o, true);
853 timers[o.Id] = DateTime.UtcNow.AddMinutes(minutes);
854 CheatsChanged();
855 SetMessage(o.Name + " turns off by itself in " + minutes + (minutes == 1 ? " minute." : " minutes."), false);
856 RebuildTools(false);
857 }
858
859 private void SaveNever()
860 {
861 settings["rand.never"] = string.Join(",", new List<string>(neverRandom).ToArray());
862 Settings.Save(settings);
863 }
864
865 private int RandCount() { int n; return int.TryParse(Get("rand.count", "5"), out n) ? Math.Max(1, Math.Min(12, n)) : 5; }
866 private int RandEvery() { int n; return int.TryParse(Get("rand.every", "0"), out n) ? Math.Max(0, Math.Min(60, n)) : 0; }
867
868 private static readonly Random rng = new Random();
869
870 private List<Option> RandPool(bool wantOn)
871 {
872 List<Option> l = new List<Option>();
873 foreach (Option o in CheatToggles()) if (!neverRandom.Contains(o.Id) && o.On == wantOn) l.Add(o);
874 return l;
875 }
876
877 private Option RandomOn()
878 {
879 List<Option> l = RandPool(false);
880 if (l.Count == 0) return null;
881 Option o = l[rng.Next(l.Count)];
882 SetCheat(o, true);
883 randOn.Add(o.Id);
884 return o;
885 }
886
887 private void Shuffle(int n)
888 {
889 foreach (Option o in CheatToggles()) if (!neverRandom.Contains(o.Id)) SetCheat(o, false);
890 randOn.Clear();
891 List<string> got = new List<string>();
892 for (int i = 0; i < n; i++) { Option o = RandomOn(); if (o != null) got.Add(o.Name); }
893 CheatsChanged();
894 SetMessage(got.Count == 0 ? "Nothing to randomise: every cheat is on the never list." : "Randomizer: " + string.Join(", ", got.ToArray()) + ".", false);
895 }
896
897 private void RandomTick()
898 {
899 int every = RandEvery();
900 if (every <= 0) { nextRandom = DateTime.MaxValue; return; }
901 if (nextRandom == DateTime.MaxValue) nextRandom = DateTime.UtcNow.AddMinutes(every);
902 if (DateTime.UtcNow < nextRandom) return;
903 nextRandom = DateTime.UtcNow.AddMinutes(every);
904 List<string> mine = new List<string>(randOn);
905 string offName = null;
906 if (mine.Count > 0)
907 {
908 Option off; if (byId.TryGetValue(mine[rng.Next(mine.Count)], out off)) { SetCheat(off, false); offName = off.Name; }
909 }
910 Option on = RandomOn();
911 CheatsChanged();
912 string s = (offName != null ? offName + " off" : "") + (on != null ? (offName != null ? ", " : "") + on.Name + " on" : "");
913 if (s.Length > 0) { overlay.Toast("Randomizer: " + s, true); SetMessage("Randomizer: " + s + ".", false); }
914 }
915
916 private static int WatchIndex(string k)
917 {
918 for (int i = 0; i < WatchKeys.Length; i++) if (WatchKeys[i][0] == k) return i;
919 return -1;
920 }
921
922 private string WatchValue(string k)
923 {
924 Dictionary<string, string> v = health.Vitals;
925 string s;
926 if (v == null || !v.TryGetValue(k, out s)) return "-";
927 int i = WatchIndex(k);
928 return s + (i >= 0 ? WatchKeys[i][2] : "");
929 }
930
931 private void SaveWatch()
932 {
933 settings["watch"] = string.Join(",", watched.ToArray());
934 Settings.Save(settings);
935 }
936
937 private string AlertText(string k)
938 {
939 string a = Get("watch.alert." + k, "");
940 if (a.Length < 2) return "";
941 return (a[0] == '<' ? "alert below " : "alert above ") + a.Substring(1);
942 }
943
944 private void WatchTick()
945 {
946 Dictionary<string, string> v = health.Vitals;
947 List<KeyValuePair<string, string>> rows = new List<KeyValuePair<string, string>>();
948 foreach (string k in watched)
949 {
950 int i = WatchIndex(k);
951 if (i < 0) continue;
952 rows.Add(new KeyValuePair<string, string>(WatchKeys[i][1], WatchValue(k)));
953 string a = Get("watch.alert." + k, "");
954 float thr;
955 if (v == null || a.Length < 2 || !float.TryParse(a.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out thr)) { alerting.Remove(k); continue; }
956 float cur = V(v, k, float.NaN);
957 if (float.IsNaN(cur)) continue;
958 bool hit = a[0] == '<' ? cur < thr : cur > thr;
959 if (hit && alerting.Add(k))
960 {
961 string msg = WatchKeys[i][1] + " is " + WatchValue(k) + " (" + AlertText(k) + ")";
962 overlay.Toast(msg, false);
963 SetMessage(msg + ".", true);
964 System.Media.SystemSounds.Exclamation.Play();
965 }
966 else if (!hit) alerting.Remove(k);
967 }
968 if (v == null) rows.Clear();
969 if (overlay.SetWatch(rows, alerting.Count)) overlay.Invalidate();
970 }
971
972 private static string CheckRule(string id, Dictionary<string, string> v, out bool ok)
973 {
974 ok = true;
975 switch (id)
976 {
977 case "GodMode": ok = V(v, "alive", 1f) > 0 && V(v, "arrest", 0f) <= 0; return "you're alive and your heart is beating";
978 case "NoHunger": ok = V(v, "hunger", 100f) >= 80f; return "food stays full";
979 case "NoThirst": ok = V(v, "thirst", 100f) >= 80f; return "water stays full";
980 case "NoTiredness": ok = V(v, "energy", 100f) >= 80f; return "energy stays full";
981 case "NoBleeding": ok = V(v, "bleed", 0f) <= 0.02f; return "no bleeding";
982 case "NoPain": ok = V(v, "pain", 0f) <= 5f; return "no pain";
983 case "NoInfection": ok = V(v, "infect", 0f) <= 1f; return "no infection";
984 case "NoSickness": ok = V(v, "sick", 0f) <= 1f; return "no sickness";
985 case "NoRadiation": ok = V(v, "rad", 0f) <= 1f; return "no radiation sickness";
986 case "UnlimitedOxygen": ok = V(v, "oxy", 100f) >= 90f; return "blood oxygen stays high";
987 case "UnlimitedCarry": ok = V(v, "enc", 0f) <= 0f; return "you're not over-encumbered";
988 default: return null;
989 }
990 }
991
992 private string CheckLine(Option o)
993 {
994 Dictionary<string, string> v = health.Vitals;
995 if (v == null) return o.Name + ": start a run to check it";
996 bool ok;
997 string what = CheckRule(o.Id, v, out ok);
998 if (what == null) return o.Name + ": on (can't be checked from here)";
999 DateTime since;
1000 if (ok) { checkBad.Remove(o.Id); return "✔ " + o.Name + ": working (" + what + ")"; }
1001 if (!checkBad.TryGetValue(o.Id, out since)) { checkBad[o.Id] = DateTime.UtcNow; since = DateTime.UtcNow; }
1002 if ((DateTime.UtcNow - since).TotalSeconds < 6) return o.Name + ": checking...";
1003 return "⚠ " + o.Name + ": doesn't look like it's working";
1004 }
1005
1006 private void OnSent(string s)
1007 {
1008 string[] p = s.Split(new char[] { ' ' }, 3);
1009 string text = null;
1010 Option o;
1011 switch (p[0])
1012 {
1013 case "SET":
1014 if (p.Length < 3 || !byId.TryGetValue(p[1], out o)) return;
1015 text = o.Name + (p[2] == "1" ? " on" : " off");
1016 if (p[2] == "1" && run != null) run.Cheats.Add(o.Id);
1017 break;
1018 case "VAL":
1019 if (p.Length < 3 || !byId.TryGetValue(p[1], out o)) return;
1020 text = o.Name + " set to " + p[2];
1021 if (history.Count > 0 && history[history.Count - 1].Value.StartsWith(o.Name + " set to ", StringComparison.Ordinal)) history.RemoveAt(history.Count - 1);
1022 break;
1023 case "ACT":
1024 if (p.Length < 2) return;
1025 text = byId.TryGetValue(p[1], out o) ? o.Name : p[1];
1026 if (p[1] == "tpgo") text = "Teleported to a bookmark";
1027 if (run != null) run.Actions++;
1028 break;
1029 case "SPAWN":
1030 {
1031 if (p.Length < 3) return;
1032 int n; if (!int.TryParse(p[2], out n)) n = 1;
1033 text = "Spawned " + n + " x " + p[1];
1034 if (run != null) run.Spawned += n;
1035 break;
1036 }
1037 case "MODACT": text = "My Mods: " + (p.Length >= 3 ? p[2] : ""); break;
1038 case "MUSICPLAY": text = "Music: " + (p.Length >= 3 ? p[2] : ""); break;
1039 default: return;
1040 }
1041 AddHistory(text);
1042 }
1043
1044 private void AddHistory(string text)
1045 {
1046 history.Add(new KeyValuePair<DateTime, string>(DateTime.Now, text));
1047 if (history.Count > 300) history.RemoveRange(0, history.Count - 300);
1048 historyDirty = true;
1049 }
1050
1051 private void HistoryLine(string cmd, string rest)
1052 {
1053 if (cmd == "MSG" && rest.Length > 0) AddHistory("Game: " + rest);
1054 }
1055
1056 private void LoadRuns()
1057 {
1058 pastRuns.Clear();
1059 try
1060 {
1061 if (!File.Exists(RunsFile)) return;
1062 foreach (string l in File.ReadAllLines(RunsFile)) { RunStat r = RunStat.Parse(l); if (r != null) pastRuns.Add(r); }
1063 }
1064 catch (Exception) { }
1065 }
1066
1067 private void SaveRuns()
1068 {
1069 try
1070 {
1071 Directory.CreateDirectory(AppFolder);
1072 List<string> l = new List<string>();
1073 foreach (RunStat r in pastRuns) l.Add(r.Line());
1074 File.WriteAllLines(RunsFile, l.ToArray());
1075 }
1076 catch (Exception) { }
1077 }
1078
1079 private void RunTick()
1080 {
1081 Dictionary<string, string> v = health.Vitals;
1082 bool inRun = link.IsConnected && v != null;
1083 DateTime now = DateTime.UtcNow;
1084 if (inRun)
1085 {
1086 noRunSince = DateTime.MinValue;
1087 if (run == null)
1088 {
1089 run = new RunStat(); run.Start = DateTime.Now;
1090 foreach (Option o in CheatToggles()) if (o.On) run.Cheats.Add(o.Id);
1091 bookmarks.Clear();
1092 lastRunTick = now;
1093 toolsSig = "";
1094 }
1095 if (V(v, "alive", 1f) > 0) run.Secs += Math.Min(5.0, (now - lastRunTick).TotalSeconds);
1096 else run.Died = true;
1097 int depth = (int)V(view.Info, "depth", -2f);
1098 if (depth >= 0) run.Deepest = Math.Max(run.Deepest, depth + 1);
1099 float blood = V(v, "blood", -1f);
1100 if (blood >= 0 && run.LastBlood >= 0)
1101 {
1102 float d = blood - run.LastBlood;
1103 if (d < 0) run.BloodLost -= d; else run.BloodGained += d;
1104 }
1105 if (blood >= 0) run.LastBlood = blood;
1106 int miss = (int)V(v, "missing", -1f);
1107 if (miss >= 0 && run.LastMissing >= 0 && miss > run.LastMissing) run.LimbsLost += miss - run.LastMissing;
1108 if (miss >= 0) run.LastMissing = miss;
1109 }
1110 else if (run != null)
1111 {
1112 if (noRunSince == DateTime.MinValue) noRunSince = now;
1113 else if ((now - noRunSince).TotalSeconds >= 4 || !link.IsConnected) EndRun();
1114 }
1115 lastRunTick = now;
1116 }
1117
1118 private void EndRun()
1119 {
1120 if (run == null) return;
1121 if (run.Secs >= 10)
1122 {
1123 pastRuns.Add(run);
1124 if (pastRuns.Count > 40) pastRuns.RemoveRange(0, pastRuns.Count - 40);
1125 SaveRuns();
1126 }
1127 run = null;
1128 bookmarks.Clear();
1129 toolsSig = "";
1130 }
1131
1132 private static string Long(double secs)
1133 {
1134 int s = (int)secs;
1135 return s >= 3600 ? (s / 3600) + "h " + ((s / 60) % 60).ToString("00") + "m" : Clock(s);
1136 }
1137
1138 private string RunSummary(RunStat r)
1139 {
1140 return 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");
1141 }
1142
1143 private void RebuildTools(bool force)
1144 {
1145 StringBuilder sig = new StringBuilder();
1146 foreach (string k in timers.Keys) sig.Append(k).Append(',');
1147 sig.Append('|').Append(bookmarks.Count).Append('|').Append(watched.Count).Append('|').Append(pastRuns.Count).Append('|').Append(run != null);
1148 foreach (Option o in CheatToggles()) if (o.On) sig.Append(o.Id).Append(',');
1149 if (!force && sig.ToString() == toolsSig && !historyDirty) return;
1150 toolsSig = sig.ToString();
1151 historyDirty = false;
1152 BuildProfilesTab();
1153 BuildToolsTab();
1154 BuildWatchTab();
1155 BuildStatsTab();
1156 if (view.Tab == profTab || view.Tab == toolsTab || view.Tab == watchTab || view.Tab == statsTab) view.Invalidate();
1157 }
1158
1159 private void BuildProfilesTab()
1160 {
1161 if (profTab == null) return;
1162 foreach (List<Section> c in profTab.Cols) c.Clear();
1163 Section s = new Section("PROFILES");
1164 profTab.Cols[0].Add(s);
1165 s.Rows.Add(NoteRow("A profile is a set of cheats, sliders and hotkeys. Load one to switch everything at once. Click More for rename, duplicate, hotkey, export and delete."));
1166 string active = Get("profile.active", "");
1167 foreach (Profile p in profiles)
1168 {
1169 Profile pp = p;
1170 s.Rows.Add(XBtns(null, delegate
1171 {
1172 string t = (pp.Name == active ? "● " : "") + pp.Name + (pp.Chaos ? " (random)" : " (" + pp.On.Count + ")");
1173 return pp.Hot != Keys.None ? t + " " + KeyText.Of(pp.Hot) : t;
1174 }, new Btn("Load", "@x:pload", pp.Name), new Btn("Save Here", "@x:psave", pp.Name), new Btn("More", "@x:pmore", pp.Name)));
1175 }
1176 s.Rows.Add(XBtns(null, null, new Btn("New From Current Cheats", "@x:pnew", null), new Btn("Import...", "@x:pimport", null)));
1177
1178 s = new Section("MACROS");
1179 profTab.Cols[1].Add(s);
1180 s.Rows.Add(NoteRow("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."));
1181 for (int i = 0; i < macros.Count; i++)
1182 {
1183 Macro m = macros[i];
1184 string idx = i.ToString(CultureInfo.InvariantCulture);
1185 s.Rows.Add(XBtns(null, delegate { return m.Name + (m.Key != Keys.None ? " " + KeyText.Of(m.Key) : ""); }, new Btn("Run", "@x:mrun", idx), new Btn("Edit", "@x:medit", idx), new Btn("Delete", "@x:mdel", idx)));
1186 s.Rows.Add(NoteRow(MacroText(m) + (m.Cond != "always" ? " · " + Dialogs.CondNames[Math.Max(0, Array.IndexOf(Dialogs.CondIds, m.Cond))].ToLowerInvariant() : "")));
1187 }
1188 s.Rows.Add(XBtns(null, null, new Btn("New Macro...", "@x:mnew", null)));
1189
1190 s = new Section("BACK UP EVERYTHING");
1191 profTab.Cols[2].Add(s);
1192 s.Rows.Add(NoteRow("Saves your settings, hotkeys, theme, profiles, macros, favorites and run history to one .zip file. Restore it on another PC or after a reinstall."));
1193 s.Rows.Add(XBtns(null, null, new Btn("Back Up...", "@x:backup", null), new Btn("Restore...", "@x:restore", null)));
1194 }
1195
1196 private void BuildToolsTab()
1197 {
1198 if (toolsTab == null) return;
1199 foreach (List<Section> c in toolsTab.Cols) c.Clear();
1200 Section s = new Section("TIMED CHEATS");
1201 toolsTab.Cols[0].Add(s);
1202 s.Rows.Add(NoteRow("Right-click any cheat and pick a time. It turns itself off when the time is up. The overlay shows the time left."));
1203 foreach (string id in new List<string>(timers.Keys))
1204 {
1205 Option o; if (!byId.TryGetValue(id, out o)) continue;
1206 string iid = id; Option oo = o;
1207 s.Rows.Add(XBtns(null, delegate
1208 {
1209 DateTime t; return timers.TryGetValue(iid, out t) ? oo.Name + " " + Clock(Math.Max(0, (int)(t - DateTime.UtcNow).TotalSeconds)) : oo.Name;
1210 }, new Btn("+5 min", "@x:tadd", id), new Btn("Keep On", "@x:tkeep", id), new Btn("Off Now", "@x:toff", id)));
1211 }
1212 if (timers.Count == 0) s.Rows.Add(XInfo(delegate { return "No timers running."; }));
1213
1214 s = new Section("RANDOMIZER");
1215 toolsTab.Cols[0].Add(s);
1216 s.Rows.Add(XBtns(null, null, new Btn("Random Cheat", "@x:rone", null), new Btn("Shuffle", "@x:rshuffle", null), new Btn("Never List...", "@x:rnever", null)));
1217 s.Rows.Add(XBtns("Shuffle turns on", delegate { return "Shuffle turns on " + RandCount(); }, new Btn("3", "@x:rcount", "3"), new Btn("5", "@x:rcount", "5"), new Btn("8", "@x:rcount", "8")));
1218 s.Rows.Add(XBtns(null, delegate
1219 {
1220 int e = RandEvery();
1221 return e == 0 ? "Change one: off" : "Change one every " + e + " min";
1222 }, new Btn("Off", "@x:revery", "0"), new Btn("1", "@x:revery", "1"), new Btn("2", "@x:revery", "2"), new Btn("5", "@x:revery", "5"), new Btn("10", "@x:revery", "10")));
1223 s.Rows.Add(NoteRow("The randomizer skips cheats on the never list (challenges, noclip and free camera start on it). Right-click a cheat to add or remove it. Every N minutes it swaps one of its own cheats for a new one."));
1224
1225 s = new Section("TELEPORT BOOKMARKS");
1226 toolsTab.Cols[1].Add(s);
1227 s.Rows.Add(NoteRow("Save where you're standing and jump back later on the same layer. Bookmarks clear when the run ends, because every run builds new layers."));
1228 s.Rows.Add(XBtns(null, null, new Btn("Save This Spot", "@x:bsave", null)));
1229 for (int i = 0; i < bookmarks.Count; i++)
1230 {
1231 Bookmark b = bookmarks[i];
1232 string idx = i.ToString(CultureInfo.InvariantCulture);
1233 s.Rows.Add(XBtns(null, delegate { return b.Name + (b.Depth >= 0 ? " (layer " + (b.Depth + 1) + ")" : " (special area)"); }, new Btn("Go", "@x:bgo", idx), new Btn("Delete", "@x:bdel", idx)));
1234 }
1235
1236 s = new Section("CHEAT CHECK");
1237 toolsTab.Cols[2].Add(s);
1238 s.Rows.Add(NoteRow("Checks that the cheats you have on are really doing their job in the game, using your character's live health."));
1239 int n = 0;
1240 foreach (Option o in CheatToggles())
1241 {
1242 if (!o.On) continue;
1243 Option oo = o;
1244 s.Rows.Add(XInfo(delegate { return CheckLine(oo); }));
1245 n++;
1246 }
1247 if (n == 0) s.Rows.Add(XInfo(delegate { return "No cheats are on."; }));
1248 }
1249
1250 private void BuildWatchTab()
1251 {
1252 if (watchTab == null) return;
1253 foreach (List<Section> c in watchTab.Cols) c.Clear();
1254 Section s = new Section("WATCHING");
1255 watchTab.Cols[0].Add(s);
1256 s.Rows.Add(NoteRow("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."));
1257 foreach (string k in watched)
1258 {
1259 int i = WatchIndex(k); if (i < 0) continue;
1260 string kk = k;
1261 s.Rows.Add(XBtns(null, delegate
1262 {
1263 string a = AlertText(kk);
1264 return WatchKeys[WatchIndex(kk)][1] + ": " + WatchValue(kk) + (a.Length > 0 ? " (" + a + ")" : "");
1265 }, new Btn("Alert...", "@x:walert", k), new Btn("Unpin", "@x:wunpin", k)));
1266 }
1267 if (watched.Count == 0) s.Rows.Add(XInfo(delegate { return "Nothing pinned yet. Pin values from the list."; }));
1268
1269 for (int c = 1; c <= 2; c++)
1270 {
1271 s = new Section(c == 1 ? "LIVE VALUES" : "MORE VALUES");
1272 watchTab.Cols[c].Add(s);
1273 int half = (WatchKeys.Length + 1) / 2;
1274 for (int i = c == 1 ? 0 : half; i < (c == 1 ? half : WatchKeys.Length); i++)
1275 {
1276 string k = WatchKeys[i][0];
1277 string lbl = WatchKeys[i][1];
1278 s.Rows.Add(XBtns(null, delegate { return lbl + ": " + WatchValue(k); }, new Btn(watched.Contains(k) ? "Pinned" : "Pin", "@x:wpin", k)));
1279 }
1280 }
1281 }
1282
1283 private void BuildStatsTab()
1284 {
1285 if (statsTab == null) return;
1286 foreach (List<Section> c in statsTab.Cols) c.Clear();
1287 Section s = new Section("THIS RUN");
1288 statsTab.Cols[0].Add(s);
1289 s.Rows.Add(XInfo(delegate { return run == null ? "Not in a run." : "Time: " + Long(run.Secs) + (run.Died ? " (died)" : ""); }));
1290 s.Rows.Add(XInfo(delegate { return run == null ? "" : "Deepest layer: " + Math.Max(1, run.Deepest); }));
1291 s.Rows.Add(XInfo(delegate { return run == null ? "" : "Blood lost: " + run.BloodLost.ToString("0", CultureInfo.InvariantCulture) + " healed: " + run.BloodGained.ToString("0", CultureInfo.InvariantCulture); }));
1292 s.Rows.Add(XInfo(delegate { return run == null ? "" : "Limbs lost: " + run.LimbsLost; }));
1293 s.Rows.Add(XInfo(delegate { return run == null ? "" : "Items spawned: " + run.Spawned + " actions used: " + run.Actions; }));
1294 s.Rows.Add(XInfo(delegate { return 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"; }));
1295
1296 s = new Section("PAST RUNS");
1297 statsTab.Cols[1].Add(s);
1298 double total = 0; int deaths = 0, clean = 0;
1299 foreach (RunStat r in pastRuns) { total += r.Secs; if (r.Died) deaths++; if (!r.Cheated) clean++; }
1300 s.Rows.Add(XInfo(delegate { return pastRuns.Count + " runs · " + Long(total) + " played · " + deaths + " deaths · " + clean + " without cheats"; }));
1301 for (int i = pastRuns.Count - 1; i >= 0 && i >= pastRuns.Count - 12; i--)
1302 {
1303 RunStat r = pastRuns[i];
1304 s.Rows.Add(XInfo(delegate { return RunSummary(r); }));
1305 }
1306 if (pastRuns.Count > 0) s.Rows.Add(XBtns(null, null, new Btn("Clear Run History", "@x:rclear", null)));
1307 s.Rows.Add(NoteRow("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."));
1308
1309 s = new Section("ACTIVITY HISTORY");
1310 statsTab.Cols[2].Add(s);
1311 s.Rows.Add(XBtns(null, null, new Btn("Save to File...", "@x:hsave", null), new Btn("Clear", "@x:hclear", null)));
1312 if (history.Count == 0) s.Rows.Add(XInfo(delegate { return "Nothing yet. Everything the trainer does shows up here."; }));
1313 for (int i = history.Count - 1; i >= 0 && i >= history.Count - 40; i--)
1314 {
1315 KeyValuePair<DateTime, string> h = history[i];
1316 s.Rows.Add(XInfo(delegate { return h.Key.ToString("HH:mm:ss", CultureInfo.InvariantCulture) + " " + h.Value; }));
1317 }
1318 }
1319
1320 private void NewMacro(Macro m)
1321 {
1322 if (!Dialogs.EditMacro(this, m, MacroPool())) return;
1323 if (m.Key != Keys.None && KeyTaken(m.Key, m)) { SetMessage(KeyText.Of(m.Key) + " is already used, so the macro was saved without a hotkey.", true); m.Key = Keys.None; }
1324 if (!macros.Contains(m)) macros.Add(m);
1325 SaveMacros(); ReRegister(); RebuildTools(true);
1326 }
1327
1328 private void ToolsButton(Btn b)
1329 {
1330 int idx;
1331 int.TryParse(b.Arg ?? "", out idx);
1332 Option o;
1333 switch (b.Act)
1334 {
1335 case "@x:pload": { Profile p = FindProfile(b.Arg); if (p != null) LoadProfile(p); return; }
1336 case "@x:psave":
1337 {
1338 Profile p = FindProfile(b.Arg); if (p == null) return;
1339 if (!Dialogs.Confirm(this, "Save profile", "Replace the " + p.Name + " profile with the cheats, sliders and hotkeys you have now?")) return;
1340 CaptureInto(p); p.Chaos = false; SaveProfiles(); RebuildTools(true);
1341 SetMessage("Saved the " + p.Name + " profile.", false);
1342 return;
1343 }
1344 case "@x:pmore": { Profile p = FindProfile(b.Arg); if (p != null) ProfileMenu(p); return; }
1345 case "@x:pnew":
1346 {
1347 string n = Dialogs.Ask(this, "New profile", "Name for the new profile (it starts with the cheats you have on now):", "My Profile");
1348 if (n == null) return;
1349 Profile p = new Profile(); p.Name = UniqueName(n); CaptureInto(p);
1350 profiles.Add(p); SaveProfiles(); RebuildTools(true);
1351 return;
1352 }
1353 case "@x:pimport": ImportProfile(); return;
1354 case "@x:backup": BackupAll(); return;
1355 case "@x:restore": RestoreAll(); return;
1356 case "@x:mnew": NewMacro(new Macro()); return;
1357 case "@x:mrun": if (idx >= 0 && idx < macros.Count) RunMacro(macros[idx]); return;
1358 case "@x:medit": if (idx >= 0 && idx < macros.Count) NewMacro(macros[idx]); return;
1359 case "@x:mdel":
1360 if (idx < 0 || idx >= macros.Count) return;
1361 if (!Dialogs.Confirm(this, "Delete macro", "Delete the " + macros[idx].Name + " macro?")) return;
1362 macros.RemoveAt(idx); SaveMacros(); ReRegister(); RebuildTools(true);
1363 return;
1364 case "@x:tadd": { DateTime t; if (timers.TryGetValue(b.Arg, out t)) timers[b.Arg] = t.AddMinutes(5); return; }
1365 case "@x:tkeep": timers.Remove(b.Arg); overlay.Invalidate(); RebuildTools(false); return;
1366 case "@x:toff": if (byId.TryGetValue(b.Arg, out o)) { SetCheat(o, false); CheatsChanged(); } RebuildTools(false); return;
1367 case "@x:rone": { Option r = RandomOn(); CheatsChanged(); SetMessage(r == null ? "No cheats left to turn on." : "Randomizer: " + r.Name + " on.", false); return; }
1368 case "@x:rshuffle": Shuffle(RandCount()); return;
1369 case "@x:rnever":
1370 {
1371 HashSet<string> pick = new HashSet<string>(neverRandom);
1372 if (Dialogs.PickMany(this, "Never randomise", "Tick the cheats the randomizer and the Chaos profile should never touch.", CheatToggles(), pick))
1373 {
1374 neverRandom.Clear(); foreach (string x in pick) neverRandom.Add(x); SaveNever();
1375 }
1376 return;
1377 }
1378 case "@x:rcount": settings["rand.count"] = b.Arg; Settings.Save(settings); view.Invalidate(); return;
1379 case "@x:revery": settings["rand.every"] = b.Arg; Settings.Save(settings); nextRandom = DateTime.MaxValue; view.Invalidate(); return;
1380 case "@x:bsave":
1381 {
1382 if (!link.IsConnected || health.Vitals == null) { SetMessage("Start a run first.", true); return; }
1383 float x = V(view.Info, "px", float.NaN), y = V(view.Info, "py", float.NaN);
1384 int d = (int)V(view.Info, "depth", -2f);
1385 if (float.IsNaN(x) || float.IsNaN(y) || d < -1) { SetMessage("The game hasn't sent your position yet. Update UltraPara.dll (UltraPara tab) and try again.", true); return; }
1386 string n = Dialogs.Ask(this, "Save spot", "Name for this spot:", "Spot " + (bookmarks.Count + 1));
1387 if (n == null) return;
1388 Bookmark bm = new Bookmark(); bm.Name = ProfileName(n).Length > 0 ? ProfileName(n) : "Spot"; bm.X = x; bm.Y = y; bm.Depth = d;
1389 bookmarks.Add(bm);
1390 if (bookmarks.Count > 20) bookmarks.RemoveAt(0);
1391 RebuildTools(true);
1392 return;
1393 }
1394 case "@x:bgo":
1395 {
1396 if (idx < 0 || idx >= bookmarks.Count) return;
1397 if (!link.IsConnected) { SetMessage("Attach to the game first.", true); return; }
1398 Bookmark bm = bookmarks[idx];
1399 link.Send("ACT tpgo " + bm.X.ToString(CultureInfo.InvariantCulture) + " " + bm.Y.ToString(CultureInfo.InvariantCulture) + " " + bm.Depth);
1400 return;
1401 }
1402 case "@x:bdel": if (idx >= 0 && idx < bookmarks.Count) { bookmarks.RemoveAt(idx); RebuildTools(true); } return;
1403 case "@x:wpin":
1404 if (watched.Contains(b.Arg)) watched.Remove(b.Arg); else watched.Add(b.Arg);
1405 SaveWatch(); RebuildTools(true);
1406 return;
1407 case "@x:wunpin": watched.Remove(b.Arg); alerting.Remove(b.Arg); SaveWatch(); RebuildTools(true); return;
1408 case "@x:walert":
1409 {
1410 int i = WatchIndex(b.Arg); if (i < 0) return;
1411 string a = Get("watch.alert." + b.Arg, "");
1412 string op = a.Length > 0 ? a.Substring(0, 1) : "<";
1413 float thr = 50f;
1414 if (a.Length > 1) float.TryParse(a.Substring(1), NumberStyles.Float, CultureInfo.InvariantCulture, out thr);
1415 if (!Dialogs.AskAlert(this, WatchKeys[i][1].ToLowerInvariant(), ref op, ref thr)) return;
1416 if (op.Length == 0) settings.Remove("watch.alert." + b.Arg);
1417 else settings["watch.alert." + b.Arg] = op + thr.ToString(CultureInfo.InvariantCulture);
1418 Settings.Save(settings);
1419 alerting.Remove(b.Arg);
1420 view.Invalidate();
1421 return;
1422 }
1423 case "@x:rclear":
1424 if (!Dialogs.Confirm(this, "Clear run history", "Delete every saved run?")) return;
1425 pastRuns.Clear(); SaveRuns(); RebuildTools(true);
1426 return;
1427 case "@x:hclear": history.Clear(); RebuildTools(true); return;
1428 case "@x:hsave":
1429 using (SaveFileDialog d = new SaveFileDialog())
1430 {
1431 d.Title = "Save activity history"; d.Filter = "Text file (*.txt)|*.txt"; d.FileName = "Ultra Paradise activity.txt";
1432 if (d.ShowDialog(this) != DialogResult.OK) return;
1433 List<string> l = new List<string>();
1434 foreach (KeyValuePair<DateTime, string> h in history) l.Add(h.Key.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + " " + h.Value);
1435 try { File.WriteAllLines(d.FileName, l.ToArray()); } catch (Exception e) { SetMessage("Couldn't save: " + e.Message, true); }
1436 }
1437 return;
1438 }
1439 }
1440
1441 private static bool BackupName(string n)
1442 {
1443 string e = Path.GetExtension(n).ToLowerInvariant();
1444 return n.IndexOfAny(new char[] { '/', '\\', ':' }) < 0 && (e == ".ini" || e == ".txt" || e == ".json" || e == ".cfg");
1445 }
1446
1447 private void BackupAll()
1448 {
1449 Settings.Save(settings);
1450 using (SaveFileDialog d = new SaveFileDialog())
1451 {
1452 d.Title = "Back up everything";
1453 d.Filter = "Zip file (*.zip)|*.zip";
1454 d.FileName = "Ultra Paradise backup " + DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".zip";
1455 if (d.ShowDialog(this) != DialogResult.OK) return;
1456 try
1457 {
1458 int n = 0;
1459 using (FileStream fs = new FileStream(d.FileName, FileMode.Create))
1460 using (ZipArchive z = new ZipArchive(fs, ZipArchiveMode.Create))
1461 {
1462 foreach (string f in Directory.GetFiles(AppFolder))
1463 {
1464 string name = Path.GetFileName(f);
1465 if (!BackupName(name) || new FileInfo(f).Length > 4 * 1024 * 1024) continue;
1466 ZipArchiveEntry e = z.CreateEntry(name);
1467 using (Stream w = e.Open()) { byte[] b = File.ReadAllBytes(f); w.Write(b, 0, b.Length); }
1468 n++;
1469 }
1470 }
1471 SetMessage("Backed up " + n + " files to " + Path.GetFileName(d.FileName) + ".", false);
1472 }
1473 catch (Exception e) { SetMessage("Couldn't make the backup: " + e.Message, true); }
1474 }
1475 }
1476
1477 private void RestoreAll()
1478 {
1479 using (OpenFileDialog d = new OpenFileDialog())
1480 {
1481 d.Title = "Restore a backup";
1482 d.Filter = "Zip file (*.zip)|*.zip";
1483 if (d.ShowDialog(this) != DialogResult.OK) return;
1484 if (!Dialogs.Confirm(this, "Restore backup", "Replace your current settings, profiles, macros and theme with the ones in this backup? The trainer restarts afterwards.")) return;
1485 try
1486 {
1487 int n = 0;
1488 using (ZipArchive z = ZipFile.OpenRead(d.FileName))
1489 {
1490 bool hasSettings = false;
1491 foreach (ZipArchiveEntry e in z.Entries) if (e.FullName == "settings.ini") hasSettings = true;
1492 if (!hasSettings) { SetMessage("That zip isn't an Ultra Paradise backup.", true); return; }
1493 Directory.CreateDirectory(AppFolder);
1494 foreach (ZipArchiveEntry e in z.Entries)
1495 {
1496 if (!BackupName(e.FullName) || e.Length > 4 * 1024 * 1024) continue;
1497 e.ExtractToFile(Path.Combine(AppFolder, e.FullName), true);
1498 n++;
1499 }
1500 }
1501 settings.Clear();
1502 foreach (KeyValuePair<string, string> kv in Settings.Load()) settings[kv.Key] = kv.Value;
1503 MessageBox.Show(this, "Restored " + n + " files. The trainer will restart now.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
1504 Program.Relaunch = true;
1505 Close();
1506 }
1507 catch (Exception e) { SetMessage("Couldn't restore the backup: " + e.Message, true); }
1508 }
1509 }
1510
1511 private void ToolsTick()
1512 {
1513 DateTime now = DateTime.UtcNow;
1514 List<string> done = new List<string>();
1515 foreach (KeyValuePair<string, DateTime> kv in timers) if (now >= kv.Value) done.Add(kv.Key);
1516 foreach (string id in done)
1517 {
1518 Option o;
1519 timers.Remove(id);
1520 if (!byId.TryGetValue(id, out o)) continue;
1521 SetCheat(o, false);
1522 CheatsChanged();
1523 overlay.Toast(o.Name + " OFF (time's up)", true);
1524 SetMessage(o.Name + " turned itself off.", false);
1525 }
1526 if (now < nextToolsSecond) return;
1527 nextToolsSecond = now.AddSeconds(1);
1528 RunTick();
1529 WatchTick();
1530 RandomTick();
1531 if (timers.Count > 0) overlay.Invalidate();
1532 RebuildTools(false);
1533 if (view.Tab == toolsTab || view.Tab == watchTab || view.Tab == statsTab) view.Invalidate();
1534 }
1535 }
1536}