cu-trainer/Ultra Paradise Application/src/Trainer.cs
| 1 | using System; |
| 2 | using System.Collections.Generic; |
| 3 | using System.Diagnostics; |
| 4 | using System.Drawing; |
| 5 | using System.Drawing.Drawing2D; |
| 6 | using System.Drawing.Text; |
| 7 | using System.Globalization; |
| 8 | using System.IO; |
| 9 | using System.Net; |
| 10 | using System.Net.Sockets; |
| 11 | using System.Reflection; |
| 12 | using System.Runtime.InteropServices; |
| 13 | using System.Text; |
| 14 | using System.Threading; |
| 15 | using System.Windows.Forms; |
| 16 | |
| 17 | [assembly: AssemblyMetadata("Notice", "Copyright (c) casualexpie. Source available at https://opensource.smellypawz.com under the casualexpie Source-Available License. Don't redistribute, sell or reuse it without permission.")] |
| 18 | [assembly: AssemblyTitle("Ultra Paradise CU:Trainer")] |
| 19 | [assembly: AssemblyDescription("Trainer for Casualties: Unknown")] |
| 20 | [assembly: AssemblyProduct("Ultra Paradise CU:Trainer")] |
| 21 | [assembly: AssemblyCompany("casualexpie")] |
| 22 | [assembly: AssemblyCopyright("Copyright (c) casualexpie")] |
| 23 | [assembly: AssemblyVersion("2.0.12.0")] |
| 24 | [assembly: AssemblyFileVersion("2.0.12.0")] |
| 25 | |
| 26 | namespace UltraParadise |
| 27 | { |
| 28 | internal static class Program |
| 29 | { |
| 30 | public const string Version = "2.0.14"; |
| 31 | internal static bool Quiet; |
| 32 | public const string Name = "Ultra Paradise CU:Trainer"; |
| 33 | public const string GameProcess = "CasualtiesUnknown"; |
| 34 | |
| 35 | internal static bool JustUpdated, JustInstalled, JustRestyled, Relaunch; |
| 36 | |
| 37 | [STAThread] |
| 38 | private static void Main(string[] args) |
| 39 | { |
| 40 | JustUpdated = Array.IndexOf(args, "--updated") >= 0; |
| 41 | JustInstalled = Array.IndexOf(args, "--installed") >= 0; |
| 42 | JustRestyled = Array.IndexOf(args, "--restyled") >= 0; |
| 43 | bool uninstall = Array.IndexOf(args, "--uninstall") >= 0; |
| 44 | using (Mutex m = new Mutex(false, "UltraParadiseCUTrainer")) |
| 45 | { |
| 46 | bool have; |
| 47 | try { have = m.WaitOne(JustUpdated || JustInstalled || JustRestyled ? 30000 : 0); } |
| 48 | catch (AbandonedMutexException) { have = true; } |
| 49 | if (!have) |
| 50 | { |
| 51 | MessageBox.Show(uninstall ? "Close " + Name + " first, then uninstall it." : Name + " is already open.", Name, MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 52 | return; |
| 53 | } |
| 54 | try |
| 55 | { |
| 56 | try { Native.SetProcessDPIAware(); } catch (Exception) { } |
| 57 | Application.EnableVisualStyles(); |
| 58 | Application.SetCompatibleTextRenderingDefault(false); |
| 59 | if (uninstall) { Setup.Uninstall(); return; } |
| 60 | Theme.Load(); |
| 61 | Updater.Cleanup(); |
| 62 | Setup.RefreshIfInstalled(); |
| 63 | Image splash = Res.Image("splash.jpg"); |
| 64 | if (!JustUpdated && !JustInstalled && !JustRestyled) |
| 65 | { |
| 66 | using (LauncherForm l = new LauncherForm(splash)) |
| 67 | { |
| 68 | Application.Run(l); |
| 69 | if (l.Restarting) return; |
| 70 | } |
| 71 | } |
| 72 | Application.Run(new MainForm(splash)); |
| 73 | if (Relaunch) { try { Process.Start(Application.ExecutablePath, "--restyled"); } catch (Exception) { } } |
| 74 | } |
| 75 | finally { try { m.ReleaseMutex(); } catch (Exception) { } } |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | internal static class Res |
| 81 | { |
| 82 | public static Stream Open(string name) |
| 83 | { |
| 84 | return Assembly.GetExecutingAssembly().GetManifestResourceStream("UltraParadise." + name); |
| 85 | } |
| 86 | |
| 87 | public static Image Image(string name) |
| 88 | { |
| 89 | try |
| 90 | { |
| 91 | Stream s = Open(name); |
| 92 | if (s == null) return null; |
| 93 | using (s) |
| 94 | { |
| 95 | MemoryStream ms = new MemoryStream(); |
| 96 | s.CopyTo(ms); |
| 97 | ms.Position = 0; |
| 98 | return System.Drawing.Image.FromStream(ms); |
| 99 | } |
| 100 | } |
| 101 | catch (Exception) { return null; } |
| 102 | } |
| 103 | |
| 104 | public static byte[] Bytes(string name) |
| 105 | { |
| 106 | Stream s = Open(name); |
| 107 | if (s == null) return null; |
| 108 | using (s) |
| 109 | { |
| 110 | MemoryStream ms = new MemoryStream(); |
| 111 | s.CopyTo(ms); |
| 112 | return ms.ToArray(); |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | internal static class Native |
| 118 | { |
| 119 | [DllImport("user32.dll")] public static extern bool FlashWindow(IntPtr hWnd, bool invert); |
| 120 | [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; } |
| 121 | [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; } |
| 122 | |
| 123 | [DllImport("user32.dll")] public static extern bool SetProcessDPIAware(); |
| 124 | [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); |
| 125 | [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid); |
| 126 | [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr hWnd, out RECT r); |
| 127 | [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr hWnd, ref POINT p); |
| 128 | [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr hWnd); |
| 129 | [DllImport("user32.dll")] public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint mods, uint vk); |
| 130 | [DllImport("user32.dll")] public static extern bool UnregisterHotKey(IntPtr hWnd, int id); |
| 131 | [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, string lParam); |
| 132 | |
| 133 | } |
| 134 | |
| 135 | internal class LinkServer |
| 136 | { |
| 137 | private readonly TcpListener listener; |
| 138 | private readonly string token; |
| 139 | private readonly object gate = new object(); |
| 140 | private TcpClient current; |
| 141 | private StreamWriter writer; |
| 142 | public event Action<string> Line; |
| 143 | public event Action<string> Sent; |
| 144 | public event Action Connected; |
| 145 | public event Action Disconnected; |
| 146 | public int Port { get; private set; } |
| 147 | public bool IsConnected { get { lock (gate) return writer != null; } } |
| 148 | |
| 149 | public LinkServer() |
| 150 | { |
| 151 | byte[] r = new byte[16]; |
| 152 | using (System.Security.Cryptography.RandomNumberGenerator g = System.Security.Cryptography.RandomNumberGenerator.Create()) g.GetBytes(r); |
| 153 | token = BitConverter.ToString(r).Replace("-", "").ToLowerInvariant(); |
| 154 | listener = new TcpListener(IPAddress.Loopback, 0); |
| 155 | listener.Start(); |
| 156 | Port = ((IPEndPoint)listener.LocalEndpoint).Port; |
| 157 | Thread t = new Thread(AcceptLoop); |
| 158 | t.IsBackground = true; |
| 159 | t.Start(); |
| 160 | } |
| 161 | |
| 162 | public const string CodeVersion = "4"; |
| 163 | public volatile string GameCode = ""; |
| 164 | |
| 165 | public static string LinkFolder { get { return Path.Combine(Path.GetTempPath(), "UltraParadise"); } } |
| 166 | |
| 167 | public void WriteLinkFile(int pid) |
| 168 | { |
| 169 | Directory.CreateDirectory(LinkFolder); |
| 170 | File.WriteAllText(Path.Combine(LinkFolder, "link-" + pid + ".txt"), Port + " " + token); |
| 171 | } |
| 172 | |
| 173 | public static void DeleteLinkFile(int pid) |
| 174 | { |
| 175 | try { File.Delete(Path.Combine(LinkFolder, "link-" + pid + ".txt")); } catch (Exception) { } |
| 176 | } |
| 177 | |
| 178 | private void AcceptLoop() |
| 179 | { |
| 180 | while (true) |
| 181 | { |
| 182 | TcpClient c; |
| 183 | try { c = listener.AcceptTcpClient(); } |
| 184 | catch (Exception) { return; } |
| 185 | Thread t = new Thread(delegate () { Serve(c); }); |
| 186 | t.IsBackground = true; |
| 187 | t.Start(); |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | private void Serve(TcpClient c) |
| 192 | { |
| 193 | bool mine = false; |
| 194 | try |
| 195 | { |
| 196 | c.NoDelay = true; |
| 197 | NetworkStream ns = c.GetStream(); |
| 198 | ns.ReadTimeout = 5000; |
| 199 | StreamReader r = new StreamReader(ns, new UTF8Encoding(false)); |
| 200 | StreamWriter w = new StreamWriter(ns, new UTF8Encoding(false)); |
| 201 | w.NewLine = "\n"; |
| 202 | w.AutoFlush = true; |
| 203 | string hello = r.ReadLine(); |
| 204 | if (hello == null) return; |
| 205 | string[] p = hello.Split(' '); |
| 206 | if (p.Length < 2 || p[0] != "HELLO" || p[1] != token) return; |
| 207 | ns.ReadTimeout = Timeout.Infinite; |
| 208 | w.WriteLine("OK"); |
| 209 | GameCode = p.Length >= 3 ? p[2] : ""; |
| 210 | lock (gate) |
| 211 | { |
| 212 | if (current != null) { try { current.Close(); } catch (Exception) { } } |
| 213 | current = c; |
| 214 | writer = w; |
| 215 | mine = true; |
| 216 | } |
| 217 | if (Connected != null) Connected(); |
| 218 | string line; |
| 219 | while ((line = r.ReadLine()) != null) |
| 220 | { |
| 221 | if (line.Length > 2048 && !(line.Length < 12000000 && (line.StartsWith("SFX ", StringComparison.Ordinal) || line.StartsWith("MICON ", StringComparison.Ordinal) || (line.Length < 200000 && (line.StartsWith("MOODLES ", StringComparison.Ordinal) || line.StartsWith("DLOG ", StringComparison.Ordinal) || line.StartsWith("DSNAP ", StringComparison.Ordinal) || line.StartsWith("DSYS ", StringComparison.Ordinal) || line.StartsWith("MODS ", StringComparison.Ordinal) || line.StartsWith("MUSICLIST ", StringComparison.Ordinal)))))) continue; |
| 222 | if (Line != null) Line(line); |
| 223 | } |
| 224 | } |
| 225 | catch (Exception) { } |
| 226 | finally |
| 227 | { |
| 228 | bool dropped = false; |
| 229 | lock (gate) |
| 230 | { |
| 231 | if (mine && current == c) { current = null; writer = null; dropped = true; } |
| 232 | } |
| 233 | try { c.Close(); } catch (Exception) { } |
| 234 | if (dropped && Disconnected != null) Disconnected(); |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | public void Send(string s) |
| 239 | { |
| 240 | lock (gate) |
| 241 | { |
| 242 | if (writer == null) return; |
| 243 | try { writer.WriteLine(s); } |
| 244 | catch (Exception) { try { current.Close(); } catch (Exception) { } return; } |
| 245 | } |
| 246 | Action<string> h = Sent; |
| 247 | if (h != null) { try { h(s); } catch (Exception) { } } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | internal enum Kind { Toggle, Action, Slider, Buttons, Info, Note } |
| 252 | |
| 253 | internal class Btn |
| 254 | { |
| 255 | public string Label, Act, Arg; |
| 256 | public Image Icon; |
| 257 | public Btn(string label, string act, string arg) { Label = label; Act = act; Arg = arg; } |
| 258 | |
| 259 | private static Image nexus, banana, discord; |
| 260 | private static bool loaded; |
| 261 | |
| 262 | public static Btn Logo(Btn b) |
| 263 | { |
| 264 | if (!loaded) { loaded = true; nexus = Res.Image("logo-nexus.png"); banana = Res.Image("logo-gamebanana.png"); discord = Res.Image("logo-discord.png"); } |
| 265 | if (b.Act == "@discord") b.Icon = discord; |
| 266 | else if (b.Arg != null && b.Arg.StartsWith("https://gamebanana.com/", StringComparison.Ordinal)) b.Icon = banana; |
| 267 | else if (b.Arg != null && b.Arg.StartsWith("https://www.nexusmods.com/", StringComparison.Ordinal) && b.Arg.IndexOf("tab=bugs", StringComparison.Ordinal) < 0) b.Icon = nexus; |
| 268 | return b; |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | internal class Option |
| 273 | { |
| 274 | public Kind Kind; |
| 275 | public string Id, Name, Hint; |
| 276 | public Keys Key, DefaultKey; |
| 277 | public bool On; |
| 278 | public float Value, Min, Max, Step, Default; |
| 279 | public string Format = "x{0:0.00}"; |
| 280 | public List<Btn> Buttons; |
| 281 | public Func<Dictionary<string, string>, string> Text; |
| 282 | public Func<Color> Swatch; |
| 283 | public bool Local; |
| 284 | public bool Fav; |
| 285 | public string Origin; |
| 286 | public Func<bool> Show; |
| 287 | public bool Bindable { get { return Kind == Kind.Toggle || Kind == Kind.Action; } } |
| 288 | } |
| 289 | |
| 290 | internal class Section |
| 291 | { |
| 292 | public string Title; |
| 293 | public readonly List<Option> Rows = new List<Option>(); |
| 294 | public Section(string title) { Title = title; } |
| 295 | } |
| 296 | |
| 297 | internal class Tab |
| 298 | { |
| 299 | public string Name, Group; |
| 300 | public char Icon; |
| 301 | public bool Spawner, Health, About, Mods, Report, MyMods, Search, Favs, Music, VtLogo; |
| 302 | public readonly List<Section>[] Cols = { new List<Section>(), new List<Section>(), new List<Section>() }; |
| 303 | public Tab(string name) { Name = name; } |
| 304 | |
| 305 | public IEnumerable<Option> All() |
| 306 | { |
| 307 | foreach (List<Section> c in Cols) |
| 308 | foreach (Section s in c) |
| 309 | foreach (Option o in s.Rows) yield return o; |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | internal static class Catalog |
| 314 | { |
| 315 | private static Section sec; |
| 316 | private static List<Option> all; |
| 317 | |
| 318 | private static Option Add(Option o) { sec.Rows.Add(o); all.Add(o); return o; } |
| 319 | |
| 320 | private static Option T(string id, string name, Keys key, string hint) |
| 321 | { |
| 322 | Option o = new Option(); o.Kind = Kind.Toggle; o.Id = id; o.Name = name; o.Key = key; o.DefaultKey = key; o.Hint = hint; |
| 323 | return Add(o); |
| 324 | } |
| 325 | |
| 326 | private static Option A(string id, string name, Keys key, string hint) |
| 327 | { |
| 328 | Option o = new Option(); o.Kind = Kind.Action; o.Id = id; o.Name = name; o.Key = key; o.DefaultKey = key; o.Hint = hint; |
| 329 | return Add(o); |
| 330 | } |
| 331 | |
| 332 | private static Option S(string id, string name, float min, float max, float step, float def, string fmt) |
| 333 | { |
| 334 | Option o = new Option(); o.Kind = Kind.Slider; o.Id = id; o.Name = name; o.Min = min; o.Max = max; o.Step = step; o.Default = def; o.Value = def; |
| 335 | if (fmt != null) o.Format = fmt; |
| 336 | o.Hint = "Drag to change. Right-click resets it."; |
| 337 | return Add(o); |
| 338 | } |
| 339 | |
| 340 | private static Option B(string name, Func<Dictionary<string, string>, string> text, params Btn[] btns) |
| 341 | { |
| 342 | Option o = new Option(); o.Kind = Kind.Buttons; o.Id = "btn:" + all.Count; o.Name = name; o.Text = text; o.Buttons = new List<Btn>(btns); |
| 343 | return Add(o); |
| 344 | } |
| 345 | |
| 346 | private static Option I(Func<Dictionary<string, string>, string> text) |
| 347 | { |
| 348 | Option o = new Option(); o.Kind = Kind.Info; o.Id = "info:" + all.Count; o.Text = text; |
| 349 | return Add(o); |
| 350 | } |
| 351 | |
| 352 | private static Option N(string text) |
| 353 | { |
| 354 | Option o = new Option(); o.Kind = Kind.Note; o.Id = "note:" + all.Count; o.Name = text; |
| 355 | return Add(o); |
| 356 | } |
| 357 | |
| 358 | private static Option TB(Func<Dictionary<string, string>, string> text, params string[] pairs) |
| 359 | { |
| 360 | List<Btn> l = new List<Btn>(); |
| 361 | for (int i = 0; i + 1 < pairs.Length; i += 2) if (pairs[i] != null) l.Add(new Btn(pairs[i], "@theme", pairs[i + 1])); |
| 362 | Option o = B(null, text, l.ToArray()); |
| 363 | o.Local = true; |
| 364 | return o; |
| 365 | } |
| 366 | |
| 367 | private static Option Slider(string id, string name, float min, float max, float step, float def, string fmt) |
| 368 | { |
| 369 | Option o = S(id, name, min, max, step, def, fmt); |
| 370 | o.Local = true; |
| 371 | o.Hint = "Drag to change. Right-click puts it back."; |
| 372 | return o; |
| 373 | } |
| 374 | |
| 375 | private static string Get(Dictionary<string, string> d, string k, string def) |
| 376 | { |
| 377 | string v; |
| 378 | return d != null && d.TryGetValue(k, out v) ? v : def; |
| 379 | } |
| 380 | |
| 381 | private static Func<Dictionary<string, string>, string> Skill(string label, string key) |
| 382 | { |
| 383 | return delegate (Dictionary<string, string> d) { return label + " " + Get(d, key, "-"); }; |
| 384 | } |
| 385 | |
| 386 | public static List<Tab> Build(out List<Option> options) |
| 387 | { |
| 388 | all = new List<Option>(); |
| 389 | List<Tab> tabs = new List<Tab>(); |
| 390 | Keys C = Keys.Control; |
| 391 | |
| 392 | Tab t = new Tab("Welcome"); tabs.Add(t); |
| 393 | sec = new Section("WELCOME"); t.Cols[0].Add(sec); |
| 394 | N("Thanks for trying " + Program.Name + " v" + Program.Version + "!\n\nIt's a cheat app for Casualties: Unknown. Leave it open next to the game: it attaches by itself once the game has loaded, and you switch cheats on and off with a click or with your own hotkeys.\n\nYou don't need BepInEx. The trainer puts one small loader, UltraPara.dll, in your game folder for you (UltraPara tab), and everything else runs from this window."); |
| 395 | sec = new Section("PEOPLE USING THE TRAINER"); t.Cols[0].Add(sec); |
| 396 | I(delegate (Dictionary<string, string> d) { return Usage.Board; }).Local = true; |
| 397 | N("Counts the people who said yes to being counted (Settings, Count Me as a User), so the real number is higher. Updated every hour."); |
| 398 | sec = new Section("GETTING STARTED"); t.Cols[0].Add(sec); |
| 399 | N("1. Start the game (button below, or open it as usual).\n2. Wait for the dot in the bottom left to turn green.\n3. Pick a tab on the left and click a cheat, or click its key box to give it a hotkey.\n\nHotkeys only work while the game window is in front. Insert shows or hides the in-game overlay."); |
| 400 | Option wb = B(null, null, new Btn("Start Game", "@launch", null), new Btn("Pick Game .exe", "@pickexe", null)); |
| 401 | wb.Local = true; |
| 402 | wb.Hint = "Start Game opens Casualties: Unknown. Pick Game .exe is for copies the trainer can't find by itself."; |
| 403 | sec = new Section("WHAT'S ON THE LEFT"); t.Cols[0].Add(sec); |
| 404 | N("CHEATS: Player, Health, Movement, Items, Combat, World, Traders and Challenges. Health shows your vitals live and suggests the cheat that fixes a problem.\n\nTRAINER: Settings (overlay, tray, updates, install), Appearance (themes, colours, your own background picture, fonts) and Debug (a separate window that shows everything the game is doing, live).\n\nEXTRAS: Install My Mods, Report a Bug and About Me."); |
| 405 | sec = new Section("WHAT IT'S BUILT FROM"); t.Cols[1].Add(sec); |
| 406 | N("The app is written in C# on Microsoft's .NET Framework, with Windows Forms. Most of the window is drawn by hand, so it can follow your theme.\n\nThe cheats run in a small piece of code that UltraPara.dll (written in C) loads into the game when it starts. That part uses HarmonyX, MonoMod and Mono.Cecil (MIT licence) to change the game's code in memory only. The only files added to your game folder are UltraPara.dll and version.dll (plus any mods you install from Install My Mods). Closing the trainer switches every cheat off, and closing the game clears the rest.\n\nThe app and the game talk over a private connection on your own PC.\n\nUpdates come from casualexpie's update server (updates.smellypawz.com, run on Cloudflare). Every download is checked against the fingerprints on the official Nexus page before it's installed.\n\nThe Linux version is built with Avalonia and .NET 8 and uses the same UltraPara.dll, because the game runs through Proton there."); |
| 407 | sec = new Section("SAFE AND PRIVATE"); t.Cols[1].Add(sec); |
| 408 | N("Single player only: if a multiplayer mod is loaded, the cheats stay off.\n\nIt only goes online to Nexus Mods (to check your copy is official, and for About Me), to Thunderstore (for the newest versions of my mods), to the update server, and to the official BepInEx GitHub if you ask it to install BepInEx. It sends nothing about you. If you agree to be counted as a user, it sends a random ID once a day, nothing else.\n\nAntivirus programs sometimes flag trainers, because loading code into a game is what they watch for. Only download it from casualexpie's pages on Nexus Mods or GameBanana."); |
| 409 | sec = new Section("TWO SCREENS? (RECOMMENDED)"); t.Cols[2].Add(sec); |
| 410 | I(delegate (Dictionary<string, string> d) { return Monitors.Advice(); }).Local = true; |
| 411 | N("In my opinion the best setup is two screens: the game on one, and the trainer and the Debug window on the other, so nothing ever covers the game.\n\nIf you have a second screen plugged in, the trainer spots it. The buttons below move the trainer or the Debug window to the screen the game isn't on."); |
| 412 | Option ws = B(null, null, new Btn("Move Trainer", "@trainerother", null), new Btn("Open Debug Window", "@debug", null)); |
| 413 | ws.Local = true; |
| 414 | ws.Hint = "Move Trainer puts this window on your other screen. The Debug window opens on the screen without the game by itself."; |
| 415 | sec = new Section("THE GAME"); t.Cols[2].Add(sec); |
| 416 | N("Casualties: Unknown is made by Orsoniks and Oro Interactive. This trainer isn't made by them or connected to them. If you enjoy the game, support them on Steam and leave a review."); |
| 417 | Option gb2 = B(null, null, new Btn("Steam Page", "@url", "https://store.steampowered.com/app/4576490/")); |
| 418 | gb2.Local = true; |
| 419 | gb2.Hint = "Opens the game's official Steam page."; |
| 420 | sec = new Section("FROM CASUALEXPIE"); t.Cols[2].Add(sec); |
| 421 | N("Made by casualexpie. I also make other mods for the game: see Install My Mods for the ones I recommend, and About Me for all of them.\n\nFound a bug? The Report a Bug tab collects everything I need. Paste it on the Nexus Bugs page."); |
| 422 | Option nb = B(null, null, Btn.Logo(new Btn("Nexus Page", "@url", "https://www.nexusmods.com/scavprototype/mods/1203")), Btn.Logo(new Btn("GameBanana", "@url", "https://gamebanana.com/mods/749667")), new Btn("Report a Bug", "@url", "https://www.nexusmods.com/scavprototype/mods/1203?tab=bugs"), new Btn("Source Code", "@url", "https://opensource.smellypawz.com/cu-trainer/")); |
| 423 | nb.Local = true; |
| 424 | nb.Hint = "Opens my official pages on Nexus Mods and GameBanana, the Nexus Bugs tab, or the trainer's source code."; |
| 425 | sec = new Section("LEGAL"); t.Cols[2].Add(sec); |
| 426 | N("Copyright (c) casualexpie. Open source: the code is public at opensource.smellypawz.com under a source-available license. You can read it and build it yourself, but don't reupload, sell or reuse it."); |
| 427 | |
| 428 | t = new Tab("Search"); tabs.Add(t); |
| 429 | t.Search = true; |
| 430 | t = new Tab("Favorites"); tabs.Add(t); |
| 431 | t.Favs = true; |
| 432 | |
| 433 | t = new Tab("Player"); tabs.Add(t); |
| 434 | sec = new Section("PLAYER"); t.Cols[0].Add(sec); |
| 435 | T("GodMode", "God Mode", Keys.NumPad1, "Can't be hurt or killed. Pauses itself if your character gives up or tries to end it."); |
| 436 | T("NoFallDamage", "No Fall Damage", Keys.None, "Falls and hard landings don't hurt."); |
| 437 | T("InfiniteStamina", "Infinite Stamina", Keys.NumPad2, null); |
| 438 | T("NoHunger", "No Hunger", Keys.NumPad3, null); |
| 439 | T("NoThirst", "No Thirst", Keys.NumPad4, null); |
| 440 | T("NoTiredness", "No Tiredness", Keys.NumPad5, "You can't sleep while this is on."); |
| 441 | sec = new Section("HEALING"); t.Cols[0].Add(sec); |
| 442 | A("heal", "Heal All Wounds", C | Keys.NumPad1, "Heals every wound, fixes bones and blood, and clears hearing loss."); |
| 443 | A("limbs", "Reattach Limbs", Keys.None, "Puts lost limbs back (not prosthetics)."); |
| 444 | sec = new Section("EMERGENCY"); t.Cols[0].Add(sec); |
| 445 | A("em_full", "Full Restore", Keys.None, "One click: heals every wound, reattaches limbs, fills blood, food and water."); |
| 446 | A("em_bleed", "Stop the Bleeding", Keys.None, "Stops all bleeding, inside and out, and tops your blood up to 70%."); |
| 447 | A("em_breathe", "Can't Breathe", Keys.None, "Fills blood oxygen and clears embolisms, collapsed lungs and barotrauma."); |
| 448 | A("em_heart", "Heart Trouble", Keys.None, "Stops fibrillation and shock, steadies heart rate and blood pressure, wakes you up."); |
| 449 | A("em_cure", "Cure Everything", Keys.None, "Clears infection, sickness, radiation sickness, venom and sepsis."); |
| 450 | A("em_body", "Food, Water, Warmth", Keys.None, "Fills hunger and thirst, sets your temperature to 37C and takes the pain away."); |
| 451 | sec = new Section("PROTECTION"); t.Cols[1].Add(sec); |
| 452 | T("NoBleeding", "No Bleeding", Keys.NumPad6, "No bleeding, inside or out."); |
| 453 | T("NoPain", "No Pain", Keys.NumPad7, null); |
| 454 | T("NoInfection", "No Infection", Keys.None, "Wounds never get infected."); |
| 455 | T("NoSickness", "No Sickness", Keys.None, "No sickness, nausea or venom."); |
| 456 | T("NoRadiation", "No Radiation Sickness", Keys.None, null); |
| 457 | T("UnlimitedOxygen", "Unlimited Oxygen", Keys.NumPad8, "Blood oxygen stays full, even underwater."); |
| 458 | T("StableTemperature", "Stable Body Temperature", Keys.None, "Your body stays at 37C."); |
| 459 | T("FasterHealing", "Faster Healing", Keys.None, "Wounds, bones and blood heal faster."); |
| 460 | S("HealingMult", "Healing rate", 1f, 10f, 0.5f, 3f, null); |
| 461 | sec = new Section("MOOD"); t.Cols[2].Add(sec); |
| 462 | I(delegate (Dictionary<string, string> d) { return "Mood " + Get(d, "mood", "-"); }); |
| 463 | T("MoodLock", "Mood Lock", Keys.None, "Keeps your mood where it is when you switch it on."); |
| 464 | B("Change", null, new Btn("Max", "moodmax", null), new Btn("+10", "mood", "10"), new Btn("-10", "mood", "-10"), new Btn("-50", "mood", "-50")).Hint = "Very low mood can lead to self-harm."; |
| 465 | sec = new Section("SKILLS"); t.Cols[2].Add(sec); |
| 466 | T("MoreXp", "Increased XP Gain", Keys.None, "Skills level up faster."); |
| 467 | S("XpMult", "XP rate", 1f, 10f, 0.5f, 3f, null); |
| 468 | B(null, Skill("Strength", "str"), new Btn("-1", "skill", "0 -1"), new Btn("+1", "skill", "0 1"), new Btn("+5", "skill", "0 5")); |
| 469 | B(null, Skill("Resilience", "res"), new Btn("-1", "skill", "1 -1"), new Btn("+1", "skill", "1 1"), new Btn("+5", "skill", "1 5")); |
| 470 | B(null, Skill("Intelligence", "int"), new Btn("-1", "skill", "2 -1"), new Btn("+1", "skill", "2 1"), new Btn("+5", "skill", "2 5")); |
| 471 | |
| 472 | t = new Tab("Health"); tabs.Add(t); |
| 473 | t.Health = true; |
| 474 | |
| 475 | t = new Tab("Movement"); tabs.Add(t); |
| 476 | sec = new Section("MOVEMENT"); t.Cols[0].Add(sec); |
| 477 | T("FasterMovement", "Faster Movement", Keys.None, "You walk and run faster."); |
| 478 | S("MoveSpeedMult", "Speed", 1f, 4f, 0.1f, 1.6f, null); |
| 479 | T("FasterClimbing", "Faster Climbing", Keys.None, "Ropes and ladders."); |
| 480 | S("ClimbSpeedMult", "Climb speed", 1f, 5f, 0.25f, 2f, null); |
| 481 | T("HigherJumps", "Higher Jumps", Keys.None, null); |
| 482 | S("JumpMult", "Jump power", 1f, 3f, 0.1f, 1.5f, null); |
| 483 | T("UnlimitedJumps", "Unlimited Jumps", Keys.None, "Jump again in mid-air as often as you like."); |
| 484 | T("UnlimitedWallJumps", "Unlimited Wall Jumps", Keys.None, "Wall jump off the same wall over and over."); |
| 485 | sec = new Section("BODY"); t.Cols[1].Add(sec); |
| 486 | T("LowGravity", "Low Gravity", Keys.None, "You fall slower and float further."); |
| 487 | S("GravityScale", "Gravity", 0.05f, 1f, 0.05f, 0.4f, null); |
| 488 | T("UnlimitedCarry", "No Over-Encumbrance", Keys.None, "Carrying too much never slows you, tires you or slows your attacks."); |
| 489 | sec = new Section("FLYING"); t.Cols[1].Add(sec); |
| 490 | T("FlyMode", "Fly Mode", Keys.None, "Movement keys to fly, Space to go up, Shift for speed. You still bump into walls."); |
| 491 | S("FlySpeed", "Fly speed", 5f, 40f, 1f, 18f, "{0:0}"); |
| 492 | T("Noclip", "Noclip", Keys.NumPad0, "Fly through walls with your movement keys. Shift for speed."); |
| 493 | sec = new Section("TELEPORT"); t.Cols[2].Add(sec); |
| 494 | T("ClickTeleport", "Middle-Click Teleport", Keys.None, "Click the middle mouse button in game to teleport to the cursor."); |
| 495 | A("exit", "Teleport to Layer Exit", C | Keys.NumPad3, "Takes you to the bottom of the layer, where the next one starts."); |
| 496 | |
| 497 | t = new Tab("Items"); tabs.Add(t); |
| 498 | t.Spawner = true; |
| 499 | sec = new Section("CRAFTING"); t.Cols[0].Add(sec); |
| 500 | T("FreeCrafting", "Free Crafting", Keys.None, "Craft any recipe you can see without ingredients."); |
| 501 | T("NoCraftFail", "No Crafting Failures", Keys.None, "Crafting never fails, even above your Intelligence."); |
| 502 | T("AllRecipes", "Show All Recipes", Keys.None, "Every recipe shows, whatever your Intelligence."); |
| 503 | sec = new Section("INVENTORY"); t.Cols[0].Add(sec); |
| 504 | T("NoDegradation", "No Item Degradation", Keys.None, "Tools, weapons, armor, containers and batteries never wear out."); |
| 505 | T("UnlimitedLiquids", "Unlimited Liquids", Keys.None, "Liquids in containers never run out."); |
| 506 | T("UnlimitedBattery", "Unlimited Battery", Keys.None, "Batteries never drain."); |
| 507 | T("MasterLockpick", "Master Lockpicker", Keys.None, "Every lock opens the moment you turn it, with a lockpicking kit or bare claws. No hurt claws, no worn-out kit."); |
| 508 | sec = new Section("LOADOUT"); t.Cols[0].Add(sec); |
| 509 | A("starterkit", "Starter Kit", Keys.None, "The game's own kit of tools, medicine and supplies."); |
| 510 | A("randomloadout", "Random Loadout", Keys.None, "Gives you 6 random items."); |
| 511 | |
| 512 | t = new Tab("Combat"); tabs.Add(t); |
| 513 | sec = new Section("WEAPONS"); t.Cols[0].Add(sec); |
| 514 | T("UnlimitedAmmo", "Unlimited Ammo", Keys.NumPad9, "Load the gun once (magazine in, or a shell in the shotgun) and it keeps refilling."); |
| 515 | T("NoGunJams", "No Gun Jams", Keys.None, null); |
| 516 | T("NoRecoil", "No Recoil", Keys.None, "Guns don't kick you back or spread."); |
| 517 | T("MoreDamage", "Increased Damage", Keys.None, "Your melee and gun hits do more damage."); |
| 518 | S("DamageMult", "Damage", 1f, 10f, 0.5f, 2f, null); |
| 519 | T("FasterAttacks", "Faster Attacks", Keys.None, "Shorter wait between melee swings."); |
| 520 | S("AttackSpeedMult", "Swing speed", 1f, 5f, 0.25f, 2.5f, null); |
| 521 | T("OneHitKills", "One-Hit Kills", Keys.None, "Your melee hits and gunshots kill enemies in one hit."); |
| 522 | T("InstantMine", "Instant Mine", Keys.None, "Your melee hits break any breakable block in one hit."); |
| 523 | sec = new Section("ENEMIES"); t.Cols[1].Add(sec); |
| 524 | T("FreezeEnemies", "Freeze Enemies", Keys.None, "Enemies can't move or attack."); |
| 525 | T("Invisibility", "Invisibility", Keys.None, "Enemies and turrets can't attack you."); |
| 526 | T("DisableTraps", "Disable Traps", Keys.None, "Mines, bear traps, spike stabbers, fans, sound cannons and turrets do nothing."); |
| 527 | A("killall", "Kill All Enemies", C | Keys.NumPad2, null); |
| 528 | A("spiders", "Spider Ambush", Keys.None, "Drops cave ticks around you. Good luck."); |
| 529 | |
| 530 | t = new Tab("World"); tabs.Add(t); |
| 531 | sec = new Section("LAYER"); t.Cols[0].Add(sec); |
| 532 | T("PauseRadiation", "Pause Radiation Line", Keys.None, "The layer timer and the radiation line stop."); |
| 533 | T("LongerEscape", "Longer Escape Timer", Keys.None, "The end lab countdown is 2 minutes instead of 1."); |
| 534 | T("MoreLoot", "Increased Loot", Keys.None, "New layers have more loot. Starts on the next layer."); |
| 535 | S("LootMult", "Loot", 1f, 5f, 0.25f, 2f, null); |
| 536 | A("back", "Previous Layer", C | Keys.NumPad4, null); |
| 537 | A("skip", "Skip Layer", C | Keys.NumPad5, null); |
| 538 | sec = new Section("EVENTS"); t.Cols[1].Add(sec); |
| 539 | T("NoEarthquakes", "No Earthquakes", Keys.None, null); |
| 540 | A("quake", "Start Earthquake", Keys.None, null); |
| 541 | A("downpour", "Fungal Downpour", Keys.None, "Fungal rain for 60 seconds."); |
| 542 | sec = new Section("UNLOCKS"); t.Cols[1].Add(sec); |
| 543 | A("unlock", "Unlock All Characters", Keys.None, "Permanent: marks every character as beaten so the next one unlocks."); |
| 544 | sec = new Section("VIEW"); t.Cols[2].Add(sec); |
| 545 | T("FullBright", "Full Bright", Keys.Decimal, "Lights up everything."); |
| 546 | T("FreeCamera", "Free Camera", Keys.None, "Arrow keys move the camera on its own, Shift for speed."); |
| 547 | S("CameraZoom", "Camera zoom", 0.5f, 3f, 0.05f, 1f, null).Hint = "Above 1 shows more of the cave. Right-click resets it."; |
| 548 | S("GameSpeed", "Game speed", 0.25f, 3f, 0.05f, 1f, null); |
| 549 | A("speedcycle", "Cycle Game Speed", C | Keys.NumPad6, "Cycles 1x, 1.5x, 2x and 0.5x.").Local = true; |
| 550 | |
| 551 | t = new Tab("Traders"); tabs.Add(t); |
| 552 | sec = new Section("TRADERS"); t.Cols[0].Add(sec); |
| 553 | T("MaxTraderRep", "Max Reputation", Keys.None, "Nearby survivors always have max reputation and are never hostile."); |
| 554 | T("FreeShopping", "Free Shopping", Keys.None, "Everything survivors sell costs 0."); |
| 555 | T("InfiniteCredit", "Infinite Credit", Keys.None, "Keeps the nearest survivor's trade credit at 9999."); |
| 556 | sec = new Section("NEAREST SURVIVOR"); t.Cols[1].Add(sec); |
| 557 | I(delegate (Dictionary<string, string> d) |
| 558 | { |
| 559 | string n = Get(d, "trader", null); |
| 560 | if (n == null) return "No survivor within 20 m"; |
| 561 | return n + " " + Get(d, "tdist", "?") + " m away, rep " + Get(d, "rep", "?") + (Get(d, "hostile", null) != null ? ", hostile" : ""); |
| 562 | }); |
| 563 | I(delegate (Dictionary<string, string> d) { return Get(d, "trader", null) == null ? "" : "Trade credit " + Get(d, "credit", "0"); }); |
| 564 | B("Credit", null, new Btn("+10", "credit", "10"), new Btn("+50", "credit", "50"), new Btn("+100", "credit", "100"), new Btn("+1000", "credit", "1000")); |
| 565 | B("", null, new Btn("-10", "credit", "-10"), new Btn("Set 0", "credit", "zero"), new Btn("Restock", "restock", null)); |
| 566 | sec = new Section("HOW TRADING WORKS"); t.Cols[2].Add(sec); |
| 567 | N("The game has no money. Each survivor keeps a trade credit for what you've given them. Add credit here, then spend it in their trade menu.\n\nCredit belongs to each survivor, so stand near the one you want to trade with."); |
| 568 | |
| 569 | t = new Tab("Challenges"); tabs.Add(t); |
| 570 | sec = new Section("CHALLENGES"); t.Cols[0].Add(sec); |
| 571 | T("FragileBody", "Fragile Body", Keys.None, "You take double damage."); |
| 572 | T("FastMetabolism", "Faster Hunger and Thirst", Keys.None, "Hunger, thirst and tiredness drain twice as fast."); |
| 573 | T("HopelessStart", "Hopeless Start", Keys.None, "New runs start with no supplies at all. Starts with your next new run."); |
| 574 | T("BrittleGear", "Brittle Gear", Keys.None, "Items decay three times faster."); |
| 575 | T("StrongerEnemies", "Stronger Enemies", Keys.None, "Enemies take half damage and creatures hit harder."); |
| 576 | sec = new Section(" "); t.Cols[1].Add(sec); |
| 577 | T("FastRadiation", "Fast Radiation Line", Keys.None, "The layer timer and the radiation line go twice as fast."); |
| 578 | T("UnchippedChallenge", "Unchipped Mode", Keys.None, "No health readouts and limited vision."); |
| 579 | T("ColdCaves", "Cold Caves", Keys.None, "The caves are 15C colder."); |
| 580 | T("MoreTraps", "More Traps", Keys.None, "Twice as many traps, from the next layer."); |
| 581 | T("LootScarcity", "Loot Scarcity", Keys.None, "Much less loot, from the next layer."); |
| 582 | sec = new Section("ABOUT CHALLENGES"); t.Cols[2].Add(sec); |
| 583 | N("Make the game harder. They stack with the game's own run settings, and you can mix them with cheats however you like."); |
| 584 | |
| 585 | t = new Tab("Settings"); tabs.Add(t); |
| 586 | sec = new Section("TRAINER"); t.Cols[0].Add(sec); |
| 587 | T("overlay", "In-Game Overlay", Keys.Insert, "Shows your keys and what's on in the corner of the game.").Local = true; |
| 588 | T("autoattach", "Attach Automatically", Keys.None, "Attach as soon as the game has loaded.").Local = true; |
| 589 | T("bark", "Bark When a Cheat Turns On", Keys.None, "The trainer barks when you switch a cheat on, with your runner's own bark (Dune's sound for Dune). It picks the sounds up from your game the first time it attaches.").Local = true; |
| 590 | B(null, null, new Btn("Test Bark", "@barktest", null)).Local = true; |
| 591 | T("trayhide", "Minimize to Tray", Keys.None, "Minimizing hides the window. The trainer stays in the system tray (bottom right): hover for its status, right-click for options, double-click to open.").Local = true; |
| 592 | T("remember", "Remember My Cheats", Keys.None, "The cheats you had on (and game speed and zoom) switch back on the next time you open the trainer.").Local = true; |
| 593 | A("alloff", "Switch Everything Off", Keys.None, null).Local = true; |
| 594 | A("resetkeys", "Reset All Keys", Keys.None, "Puts every key back to its default.").Local = true; |
| 595 | sec = new Section("GAME"); t.Cols[0].Add(sec); |
| 596 | I(delegate (Dictionary<string, string> d) { return Installer.GameLabel(); }).Local = true; |
| 597 | Option gb = B(null, null, new Btn("Start Game", "@launch", null), new Btn("Pick Game .exe", "@pickexe", null), new Btn("Find Again", "@findgame", null)); |
| 598 | gb.Local = true; |
| 599 | gb.Hint = "Start Game opens Casualties: Unknown (through Steam if that's where it's from). If the trainer can't find your game, use Pick Game .exe."; |
| 600 | T("launchwith", "Start Game With Trainer", Keys.None, "Opens the game when you open the trainer, if it isn't running yet.").Local = true; |
| 601 | T("closewithgame", "Close With the Game", Keys.None, "Closes the trainer when you quit the game, if it was attached to it.").Local = true; |
| 602 | sec = new Section("HOW TO USE"); t.Cols[1].Add(sec); |
| 603 | N("Click a cheat to switch it on or off. To pick a new key, click its key box and press the key. Esc cancels, Delete clears it.\n\nSliders: drag them, or right click to reset.\n\nKeys only work while the game window is in front. Closing the trainer switches every cheat off in the game. Remember My Cheats (on unless you switch it off) turns them back on when you open the trainer again. Close With the Game closes the trainer when you quit the game."); |
| 604 | sec = new Section("UPDATES"); t.Cols[1].Add(sec); |
| 605 | I(delegate (Dictionary<string, string> d) { return Updater.Status; }).Local = true; |
| 606 | Option ub = B(null, null, new Btn("Check Now", "@updcheck", null), new Btn("Update Now", "@updnow", null)); |
| 607 | ub.Local = true; |
| 608 | ub.Hint = "Updates download from casualexpie's update server and are checked against the fingerprints on the official Nexus page before they're installed."; |
| 609 | T("autoupdate", "Check for Updates", Keys.None, "Looks for a new version each time you open the trainer.").Local = true; |
| 610 | T("silentupdate", "Update Without Asking", Keys.None, "Installs new versions by itself when the game isn't running. Otherwise it asks first.").Local = true; |
| 611 | sec = new Section("USER COUNT"); t.Cols[1].Add(sec); |
| 612 | I(delegate (Dictionary<string, string> d) { return Usage.Status; }).Local = true; |
| 613 | T("usagecount", "Count Me as a User", Keys.None, "Once a day the trainer tells casualexpie's update server it's being used, so casualexpie knows how many people use it. It sends a random ID made on this PC, the trainer version and that you're on Windows. No name, no account, nothing about your PC or game, and the server doesn't keep your IP address. Turn it off to stop, and the server deletes what this PC sent.").Local = true; |
| 614 | sec = new Section("ABOUT"); t.Cols[2].Add(sec); |
| 615 | N(Program.Name + " v" + Program.Version + "\nCopyright (c) casualexpie.\n\nOpen source: read the code at opensource.smellypawz.com. It's source-available, so you can build it yourself, but don't reupload, sell or reuse it.\n\nSingle player only. Cheats stay off while a multiplayer mod is loaded.\n\nUses HarmonyX, MonoMod and Mono.Cecil (MIT licence)."); |
| 616 | sec = new Section("THIS PC"); t.Cols[2].Add(sec); |
| 617 | I(delegate (Dictionary<string, string> d) { return Setup.Status(); }).Local = true; |
| 618 | Option ib = B(null, null, new Btn("Install", "@install", null), new Btn("Uninstall", "@uninstall", null)); |
| 619 | ib.Local = true; |
| 620 | ib.Hint = "Install puts the trainer in your user folder with Start Menu and desktop shortcuts, and lists it in Windows' Installed apps."; |
| 621 | |
| 622 | t = new Tab("Appearance"); tabs.Add(t); |
| 623 | sec = new Section("THEME"); t.Cols[0].Add(sec); |
| 624 | I(delegate (Dictionary<string, string> d) { return "Theme: " + Theme.PresetName; }).Local = true; |
| 625 | TB(null, "Dark", "preset:dark", "Light", "preset:light", "Midnight", "preset:midnight").Hint = "Picks a ready-made theme. Your colour changes are cleared, your picture and font stay."; |
| 626 | TB(null, "High Contrast", "preset:contrast", "Paradise", "preset:paradise", "Follow Windows", "preset:system").Hint = "Follow Windows uses Light or Dark to match your Windows setting."; |
| 627 | sec = new Section("COLOURS"); t.Cols[0].Add(sec); |
| 628 | for (int i = 0; i < Theme.ColorKeys.Length; i++) |
| 629 | { |
| 630 | string key = Theme.ColorKeys[i], label = Theme.ColorNames[i]; |
| 631 | Option co = TB(null, "Pick", "pick:" + key, "Reset", "reset:" + key); |
| 632 | co.Text = delegate (Dictionary<string, string> d) { return label + " " + Theme.Hex(Theme.ColorOf(key)).ToUpperInvariant(); }; |
| 633 | co.Swatch = delegate { return Theme.ColorOf(key); }; |
| 634 | co.Hint = "Pick opens a colour picker. Reset puts back the theme's own colour."; |
| 635 | } |
| 636 | sec = new Section("BACKGROUND PICTURE"); t.Cols[1].Add(sec); |
| 637 | TB(delegate (Dictionary<string, string> d) { string p; return Theme.Values.TryGetValue("image", out p) && p.Trim().Length > 0 ? (Theme.BgImage != null ? Path.GetFileName(p) : "Missing: " + Path.GetFileName(p)) : "No picture"; }, "Choose...", "img:choose", "Remove", "img:none").Hint = "Shows a picture of your own behind the trainer (PNG, JPG, GIF or BMP)."; |
| 638 | Slider("theme.bgop", "Visibility", 0, 100, 5, 30, "{0:0}%"); |
| 639 | TB(delegate (Dictionary<string, string> d) { return "Fit"; }, "Cover", "fit:cover", "Fit", "fit:fit", "Stretch", "fit:stretch").Hint = "Cover fills the window, Fit shows the whole picture, Stretch squashes it to the window."; |
| 640 | TB(null, "Center", "fit:center", "Tile", "fit:tile").Hint = "Center shows it at its real size. Tile repeats it."; |
| 641 | TB(delegate (Dictionary<string, string> d) { return "Header art"; }, "Show", "banner:art", "Hide", "banner:plain").Hint = "The artwork at the top of the window."; |
| 642 | sec = new Section("TEXT AND SIZE"); t.Cols[1].Add(sec); |
| 643 | TB(delegate (Dictionary<string, string> d) { return Theme.FontName ?? "Default font"; }, "Choose...", "font:choose", "Default", "font:none").Hint = "Fonts and size change after a restart."; |
| 644 | Slider("theme.scale", "Size", 80, 160, 5, 100, "{0:0}%"); |
| 645 | TB(delegate (Dictionary<string, string> d) { return "Font and size need a restart"; }, "Restart Now", "restart", null, null).Hint = "Closes the trainer and opens it again straight away. Remember My Cheats switches your cheats back on."; |
| 646 | sec = new Section("IN-GAME OVERLAY"); t.Cols[2].Add(sec); |
| 647 | Slider("theme.ovop", "Visibility", 30, 100, 1, 93, "{0:0}%"); |
| 648 | Slider("theme.ovsize", "Size", 60, 160, 5, 100, "{0:0}%"); |
| 649 | TB(delegate (Dictionary<string, string> d) { return "Corner"; }, "Top Left", "corner:top-left", "Top Right", "corner:top-right").Hint = "Where the overlay sits in the game window."; |
| 650 | TB(null, "Bottom Left", "corner:bottom-left", "Bottom Right", "corner:bottom-right").Hint = "Where the overlay sits in the game window."; |
| 651 | sec = new Section("THEME FILE"); t.Cols[2].Add(sec); |
| 652 | N("Everything here is saved in theme.ini. Open it in Notepad to change anything by hand (it explains every setting), then click Reload. Export makes a copy to share, Import loads one. The same file works in the Linux and Mac trainers."); |
| 653 | TB(null, "Open File", "file:open", "Reload", "file:reload").Hint = "Opens theme.ini, or reloads it after you've changed it."; |
| 654 | TB(null, "Import...", "file:import", "Export...", "file:export").Hint = "Share your theme with friends, or use one they made."; |
| 655 | TB(null, "Reset Everything", "reset", null, null).Hint = "Back to the standard dark theme, with no picture or custom font."; |
| 656 | |
| 657 | t = new Tab("Debug"); tabs.Add(t); |
| 658 | sec = new Section("DEBUG WINDOW"); t.Cols[0].Add(sec); |
| 659 | N("A separate window that shows everything, live: the game's own log (with errors and warnings), what happens to your character, what the cheats block, and a status panel with FPS, the world, every enemy type, your vitals and every limb.\n\nIt's the same kind of debug window as in my CU Cheats mod, but outside the game, so it never gets in your way."); |
| 660 | Option db = B(null, null, new Btn("Open Debug Window", "@debug", null), new Btn("Other Screen", "@debugother", null)); |
| 661 | db.Local = true; |
| 662 | db.Hint = "Open shows the Debug window. Other Screen moves it to the screen the game isn't on."; |
| 663 | A("debugwin", "Show or Hide Debug Window", Keys.F9, "Works while the game is in front, like your cheat keys.").Local = true; |
| 664 | T("debugwithgame", "Open It With the Game", Keys.None, "Opens the Debug window by itself every time the trainer attaches to the game.").Local = true; |
| 665 | sec = new Section("SAVE CHECK"); t.Cols[0].Add(sec); |
| 666 | I(delegate (Dictionary<string, string> d) { return SaveCheck.Line(d); }); |
| 667 | I(delegate (Dictionary<string, string> d) { return SaveCheck.Ach(d); }); |
| 668 | N("Reads the game's own save file (save.sv) to see if the game marked it as cheated. TRUE means the game would turn achievements off when it loads this save. The game deletes the file when it loads a save and writes it again when it saves, so \"no save file\" during a run is normal."); |
| 669 | sec = new Section("HOW TO USE IT"); t.Cols[1].Add(sec); |
| 670 | N("Left: LIVE STATUS, updated every second.\nRight: LIVE FEED, every line the game and the trainer log.\n\nTick the boxes to show or hide kinds of lines, or type in Find to search. Pause (F5) freezes the feed so you can read it; nothing is lost. Select lines and press Ctrl+C to copy them, or Copy for the status and the last 500 lines.\n\nEverything is also saved to debug.log (Log Folder button) while the window is open, so you can attach it to a bug report.\n\nIt only collects data while the window is open, so it costs nothing when it's closed."); |
| 671 | sec = new Section("SCREENS"); t.Cols[2].Add(sec); |
| 672 | I(delegate (Dictionary<string, string> d) { return Monitors.Advice(); }).Local = true; |
| 673 | N("Recommended (in my opinion): a dual monitor setup. Put the game on one screen and the trainer and Debug window on the other one, the screen that isn't showing the game.\n\nWhen the trainer finds more than one screen, the Debug window opens on the one without the game, and Other Screen buttons appear.\n\nOne screen only? Play the game in windowed mode and use Pin on Top in the Debug window."); |
| 674 | Option sb2 = B(null, null, new Btn("Move Trainer", "@trainerother", null), new Btn("Move Debug", "@debugother", null)); |
| 675 | sb2.Local = true; |
| 676 | sb2.Hint = "Moves the window to your other screen (the one the game isn't on)."; |
| 677 | |
| 678 | t = new Tab("UltraPara"); tabs.Add(t); |
| 679 | sec = new Section("ULTRAPARA.DLL"); t.Cols[0].Add(sec); |
| 680 | I(delegate (Dictionary<string, string> d) { return UltraPara.Status; }).Local = true; |
| 681 | Option upb = B(null, null, new Btn("Install / Update", "@upinstall", null), new Btn("Remove", "@upremove", null)); |
| 682 | upb.Local = true; |
| 683 | upb.Hint = "Install / Update downloads UltraPara.dll from the update server and checks it before it goes in your game folder. Close the game first."; |
| 684 | Option ub2 = B(null, null, new Btn("Game Folder", "@upfolder", null), new Btn("Loader Log", "@uplog", null)); |
| 685 | ub2.Local = true; |
| 686 | ub2.Hint = "Game Folder opens the folder UltraPara.dll lives in. Loader Log shows what UltraPara.dll did the last time the game started."; |
| 687 | sec = new Section("WHAT IT IS"); t.Cols[1].Add(sec); |
| 688 | N("The trainer needs UltraPara.dll in your game folder. It's what loads the cheats into the game. Without it, the trainer can't attach.\n\nIt's two small files next to CasualtiesUnknown.exe: version.dll, which the game opens by itself when it starts, and UltraPara.dll, which carries the cheat code.\n\nIt doesn't need BepInEx. My other mods still do, and both work together.\n\nThe trainer gets it from casualexpie's update server and checks it against the fingerprint built into this trainer before installing it. It also updates it by itself when the game is closed."); |
| 689 | sec = new Section("IF IT DOESN'T LOAD"); t.Cols[1].Add(sec); |
| 690 | N("Restart the game after installing it: it only loads when the game starts.\n\nIf you already have a version.dll from another program (like ReShade), the two can't share the name. Move the other one out first.\n\nAntivirus programs can flag it, because loading code into a game is what they look for. Only get it through this trainer."); |
| 691 | sec = new Section("LINKS"); t.Cols[2].Add(sec); |
| 692 | N("The official pages for this trainer."); |
| 693 | Option lk = B(null, null, Btn.Logo(new Btn("Nexus Mods", "@url", "https://www.nexusmods.com/scavprototype/mods/1203")), Btn.Logo(new Btn("GameBanana", "@url", "https://gamebanana.com/mods/749667")), Btn.Logo(new Btn("Discord", "@discord", null))); |
| 694 | lk.Local = true; |
| 695 | lk.Hint = "Opens the page in your browser. Discord is coming later. Not affiliated with Nexus Mods, GameBanana or Discord. Logos belong to their owners."; |
| 696 | |
| 697 | t = new Tab("VirusTotal"); tabs.Add(t); |
| 698 | t.VtLogo = true; |
| 699 | sec = new Section("THIS COPY"); t.Cols[0].Add(sec); |
| 700 | I(delegate (Dictionary<string, string> d) { return VirusTotal.Status; }).Local = true; |
| 701 | I(delegate (Dictionary<string, string> d) { return VirusTotal.Self != null ? VirusTotal.Self.Detail : "Engine breakdown: not checked yet."; }).Local = true; |
| 702 | I(delegate (Dictionary<string, string> d) { string s; try { s = VirusTotal.SelfSha; } catch (Exception) { s = "unknown"; } return "Fingerprint (SHA-256): " + s; }).Local = true; |
| 703 | Option vb = B(null, null, new Btn("Open Report", "@vtopen", null), new Btn("Check Again", "@vtcheck", null), new Btn("Copy Fingerprint", "@vtcopy", null)); |
| 704 | vb.Local = true; |
| 705 | vb.Hint = "Open Report shows the full VirusTotal page for this exact file: every engine and what it said. Check Again asks for the newest result. Copy Fingerprint copies this file's SHA-256, so you can compare it with the one on the Nexus page."; |
| 706 | sec = new Section("NEWEST VERSION"); t.Cols[0].Add(sec); |
| 707 | I(delegate (Dictionary<string, string> d) { return Updater.Ready != null ? "v" + Updater.Ready.Version + " is out. " + Updater.Ready.VtLine : "You have the newest version, so the result above is the newest one."; }).Local = true; |
| 708 | N("When an update comes out, its result shows here and in the update prompt before you install it. Update Without Asking only installs updates VirusTotal says are clean; anything flagged always asks you first."); |
| 709 | sec = new Section("WHAT IT IS"); t.Cols[1].Add(sec); |
| 710 | N("VirusTotal checks a file with about 70 antivirus engines at once (Microsoft Defender, Kaspersky, BitDefender, ESET and many more) and shows what each of them thinks.\n\nEvery official version of this trainer is sent to VirusTotal by casualexpie's update server as soon as it's released, and scanned again every few days, because antivirus engines keep learning.\n\nThe check here is for the exact file you're running. If your copy was changed in any way, its fingerprint won't match an official release and it won't have a result."); |
| 711 | sec = new Section("WHAT THE NUMBERS MEAN"); t.Cols[1].Add(sec); |
| 712 | N("0 flagged: no engine found anything.\n\n1 to 3 flagged: normal for a trainer. Open the report: it's almost always names like HackTool, RiskWare or GameHack, which mean \"this program changes a game\". That's what a trainer does.\n\nMany engines, or names like Trojan or Stealer: don't trust that copy. Delete it and get the trainer from the official Nexus page."); |
| 713 | sec = new Section("WHY TRAINERS GET FLAGGED"); t.Cols[2].Add(sec); |
| 714 | N("To give you cheats, a trainer loads code into a running game and changes its memory. Some malware does that too, so a few engines flag any program that does it, without checking what the code actually does.\n\nThis trainer only ever touches Casualties: Unknown, sends nothing about you, and checks every update against the official fingerprints on Nexus before installing it.\n\nNot affiliated with VirusTotal. VirusTotal and its logo belong to their owners."); |
| 715 | sec = new Section("ON NEXUS"); t.Cols[2].Add(sec); |
| 716 | N("The official fingerprints for every version are on the Nexus page, under \"Official SHA-256 fingerprints\". They should match the fingerprint on the left."); |
| 717 | Option vn = B(null, null, Btn.Logo(new Btn("Nexus Mods", "@url", "https://www.nexusmods.com/scavprototype/mods/1203"))); |
| 718 | vn.Local = true; |
| 719 | vn.Hint = "Opens the trainer's official Nexus page in your browser."; |
| 720 | |
| 721 | t = new Tab("My Mods"); tabs.Add(t); |
| 722 | t.MyMods = true; |
| 723 | |
| 724 | t = new Tab("Music"); tabs.Add(t); |
| 725 | t.Music = true; |
| 726 | |
| 727 | tabs.Insert(tabs.FindIndex(delegate (Tab q) { return q.Name == "Settings"; }), new Tab("Run Stats")); |
| 728 | tabs.Insert(tabs.FindIndex(delegate (Tab q) { return q.Name == "Run Stats"; }), new Tab("Watchlist")); |
| 729 | tabs.Insert(tabs.FindIndex(delegate (Tab q) { return q.Name == "Watchlist"; }), new Tab("Tools")); |
| 730 | tabs.Insert(tabs.FindIndex(delegate (Tab q) { return q.Name == "Tools"; }), new Tab("Profiles")); |
| 731 | |
| 732 | t = new Tab("Install My Mods"); tabs.Add(t); |
| 733 | t.Mods = true; |
| 734 | |
| 735 | t = new Tab("Report a Bug"); tabs.Add(t); |
| 736 | t.Report = true; |
| 737 | |
| 738 | t = new Tab("About Me"); tabs.Add(t); |
| 739 | t.About = true; |
| 740 | |
| 741 | string[] names = { "Welcome", "Search", "Favorites", "Player", "Health", "Movement", "Items", "Combat", "World", "Traders", "Challenges", "Settings", "Appearance", "Debug", "UltraPara", "My Mods", "Music", "Install My Mods", "Report a Bug", "About Me", "Profiles", "Tools", "Watchlist", "Run Stats" }; |
| 742 | char[] icons = { (char)0xE80F, (char)0xE721, (char)0xE734, (char)0xE77B, (char)0xE95E, (char)0xE805, (char)0xE7B8, (char)0xE945, (char)0xE774, (char)0xE719, (char)0xE7C1, (char)0xE713, (char)0xE790, (char)0xE9D9, (char)0xE943, (char)0xE8F1, (char)0xE8D6, (char)0xE896, (char)0xEBE8, (char)0xE946, (char)0xE716, (char)0xE90F, (char)0xE7B3, (char)0xE9D2 }; |
| 743 | foreach (Tab x in tabs) |
| 744 | { |
| 745 | int k = Array.IndexOf(names, x.Name); |
| 746 | if (k >= 0) x.Icon = icons[k]; |
| 747 | x.Group = k == 0 ? "START" : k >= 1 && k < 11 ? "CHEATS" : k >= 20 ? "TOOLS" : k >= 11 && k < 15 ? "TRAINER" : "EXTRAS"; |
| 748 | if (x.VtLogo) x.Group = "TRAINER"; |
| 749 | } |
| 750 | foreach (Tab x in tabs) foreach (Option o in x.All()) if (o.Origin == null) o.Origin = x.Name; |
| 751 | options = all; |
| 752 | return tabs; |
| 753 | } |
| 754 | } |
| 755 | |
| 756 | internal static class Settings |
| 757 | { |
| 758 | private static string File { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"), "settings.ini"); } } |
| 759 | |
| 760 | public static Dictionary<string, string> Load() |
| 761 | { |
| 762 | Dictionary<string, string> d = new Dictionary<string, string>(); |
| 763 | try |
| 764 | { |
| 765 | if (!System.IO.File.Exists(File)) return d; |
| 766 | foreach (string line in System.IO.File.ReadAllLines(File)) |
| 767 | { |
| 768 | int eq = line.IndexOf('='); |
| 769 | if (eq > 0) d[line.Substring(0, eq).Trim()] = line.Substring(eq + 1).Trim(); |
| 770 | } |
| 771 | } |
| 772 | catch (Exception) { } |
| 773 | return d; |
| 774 | } |
| 775 | |
| 776 | public static void Save(Dictionary<string, string> d) |
| 777 | { |
| 778 | try |
| 779 | { |
| 780 | Directory.CreateDirectory(Path.GetDirectoryName(File)); |
| 781 | List<string> lines = new List<string>(); |
| 782 | foreach (KeyValuePair<string, string> kv in d) lines.Add(kv.Key + "=" + kv.Value); |
| 783 | lines.Sort(StringComparer.Ordinal); |
| 784 | System.IO.File.WriteAllLines(File, lines.ToArray()); |
| 785 | } |
| 786 | catch (Exception) { } |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | internal static class KeyText |
| 791 | { |
| 792 | public static string Of(Keys k) |
| 793 | { |
| 794 | if (k == Keys.None) return "-"; |
| 795 | StringBuilder sb = new StringBuilder(); |
| 796 | if ((k & Keys.Control) != 0) sb.Append("Ctrl+"); |
| 797 | if ((k & Keys.Shift) != 0) sb.Append("Shift+"); |
| 798 | if ((k & Keys.Alt) != 0) sb.Append("Alt+"); |
| 799 | Keys c = k & Keys.KeyCode; |
| 800 | string n; |
| 801 | if (c >= Keys.NumPad0 && c <= Keys.NumPad9) n = "Num " + (c - Keys.NumPad0); |
| 802 | else if (c >= Keys.D0 && c <= Keys.D9) n = ((int)(c - Keys.D0)).ToString(); |
| 803 | else |
| 804 | { |
| 805 | switch (c) |
| 806 | { |
| 807 | case Keys.Decimal: n = "Num ."; break; |
| 808 | case Keys.Add: n = "Num +"; break; |
| 809 | case Keys.Subtract: n = "Num -"; break; |
| 810 | case Keys.Multiply: n = "Num *"; break; |
| 811 | case Keys.Divide: n = "Num /"; break; |
| 812 | case Keys.Insert: n = "Ins"; break; |
| 813 | case Keys.Delete: n = "Del"; break; |
| 814 | case Keys.PageUp: n = "PgUp"; break; |
| 815 | case Keys.PageDown: n = "PgDn"; break; |
| 816 | case Keys.Oemtilde: n = "`"; break; |
| 817 | case Keys.OemMinus: n = "-"; break; |
| 818 | case Keys.Oemplus: n = "="; break; |
| 819 | case Keys.OemOpenBrackets: n = "["; break; |
| 820 | case Keys.OemCloseBrackets: n = "]"; break; |
| 821 | case Keys.OemPipe: n = "\\"; break; |
| 822 | case Keys.OemSemicolon: n = ";"; break; |
| 823 | case Keys.OemQuotes: n = "'"; break; |
| 824 | case Keys.Oemcomma: n = ","; break; |
| 825 | case Keys.OemPeriod: n = "."; break; |
| 826 | case Keys.OemQuestion: n = "/"; break; |
| 827 | default: n = c.ToString(); break; |
| 828 | } |
| 829 | } |
| 830 | sb.Append(n); |
| 831 | return sb.ToString(); |
| 832 | } |
| 833 | } |
| 834 | |
| 835 | internal class SplashForm : Form |
| 836 | { |
| 837 | private readonly Image img; |
| 838 | private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); |
| 839 | private readonly Stopwatch clock = Stopwatch.StartNew(); |
| 840 | private const int FadeIn = 350, Hold = 1700, FadeOut = 350; |
| 841 | private bool skipping; |
| 842 | private double skipFrom; |
| 843 | |
| 844 | public SplashForm(Image image) |
| 845 | { |
| 846 | img = image; |
| 847 | FormBorderStyle = FormBorderStyle.None; |
| 848 | StartPosition = FormStartPosition.CenterScreen; |
| 849 | ShowInTaskbar = true; |
| 850 | Text = Program.Name; |
| 851 | BackColor = Color.Black; |
| 852 | DoubleBuffered = true; |
| 853 | Opacity = 0; |
| 854 | Rectangle wa = Screen.PrimaryScreen.WorkingArea; |
| 855 | int w = Math.Min(900, (int)(wa.Width * 0.55)); |
| 856 | int h = w * image.Height / image.Width; |
| 857 | ClientSize = new Size(w, h); |
| 858 | try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch (Exception) { } |
| 859 | timer.Interval = 15; |
| 860 | timer.Tick += delegate { Step(); }; |
| 861 | Click += delegate { Skip(); }; |
| 862 | KeyPreview = true; |
| 863 | KeyDown += delegate { Skip(); }; |
| 864 | } |
| 865 | |
| 866 | protected override void OnShown(EventArgs e) |
| 867 | { |
| 868 | base.OnShown(e); |
| 869 | clock.Restart(); |
| 870 | timer.Start(); |
| 871 | } |
| 872 | |
| 873 | private void Skip() |
| 874 | { |
| 875 | if (skipping || clock.ElapsedMilliseconds >= FadeIn + Hold) return; |
| 876 | skipFrom = Opacity; |
| 877 | skipping = true; |
| 878 | clock.Restart(); |
| 879 | } |
| 880 | |
| 881 | private void Step() |
| 882 | { |
| 883 | long t = clock.ElapsedMilliseconds; |
| 884 | if (skipping) |
| 885 | { |
| 886 | double o = skipFrom * (1.0 - t / (double)FadeOut); |
| 887 | if (o <= 0) { timer.Stop(); Close(); return; } |
| 888 | Opacity = o; |
| 889 | return; |
| 890 | } |
| 891 | if (t < FadeIn) Opacity = t / (double)FadeIn; |
| 892 | else if (t < FadeIn + Hold) Opacity = 1; |
| 893 | else if (t < FadeIn + Hold + FadeOut) Opacity = 1 - (t - FadeIn - Hold) / (double)FadeOut; |
| 894 | else { timer.Stop(); Close(); } |
| 895 | } |
| 896 | |
| 897 | protected override void OnPaint(PaintEventArgs e) |
| 898 | { |
| 899 | e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 900 | e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; |
| 901 | e.Graphics.DrawImage(img, ClientRectangle); |
| 902 | int band = 46; |
| 903 | Rectangle br = new Rectangle(0, ClientSize.Height - band, ClientSize.Width, band); |
| 904 | using (LinearGradientBrush lg = new LinearGradientBrush(new Rectangle(br.X, br.Y - 30, br.Width, band + 30), Color.FromArgb(0, 10, 10, 11), Color.FromArgb(215, 10, 10, 11), LinearGradientMode.Vertical)) |
| 905 | e.Graphics.FillRectangle(lg, br.X, br.Y - 30, br.Width, band + 30); |
| 906 | e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 907 | using (Font bold = Theme.F("Segoe UI Semibold", 9.5f)) |
| 908 | using (Font f = Theme.F("Segoe UI", 8.5f)) |
| 909 | using (SolidBrush w = new SolidBrush(Color.White)) |
| 910 | using (SolidBrush o = new SolidBrush(Theme.Orange)) |
| 911 | using (SolidBrush d = new SolidBrush(Color.FromArgb(170, 170, 170))) |
| 912 | { |
| 913 | e.Graphics.DrawString("The only official trainer app by casualexpie", bold, w, 12, ClientSize.Height - 40); |
| 914 | e.Graphics.DrawString("Only download it from Nexus Mods or GameBanana", f, o, 13, ClientSize.Height - 21); |
| 915 | string v = "CU:Trainer v" + Program.Version + " · open source, (c) casualexpie"; |
| 916 | SizeF sz = e.Graphics.MeasureString(v, f); |
| 917 | e.Graphics.DrawString(v, f, d, ClientSize.Width - sz.Width - 10, ClientSize.Height - sz.Height - 8); |
| 918 | } |
| 919 | } |
| 920 | } |
| 921 | |
| 922 | internal class LauncherForm : Form |
| 923 | { |
| 924 | [DllImport("user32.dll")] private static extern bool ReleaseCapture(); |
| 925 | [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr h, int msg, IntPtr w, IntPtr l); |
| 926 | [DllImport("dwmapi.dll")] private static extern int DwmSetWindowAttribute(IntPtr h, int attr, ref int value, int size); |
| 927 | |
| 928 | public static string Result; |
| 929 | public static UpdateInfo Later; |
| 930 | public bool Restarting; |
| 931 | |
| 932 | private readonly Image art, logo; |
| 933 | private readonly Dictionary<string, string> settings; |
| 934 | private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); |
| 935 | private readonly Stopwatch clock = Stopwatch.StartNew(); |
| 936 | private readonly Font bigFont, smallFont, btnFont, footFont; |
| 937 | private string status = "Starting up", detail = ""; |
| 938 | private int progress = -1; |
| 939 | private bool busy = true, asking, closing; |
| 940 | private long closeAt = long.MaxValue, closingFrom; |
| 941 | private UpdateInfo found; |
| 942 | private Rectangle updRect, laterRect; |
| 943 | private int hoverBtn, detailH; |
| 944 | |
| 945 | public LauncherForm(Image splash) |
| 946 | { |
| 947 | art = splash; |
| 948 | logo = Res.Image("tile.png"); |
| 949 | using (Graphics g = CreateGraphics()) Theme.Scale = g.DpiX / 96f * Theme.UiScale; |
| 950 | settings = Settings.Load(); |
| 951 | AutoScaleMode = AutoScaleMode.None; |
| 952 | FormBorderStyle = FormBorderStyle.None; |
| 953 | StartPosition = FormStartPosition.CenterScreen; |
| 954 | ShowInTaskbar = true; |
| 955 | Text = Program.Name; |
| 956 | BackColor = Theme.Back; |
| 957 | DoubleBuffered = true; |
| 958 | Opacity = 0; |
| 959 | ClientSize = new Size(Theme.S(300), Theme.S(350)); |
| 960 | try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch (Exception) { } |
| 961 | bigFont = Theme.F("Segoe UI Semibold", 11f); |
| 962 | smallFont = Theme.F("Segoe UI", 8.75f); |
| 963 | btnFont = Theme.F("Segoe UI Semibold", 9f); |
| 964 | footFont = Theme.F("Segoe UI", 7.5f); |
| 965 | timer.Interval = 15; |
| 966 | timer.Tick += delegate { Step(); }; |
| 967 | } |
| 968 | |
| 969 | private string Get(string k, string def) |
| 970 | { |
| 971 | string v; |
| 972 | return settings != null && settings.TryGetValue(k, out v) ? v : def; |
| 973 | } |
| 974 | |
| 975 | protected override void OnHandleCreated(EventArgs e) |
| 976 | { |
| 977 | base.OnHandleCreated(e); |
| 978 | try { int round = 2; DwmSetWindowAttribute(Handle, 33, ref round, 4); } catch (Exception) { } |
| 979 | } |
| 980 | |
| 981 | protected override void OnShown(EventArgs e) |
| 982 | { |
| 983 | base.OnShown(e); |
| 984 | clock.Restart(); |
| 985 | timer.Start(); |
| 986 | Thread t = new Thread(Work); |
| 987 | t.IsBackground = true; |
| 988 | t.Start(); |
| 989 | } |
| 990 | |
| 991 | private void Ui(Action a) |
| 992 | { |
| 993 | try { if (IsHandleCreated && !IsDisposed) BeginInvoke(a); } catch (Exception) { } |
| 994 | } |
| 995 | |
| 996 | private void SetState(string s, string d, int pc) |
| 997 | { |
| 998 | Ui(delegate { status = s; detail = d ?? ""; progress = pc; Invalidate(); }); |
| 999 | } |
| 1000 | |
| 1001 | private void Finish(string s, string d, int ms) |
| 1002 | { |
| 1003 | Ui(delegate |
| 1004 | { |
| 1005 | status = s; detail = d ?? ""; progress = -1; busy = false; asking = false; |
| 1006 | closeAt = clock.ElapsedMilliseconds + ms; |
| 1007 | Invalidate(); |
| 1008 | }); |
| 1009 | } |
| 1010 | |
| 1011 | private void Work() |
| 1012 | { |
| 1013 | Thread.Sleep(450); |
| 1014 | if (Get("autoupdate", "1") != "1") { Finish("Starting", null, 250); return; } |
| 1015 | SetState("Checking for updates", "", -1); |
| 1016 | UpdateInfo u; |
| 1017 | try { u = Updater.Check(); } |
| 1018 | catch (Exception) |
| 1019 | { |
| 1020 | Result = "Couldn't reach the update server. You have v" + Program.Version + "."; |
| 1021 | Finish("Couldn't check for updates", "Starting anyway", 1100); |
| 1022 | return; |
| 1023 | } |
| 1024 | Updater.Ready = u; |
| 1025 | if (u == null) |
| 1026 | { |
| 1027 | Result = "You're up to date (v" + Program.Version + "). Checked " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + "."; |
| 1028 | Finish("You're up to date", "Starting", 500); |
| 1029 | return; |
| 1030 | } |
| 1031 | Result = "v" + u.Version + " is out (you have v" + Program.Version + "). Click Update Now."; |
| 1032 | bool gameOn = Installer.GameRunning(); |
| 1033 | if (Get("silentupdate", "0") == "1" && !gameOn && u.VtClean) { Install(u); return; } |
| 1034 | if (Get("update.skip", "") == u.Version && !u.Required && !u.VtFlagged) { Later = u; Finish("Starting", null, 250); return; } |
| 1035 | Ui(delegate |
| 1036 | { |
| 1037 | found = u; |
| 1038 | busy = false; |
| 1039 | asking = true; |
| 1040 | status = "Update available"; |
| 1041 | detail = "v" + u.Version + (u.Required ? " is required" : " is ready to install") + (u.Notes.Length > 0 ? "\n\nWhat's new:\n" + u.Notes : "") + "\n\n" + u.VtLine + (u.VtFlagged ? " Look at the report on virustotal.com before you install it." : ""); |
| 1042 | FitNotes(); |
| 1043 | Invalidate(); |
| 1044 | }); |
| 1045 | } |
| 1046 | |
| 1047 | private void Install(UpdateInfo u) |
| 1048 | { |
| 1049 | SetState("Downloading update", "v" + u.Version + " · 0%", 0); |
| 1050 | string file = null, err; |
| 1051 | try |
| 1052 | { |
| 1053 | err = Updater.Download(u, delegate (int pc) { SetState("Downloading update", "v" + u.Version + " · " + pc + "%", pc); }, out file); |
| 1054 | if (err == null) |
| 1055 | { |
| 1056 | SetState("Installing update", "v" + u.Version, 100); |
| 1057 | err = Updater.Apply(file, u.Sha); |
| 1058 | } |
| 1059 | } |
| 1060 | catch (Exception e) { err = e.Message; } |
| 1061 | if (err == null) |
| 1062 | { |
| 1063 | Ui(delegate { Restarting = true; }); |
| 1064 | Finish("Restarting", "Opening v" + u.Version, 350); |
| 1065 | return; |
| 1066 | } |
| 1067 | Later = u; |
| 1068 | Result = "Update failed: " + err; |
| 1069 | Finish("Update failed", err, 4000); |
| 1070 | } |
| 1071 | |
| 1072 | private void Step() |
| 1073 | { |
| 1074 | long t = clock.ElapsedMilliseconds; |
| 1075 | if (closing) |
| 1076 | { |
| 1077 | double o = 1.0 - (t - closingFrom) / 180.0; |
| 1078 | if (o <= 0) { timer.Stop(); Close(); return; } |
| 1079 | Opacity = o; |
| 1080 | return; |
| 1081 | } |
| 1082 | if (Opacity < 1) Opacity = Math.Min(1.0, t / 220.0); |
| 1083 | if (t >= closeAt) { closing = true; closingFrom = t; } |
| 1084 | Invalidate(); |
| 1085 | } |
| 1086 | |
| 1087 | protected override void OnMouseDown(MouseEventArgs e) |
| 1088 | { |
| 1089 | base.OnMouseDown(e); |
| 1090 | if (e.Button != MouseButtons.Left) return; |
| 1091 | if (asking && updRect.Contains(e.Location)) |
| 1092 | { |
| 1093 | asking = false; |
| 1094 | busy = true; |
| 1095 | UpdateInfo u = found; |
| 1096 | Thread t = new Thread(delegate () { Install(u); }); |
| 1097 | t.IsBackground = true; |
| 1098 | t.Start(); |
| 1099 | Invalidate(); |
| 1100 | return; |
| 1101 | } |
| 1102 | if (asking && laterRect.Contains(e.Location)) |
| 1103 | { |
| 1104 | Later = found; |
| 1105 | Finish("Starting", null, 200); |
| 1106 | return; |
| 1107 | } |
| 1108 | ReleaseCapture(); |
| 1109 | SendMessage(Handle, 0xA1, (IntPtr)2, IntPtr.Zero); |
| 1110 | } |
| 1111 | |
| 1112 | protected override void OnMouseMove(MouseEventArgs e) |
| 1113 | { |
| 1114 | base.OnMouseMove(e); |
| 1115 | int h = asking ? (updRect.Contains(e.Location) ? 1 : laterRect.Contains(e.Location) ? 2 : 0) : 0; |
| 1116 | if (h != hoverBtn) { hoverBtn = h; Cursor = h != 0 ? Cursors.Hand : Cursors.Default; Invalidate(); } |
| 1117 | } |
| 1118 | |
| 1119 | private void FitNotes() |
| 1120 | { |
| 1121 | int W = Theme.S(440); |
| 1122 | Rectangle wa = Screen.FromControl(this).WorkingArea; |
| 1123 | int maxText = Math.Max(Theme.S(60), wa.Height - Theme.S(186 + 28 + 14 + 34 + 50)); |
| 1124 | using (Graphics g = CreateGraphics()) |
| 1125 | { |
| 1126 | SizeF sz = g.MeasureString(detail, smallFont, W - Theme.S(48)); |
| 1127 | detailH = Math.Min(maxText, (int)Math.Ceiling(sz.Height) + Theme.S(4)); |
| 1128 | } |
| 1129 | int H = Theme.S(186 + 28) + detailH + Theme.S(14 + 34 + 46); |
| 1130 | Rectangle old = Bounds; |
| 1131 | ClientSize = new Size(W, Math.Max(Theme.S(350), H)); |
| 1132 | Location = new Point(Math.Max(wa.Left, old.Left + (old.Width - Width) / 2), Math.Max(wa.Top, Math.Min(old.Top + (old.Height - Height) / 2, wa.Bottom - Height))); |
| 1133 | } |
| 1134 | |
| 1135 | protected override void OnPaint(PaintEventArgs e) |
| 1136 | { |
| 1137 | Graphics g = e.Graphics; |
| 1138 | g.SmoothingMode = SmoothingMode.AntiAlias; |
| 1139 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 1140 | int W = ClientSize.Width, H = ClientSize.Height; |
| 1141 | double t = clock.ElapsedMilliseconds / 1000.0; |
| 1142 | g.Clear(BackColor); |
| 1143 | |
| 1144 | int band = Theme.S(150); |
| 1145 | if (art != null) |
| 1146 | { |
| 1147 | float sc = Math.Max(W / (float)art.Width, band / (float)art.Height); |
| 1148 | int sw = (int)(W / sc), sh = (int)(band / sc); |
| 1149 | Rectangle src = new Rectangle((art.Width - sw) / 2, (int)(art.Height * 0.45f) - sh / 2, sw, sh); |
| 1150 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 1151 | g.DrawImage(art, new Rectangle(0, 0, W, band), src, GraphicsUnit.Pixel); |
| 1152 | } |
| 1153 | using (LinearGradientBrush lg = new LinearGradientBrush(new Rectangle(0, 0, W, band + 1), Color.FromArgb(70, Theme.Back), Theme.Back, LinearGradientMode.Vertical)) |
| 1154 | g.FillRectangle(lg, 0, 0, W, band + 1); |
| 1155 | |
| 1156 | int ls = Theme.S(92); |
| 1157 | float bob = busy ? (float)Math.Sin(t * 3.2) * Theme.S(4) : 0f; |
| 1158 | float pulse = busy ? 1f + (float)Math.Sin(t * 3.2 + 1.2) * 0.03f : 1f; |
| 1159 | int lw = (int)(ls * pulse); |
| 1160 | int lx = (W - lw) / 2, ly = Theme.S(70) + (int)bob - (lw - ls) / 2; |
| 1161 | using (SolidBrush glow = new SolidBrush(Color.FromArgb(busy ? 40 + (int)(25 * Math.Sin(t * 3.2)) : 30, Theme.Orange))) |
| 1162 | g.FillEllipse(glow, lx - Theme.S(12), ly - Theme.S(12), lw + Theme.S(24), lw + Theme.S(24)); |
| 1163 | if (logo != null) |
| 1164 | { |
| 1165 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 1166 | g.DrawImage(logo, lx, ly, lw, lw); |
| 1167 | } |
| 1168 | |
| 1169 | StringFormat c = new StringFormat(); c.Alignment = StringAlignment.Center; c.LineAlignment = StringAlignment.Near; |
| 1170 | int ty = Theme.S(186); |
| 1171 | using (SolidBrush w = new SolidBrush(Theme.Bright)) g.DrawString(status, bigFont, w, new RectangleF(Theme.S(12), ty, W - Theme.S(24), Theme.S(26)), c); |
| 1172 | StringFormat cw = new StringFormat(c); cw.Trimming = StringTrimming.EllipsisWord; |
| 1173 | int by = Theme.S(262); |
| 1174 | using (SolidBrush d = new SolidBrush(Theme.Soft)) |
| 1175 | { |
| 1176 | if (asking && detailH > 0) |
| 1177 | { |
| 1178 | StringFormat lw0 = new StringFormat(); lw0.Trimming = StringTrimming.EllipsisWord; |
| 1179 | g.DrawString(detail, smallFont, d, new RectangleF(Theme.S(24), ty + Theme.S(28), W - Theme.S(48), detailH), lw0); |
| 1180 | by = ty + Theme.S(28) + detailH + Theme.S(14); |
| 1181 | } |
| 1182 | else g.DrawString(detail, smallFont, d, new RectangleF(Theme.S(20), ty + Theme.S(28), W - Theme.S(40), Theme.S(40)), cw); |
| 1183 | } |
| 1184 | if (progress >= 0) |
| 1185 | { |
| 1186 | Rectangle bar = new Rectangle(Theme.S(40), by + Theme.S(10), W - Theme.S(80), Theme.S(6)); |
| 1187 | using (SolidBrush b = new SolidBrush(Theme.Line)) FillRound(g, b, bar); |
| 1188 | Rectangle fill = new Rectangle(bar.X, bar.Y, Math.Max(bar.Height, bar.Width * Math.Min(100, progress) / 100), bar.Height); |
| 1189 | using (SolidBrush b = new SolidBrush(Theme.Orange)) FillRound(g, b, fill); |
| 1190 | } |
| 1191 | else if (asking) |
| 1192 | { |
| 1193 | int bw = Theme.S(112), bh = Theme.S(34), gap = Theme.S(10); |
| 1194 | int bx = (W - bw * 2 - gap) / 2; |
| 1195 | updRect = new Rectangle(bx, by, bw, bh); |
| 1196 | laterRect = new Rectangle(bx + bw + gap, by, bw, bh); |
| 1197 | using (SolidBrush b = new SolidBrush(hoverBtn == 1 ? Theme.AccentHover : Theme.Orange)) FillRound(g, b, updRect); |
| 1198 | using (SolidBrush b = new SolidBrush(hoverBtn == 2 ? Theme.Edge : Theme.Line)) FillRound(g, b, laterRect); |
| 1199 | StringFormat m = new StringFormat(); m.Alignment = StringAlignment.Center; m.LineAlignment = StringAlignment.Center; |
| 1200 | using (SolidBrush b = new SolidBrush(Theme.OnAccent)) g.DrawString("Update", btnFont, b, updRect, m); |
| 1201 | using (SolidBrush b = new SolidBrush(Theme.Text)) g.DrawString(found != null && found.Required ? "Not now" : "Later", btnFont, b, laterRect, m); |
| 1202 | } |
| 1203 | else if (busy) |
| 1204 | { |
| 1205 | int n = 3, r = Theme.S(4), sp = Theme.S(14); |
| 1206 | int dx = (W - (n - 1) * sp) / 2; |
| 1207 | for (int i = 0; i < n; i++) |
| 1208 | { |
| 1209 | double ph = Math.Sin(t * 6 - i * 0.7); |
| 1210 | int a = 90 + (int)(165 * Math.Max(0, ph)); |
| 1211 | using (SolidBrush b = new SolidBrush(Color.FromArgb(a, Theme.Orange))) |
| 1212 | g.FillEllipse(b, dx + i * sp - r, by + Theme.S(12) - r - (int)(Math.Max(0, ph) * Theme.S(3)), r * 2, r * 2); |
| 1213 | } |
| 1214 | } |
| 1215 | |
| 1216 | StringFormat f = new StringFormat(); f.Alignment = StringAlignment.Center; |
| 1217 | using (SolidBrush b = new SolidBrush(Theme.Dim)) |
| 1218 | g.DrawString("v" + Program.Version + " · official copies only on Nexus Mods and GameBanana", footFont, b, new RectangleF(0, H - Theme.S(26), W, Theme.S(18)), f); |
| 1219 | } |
| 1220 | |
| 1221 | private static void FillRound(Graphics g, Brush b, Rectangle r) |
| 1222 | { |
| 1223 | int d = Math.Min(r.Height, Theme.S(10)); |
| 1224 | using (GraphicsPath p = new GraphicsPath()) |
| 1225 | { |
| 1226 | p.AddArc(r.X, r.Y, d, d, 180, 90); |
| 1227 | p.AddArc(r.Right - d, r.Y, d, d, 270, 90); |
| 1228 | p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90); |
| 1229 | p.AddArc(r.X, r.Bottom - d, d, d, 90, 90); |
| 1230 | p.CloseFigure(); |
| 1231 | g.FillPath(b, p); |
| 1232 | } |
| 1233 | } |
| 1234 | } |
| 1235 | |
| 1236 | internal class SideBar : Control |
| 1237 | { |
| 1238 | public List<Tab> Tabs; |
| 1239 | public int Selected; |
| 1240 | public Func<Tab, int> ActiveCount; |
| 1241 | public Func<Tab, bool> Alert; |
| 1242 | public event Action<int> TabSelected; |
| 1243 | private int hover = -1; |
| 1244 | private readonly Font font = Theme.F("Segoe UI", 9.75f); |
| 1245 | private readonly Font bold = Theme.F("Segoe UI Semibold", 9.75f); |
| 1246 | private readonly Font small = Theme.F("Segoe UI Semibold", 7.5f); |
| 1247 | private readonly Font group = Theme.F("Segoe UI Semibold", 7f); |
| 1248 | private Font icon; |
| 1249 | private readonly List<Rectangle> rects = new List<Rectangle>(); |
| 1250 | |
| 1251 | public SideBar() |
| 1252 | { |
| 1253 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); |
| 1254 | try { icon = new Font("Segoe MDL2 Assets", 11f * Theme.UiScale); if (icon.Name != "Segoe MDL2 Assets") icon = null; } catch (Exception) { icon = null; } |
| 1255 | } |
| 1256 | |
| 1257 | private int GroupH { get { return Theme.S(24); } } |
| 1258 | |
| 1259 | private void Layout0() |
| 1260 | { |
| 1261 | rects.Clear(); |
| 1262 | if (Tabs == null) return; |
| 1263 | int groups = 0; |
| 1264 | string last = null; |
| 1265 | foreach (Tab t in Tabs) if (t.Group != last) { groups++; last = t.Group; } |
| 1266 | int room = Height - Theme.S(44) - groups * GroupH; |
| 1267 | int rh = Math.Max(Theme.S(20), Math.Min(Theme.S(36), room / Math.Max(1, Tabs.Count))); |
| 1268 | int y = Theme.S(4); |
| 1269 | last = null; |
| 1270 | foreach (Tab t in Tabs) |
| 1271 | { |
| 1272 | if (t.Group != last) { y += GroupH; last = t.Group; } |
| 1273 | rects.Add(new Rectangle(Theme.S(8), y, Width - Theme.S(16), rh - Theme.S(2))); |
| 1274 | y += rh; |
| 1275 | } |
| 1276 | } |
| 1277 | |
| 1278 | private int At(Point p) |
| 1279 | { |
| 1280 | for (int i = 0; i < rects.Count; i++) if (rects[i].Contains(p)) return i; |
| 1281 | return -1; |
| 1282 | } |
| 1283 | |
| 1284 | protected override void OnResize(EventArgs e) { base.OnResize(e); Layout0(); } |
| 1285 | |
| 1286 | protected override void OnMouseMove(MouseEventArgs e) |
| 1287 | { |
| 1288 | if (rects.Count != (Tabs != null ? Tabs.Count : 0)) Layout0(); |
| 1289 | int h = At(e.Location); |
| 1290 | if (h != hover) { hover = h; Invalidate(); } |
| 1291 | Cursor = h >= 0 ? Cursors.Hand : Cursors.Default; |
| 1292 | } |
| 1293 | |
| 1294 | protected override void OnMouseLeave(EventArgs e) { hover = -1; Invalidate(); } |
| 1295 | |
| 1296 | protected override void OnMouseDown(MouseEventArgs e) |
| 1297 | { |
| 1298 | int i = At(e.Location); |
| 1299 | if (i < 0 || i == Selected) return; |
| 1300 | Selected = i; |
| 1301 | Invalidate(); |
| 1302 | if (TabSelected != null) TabSelected(i); |
| 1303 | } |
| 1304 | |
| 1305 | protected override void OnPaint(PaintEventArgs e) |
| 1306 | { |
| 1307 | Graphics g = e.Graphics; |
| 1308 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 1309 | g.Clear(Theme.Side); |
| 1310 | if (Tabs == null) return; |
| 1311 | if (rects.Count != Tabs.Count) Layout0(); |
| 1312 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; mid.Trimming = StringTrimming.EllipsisCharacter; |
| 1313 | StringFormat center = new StringFormat(mid); center.Alignment = StringAlignment.Center; |
| 1314 | string last = null; |
| 1315 | for (int i = 0; i < Tabs.Count; i++) |
| 1316 | { |
| 1317 | Tab t = Tabs[i]; |
| 1318 | Rectangle r = rects[i]; |
| 1319 | if (t.Group != last) |
| 1320 | { |
| 1321 | last = t.Group; |
| 1322 | using (SolidBrush b = new SolidBrush(Theme.Faint)) |
| 1323 | g.DrawString(Theme.Spaced(t.Group), group, b, new RectangleF(Theme.S(18), r.Y - GroupH + Theme.S(6), Width, GroupH - Theme.S(6)), mid); |
| 1324 | } |
| 1325 | bool sel = i == Selected, hov = i == hover; |
| 1326 | if (sel) Theme.FillRound(g, Theme.Mix(Theme.Side, Theme.Orange, Theme.Light ? 0.14 : 0.16), r, Theme.S(7)); |
| 1327 | else if (hov) Theme.FillRound(g, Theme.Hover, r, Theme.S(7)); |
| 1328 | if (sel) Theme.FillRound(g, Theme.Orange, new Rectangle(r.X, r.Y + r.Height / 4, Theme.S(3), r.Height / 2), Theme.S(2)); |
| 1329 | int tx = r.X + Theme.S(12); |
| 1330 | if (t.VtLogo) |
| 1331 | { |
| 1332 | float sz = Theme.S(15); |
| 1333 | float ox = tx - Theme.S(2) + (Theme.S(22) - sz) / 2f, oy = r.Y + (r.Height - sz * 0.89f) / 2f + Theme.S(1); |
| 1334 | float k = sz / 100f; |
| 1335 | using (GraphicsPath p = new GraphicsPath(FillMode.Alternate)) |
| 1336 | { |
| 1337 | p.AddPolygon(new PointF[] { new PointF(ox + 45.292f * k, oy + 44.5f * k), new PointF(ox, oy + 89f * k), new PointF(ox + 100f * k, oy + 89f * k), new PointF(ox + 100f * k, oy), new PointF(ox, oy) }); |
| 1338 | p.AddPolygon(new PointF[] { new PointF(ox + 90f * k, oy + 80f * k), new PointF(ox + 22f * k, oy + 80f * k), new PointF(ox + 57.987f * k, oy + 44.8f * k), new PointF(ox + 22f * k, oy + 9f * k), new PointF(ox + 90f * k, oy + 9f * k) }); |
| 1339 | SmoothingMode old = g.SmoothingMode; |
| 1340 | g.SmoothingMode = SmoothingMode.AntiAlias; |
| 1341 | Color vc = Theme.Light ? Color.FromArgb(0x0b, 0x4d, 0xda) : Color.FromArgb(0x3d, 0x7b, 0xff); |
| 1342 | if (!sel && !hov) vc = Theme.Mix(vc, Theme.Side, 0.15); |
| 1343 | using (SolidBrush vb = new SolidBrush(vc)) g.FillPath(vb, p); |
| 1344 | g.SmoothingMode = old; |
| 1345 | } |
| 1346 | tx += Theme.S(26); |
| 1347 | } |
| 1348 | else if (icon != null && t.Icon != '\0') |
| 1349 | { |
| 1350 | using (SolidBrush b = new SolidBrush(sel ? Theme.Orange : hov ? Theme.Text : Theme.Dim)) |
| 1351 | g.DrawString(t.Icon.ToString(), icon, b, new RectangleF(tx - Theme.S(2), r.Y + Theme.S(1), Theme.S(22), r.Height), center); |
| 1352 | tx += Theme.S(26); |
| 1353 | } |
| 1354 | int n = ActiveCount != null ? ActiveCount(t) : 0; |
| 1355 | int bw = 0; |
| 1356 | if (n > 0) |
| 1357 | { |
| 1358 | string ns = n > 99 ? "99+" : n.ToString(); |
| 1359 | bw = Math.Max(Theme.S(20), (int)g.MeasureString(ns, small).Width + Theme.S(8)); |
| 1360 | Rectangle pill = new Rectangle(r.Right - bw - Theme.S(8), r.Y + (r.Height - Theme.S(17)) / 2, bw, Theme.S(17)); |
| 1361 | bool bad = Alert != null && Alert(t); |
| 1362 | Color pc = bad ? Theme.Bad : Theme.Orange; |
| 1363 | Theme.FillRound(g, pc, pill, Theme.S(8)); |
| 1364 | using (SolidBrush b = new SolidBrush(Theme.Lum(pc) > 0.45 ? Color.FromArgb(20, 20, 21) : Color.White)) g.DrawString(ns, small, b, pill, center); |
| 1365 | bw += Theme.S(10); |
| 1366 | } |
| 1367 | using (SolidBrush b = new SolidBrush(sel ? Theme.Text : hov ? Theme.Text : Theme.Soft)) |
| 1368 | g.DrawString(t.Name, sel ? bold : font, b, new RectangleF(tx, r.Y, r.Right - tx - bw - Theme.S(4), r.Height), mid); |
| 1369 | } |
| 1370 | using (Pen p = new Pen(Theme.Line)) g.DrawLine(p, Width - 1, 0, Width - 1, Height); |
| 1371 | using (SolidBrush b = new SolidBrush(Theme.Faint)) |
| 1372 | g.DrawString("v" + Program.Version, small, b, new RectangleF(Theme.S(18), Height - Theme.S(30), Width, Theme.S(22)), mid); |
| 1373 | } |
| 1374 | } |
| 1375 | internal class TabView : Control |
| 1376 | { |
| 1377 | public Tab Tab; |
| 1378 | public Dictionary<string, string> Info = new Dictionary<string, string>(); |
| 1379 | public bool Linked; |
| 1380 | public Option Capturing; |
| 1381 | public event Action<Option> Clicked; |
| 1382 | public event Action<Option> Rebind; |
| 1383 | public event Action<Option> HoverChanged; |
| 1384 | public event Action<Option, float> SliderChanged; |
| 1385 | public event Action<Btn> ButtonClicked; |
| 1386 | public event Action<Option> StarClicked; |
| 1387 | public int TopPad; |
| 1388 | |
| 1389 | private class Hit |
| 1390 | { |
| 1391 | public Option Opt; |
| 1392 | public Rectangle Row, Key, Bar, Star; |
| 1393 | public readonly List<KeyValuePair<Rectangle, Btn>> Btns = new List<KeyValuePair<Rectangle, Btn>>(); |
| 1394 | } |
| 1395 | |
| 1396 | private readonly List<Hit> hits = new List<Hit>(); |
| 1397 | private Option hover; |
| 1398 | private Btn hoverBtn; |
| 1399 | private Hit dragging; |
| 1400 | private int scroll, contentH; |
| 1401 | private readonly Font nameFont = Theme.F("Segoe UI", 9.5f); |
| 1402 | private readonly Font keyFont = Theme.F("Consolas", 8.5f); |
| 1403 | private readonly Font headFont = Theme.F("Segoe UI Semibold", 8f); |
| 1404 | private readonly Font smallFont = Theme.F("Segoe UI", 8.5f); |
| 1405 | private readonly Font stateFont = Theme.F("Segoe UI Semibold", 8.5f); |
| 1406 | |
| 1407 | public TabView() |
| 1408 | { |
| 1409 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); |
| 1410 | BackColor = Theme.Back; |
| 1411 | } |
| 1412 | |
| 1413 | private int Pad { get { return Theme.S(18); } } |
| 1414 | private int Gap { get { return Theme.S(22); } } |
| 1415 | private int RowH { get { return Theme.S(28); } } |
| 1416 | private int HeadH { get { return Theme.S(34); } } |
| 1417 | private int KeyW { get { return Theme.S(70); } } |
| 1418 | private int ColW { get { return (Width - Pad * 2 - Gap * 2) / 3; } } |
| 1419 | private int ColX(int c) { return Pad + c * (ColW + Gap); } |
| 1420 | |
| 1421 | public Rectangle ColumnBounds(int c) |
| 1422 | { |
| 1423 | return new Rectangle(ColX(c), Theme.S(8), ColW, Height - Theme.S(16)); |
| 1424 | } |
| 1425 | |
| 1426 | public Rectangle SpawnerBounds() |
| 1427 | { |
| 1428 | return new Rectangle(ColX(1), Theme.S(8), ColW * 2 + Gap, Height - Theme.S(16)); |
| 1429 | } |
| 1430 | |
| 1431 | public void ShowTab(Tab t) |
| 1432 | { |
| 1433 | Tab = t; |
| 1434 | scroll = 0; |
| 1435 | hover = null; |
| 1436 | hoverBtn = null; |
| 1437 | dragging = null; |
| 1438 | Invalidate(); |
| 1439 | } |
| 1440 | |
| 1441 | private int RowHeight(Graphics g, Option o, int w) |
| 1442 | { |
| 1443 | if (o.Kind == Kind.Note) |
| 1444 | { |
| 1445 | SizeF sz = g.MeasureString(o.Name, smallFont, w); |
| 1446 | return (int)Math.Ceiling(sz.Height) + Theme.S(8); |
| 1447 | } |
| 1448 | if (o.Kind == Kind.Info) return Theme.S(26); |
| 1449 | if (o.Kind == Kind.Slider) return Theme.S(26); |
| 1450 | return RowH; |
| 1451 | } |
| 1452 | |
| 1453 | protected override void OnPaint(PaintEventArgs e) |
| 1454 | { |
| 1455 | Graphics g = e.Graphics; |
| 1456 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 1457 | Theme.PaintBack(g, this); |
| 1458 | hits.Clear(); |
| 1459 | if (Tab == null || Tab.Health || Tab.About || Tab.Mods || Tab.Report) { contentH = 0; return; } |
| 1460 | int maxY = 0; |
| 1461 | for (int c = 0; c < 3; c++) |
| 1462 | { |
| 1463 | if (Tab.Spawner && c >= 1) continue; |
| 1464 | int x = ColX(c), w = ColW; |
| 1465 | int y = Theme.S(6) + TopPad - scroll; |
| 1466 | foreach (Section s in Tab.Cols[c]) |
| 1467 | { |
| 1468 | DrawHead(g, s.Title, x, y, w); |
| 1469 | y += HeadH; |
| 1470 | foreach (Option o in s.Rows) |
| 1471 | { |
| 1472 | int h = RowHeight(g, o, w); |
| 1473 | if (o.Kind == Kind.Info && o.Text != null && string.IsNullOrEmpty(o.Text(Info))) continue; |
| 1474 | if (o.Show != null && !o.Show()) continue; |
| 1475 | DrawRow(g, o, x, y, w, h); |
| 1476 | y += h; |
| 1477 | } |
| 1478 | y += Theme.S(10); |
| 1479 | } |
| 1480 | maxY = Math.Max(maxY, y + scroll); |
| 1481 | } |
| 1482 | contentH = maxY; |
| 1483 | if (contentH > Height) |
| 1484 | { |
| 1485 | int th = Math.Max(Theme.S(30), Height * Height / contentH); |
| 1486 | int ty = (Height - th) * scroll / Math.Max(1, contentH - Height); |
| 1487 | using (SolidBrush sb = new SolidBrush(Theme.Scroll)) g.FillRectangle(sb, Width - Theme.S(6), ty, Theme.S(3), th); |
| 1488 | } |
| 1489 | } |
| 1490 | |
| 1491 | private void DrawHead(Graphics g, string title, int x, int y, int w) |
| 1492 | { |
| 1493 | if (string.IsNullOrEmpty(title) || title.Trim().Length == 0) return; |
| 1494 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; |
| 1495 | Theme.FillRound(g, Theme.Orange, new Rectangle(x, y + Theme.S(8) + (HeadH - Theme.S(12)) / 2 - Theme.S(6), Theme.S(3), Theme.S(12)), Theme.S(1)); |
| 1496 | string sp = Theme.Spaced(title); |
| 1497 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 1498 | g.DrawString(sp, headFont, orange, new RectangleF(x + Theme.S(9), y + Theme.S(8), w, HeadH - Theme.S(12)), mid); |
| 1499 | int tw = (int)g.MeasureString(sp, headFont).Width + Theme.S(16); |
| 1500 | int ly = y + Theme.S(8) + (HeadH - Theme.S(12)) / 2; |
| 1501 | using (LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(x + tw - 1, ly, Math.Max(2, w - tw + 2), 1), Theme.Line, Color.FromArgb(0, Theme.Line), LinearGradientMode.Horizontal)) |
| 1502 | g.FillRectangle(lb, x + tw, ly, Math.Max(1, w - tw), 1); |
| 1503 | } |
| 1504 | |
| 1505 | private void DrawRow(Graphics g, Option o, int x, int y, int w, int h) |
| 1506 | { |
| 1507 | Hit hit = new Hit(); |
| 1508 | hit.Opt = o; |
| 1509 | hit.Row = new Rectangle(x - Theme.S(6), y, w + Theme.S(12), h); |
| 1510 | hits.Add(hit); |
| 1511 | if (y + h < 0 || y > Height) return; |
| 1512 | |
| 1513 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.Trimming = StringTrimming.EllipsisCharacter; mid.FormatFlags = StringFormatFlags.NoWrap; |
| 1514 | StringFormat center = new StringFormat(mid); center.Alignment = StringAlignment.Center; |
| 1515 | StringFormat right = new StringFormat(mid); right.Alignment = StringAlignment.Far; |
| 1516 | bool isHover = o == hover; |
| 1517 | |
| 1518 | using (SolidBrush text = new SolidBrush(Theme.Text)) |
| 1519 | using (SolidBrush dim = new SolidBrush(Theme.Dim)) |
| 1520 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 1521 | using (SolidBrush on = new SolidBrush(Theme.On)) |
| 1522 | using (Pen edge = new Pen(Theme.Edge)) |
| 1523 | using (Pen cap = new Pen(Theme.Orange)) |
| 1524 | { |
| 1525 | switch (o.Kind) |
| 1526 | { |
| 1527 | case Kind.Toggle: |
| 1528 | case Kind.Action: |
| 1529 | { |
| 1530 | if (isHover) Theme.FillRound(g, Theme.Hover, hit.Row, Theme.S(6)); |
| 1531 | Rectangle kr = new Rectangle(x, y + Theme.S(5), KeyW, h - Theme.S(10)); |
| 1532 | hit.Key = kr; |
| 1533 | bool capturing = Capturing == o; |
| 1534 | Theme.FillRound(g, Theme.Sunk, kr, Theme.S(5)); |
| 1535 | Theme.DrawRound(g, capturing ? Theme.Orange : Theme.Line, kr, Theme.S(5)); |
| 1536 | g.DrawString(capturing ? "press key" : KeyText.Of(o.Key), keyFont, capturing ? orange : (o.Key == Keys.None ? dim : text), kr, center); |
| 1537 | int nx = x + KeyW + Theme.S(12); |
| 1538 | int sw = Theme.S(40); |
| 1539 | bool usable = o.Kind == Kind.Toggle || Linked || o.Local; |
| 1540 | int stw = Theme.S(20); |
| 1541 | Rectangle star = new Rectangle(x + w - sw - stw - Theme.S(2), y, stw, h); |
| 1542 | hit.Star = star; |
| 1543 | if (o.Fav || isHover) |
| 1544 | using (SolidBrush sbr = new SolidBrush(o.Fav ? Theme.Orange : Theme.Dim)) g.DrawString(o.Fav ? "\u2605" : "\u2606", nameFont, sbr, star, center); |
| 1545 | g.DrawString(o.Name, nameFont, usable ? text : dim, new RectangleF(nx, y, x + w - nx - sw - stw - Theme.S(4), h), mid); |
| 1546 | Rectangle sr = new Rectangle(x + w - sw, y, sw, h); |
| 1547 | if (o.Kind == Kind.Toggle) |
| 1548 | { |
| 1549 | int pw = Theme.S(32), ph = Theme.S(18); |
| 1550 | Rectangle pill = new Rectangle(sr.Right - pw - Theme.S(2), y + (h - ph) / 2, pw, ph); |
| 1551 | Theme.FillRound(g, o.On ? Theme.On : Theme.Line, pill, ph / 2); |
| 1552 | int kd = ph - Theme.S(6); |
| 1553 | Rectangle kn = new Rectangle(o.On ? pill.Right - kd - Theme.S(3) : pill.X + Theme.S(3), pill.Y + Theme.S(3), kd, kd); |
| 1554 | Theme.FillRound(g, o.On ? (Theme.Lum(Theme.On) > 0.55 ? Theme.Side : Color.White) : Theme.Dim, kn, kd / 2); |
| 1555 | } |
| 1556 | else |
| 1557 | g.DrawString("RUN", stateFont, isHover && usable ? orange : dim, sr, right); |
| 1558 | break; |
| 1559 | } |
| 1560 | case Kind.Slider: |
| 1561 | { |
| 1562 | if (isHover) Theme.FillRound(g, Theme.Hover, hit.Row, Theme.S(6)); |
| 1563 | int lx = x + KeyW + Theme.S(12); |
| 1564 | int lw = Theme.S(84); |
| 1565 | int vw = Theme.S(48); |
| 1566 | g.DrawString(o.Name, smallFont, dim, new RectangleF(lx, y, lw, h), mid); |
| 1567 | Rectangle bar = new Rectangle(lx + lw, y + h / 2 - Theme.S(2), Math.Max(Theme.S(20), x + w - vw - (lx + lw) - Theme.S(8)), Theme.S(4)); |
| 1568 | hit.Bar = new Rectangle(bar.X - Theme.S(6), y, bar.Width + Theme.S(12), h); |
| 1569 | Theme.FillRound(g, Theme.Line, bar, Theme.S(2)); |
| 1570 | float t = (o.Value - o.Min) / (o.Max - o.Min); |
| 1571 | t = Math.Max(0f, Math.Min(1f, t)); |
| 1572 | int fill = (int)(bar.Width * t); |
| 1573 | if (fill > 0) Theme.FillRound(g, Theme.Orange, new Rectangle(bar.X, bar.Y, fill, bar.Height), Theme.S(2)); |
| 1574 | Rectangle knob = new Rectangle(bar.X + fill - Theme.S(7), y + h / 2 - Theme.S(7), Theme.S(14), Theme.S(14)); |
| 1575 | Theme.FillRound(g, dragging != null && dragging.Opt == o ? Theme.Orange : Theme.Text, knob, Theme.S(7)); |
| 1576 | g.DrawString(string.Format(CultureInfo.InvariantCulture, o.Format, o.Value), keyFont, Math.Abs(o.Value - o.Default) < 0.001f ? dim : text, new RectangleF(x + w - vw, y, vw, h), right); |
| 1577 | break; |
| 1578 | } |
| 1579 | case Kind.Buttons: |
| 1580 | { |
| 1581 | string label = o.Text != null ? o.Text(Info) : o.Name; |
| 1582 | bool live = Linked || o.Local; |
| 1583 | int bx = x + w; |
| 1584 | int bh = h - Theme.S(8); |
| 1585 | for (int i = o.Buttons.Count - 1; i >= 0; i--) |
| 1586 | { |
| 1587 | Btn btn = o.Buttons[i]; |
| 1588 | int iw = btn.Icon != null ? bh - Theme.S(10) : 0; |
| 1589 | int bw = (int)g.MeasureString(btn.Label, smallFont).Width + Theme.S(14) + (iw > 0 ? iw + Theme.S(6) : 0); |
| 1590 | bx -= bw; |
| 1591 | Rectangle br = new Rectangle(bx, y + Theme.S(4), bw, bh); |
| 1592 | hit.Btns.Insert(0, new KeyValuePair<Rectangle, Btn>(br, btn)); |
| 1593 | bool hb = btn == hoverBtn; |
| 1594 | Theme.FillRound(g, hb && live ? Theme.Hover : Theme.Panel, br, Theme.S(5)); |
| 1595 | Theme.DrawRound(g, hb && live ? Theme.Orange : Theme.Line, br, Theme.S(5)); |
| 1596 | if (iw > 0) |
| 1597 | { |
| 1598 | InterpolationMode im = g.InterpolationMode; |
| 1599 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 1600 | g.DrawImage(btn.Icon, new Rectangle(br.X + Theme.S(7), br.Y + (bh - iw) / 2, iw, iw)); |
| 1601 | g.InterpolationMode = im; |
| 1602 | g.DrawString(btn.Label, smallFont, live ? text : dim, new Rectangle(br.X + iw + Theme.S(6), br.Y, br.Width - iw - Theme.S(6), bh), center); |
| 1603 | } |
| 1604 | else g.DrawString(btn.Label, smallFont, live ? text : dim, br, center); |
| 1605 | bx -= Theme.S(5); |
| 1606 | } |
| 1607 | int lx0 = x; |
| 1608 | if (o.Swatch != null) |
| 1609 | { |
| 1610 | int sz = Theme.S(16); |
| 1611 | Rectangle sq = new Rectangle(x, y + (h - sz) / 2, sz, sz); |
| 1612 | Theme.FillRound(g, o.Swatch(), sq, Theme.S(4)); |
| 1613 | Theme.DrawRound(g, Theme.Edge, sq, Theme.S(4)); |
| 1614 | lx0 += sz + Theme.S(8); |
| 1615 | } |
| 1616 | if (!string.IsNullOrEmpty(label)) |
| 1617 | g.DrawString(label, nameFont, live ? text : dim, new RectangleF(lx0, y, bx - lx0 - Theme.S(6), h), mid); |
| 1618 | break; |
| 1619 | } |
| 1620 | case Kind.Info: |
| 1621 | { |
| 1622 | string s = o.Text != null ? o.Text(Info) : o.Name; |
| 1623 | bool live = Linked || o.Local; |
| 1624 | g.DrawString(live ? s : "Not attached", o.Local ? smallFont : nameFont, live ? text : dim, new RectangleF(x, y, w, h), mid); |
| 1625 | break; |
| 1626 | } |
| 1627 | case Kind.Note: |
| 1628 | g.DrawString(o.Name, smallFont, dim, new RectangleF(x, y + Theme.S(4), w, h)); |
| 1629 | break; |
| 1630 | } |
| 1631 | } |
| 1632 | } |
| 1633 | |
| 1634 | private Hit HitAt(Point p) |
| 1635 | { |
| 1636 | foreach (Hit h in hits) if (h.Row.Contains(p)) return h; |
| 1637 | return null; |
| 1638 | } |
| 1639 | |
| 1640 | private void SetSlider(Hit h, int mx) |
| 1641 | { |
| 1642 | Option o = h.Opt; |
| 1643 | Rectangle bar = new Rectangle(h.Bar.X + Theme.S(6), h.Bar.Y, h.Bar.Width - Theme.S(12), h.Bar.Height); |
| 1644 | float t = (mx - bar.X) / (float)Math.Max(1, bar.Width); |
| 1645 | t = Math.Max(0f, Math.Min(1f, t)); |
| 1646 | float v = o.Min + t * (o.Max - o.Min); |
| 1647 | v = (float)Math.Round(v / o.Step) * o.Step; |
| 1648 | v = Math.Max(o.Min, Math.Min(o.Max, (float)Math.Round(v, 3))); |
| 1649 | if (Math.Abs(v - o.Value) > 0.0001f && SliderChanged != null) SliderChanged(o, v); |
| 1650 | Invalidate(); |
| 1651 | } |
| 1652 | |
| 1653 | protected override void OnMouseDown(MouseEventArgs e) |
| 1654 | { |
| 1655 | Focus(); |
| 1656 | Hit h = HitAt(e.Location); |
| 1657 | if (h == null) return; |
| 1658 | Option o = h.Opt; |
| 1659 | switch (o.Kind) |
| 1660 | { |
| 1661 | case Kind.Slider: |
| 1662 | if (e.Button == MouseButtons.Right) { if (SliderChanged != null) SliderChanged(o, o.Default); Invalidate(); } |
| 1663 | else if (h.Bar.Contains(e.Location)) { dragging = h; Capture = true; SetSlider(h, e.X); } |
| 1664 | break; |
| 1665 | case Kind.Buttons: |
| 1666 | foreach (KeyValuePair<Rectangle, Btn> kv in h.Btns) |
| 1667 | if (kv.Key.Contains(e.Location) && ButtonClicked != null) ButtonClicked(kv.Value); |
| 1668 | break; |
| 1669 | case Kind.Toggle: |
| 1670 | case Kind.Action: |
| 1671 | if (e.Button == MouseButtons.Left && h.Star.Contains(e.Location)) { if (StarClicked != null) StarClicked(o); } |
| 1672 | else if (e.Button == MouseButtons.Right || h.Key.Contains(e.Location)) { if (Rebind != null) Rebind(o); } |
| 1673 | else if (e.Button == MouseButtons.Left && Clicked != null) Clicked(o); |
| 1674 | break; |
| 1675 | } |
| 1676 | Invalidate(); |
| 1677 | } |
| 1678 | |
| 1679 | protected override void OnMouseMove(MouseEventArgs e) |
| 1680 | { |
| 1681 | if (dragging != null) { SetSlider(dragging, e.X); return; } |
| 1682 | Hit h = HitAt(e.Location); |
| 1683 | Option o = h != null ? h.Opt : null; |
| 1684 | Btn b = null; |
| 1685 | if (h != null) foreach (KeyValuePair<Rectangle, Btn> kv in h.Btns) if (kv.Key.Contains(e.Location)) b = kv.Value; |
| 1686 | bool clickable = o != null && (o.Kind == Kind.Toggle || o.Kind == Kind.Action || b != null || (o.Kind == Kind.Slider && h.Bar.Contains(e.Location))); |
| 1687 | Cursor = clickable ? Cursors.Hand : Cursors.Default; |
| 1688 | if (o != hover || b != hoverBtn) |
| 1689 | { |
| 1690 | bool changed = o != hover; |
| 1691 | hover = o; |
| 1692 | hoverBtn = b; |
| 1693 | Invalidate(); |
| 1694 | if (changed && HoverChanged != null) HoverChanged(o); |
| 1695 | } |
| 1696 | } |
| 1697 | |
| 1698 | protected override void OnMouseUp(MouseEventArgs e) |
| 1699 | { |
| 1700 | if (dragging != null) { dragging = null; Capture = false; Invalidate(); } |
| 1701 | } |
| 1702 | |
| 1703 | protected override void OnMouseLeave(EventArgs e) |
| 1704 | { |
| 1705 | if (hover != null || hoverBtn != null) |
| 1706 | { |
| 1707 | hover = null; |
| 1708 | hoverBtn = null; |
| 1709 | Invalidate(); |
| 1710 | if (HoverChanged != null) HoverChanged(null); |
| 1711 | } |
| 1712 | } |
| 1713 | |
| 1714 | protected override void OnMouseWheel(MouseEventArgs e) |
| 1715 | { |
| 1716 | scroll -= e.Delta / 120 * RowH * 2; |
| 1717 | scroll = Math.Max(0, Math.Min(scroll, Math.Max(0, contentH - Height))); |
| 1718 | Invalidate(); |
| 1719 | } |
| 1720 | } |
| 1721 | |
| 1722 | internal class SpawnerPanel : Control |
| 1723 | { |
| 1724 | public readonly TextBox Search = new TextBox(); |
| 1725 | public readonly ListBox List = new ListBox(); |
| 1726 | public int Amount = 1; |
| 1727 | public event Action<string, int> Spawn; |
| 1728 | public event Action ListsChanged; |
| 1729 | public readonly HashSet<string> Favs = new HashSet<string>(); |
| 1730 | public readonly List<string> Recent = new List<string>(); |
| 1731 | private readonly HashSet<string> recentRows = new HashSet<string>(); |
| 1732 | private readonly List<KeyValuePair<string, string>> items = new List<KeyValuePair<string, string>>(); |
| 1733 | private string status = "Attach to the game to load the item list."; |
| 1734 | private readonly int[] amounts = { 1, 5, 10 }; |
| 1735 | private readonly Rectangle[] chips = new Rectangle[3]; |
| 1736 | private readonly Font headFont = Theme.F("Segoe UI Semibold", 8f); |
| 1737 | private readonly Font smallFont = Theme.F("Segoe UI", 8.5f); |
| 1738 | private readonly Font itemFont = Theme.F("Segoe UI", 9.5f); |
| 1739 | private readonly Font idFont = Theme.F("Consolas", 8f); |
| 1740 | |
| 1741 | public SpawnerPanel() |
| 1742 | { |
| 1743 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); |
| 1744 | BackColor = Theme.Back; |
| 1745 | Search.BorderStyle = BorderStyle.FixedSingle; |
| 1746 | Search.BackColor = Theme.Panel; |
| 1747 | Search.ForeColor = Theme.Text; |
| 1748 | Search.Font = Theme.F("Segoe UI", 10f); |
| 1749 | Search.TextChanged += delegate { Filter(); }; |
| 1750 | Search.KeyDown += delegate (object s, KeyEventArgs e) |
| 1751 | { |
| 1752 | if (e.KeyCode == Keys.Down && List.Items.Count > 0) { List.Focus(); if (List.SelectedIndex < 0) List.SelectedIndex = 0; e.Handled = true; } |
| 1753 | else if (e.KeyCode == Keys.Enter) { SpawnMany(); e.Handled = true; e.SuppressKeyPress = true; } |
| 1754 | }; |
| 1755 | List.DrawMode = DrawMode.OwnerDrawFixed; |
| 1756 | List.BorderStyle = BorderStyle.None; |
| 1757 | List.BackColor = Theme.Back; |
| 1758 | List.ForeColor = Theme.Text; |
| 1759 | List.IntegralHeight = false; |
| 1760 | List.ItemHeight = Theme.S(26); |
| 1761 | List.DrawItem += DrawItem; |
| 1762 | List.SelectionMode = SelectionMode.MultiExtended; |
| 1763 | List.MouseClick += delegate (object s, MouseEventArgs e) |
| 1764 | { |
| 1765 | int i = List.IndexFromPoint(e.Location); |
| 1766 | if (i < 0 || (Control.ModifierKeys & (Keys.Control | Keys.Shift)) != 0) { Invalidate(); return; } |
| 1767 | SpawnSelected(i); |
| 1768 | }; |
| 1769 | List.MouseUp += delegate (object s, MouseEventArgs e) |
| 1770 | { |
| 1771 | if (e.Button != MouseButtons.Right) return; |
| 1772 | int i = List.IndexFromPoint(e.Location); |
| 1773 | if (i < 0) return; |
| 1774 | KeyValuePair<string, string> kv = (KeyValuePair<string, string>)List.Items[i]; |
| 1775 | if (!Favs.Remove(kv.Key)) Favs.Add(kv.Key); |
| 1776 | if (ListsChanged != null) ListsChanged(); |
| 1777 | Filter(); |
| 1778 | }; |
| 1779 | List.KeyDown += delegate (object s, KeyEventArgs e) |
| 1780 | { |
| 1781 | if (e.KeyCode == Keys.Enter) { SpawnMany(); e.Handled = true; e.SuppressKeyPress = true; } |
| 1782 | }; |
| 1783 | List.MouseMove += delegate (object s, MouseEventArgs e) |
| 1784 | { |
| 1785 | int i = List.IndexFromPoint(e.Location); |
| 1786 | if (i != hot) { hot = i; List.Invalidate(); } |
| 1787 | List.Cursor = i >= 0 ? Cursors.Hand : Cursors.Default; |
| 1788 | }; |
| 1789 | List.MouseLeave += delegate { hot = -1; List.Invalidate(); }; |
| 1790 | Controls.Add(Search); |
| 1791 | Controls.Add(List); |
| 1792 | Search.HandleCreated += delegate { Native.SendMessage(Search.Handle, 0x1501, (IntPtr)1, "Search items, e.g. bandage or pistol"); }; |
| 1793 | } |
| 1794 | |
| 1795 | private int hot = -1; |
| 1796 | |
| 1797 | public bool HasItems { get { return items.Count > 0; } } |
| 1798 | |
| 1799 | public void SetItems(List<KeyValuePair<string, string>> list) |
| 1800 | { |
| 1801 | items.Clear(); |
| 1802 | items.AddRange(list); |
| 1803 | items.Sort(delegate (KeyValuePair<string, string> a, KeyValuePair<string, string> b) { return string.Compare(a.Value, b.Value, StringComparison.OrdinalIgnoreCase); }); |
| 1804 | Filter(); |
| 1805 | } |
| 1806 | |
| 1807 | public void SetStatus(string s) |
| 1808 | { |
| 1809 | status = s; |
| 1810 | Invalidate(); |
| 1811 | } |
| 1812 | |
| 1813 | private void Filter() |
| 1814 | { |
| 1815 | string q = Search.Text.Trim(); |
| 1816 | List.BeginUpdate(); |
| 1817 | List.Items.Clear(); |
| 1818 | recentRows.Clear(); |
| 1819 | Dictionary<string, KeyValuePair<string, string>> byKey = new Dictionary<string, KeyValuePair<string, string>>(); |
| 1820 | foreach (KeyValuePair<string, string> kv in items) byKey[kv.Key] = kv; |
| 1821 | HashSet<string> used = new HashSet<string>(); |
| 1822 | if (q.Length == 0) |
| 1823 | { |
| 1824 | foreach (KeyValuePair<string, string> kv in items) if (Favs.Contains(kv.Key)) { List.Items.Add(kv); used.Add(kv.Key); } |
| 1825 | foreach (string r in Recent) |
| 1826 | { |
| 1827 | KeyValuePair<string, string> kv; |
| 1828 | if (used.Contains(r) || !byKey.TryGetValue(r, out kv)) continue; |
| 1829 | List.Items.Add(kv); used.Add(r); recentRows.Add(r); |
| 1830 | } |
| 1831 | } |
| 1832 | foreach (KeyValuePair<string, string> kv in items) |
| 1833 | if (!used.Contains(kv.Key) && (q.Length == 0 || kv.Value.IndexOf(q, StringComparison.OrdinalIgnoreCase) >= 0 || kv.Key.IndexOf(q, StringComparison.OrdinalIgnoreCase) >= 0)) |
| 1834 | List.Items.Add(kv); |
| 1835 | List.EndUpdate(); |
| 1836 | if (items.Count > 0) |
| 1837 | status = List.Items.Count == 0 ? "No items match." : List.Items.Count + " items. Click to spawn. Right-click to favorite. Ctrl+click several, then Enter to spawn them all."; |
| 1838 | Invalidate(); |
| 1839 | } |
| 1840 | |
| 1841 | public void NoteSpawn(string id) |
| 1842 | { |
| 1843 | Recent.Remove(id); |
| 1844 | Recent.Insert(0, id); |
| 1845 | if (Recent.Count > 12) Recent.RemoveRange(12, Recent.Count - 12); |
| 1846 | if (ListsChanged != null) ListsChanged(); |
| 1847 | } |
| 1848 | |
| 1849 | private void SpawnSelected(int i) |
| 1850 | { |
| 1851 | if (i < 0 || i >= List.Items.Count) return; |
| 1852 | KeyValuePair<string, string> kv = (KeyValuePair<string, string>)List.Items[i]; |
| 1853 | if (Spawn != null) Spawn(kv.Key, Amount); |
| 1854 | } |
| 1855 | |
| 1856 | private void SpawnMany() |
| 1857 | { |
| 1858 | if (List.SelectedIndices.Count <= 1) { SpawnSelected(List.SelectedIndex >= 0 ? List.SelectedIndex : 0); return; } |
| 1859 | List<string> ids = new List<string>(); |
| 1860 | foreach (int i in List.SelectedIndices) ids.Add(((KeyValuePair<string, string>)List.Items[i]).Key); |
| 1861 | foreach (string id in ids) if (Spawn != null) Spawn(id, Amount); |
| 1862 | } |
| 1863 | |
| 1864 | private void DrawItem(object sender, DrawItemEventArgs e) |
| 1865 | { |
| 1866 | if (e.Index < 0) return; |
| 1867 | KeyValuePair<string, string> kv = (KeyValuePair<string, string>)List.Items[e.Index]; |
| 1868 | bool sel = (e.State & DrawItemState.Selected) != 0; |
| 1869 | Color bg = sel ? Theme.Panel : e.Index == hot ? Theme.Hover : Theme.Back; |
| 1870 | using (SolidBrush b = new SolidBrush(bg)) e.Graphics.FillRectangle(b, e.Bounds); |
| 1871 | if (sel) using (SolidBrush b = new SolidBrush(Theme.Orange)) e.Graphics.FillRectangle(b, e.Bounds.X, e.Bounds.Y, Theme.S(2), e.Bounds.Height); |
| 1872 | e.Graphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 1873 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; mid.Trimming = StringTrimming.EllipsisCharacter; |
| 1874 | StringFormat right = new StringFormat(mid); right.Alignment = StringAlignment.Far; |
| 1875 | Rectangle r = new Rectangle(e.Bounds.X + Theme.S(10), e.Bounds.Y, e.Bounds.Width - Theme.S(20), e.Bounds.Height); |
| 1876 | int sw = Theme.S(18); |
| 1877 | bool fav = Favs.Contains(kv.Key); |
| 1878 | using (SolidBrush t = new SolidBrush(fav ? Theme.Orange : Theme.Dim)) |
| 1879 | e.Graphics.DrawString(fav ? "\u2605" : recentRows.Contains(kv.Key) ? "\u21BA" : "", itemFont, t, new RectangleF(r.X, r.Y, sw, r.Height), mid); |
| 1880 | using (SolidBrush t = new SolidBrush(Theme.Text)) e.Graphics.DrawString(kv.Value, itemFont, t, new RectangleF(r.X + sw, r.Y, r.Width * 0.62f - sw, r.Height), mid); |
| 1881 | using (SolidBrush t = new SolidBrush(Theme.Dim)) e.Graphics.DrawString(kv.Key, idFont, t, r, right); |
| 1882 | } |
| 1883 | |
| 1884 | protected override void OnResize(EventArgs e) |
| 1885 | { |
| 1886 | base.OnResize(e); |
| 1887 | int top = Theme.S(42); |
| 1888 | int chipW = Theme.S(44), chipGap = Theme.S(5); |
| 1889 | int chipsW = chipW * 3 + chipGap * 2; |
| 1890 | Search.Bounds = new Rectangle(0, top, Width - chipsW - Theme.S(14), Search.PreferredHeight); |
| 1891 | int cx = Width - chipsW - 1; |
| 1892 | for (int i = 0; i < 3; i++) chips[i] = new Rectangle(cx + i * (chipW + chipGap), top, chipW, Search.PreferredHeight); |
| 1893 | int ly = top + Search.PreferredHeight + Theme.S(10); |
| 1894 | List.Bounds = new Rectangle(0, ly, Width, Math.Max(Theme.S(40), Height - ly - Theme.S(26))); |
| 1895 | } |
| 1896 | |
| 1897 | protected override void OnMouseDown(MouseEventArgs e) |
| 1898 | { |
| 1899 | for (int i = 0; i < 3; i++) |
| 1900 | if (chips[i].Contains(e.Location)) { Amount = amounts[i]; Invalidate(); } |
| 1901 | } |
| 1902 | |
| 1903 | protected override void OnMouseMove(MouseEventArgs e) |
| 1904 | { |
| 1905 | bool over = false; |
| 1906 | for (int i = 0; i < 3; i++) if (chips[i].Contains(e.Location)) over = true; |
| 1907 | Cursor = over ? Cursors.Hand : Cursors.Default; |
| 1908 | } |
| 1909 | |
| 1910 | protected override void OnPaint(PaintEventArgs e) |
| 1911 | { |
| 1912 | Graphics g = e.Graphics; |
| 1913 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 1914 | Theme.PaintBack(g, this); |
| 1915 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; mid.Trimming = StringTrimming.EllipsisCharacter; |
| 1916 | StringFormat center = new StringFormat(mid); center.Alignment = StringAlignment.Center; |
| 1917 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 1918 | g.DrawString(Theme.Spaced("SPAWN ITEM"), headFont, orange, new RectangleF(0, Theme.S(6), Width, Theme.S(22)), mid); |
| 1919 | using (Pen line = new Pen(Theme.Line)) g.DrawLine(line, 0, Theme.S(29), Width, Theme.S(29)); |
| 1920 | for (int i = 0; i < 3; i++) |
| 1921 | { |
| 1922 | bool sel = amounts[i] == Amount; |
| 1923 | using (SolidBrush b = new SolidBrush(sel ? Theme.Panel : Theme.Back)) g.FillRectangle(b, chips[i]); |
| 1924 | using (Pen p = new Pen(sel ? Theme.Orange : Theme.Edge)) g.DrawRectangle(p, chips[i]); |
| 1925 | using (SolidBrush b = new SolidBrush(sel ? Theme.Orange : Theme.Dim)) g.DrawString("x" + amounts[i], smallFont, b, chips[i], center); |
| 1926 | } |
| 1927 | using (SolidBrush d = new SolidBrush(Theme.Dim)) |
| 1928 | g.DrawString(status, smallFont, d, new RectangleF(0, Height - Theme.S(22), Width, Theme.S(20)), mid); |
| 1929 | } |
| 1930 | } |
| 1931 | |
| 1932 | internal class OverlayForm : Form |
| 1933 | { |
| 1934 | private static readonly Color Key = Color.FromArgb(255, 0, 255); |
| 1935 | public List<Option> Options; |
| 1936 | public bool ShowPanel = true; |
| 1937 | private string toast; |
| 1938 | private bool toastGood = true; |
| 1939 | private DateTime toastUntil; |
| 1940 | private readonly Font title = Theme.F("Segoe UI Semibold", 8.5f); |
| 1941 | private readonly Font row = Theme.F("Segoe UI", 9f); |
| 1942 | private readonly Font keyF = Theme.F("Consolas", 8.5f); |
| 1943 | private readonly Font toastF = Theme.F("Segoe UI Semibold", 10f); |
| 1944 | private readonly Image tile = Res.Image("tile.png"); |
| 1945 | |
| 1946 | public OverlayForm() |
| 1947 | { |
| 1948 | FormBorderStyle = FormBorderStyle.None; |
| 1949 | ShowInTaskbar = false; |
| 1950 | StartPosition = FormStartPosition.Manual; |
| 1951 | TopMost = true; |
| 1952 | BackColor = Key; |
| 1953 | TransparencyKey = Key; |
| 1954 | Opacity = Theme.OverlayOpacity / 100.0; |
| 1955 | DoubleBuffered = true; |
| 1956 | } |
| 1957 | |
| 1958 | protected override bool ShowWithoutActivation { get { return true; } } |
| 1959 | |
| 1960 | protected override CreateParams CreateParams |
| 1961 | { |
| 1962 | get |
| 1963 | { |
| 1964 | CreateParams cp = base.CreateParams; |
| 1965 | cp.ExStyle |= 0x20 | 0x80 | 0x80000 | 0x08000000 | 0x8; |
| 1966 | return cp; |
| 1967 | } |
| 1968 | } |
| 1969 | |
| 1970 | public void Toast(string text, bool good) |
| 1971 | { |
| 1972 | toast = text; |
| 1973 | toastGood = good; |
| 1974 | toastUntil = DateTime.UtcNow.AddSeconds(1.8); |
| 1975 | Invalidate(); |
| 1976 | } |
| 1977 | |
| 1978 | public bool ToastActive { get { return toast != null && DateTime.UtcNow < toastUntil; } } |
| 1979 | |
| 1980 | public Func<Option, string> Suffix; |
| 1981 | private List<KeyValuePair<string, string>> watch = new List<KeyValuePair<string, string>>(); |
| 1982 | private int watchAlerts; |
| 1983 | |
| 1984 | public bool SetWatch(List<KeyValuePair<string, string>> rows, int alerts) |
| 1985 | { |
| 1986 | bool same = rows.Count == watch.Count && alerts == watchAlerts; |
| 1987 | if (same) for (int i = 0; i < rows.Count; i++) if (rows[i].Key != watch[i].Key || rows[i].Value != watch[i].Value) { same = false; break; } |
| 1988 | watch = rows; |
| 1989 | watchAlerts = alerts; |
| 1990 | return !same; |
| 1991 | } |
| 1992 | |
| 1993 | protected override void OnPaint(PaintEventArgs e) |
| 1994 | { |
| 1995 | Graphics g = e.Graphics; |
| 1996 | g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; |
| 1997 | g.Clear(Key); |
| 1998 | if (ShowPanel && Options != null) DrawPanel(g); |
| 1999 | if (ToastActive) DrawToast(g); |
| 2000 | } |
| 2001 | |
| 2002 | private void DrawPanel(Graphics g) |
| 2003 | { |
| 2004 | List<Option> shown = new List<Option>(); |
| 2005 | Option ov = null; |
| 2006 | foreach (Option o in Options) |
| 2007 | { |
| 2008 | if (o.Id == "overlay") { ov = o; continue; } |
| 2009 | if (o.Bindable && o.Key != Keys.None) shown.Add(o); |
| 2010 | } |
| 2011 | float k = Theme.OverlaySize / 100f; |
| 2012 | GraphicsState gs = g.Save(); |
| 2013 | g.ScaleTransform(k, k); |
| 2014 | int cw = (int)(ClientSize.Width / k), ch = (int)(ClientSize.Height / k); |
| 2015 | int pad = Theme.S(10), rh = Theme.S(19), kw = Theme.S(70); |
| 2016 | int w = Theme.S(270); |
| 2017 | int h = pad + Theme.S(22) + shown.Count * rh + (watch.Count > 0 ? Theme.S(6) + watch.Count * rh : 0) + Theme.S(22) + pad; |
| 2018 | int x = Theme.S(14), y = Theme.S(14); |
| 2019 | if (Theme.OverlayCorner.EndsWith("right", StringComparison.Ordinal)) x = cw - w - Theme.S(14); |
| 2020 | if (Theme.OverlayCorner.StartsWith("bottom", StringComparison.Ordinal)) y = ch - h - Theme.S(14); |
| 2021 | using (SolidBrush bg = new SolidBrush(Theme.Side)) |
| 2022 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 2023 | using (SolidBrush text = new SolidBrush(Theme.Text)) |
| 2024 | using (SolidBrush dim = new SolidBrush(Theme.Dim)) |
| 2025 | using (SolidBrush on = new SolidBrush(Theme.On)) |
| 2026 | using (Pen edge = new Pen(Theme.Scroll)) |
| 2027 | { |
| 2028 | g.FillRectangle(bg, x, y, w, h); |
| 2029 | g.DrawRectangle(edge, x, y, w - 1, h - 1); |
| 2030 | g.FillRectangle(orange, x, y, Theme.S(3), h); |
| 2031 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; mid.Trimming = StringTrimming.EllipsisCharacter; |
| 2032 | StringFormat right = new StringFormat(mid); right.Alignment = StringAlignment.Far; |
| 2033 | int tx = x + pad; |
| 2034 | if (tile != null) |
| 2035 | { |
| 2036 | int ts = Theme.S(16); |
| 2037 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 2038 | g.DrawImage(tile, tx, y + pad, ts, ts); |
| 2039 | tx += ts + Theme.S(6); |
| 2040 | } |
| 2041 | g.DrawString("ULTRA PARADISE CU:TRAINER", title, orange, new RectangleF(tx, y + pad - Theme.S(1), w, Theme.S(18)), mid); |
| 2042 | int ry = y + pad + Theme.S(22); |
| 2043 | foreach (Option o in shown) |
| 2044 | { |
| 2045 | g.DrawString(KeyText.Of(o.Key), keyF, dim, new RectangleF(x + pad, ry, kw, rh), mid); |
| 2046 | g.DrawString(o.Name, row, text, new RectangleF(x + pad + kw, ry, w - pad * 2 - kw - Theme.S(30), rh), mid); |
| 2047 | string suf = Suffix != null ? Suffix(o) : null; |
| 2048 | if (o.Kind == Kind.Toggle && o.On) g.DrawString(suf != null ? suf : "ON", row, on, new RectangleF(x, ry, w - pad, rh), right); |
| 2049 | ry += rh; |
| 2050 | } |
| 2051 | if (watch.Count > 0) |
| 2052 | { |
| 2053 | ry += Theme.S(6); |
| 2054 | foreach (KeyValuePair<string, string> wv in watch) |
| 2055 | { |
| 2056 | g.DrawString(wv.Key, row, dim, new RectangleF(x + pad, ry, w - pad * 2 - Theme.S(80), rh), mid); |
| 2057 | g.DrawString(wv.Value, row, watchAlerts > 0 ? orange : text, new RectangleF(x, ry, w - pad, rh), right); |
| 2058 | ry += rh; |
| 2059 | } |
| 2060 | } |
| 2061 | string foot = ov != null && ov.Key != Keys.None ? KeyText.Of(ov.Key) + " hides this" : ""; |
| 2062 | g.DrawString(foot, keyF, dim, new RectangleF(x + pad, ry + Theme.S(2), w, Theme.S(18)), mid); |
| 2063 | } |
| 2064 | g.Restore(gs); |
| 2065 | } |
| 2066 | |
| 2067 | private void DrawToast(Graphics g) |
| 2068 | { |
| 2069 | using (SolidBrush bg = new SolidBrush(Theme.Side)) |
| 2070 | using (SolidBrush text = new SolidBrush(Theme.Text)) |
| 2071 | using (SolidBrush bar = new SolidBrush(toastGood ? Theme.Orange : Theme.Bad)) |
| 2072 | { |
| 2073 | SizeF sz = g.MeasureString(toast, toastF); |
| 2074 | int w = (int)sz.Width + Theme.S(34), h = Theme.S(34); |
| 2075 | int x = (ClientSize.Width - w) / 2, y = Theme.S(18); |
| 2076 | g.FillRectangle(bg, x, y, w, h); |
| 2077 | g.FillRectangle(bar, x, y, Theme.S(4), h); |
| 2078 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.Alignment = StringAlignment.Center; |
| 2079 | g.DrawString(toast, toastF, text, new RectangleF(x + Theme.S(4), y, w - Theme.S(4), h), mid); |
| 2080 | } |
| 2081 | } |
| 2082 | } |
| 2083 | |
| 2084 | internal class Fix |
| 2085 | { |
| 2086 | public string Label, Act; |
| 2087 | public Option Opt; |
| 2088 | } |
| 2089 | |
| 2090 | internal class Issue |
| 2091 | { |
| 2092 | public string Title, Detail; |
| 2093 | public bool Danger; |
| 2094 | public readonly List<Fix> Fixes = new List<Fix>(); |
| 2095 | } |
| 2096 | |
| 2097 | internal static class Advisor |
| 2098 | { |
| 2099 | public static float F(Dictionary<string, string> d, string k, float def) |
| 2100 | { |
| 2101 | string v; |
| 2102 | float f; |
| 2103 | return d != null && d.TryGetValue(k, out v) && float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out f) ? f : def; |
| 2104 | } |
| 2105 | |
| 2106 | private static void Add(List<Issue> list, Dictionary<string, Option> byId, bool danger, string title, string detail, params string[] fixes) |
| 2107 | { |
| 2108 | Issue i = new Issue(); |
| 2109 | i.Danger = danger; |
| 2110 | i.Title = title; |
| 2111 | i.Detail = detail; |
| 2112 | foreach (string f in fixes) |
| 2113 | { |
| 2114 | Fix x = new Fix(); |
| 2115 | if (f.StartsWith("act:", StringComparison.Ordinal)) |
| 2116 | { |
| 2117 | string[] p = f.Substring(4).Split('|'); |
| 2118 | x.Act = p[0]; |
| 2119 | x.Label = p.Length > 1 ? p[1] : p[0]; |
| 2120 | } |
| 2121 | else |
| 2122 | { |
| 2123 | Option o; |
| 2124 | if (!byId.TryGetValue(f, out o)) continue; |
| 2125 | x.Opt = o; |
| 2126 | x.Label = o.Name; |
| 2127 | } |
| 2128 | i.Fixes.Add(x); |
| 2129 | } |
| 2130 | list.Add(i); |
| 2131 | } |
| 2132 | |
| 2133 | public static List<Issue> Check(Dictionary<string, string> d, Dictionary<string, Option> byId) |
| 2134 | { |
| 2135 | List<Issue> list = new List<Issue>(); |
| 2136 | if (d == null) return list; |
| 2137 | CultureInfo ci = CultureInfo.InvariantCulture; |
| 2138 | if (F(d, "alive", 1) < 0.5f) |
| 2139 | { |
| 2140 | Add(list, byId, true, "Your character is dead", "Nothing can save this run now."); |
| 2141 | return list; |
| 2142 | } |
| 2143 | if (F(d, "arrest", 0) > 0.5f) Add(list, byId, true, "Your heart has stopped", "Cardiac arrest. Heal right away or you won't come back.", "heal", "GodMode"); |
| 2144 | else if (F(d, "crit", 0) > 0.5f) Add(list, byId, true, "You're dying", "Your body is failing. Heal now, and God Mode keeps you alive.", "heal", "GodMode"); |
| 2145 | |
| 2146 | float bleed = F(d, "bleed", 0); |
| 2147 | if (bleed > 0.01f) Add(list, byId, bleed > 0.25f, bleed > 0.25f ? "Bleeding badly" : "Bleeding", "Losing " + bleed.ToString("0.00", ci) + " litres of blood a minute.", "NoBleeding", "heal"); |
| 2148 | float blood = F(d, "blood", 100); |
| 2149 | if (blood < 70f) Add(list, byId, blood < 45f, "Low blood", "Blood is at " + blood.ToString("0", ci) + "%. Under 25% gets very dangerous.", "heal", "FasterHealing"); |
| 2150 | float oxy = F(d, "oxy", 100); |
| 2151 | if (oxy < 85f) Add(list, byId, oxy < 70f, "Low oxygen", "Blood oxygen is at " + oxy.ToString("0", ci) + "%.", "UnlimitedOxygen", "heal"); |
| 2152 | float brain = F(d, "brain", 100); |
| 2153 | if (brain < 80f) Add(list, byId, brain < 50f, "Brain damage", "Brain health is " + brain.ToString("0", ci) + ". At 0 you die.", "heal", "GodMode"); |
| 2154 | float consc = F(d, "consc", 100); |
| 2155 | if (consc < 60f) Add(list, byId, consc < 40f, "Losing consciousness", "Consciousness is at " + consc.ToString("0", ci) + "%.", "heal", "NoPain"); |
| 2156 | float pain = F(d, "pain", 0); |
| 2157 | if (pain > 50f) Add(list, byId, pain > 75f, "In a lot of pain", "Pain is at " + pain.ToString("0", ci) + "%. It knocks you out and drags your mood down.", "NoPain"); |
| 2158 | float temp = F(d, "temp", 37); |
| 2159 | if (temp < 34f || temp > 39.5f) |
| 2160 | { |
| 2161 | bool cold = temp < 34f; |
| 2162 | Add(list, byId, temp < 30f || temp > 41f, cold ? "Too cold" : "Overheating", "Body temperature is " + temp.ToString("0.0", ci) + " °C.", "StableTemperature"); |
| 2163 | } |
| 2164 | float hunger = F(d, "hunger", 100); |
| 2165 | if (hunger < 25f) Add(list, byId, hunger < 10f, "Starving", "Hunger is at " + hunger.ToString("0", ci) + ".", "NoHunger"); |
| 2166 | float thirst = F(d, "thirst", 100); |
| 2167 | if (thirst < 25f) Add(list, byId, thirst < 10f, "Dehydrated", "Thirst is at " + thirst.ToString("0", ci) + ".", "NoThirst"); |
| 2168 | float energy = F(d, "energy", 100); |
| 2169 | if (energy < 20f) Add(list, byId, energy < 5f, "Exhausted", "Energy is at " + energy.ToString("0", ci) + "%.", "NoTiredness"); |
| 2170 | float infect = F(d, "infect", 0); |
| 2171 | if (infect >= 25f) Add(list, byId, infect >= 60f, "Infected wound", "Worst infection is at " + infect.ToString("0", ci) + ".", "NoInfection", "heal"); |
| 2172 | float sick = F(d, "sick", 0); |
| 2173 | if (sick > 40f) Add(list, byId, sick > 70f, "Sick", "Sickness is at " + sick.ToString("0", ci) + "%.", "NoSickness"); |
| 2174 | float venom = F(d, "venom", 0); |
| 2175 | if (venom > 0.5f) Add(list, byId, venom > 300f, "Poisoned", "Toxin at " + (venom * 0.1f).ToString("0.0", ci) + " ppm.", "NoSickness"); |
| 2176 | float rad = F(d, "rad", 0); |
| 2177 | if (rad > 3f) Add(list, byId, rad > 7.5f, "Radiation sickness", "Radiation dose is " + rad.ToString("0.0", ci) + " gy.", "NoRadiation"); |
| 2178 | int broken = (int)F(d, "broken", 0), disloc = (int)F(d, "disloc", 0), shrap = (int)F(d, "shrapnel", 0), missing = (int)F(d, "missing", 0); |
| 2179 | if (broken + disloc > 0) |
| 2180 | { |
| 2181 | List<string> parts = new List<string>(); |
| 2182 | if (broken > 0) parts.Add(broken + " broken"); |
| 2183 | if (disloc > 0) parts.Add(disloc + " dislocated"); |
| 2184 | Add(list, byId, false, "Injured limbs", string.Join(", ", parts.ToArray()) + ".", "heal"); |
| 2185 | } |
| 2186 | if (shrap > 0) Add(list, byId, false, "Shrapnel", shrap + " limb" + (shrap == 1 ? " has" : "s have") + " shrapnel in it.", "heal"); |
| 2187 | if (missing > 0) Add(list, byId, false, "Missing limbs", missing + " limb" + (missing == 1 ? " is" : "s are") + " gone.", "limbs"); |
| 2188 | float mood = F(d, "mood", 0); |
| 2189 | if (mood < -40f) Add(list, byId, mood <= -75f, "Very low mood", "Mood is " + mood.ToString("0", ci) + ". This low, your character may hurt themselves.", "act:moodmax|Max Mood", "MoodLock"); |
| 2190 | if (F(d, "radline", 0) > 0.5f) Add(list, byId, true, "The radiation line is here", "Get out of this layer or stop the line.", "PauseRadiation", "exit"); |
| 2191 | if (F(d, "enc", 0) > 0.5f) Add(list, byId, false, "Carrying too much", "Over-encumbered: slower, and tiring faster.", "UnlimitedCarry"); |
| 2192 | |
| 2193 | List<Issue> sorted = new List<Issue>(); |
| 2194 | foreach (Issue i in list) if (i.Danger) sorted.Add(i); |
| 2195 | foreach (Issue i in list) if (!i.Danger) sorted.Add(i); |
| 2196 | return sorted; |
| 2197 | } |
| 2198 | } |
| 2199 | |
| 2200 | internal class MoodleInfo |
| 2201 | { |
| 2202 | public string Bg = "", Icon = "", Name = "", Desc = ""; |
| 2203 | public bool Critical, Side; |
| 2204 | } |
| 2205 | |
| 2206 | internal class HealthPanel : Control |
| 2207 | { |
| 2208 | public event Action<Fix> FixClicked; |
| 2209 | public Dictionary<string, string> Vitals; |
| 2210 | public List<Issue> Issues = new List<Issue>(); |
| 2211 | public bool Linked; |
| 2212 | public List<MoodleInfo> Moodles = new List<MoodleInfo>(); |
| 2213 | public readonly Dictionary<string, Bitmap> Icons = new Dictionary<string, Bitmap>(); |
| 2214 | private readonly List<KeyValuePair<Rectangle, MoodleInfo>> moodleRects = new List<KeyValuePair<Rectangle, MoodleInfo>>(); |
| 2215 | private MoodleInfo hoverMoodle; |
| 2216 | private Point mouse; |
| 2217 | private readonly List<KeyValuePair<Rectangle, Fix>> chips = new List<KeyValuePair<Rectangle, Fix>>(); |
| 2218 | private Fix hover; |
| 2219 | private readonly Font headFont = Theme.F("Segoe UI Semibold", 8f); |
| 2220 | private readonly Font rowFont = Theme.F("Segoe UI", 9f); |
| 2221 | private readonly Font valFont = Theme.F("Segoe UI Semibold", 9f); |
| 2222 | private readonly Font titleFont = Theme.F("Segoe UI Semibold", 9.5f); |
| 2223 | private readonly Font smallFont = Theme.F("Segoe UI", 8.5f); |
| 2224 | private readonly Font keyFont = Theme.F("Consolas", 8f); |
| 2225 | |
| 2226 | public HealthPanel() |
| 2227 | { |
| 2228 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); |
| 2229 | BackColor = Theme.Back; |
| 2230 | } |
| 2231 | |
| 2232 | private int Pad { get { return Theme.S(18); } } |
| 2233 | private int Gap { get { return Theme.S(22); } } |
| 2234 | private int HeadH { get { return Theme.S(34); } } |
| 2235 | private int VitW { get { return Theme.S(280); } } |
| 2236 | |
| 2237 | public void Reset() |
| 2238 | { |
| 2239 | Vitals = null; |
| 2240 | Issues = new List<Issue>(); |
| 2241 | Moodles.Clear(); |
| 2242 | foreach (Bitmap b in Icons.Values) b.Dispose(); |
| 2243 | Icons.Clear(); |
| 2244 | hoverMoodle = null; |
| 2245 | Invalidate(); |
| 2246 | } |
| 2247 | |
| 2248 | public void SetMoodles(string rest) |
| 2249 | { |
| 2250 | List<MoodleInfo> list = new List<MoodleInfo>(); |
| 2251 | if (!string.IsNullOrEmpty(rest)) |
| 2252 | { |
| 2253 | foreach (string row in rest.Split('\u001e')) |
| 2254 | { |
| 2255 | string[] f = row.Split('\u001f'); |
| 2256 | if (f.Length < 6 || list.Count >= 60) continue; |
| 2257 | MoodleInfo m = new MoodleInfo(); |
| 2258 | m.Bg = f[0]; m.Icon = f[1]; m.Critical = f[2] == "1"; m.Side = f[3] == "1"; m.Name = f[4]; m.Desc = f[5]; |
| 2259 | list.Add(m); |
| 2260 | } |
| 2261 | } |
| 2262 | Moodles = list; |
| 2263 | if (hoverMoodle != null && !list.Exists(delegate (MoodleInfo m) { return m.Name == hoverMoodle.Name; })) hoverMoodle = null; |
| 2264 | if (Visible) Invalidate(); |
| 2265 | } |
| 2266 | |
| 2267 | public void AddIcon(string id, Bitmap b) |
| 2268 | { |
| 2269 | Bitmap old; |
| 2270 | if (Icons.TryGetValue(id, out old)) old.Dispose(); |
| 2271 | Icons[id] = b; |
| 2272 | if (Visible) Invalidate(); |
| 2273 | } |
| 2274 | |
| 2275 | private void Head(Graphics g, string title, int x, int w) |
| 2276 | { |
| 2277 | Head(g, title, x, w, 0); |
| 2278 | } |
| 2279 | |
| 2280 | private void Head(Graphics g, string title, int x, int w, int y0) |
| 2281 | { |
| 2282 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; |
| 2283 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 2284 | g.DrawString(Theme.Spaced(title), headFont, orange, new RectangleF(x, y0 + Theme.S(14), w, HeadH - Theme.S(12)), mid); |
| 2285 | using (Pen line = new Pen(Theme.Line)) g.DrawLine(line, x, y0 + Theme.S(6) + HeadH - Theme.S(5), x + w, y0 + Theme.S(6) + HeadH - Theme.S(5)); |
| 2286 | } |
| 2287 | |
| 2288 | protected override void OnPaint(PaintEventArgs e) |
| 2289 | { |
| 2290 | Graphics g = e.Graphics; |
| 2291 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 2292 | Theme.PaintBack(g, this); |
| 2293 | chips.Clear(); |
| 2294 | int top = Theme.S(6) + HeadH + Theme.S(4); |
| 2295 | |
| 2296 | int vx = Pad; |
| 2297 | Head(g, "VITALS", vx, VitW); |
| 2298 | DrawVitals(g, vx, top, VitW); |
| 2299 | |
| 2300 | int rx = vx + VitW + Gap; |
| 2301 | int rw = Width - rx - Pad; |
| 2302 | Head(g, "MOODLES", rx, rw); |
| 2303 | int after = DrawMoodles(g, rx, top, rw); |
| 2304 | int y1 = after + Theme.S(6); |
| 2305 | Head(g, "WHAT TO DO", rx, rw, y1); |
| 2306 | DrawAdvice(g, rx, y1 + top, rw); |
| 2307 | DrawTip(g); |
| 2308 | } |
| 2309 | |
| 2310 | private int MoodleSize { get { return Theme.S(46); } } |
| 2311 | |
| 2312 | private int DrawMoodles(Graphics g, int x, int y, int w) |
| 2313 | { |
| 2314 | moodleRects.Clear(); |
| 2315 | if (Moodles.Count == 0) |
| 2316 | { |
| 2317 | string msg = !Linked ? "Attach to the game to see your moodles." : Vitals == null ? "Start or load a run." : "No moodles right now."; |
| 2318 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(msg, smallFont, b, x, y + Theme.S(4)); |
| 2319 | return y + Theme.S(26); |
| 2320 | } |
| 2321 | int ms = MoodleSize, gap = Theme.S(6); |
| 2322 | int cx = x, cy = y + Theme.S(4); |
| 2323 | g.InterpolationMode = InterpolationMode.NearestNeighbor; |
| 2324 | g.PixelOffsetMode = PixelOffsetMode.Half; |
| 2325 | foreach (MoodleInfo m in Moodles) |
| 2326 | { |
| 2327 | if (cx + ms > x + w && cx > x) { cx = x; cy += ms + gap; } |
| 2328 | Rectangle r = new Rectangle(cx, cy, ms, ms); |
| 2329 | Bitmap bg = null, ic = null; |
| 2330 | if (m.Bg.Length > 0) Icons.TryGetValue(m.Bg, out bg); |
| 2331 | if (m.Icon.Length > 0) Icons.TryGetValue(m.Icon, out ic); |
| 2332 | float scale = bg != null ? ms / (float)Math.Max(bg.Width, bg.Height) : ic != null ? ms * 0.8f / Math.Max(ic.Width, ic.Height) : 1f; |
| 2333 | if (bg != null) |
| 2334 | { |
| 2335 | int bw = (int)(bg.Width * scale), bh = (int)(bg.Height * scale); |
| 2336 | g.DrawImage(bg, r.X + (ms - bw) / 2, r.Y + (ms - bh) / 2, bw, bh); |
| 2337 | } |
| 2338 | else |
| 2339 | { |
| 2340 | using (SolidBrush b = new SolidBrush(Theme.Panel)) g.FillRectangle(b, r); |
| 2341 | } |
| 2342 | if (ic != null) |
| 2343 | { |
| 2344 | int iw = (int)(ic.Width * scale), ih = (int)(ic.Height * scale); |
| 2345 | g.DrawImage(ic, r.X + (ms - iw) / 2, r.Y + (ms - ih) / 2, iw, ih); |
| 2346 | } |
| 2347 | if (m.Critical) |
| 2348 | using (Pen p = new Pen(Theme.Bad, Theme.S(2))) g.DrawRectangle(p, Rectangle.Inflate(r, Theme.S(1), Theme.S(1))); |
| 2349 | if (m == hoverMoodle) |
| 2350 | using (Pen p = new Pen(Theme.Orange)) g.DrawRectangle(p, Rectangle.Inflate(r, Theme.S(2), Theme.S(2))); |
| 2351 | moodleRects.Add(new KeyValuePair<Rectangle, MoodleInfo>(r, m)); |
| 2352 | cx += ms + gap; |
| 2353 | } |
| 2354 | g.InterpolationMode = InterpolationMode.Default; |
| 2355 | g.PixelOffsetMode = PixelOffsetMode.Default; |
| 2356 | return cy + ms + Theme.S(4); |
| 2357 | } |
| 2358 | |
| 2359 | private void DrawTip(Graphics g) |
| 2360 | { |
| 2361 | MoodleInfo m = hoverMoodle; |
| 2362 | if (m == null) return; |
| 2363 | int w = Theme.S(300); |
| 2364 | SizeF ns = g.MeasureString(m.Name, titleFont, w - Theme.S(16)); |
| 2365 | SizeF ds = m.Desc.Length > 0 ? g.MeasureString(m.Desc, smallFont, w - Theme.S(16)) : SizeF.Empty; |
| 2366 | int h = (int)Math.Ceiling(ns.Height + ds.Height) + Theme.S(18); |
| 2367 | int x = Math.Min(mouse.X + Theme.S(14), Width - w - Theme.S(6)); |
| 2368 | int y = mouse.Y + Theme.S(18); |
| 2369 | if (y + h > Height - Theme.S(4)) y = Math.Max(Theme.S(4), mouse.Y - h - Theme.S(8)); |
| 2370 | Rectangle r = new Rectangle(x, y, w, h); |
| 2371 | using (SolidBrush b = new SolidBrush(Theme.Sunk)) g.FillRectangle(b, r); |
| 2372 | using (Pen p = new Pen(m.Critical ? Theme.Bad : Theme.Edge)) g.DrawRectangle(p, r); |
| 2373 | using (SolidBrush b = new SolidBrush(m.Critical ? Theme.Bad : Theme.Text)) |
| 2374 | g.DrawString(m.Name, titleFont, b, new RectangleF(x + Theme.S(8), y + Theme.S(7), w - Theme.S(16), ns.Height + 2)); |
| 2375 | if (m.Desc.Length > 0) |
| 2376 | using (SolidBrush b = new SolidBrush(Theme.Dim)) |
| 2377 | g.DrawString(m.Desc, smallFont, b, new RectangleF(x + Theme.S(8), y + Theme.S(9) + ns.Height, w - Theme.S(16), ds.Height + 2)); |
| 2378 | } |
| 2379 | |
| 2380 | private void DrawVitals(Graphics g, int x, int y, int w) |
| 2381 | { |
| 2382 | Dictionary<string, string> d = Vitals; |
| 2383 | if (d == null) |
| 2384 | { |
| 2385 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(Linked ? "No run loaded." : "Not attached.", rowFont, b, x, y + Theme.S(4)); |
| 2386 | return; |
| 2387 | } |
| 2388 | CultureInfo ci = CultureInfo.InvariantCulture; |
| 2389 | Func<string, float, float> f = delegate (string k, float def) { return Advisor.F(d, k, def); }; |
| 2390 | List<object[]> rows = new List<object[]>(); |
| 2391 | bool arrest = f("arrest", 0) > 0.5f; |
| 2392 | rows.Add(new object[] { "Condition", f("alive", 1) < 0.5f ? "Dead" : arrest ? "Cardiac arrest" : f("crit", 0) > 0.5f ? "Critical" : "Stable", f("alive", 1) < 0.5f || arrest || f("crit", 0) > 0.5f }); |
| 2393 | rows.Add(new object[] { "Heart rate", f("hr", 0).ToString("0", ci) + " bpm", arrest }); |
| 2394 | rows.Add(new object[] { "Blood", f("blood", 100).ToString("0", ci) + "%", f("blood", 100) < 45f }); |
| 2395 | float bleed = f("bleed", 0); |
| 2396 | rows.Add(new object[] { "Bleeding", bleed > 0.001f ? bleed.ToString("0.00", ci) + " l/m" : "none", bleed > 0.25f }); |
| 2397 | rows.Add(new object[] { "Oxygen", f("oxy", 100).ToString("0", ci) + "%", f("oxy", 100) < 70f }); |
| 2398 | rows.Add(new object[] { "Brain", f("brain", 100).ToString("0", ci), f("brain", 100) < 50f }); |
| 2399 | rows.Add(new object[] { "Consciousness", f("consc", 100).ToString("0", ci) + "%", f("consc", 100) < 40f }); |
| 2400 | rows.Add(new object[] { "Pain", f("pain", 0).ToString("0", ci) + "%", f("pain", 0) > 75f }); |
| 2401 | float temp = f("temp", 37); |
| 2402 | rows.Add(new object[] { "Temperature", temp.ToString("0.0", ci) + " °C", temp < 30f || temp > 41f }); |
| 2403 | rows.Add(new object[] { "Hunger", f("hunger", 100).ToString("0", ci), f("hunger", 100) < 10f }); |
| 2404 | rows.Add(new object[] { "Thirst", f("thirst", 100).ToString("0", ci), f("thirst", 100) < 10f }); |
| 2405 | rows.Add(new object[] { "Energy", f("energy", 100).ToString("0", ci) + "%", f("energy", 100) < 5f }); |
| 2406 | rows.Add(new object[] { "Sickness", f("sick", 0).ToString("0", ci) + "%", f("sick", 0) > 70f }); |
| 2407 | rows.Add(new object[] { "Radiation", f("rad", 0).ToString("0.0", ci) + " gy", f("rad", 0) > 7.5f }); |
| 2408 | if (f("venom", 0) > 0.5f) rows.Add(new object[] { "Toxin", (f("venom", 0) * 0.1f).ToString("0.0", ci) + " ppm", f("venom", 0) > 300f }); |
| 2409 | rows.Add(new object[] { "Infection", f("infect", 0).ToString("0", ci), f("infect", 0) >= 25f }); |
| 2410 | int broken = (int)f("broken", 0), disloc = (int)f("disloc", 0), missing = (int)f("missing", 0); |
| 2411 | rows.Add(new object[] { "Limbs", broken + disloc + missing == 0 ? "fine" : (broken > 0 ? broken + " broken " : "") + (disloc > 0 ? disloc + " out " : "") + (missing > 0 ? missing + " missing" : ""), broken + disloc + missing > 0 }); |
| 2412 | rows.Add(new object[] { "Mood", f("mood", 0).ToString("0.0", ci), f("mood", 0) <= -75f }); |
| 2413 | |
| 2414 | int rh = Theme.S(23); |
| 2415 | StringFormat left = new StringFormat(); left.LineAlignment = StringAlignment.Center; |
| 2416 | StringFormat right = new StringFormat(left); right.Alignment = StringAlignment.Far; |
| 2417 | using (SolidBrush dim = new SolidBrush(Theme.Dim)) |
| 2418 | using (SolidBrush txt = new SolidBrush(Theme.Text)) |
| 2419 | using (SolidBrush bad = new SolidBrush(Theme.Bad)) |
| 2420 | using (Pen line = new Pen(Theme.Grid)) |
| 2421 | { |
| 2422 | foreach (object[] r in rows) |
| 2423 | { |
| 2424 | if (y + rh > Height - Theme.S(10)) break; |
| 2425 | RectangleF rf = new RectangleF(x, y, w, rh); |
| 2426 | g.DrawString((string)r[0], rowFont, dim, rf, left); |
| 2427 | g.DrawString((string)r[1], valFont, (bool)r[2] ? bad : txt, rf, right); |
| 2428 | g.DrawLine(line, x, y + rh - 1, x + w, y + rh - 1); |
| 2429 | y += rh; |
| 2430 | } |
| 2431 | } |
| 2432 | } |
| 2433 | |
| 2434 | private void DrawAdvice(Graphics g, int x, int y, int w) |
| 2435 | { |
| 2436 | if (Vitals == null) |
| 2437 | { |
| 2438 | using (SolidBrush b = new SolidBrush(Theme.Dim)) |
| 2439 | g.DrawString("Once you're in a run, anything going wrong with your body shows up here, with the cheats that fix it.", smallFont, b, new RectangleF(x, y + Theme.S(4), w, Theme.S(60))); |
| 2440 | return; |
| 2441 | } |
| 2442 | if (Issues.Count == 0) |
| 2443 | { |
| 2444 | using (SolidBrush b = new SolidBrush(Theme.On)) g.DrawString("All good. Nothing needs fixing right now.", titleFont, b, x, y + Theme.S(4)); |
| 2445 | return; |
| 2446 | } |
| 2447 | int chipH = Theme.S(24), chipGap = Theme.S(6); |
| 2448 | int shown = 0; |
| 2449 | foreach (Issue i in Issues) |
| 2450 | { |
| 2451 | int need = Theme.S(22) + Theme.S(18) + chipH + Theme.S(14); |
| 2452 | if (y + need > Height - Theme.S(30) && shown > 0) |
| 2453 | { |
| 2454 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString("+" + (Issues.Count - shown) + " more", smallFont, b, x, y); |
| 2455 | break; |
| 2456 | } |
| 2457 | shown++; |
| 2458 | using (SolidBrush bar = new SolidBrush(i.Danger ? Theme.Bad : Theme.Orange)) g.FillRectangle(bar, x, y + Theme.S(3), Theme.S(3), Theme.S(36)); |
| 2459 | int tx = x + Theme.S(12); |
| 2460 | using (SolidBrush b = new SolidBrush(i.Danger ? Theme.Bad : Theme.Text)) g.DrawString(i.Title, titleFont, b, tx, y); |
| 2461 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(i.Detail, smallFont, b, new RectangleF(tx, y + Theme.S(20), w - Theme.S(12), Theme.S(18)), NoWrap()); |
| 2462 | y += Theme.S(42); |
| 2463 | int cx = tx; |
| 2464 | bool any = false; |
| 2465 | foreach (Fix fx in i.Fixes) |
| 2466 | { |
| 2467 | bool on = fx.Opt != null && fx.Opt.Kind == Kind.Toggle && fx.Opt.On; |
| 2468 | string label = on ? fx.Label + " on" : fx.Label; |
| 2469 | string key = fx.Opt != null && fx.Opt.Key != Keys.None && !on ? KeyText.Of(fx.Opt.Key) : null; |
| 2470 | int lw = (int)Math.Ceiling(g.MeasureString(label, smallFont).Width); |
| 2471 | int kw = key != null ? (int)Math.Ceiling(g.MeasureString(key, keyFont).Width) + Theme.S(6) : 0; |
| 2472 | int cw = lw + kw + Theme.S(18); |
| 2473 | if (cx + cw > x + w && cx > tx) { cx = tx; y += chipH + chipGap; } |
| 2474 | Rectangle r = new Rectangle(cx, y, cw, chipH); |
| 2475 | Color fill = on ? Theme.OnFill : (hover == fx ? Theme.Hover : Theme.Panel); |
| 2476 | using (SolidBrush b = new SolidBrush(fill)) g.FillRectangle(b, r); |
| 2477 | using (Pen p = new Pen(on ? Theme.OnEdge : (hover == fx ? Theme.Orange : Theme.Edge))) g.DrawRectangle(p, r); |
| 2478 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; |
| 2479 | using (SolidBrush b = new SolidBrush(on ? Theme.On : Theme.Text)) |
| 2480 | g.DrawString(label, smallFont, b, new RectangleF(r.X + Theme.S(8), r.Y, lw + Theme.S(4), r.Height), mid); |
| 2481 | if (key != null) |
| 2482 | using (SolidBrush b = new SolidBrush(Theme.Dim)) |
| 2483 | g.DrawString(key, keyFont, b, new RectangleF(r.X + Theme.S(10) + lw, r.Y, kw, r.Height), mid); |
| 2484 | if (!on) chips.Add(new KeyValuePair<Rectangle, Fix>(r, fx)); |
| 2485 | cx += cw + chipGap; |
| 2486 | any = true; |
| 2487 | } |
| 2488 | if (any) y += chipH; |
| 2489 | y += Theme.S(14); |
| 2490 | } |
| 2491 | } |
| 2492 | |
| 2493 | private static StringFormat NoWrap() |
| 2494 | { |
| 2495 | StringFormat s = new StringFormat(); |
| 2496 | s.FormatFlags = StringFormatFlags.NoWrap; |
| 2497 | s.Trimming = StringTrimming.EllipsisCharacter; |
| 2498 | return s; |
| 2499 | } |
| 2500 | |
| 2501 | private Fix At(Point p) |
| 2502 | { |
| 2503 | foreach (KeyValuePair<Rectangle, Fix> c in chips) if (c.Key.Contains(p)) return c.Value; |
| 2504 | return null; |
| 2505 | } |
| 2506 | |
| 2507 | protected override void OnMouseMove(MouseEventArgs e) |
| 2508 | { |
| 2509 | Fix f = At(e.Location); |
| 2510 | if (f != hover) { hover = f; Invalidate(); } |
| 2511 | Cursor = f != null ? Cursors.Hand : Cursors.Default; |
| 2512 | MoodleInfo mo = null; |
| 2513 | foreach (KeyValuePair<Rectangle, MoodleInfo> kv in moodleRects) if (kv.Key.Contains(e.Location)) { mo = kv.Value; break; } |
| 2514 | if (mo != hoverMoodle || (mo != null && mouse != e.Location)) |
| 2515 | { |
| 2516 | hoverMoodle = mo; |
| 2517 | mouse = e.Location; |
| 2518 | Invalidate(); |
| 2519 | } |
| 2520 | } |
| 2521 | |
| 2522 | protected override void OnMouseLeave(EventArgs e) |
| 2523 | { |
| 2524 | if (hover != null || hoverMoodle != null) { hover = null; hoverMoodle = null; Invalidate(); } |
| 2525 | } |
| 2526 | |
| 2527 | protected override void OnMouseDown(MouseEventArgs e) |
| 2528 | { |
| 2529 | if (e.Button != MouseButtons.Left) return; |
| 2530 | Fix f = At(e.Location); |
| 2531 | if (f != null && FixClicked != null) FixClicked(f); |
| 2532 | } |
| 2533 | } |
| 2534 | |
| 2535 | internal class NexusMod |
| 2536 | { |
| 2537 | public int Id, Endorsements; |
| 2538 | public long Downloads; |
| 2539 | public string Name, Summary, Thumb; |
| 2540 | public DateTime Updated; |
| 2541 | public Bitmap Image; |
| 2542 | public bool Adult, Self; |
| 2543 | } |
| 2544 | |
| 2545 | internal static class Setup |
| 2546 | { |
| 2547 | private const string RegKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\UltraParadiseCUTrainer"; |
| 2548 | private const string ExeFile = "Ultra Paradise CU-Trainer.exe"; |
| 2549 | |
| 2550 | public static string Dir { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Programs"), "Ultra Paradise CU-Trainer"); } } |
| 2551 | public static string Exe { get { return Path.Combine(Dir, ExeFile); } } |
| 2552 | private static string StartLink { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), Program.Name.Replace(":", "-") + ".lnk"); } } |
| 2553 | private static string DesktopLink { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Program.Name.Replace(":", "-") + ".lnk"); } } |
| 2554 | |
| 2555 | public static bool RunningInstalled |
| 2556 | { |
| 2557 | get |
| 2558 | { |
| 2559 | try { return string.Equals(Path.GetFullPath(Application.ExecutablePath), Path.GetFullPath(Exe), StringComparison.OrdinalIgnoreCase); } |
| 2560 | catch (Exception) { return false; } |
| 2561 | } |
| 2562 | } |
| 2563 | |
| 2564 | public static string InstalledVersion() |
| 2565 | { |
| 2566 | try |
| 2567 | { |
| 2568 | if (!File.Exists(Exe)) return null; |
| 2569 | FileVersionInfo v = FileVersionInfo.GetVersionInfo(Exe); |
| 2570 | return v.FileMajorPart + "." + v.FileMinorPart + "." + v.FileBuildPart; |
| 2571 | } |
| 2572 | catch (Exception) { return null; } |
| 2573 | } |
| 2574 | |
| 2575 | public static string Status() |
| 2576 | { |
| 2577 | if (RunningInstalled) return "Installed on this PC (v" + Program.Version + ")."; |
| 2578 | string iv = InstalledVersion(); |
| 2579 | if (iv != null) return "v" + iv + " is installed on this PC. You're running a copy from somewhere else."; |
| 2580 | return "Not installed. Running from " + Path.GetDirectoryName(Application.ExecutablePath); |
| 2581 | } |
| 2582 | |
| 2583 | private static string Hash(string file) |
| 2584 | { |
| 2585 | using (System.Security.Cryptography.SHA256 h = System.Security.Cryptography.SHA256.Create()) |
| 2586 | using (FileStream fs = File.OpenRead(file)) |
| 2587 | return BitConverter.ToString(h.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); |
| 2588 | } |
| 2589 | |
| 2590 | public static string Install(bool desktop) |
| 2591 | { |
| 2592 | string me = Application.ExecutablePath; |
| 2593 | try |
| 2594 | { |
| 2595 | Directory.CreateDirectory(Dir); |
| 2596 | if (!RunningInstalled) |
| 2597 | { |
| 2598 | string tmp = Exe + ".new"; |
| 2599 | File.Copy(me, tmp, true); |
| 2600 | if (Hash(tmp) != Hash(me)) { File.Delete(tmp); return "the copy didn't match"; } |
| 2601 | if (File.Exists(Exe)) File.Delete(Exe); |
| 2602 | File.Move(tmp, Exe); |
| 2603 | foreach (string extra in new string[] { "README.txt", "THIRD-PARTY-NOTICES.txt" }) |
| 2604 | { |
| 2605 | string src = Path.Combine(Path.GetDirectoryName(me), extra); |
| 2606 | if (File.Exists(src)) File.Copy(src, Path.Combine(Dir, extra), true); |
| 2607 | } |
| 2608 | } |
| 2609 | } |
| 2610 | catch (Exception e) { return "couldn't copy the trainer: " + e.Message; } |
| 2611 | try |
| 2612 | { |
| 2613 | Shortcut(StartLink); |
| 2614 | if (desktop) Shortcut(DesktopLink); |
| 2615 | } |
| 2616 | catch (Exception) { } |
| 2617 | try { Register(); } catch (Exception e) { return "the trainer was copied, but Windows' app list couldn't be updated: " + e.Message; } |
| 2618 | return null; |
| 2619 | } |
| 2620 | |
| 2621 | public static void Register() |
| 2622 | { |
| 2623 | using (Microsoft.Win32.RegistryKey k = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RegKey)) |
| 2624 | { |
| 2625 | k.SetValue("DisplayName", Program.Name); |
| 2626 | k.SetValue("DisplayVersion", Program.Version); |
| 2627 | k.SetValue("Publisher", "casualexpie"); |
| 2628 | k.SetValue("DisplayIcon", Exe + ",0"); |
| 2629 | k.SetValue("InstallLocation", Dir); |
| 2630 | k.SetValue("UninstallString", "\"" + Exe + "\" --uninstall"); |
| 2631 | k.SetValue("URLInfoAbout", Nexus.ModUrl(Nexus.TrainerModId)); |
| 2632 | k.SetValue("NoModify", 1, Microsoft.Win32.RegistryValueKind.DWord); |
| 2633 | k.SetValue("NoRepair", 1, Microsoft.Win32.RegistryValueKind.DWord); |
| 2634 | long kb = 0; |
| 2635 | try { foreach (string f in Directory.GetFiles(Dir)) kb += new FileInfo(f).Length / 1024; } catch (Exception) { } |
| 2636 | k.SetValue("EstimatedSize", (int)kb, Microsoft.Win32.RegistryValueKind.DWord); |
| 2637 | k.SetValue("InstallDate", DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); |
| 2638 | } |
| 2639 | } |
| 2640 | |
| 2641 | public static void RefreshIfInstalled() |
| 2642 | { |
| 2643 | if (!RunningInstalled) return; |
| 2644 | try |
| 2645 | { |
| 2646 | using (Microsoft.Win32.RegistryKey k = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegKey, true)) |
| 2647 | if (k != null) k.SetValue("DisplayVersion", Program.Version); |
| 2648 | } |
| 2649 | catch (Exception) { } |
| 2650 | } |
| 2651 | |
| 2652 | private static void Shortcut(string path) |
| 2653 | { |
| 2654 | Type t = Type.GetTypeFromProgID("WScript.Shell"); |
| 2655 | if (t == null) return; |
| 2656 | object sh = Activator.CreateInstance(t); |
| 2657 | try |
| 2658 | { |
| 2659 | object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, sh, new object[] { path }); |
| 2660 | try |
| 2661 | { |
| 2662 | Type lt = lnk.GetType(); |
| 2663 | lt.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[] { Exe }); |
| 2664 | lt.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, lnk, new object[] { Dir }); |
| 2665 | lt.InvokeMember("Description", BindingFlags.SetProperty, null, lnk, new object[] { "Trainer for Casualties: Unknown" }); |
| 2666 | lt.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[] { Exe + ",0" }); |
| 2667 | lt.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null); |
| 2668 | } |
| 2669 | finally { Marshal.FinalReleaseComObject(lnk); } |
| 2670 | } |
| 2671 | finally { Marshal.FinalReleaseComObject(sh); } |
| 2672 | } |
| 2673 | |
| 2674 | public static void Launch(string arg) |
| 2675 | { |
| 2676 | ProcessStartInfo si = new ProcessStartInfo(Exe, arg); |
| 2677 | si.WorkingDirectory = Dir; |
| 2678 | si.UseShellExecute = false; |
| 2679 | Process.Start(si); |
| 2680 | } |
| 2681 | |
| 2682 | public static bool Uninstall() |
| 2683 | { |
| 2684 | if (MessageBox.Show("Uninstall " + Program.Name + " from this PC?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return false; |
| 2685 | bool wipe = MessageBox.Show("Also delete your trainer settings (your keys, sliders and remembered cheats)?\n\nNo keeps them, in case you install it again.", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; |
| 2686 | try { File.Delete(StartLink); } catch (Exception) { } |
| 2687 | try { File.Delete(DesktopLink); } catch (Exception) { } |
| 2688 | try { Microsoft.Win32.Registry.CurrentUser.DeleteSubKeyTree(RegKey, false); } catch (Exception) { } |
| 2689 | if (wipe) |
| 2690 | { |
| 2691 | try { Directory.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"), true); } catch (Exception) { } |
| 2692 | try { Directory.Delete(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), true); } catch (Exception) { } |
| 2693 | } |
| 2694 | string dir = Dir; |
| 2695 | if (Directory.Exists(dir)) |
| 2696 | { |
| 2697 | if (RunningInstalled) |
| 2698 | { |
| 2699 | ProcessStartInfo si = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe"), "/c ping -n 6 127.0.0.1 >nul & rmdir /s /q \"" + dir + "\""); |
| 2700 | si.CreateNoWindow = true; |
| 2701 | si.UseShellExecute = false; |
| 2702 | si.WorkingDirectory = Path.GetTempPath(); |
| 2703 | try { Process.Start(si); } catch (Exception) { } |
| 2704 | } |
| 2705 | else |
| 2706 | { |
| 2707 | try { Directory.Delete(dir, true); } catch (Exception) { } |
| 2708 | } |
| 2709 | } |
| 2710 | MessageBox.Show(Program.Name + " is uninstalled.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 2711 | return true; |
| 2712 | } |
| 2713 | } |
| 2714 | |
| 2715 | internal class UpdateInfo |
| 2716 | { |
| 2717 | public string Version, Sha, Notes; |
| 2718 | public long Size; |
| 2719 | public bool Required; |
| 2720 | public VtResult Vt; |
| 2721 | |
| 2722 | public bool VtClean { get { return Vt != null && Vt.Clean; } } |
| 2723 | public bool VtFlagged { get { return Vt != null && Vt.Status == "done" && Vt.Flagged > 0; } } |
| 2724 | public string VtLine { get { return Vt != null ? Vt.Line : "VirusTotal: couldn't get a result right now."; } } |
| 2725 | } |
| 2726 | |
| 2727 | internal class VtResult |
| 2728 | { |
| 2729 | public string Status = "unknown", Link, Sha; |
| 2730 | public int Flagged, Total, Malicious, Suspicious, Undetected, Harmless; |
| 2731 | public long Scanned; |
| 2732 | |
| 2733 | public string Detail |
| 2734 | { |
| 2735 | get |
| 2736 | { |
| 2737 | if (Status != "done") return "Engine breakdown: not ready yet."; |
| 2738 | return "Malicious " + Malicious + " · Suspicious " + Suspicious + " · Clean " + (Undetected + Harmless) + " · " + Total + " engines"; |
| 2739 | } |
| 2740 | } |
| 2741 | |
| 2742 | public bool Clean { get { return Status == "done" && Flagged == 0 && Total > 0; } } |
| 2743 | |
| 2744 | public string When |
| 2745 | { |
| 2746 | get |
| 2747 | { |
| 2748 | if (Scanned <= 0) return ""; |
| 2749 | DateTime t = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Scanned).ToLocalTime(); |
| 2750 | return " Scanned " + t.ToString("d MMM yyyy", CultureInfo.InvariantCulture) + "."; |
| 2751 | } |
| 2752 | } |
| 2753 | |
| 2754 | public string Line |
| 2755 | { |
| 2756 | get |
| 2757 | { |
| 2758 | switch (Status) |
| 2759 | { |
| 2760 | case "done": |
| 2761 | return "VirusTotal: " + Flagged + " of " + Total + " antivirus engines flagged it." + When; |
| 2762 | case "queued": |
| 2763 | return "VirusTotal: it's being scanned right now. The result shows up within about 30 minutes."; |
| 2764 | case "not_official": |
| 2765 | return "VirusTotal: this copy isn't an official release, so it has no report. Get the trainer from the official Nexus page."; |
| 2766 | default: |
| 2767 | return "VirusTotal: no result yet. The update server checks again every 30 minutes."; |
| 2768 | } |
| 2769 | } |
| 2770 | } |
| 2771 | } |
| 2772 | |
| 2773 | internal static class VirusTotal |
| 2774 | { |
| 2775 | private static readonly string Base = "https://updates.smellypawz.com"; |
| 2776 | public static string Status = "Not checked yet."; |
| 2777 | public static VtResult Self; |
| 2778 | private static string selfSha; |
| 2779 | |
| 2780 | public static string SelfSha |
| 2781 | { |
| 2782 | get |
| 2783 | { |
| 2784 | if (selfSha != null) return selfSha; |
| 2785 | using (System.Security.Cryptography.SHA256 h = System.Security.Cryptography.SHA256.Create()) |
| 2786 | using (FileStream fs = new FileStream(Application.ExecutablePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) |
| 2787 | { |
| 2788 | StringBuilder sb = new StringBuilder(); |
| 2789 | foreach (byte b in h.ComputeHash(fs)) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture)); |
| 2790 | selfSha = sb.ToString(); |
| 2791 | } |
| 2792 | return selfSha; |
| 2793 | } |
| 2794 | } |
| 2795 | |
| 2796 | private static string Field(string json, string key) |
| 2797 | { |
| 2798 | System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(json, "\"" + key + "\":(\"([^\"]*)\"|(-?\\d+)|null)"); |
| 2799 | if (!m.Success) return null; |
| 2800 | return m.Groups[2].Success ? m.Groups[2].Value : (m.Groups[3].Success ? m.Groups[3].Value : null); |
| 2801 | } |
| 2802 | |
| 2803 | private static int Num(string json, string key) |
| 2804 | { |
| 2805 | int n; |
| 2806 | string s = Field(json, key); |
| 2807 | return s != null && int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out n) ? n : 0; |
| 2808 | } |
| 2809 | |
| 2810 | public static VtResult Lookup(string sha) |
| 2811 | { |
| 2812 | if (sha == null || !System.Text.RegularExpressions.Regex.IsMatch(sha, "^[0-9a-f]{64}$")) return null; |
| 2813 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 2814 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Base + "/v1/vt?sha=" + sha); |
| 2815 | req.Method = "GET"; |
| 2816 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 2817 | req.Timeout = 20000; |
| 2818 | req.ReadWriteTimeout = 20000; |
| 2819 | req.AllowAutoRedirect = false; |
| 2820 | string json; |
| 2821 | using (WebResponse res = req.GetResponse()) |
| 2822 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 2823 | { |
| 2824 | char[] buf = new char[8192]; |
| 2825 | int n = r.ReadBlock(buf, 0, buf.Length); |
| 2826 | json = new string(buf, 0, n); |
| 2827 | } |
| 2828 | VtResult v = new VtResult(); |
| 2829 | v.Sha = sha; |
| 2830 | v.Status = Field(json, "status") ?? "unknown"; |
| 2831 | v.Flagged = Num(json, "malicious") + Num(json, "suspicious"); |
| 2832 | v.Total = Num(json, "total"); |
| 2833 | v.Malicious = Num(json, "malicious"); |
| 2834 | v.Suspicious = Num(json, "suspicious"); |
| 2835 | v.Undetected = Num(json, "undetected"); |
| 2836 | v.Harmless = Num(json, "harmless"); |
| 2837 | long sc; |
| 2838 | string s = Field(json, "scanned"); |
| 2839 | v.Scanned = s != null && long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out sc) ? sc : 0; |
| 2840 | v.Link = "https://www.virustotal.com/gui/file/" + sha; |
| 2841 | return v; |
| 2842 | } |
| 2843 | } |
| 2844 | |
| 2845 | internal static class Usage |
| 2846 | { |
| 2847 | private static readonly string Base = "https://updates.smellypawz.com"; |
| 2848 | public static string Status = "Not counted yet."; |
| 2849 | |
| 2850 | public static long Day { get { return (long)Math.Floor((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalDays); } } |
| 2851 | |
| 2852 | public static string NewId() |
| 2853 | { |
| 2854 | byte[] b = new byte[16]; |
| 2855 | using (System.Security.Cryptography.RandomNumberGenerator r = System.Security.Cryptography.RandomNumberGenerator.Create()) r.GetBytes(b); |
| 2856 | StringBuilder sb = new StringBuilder(); |
| 2857 | foreach (byte x in b) sb.Append(x.ToString("x2", CultureInfo.InvariantCulture)); |
| 2858 | return sb.ToString(); |
| 2859 | } |
| 2860 | |
| 2861 | public static bool ValidId(string id) |
| 2862 | { |
| 2863 | if (id == null || id.Length != 32) return false; |
| 2864 | foreach (char c in id) if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false; |
| 2865 | return true; |
| 2866 | } |
| 2867 | |
| 2868 | private static string Fetch(string path) |
| 2869 | { |
| 2870 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 2871 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Base + path); |
| 2872 | req.Method = "GET"; |
| 2873 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 2874 | req.Timeout = 10000; |
| 2875 | req.ReadWriteTimeout = 10000; |
| 2876 | req.AllowAutoRedirect = false; |
| 2877 | using (WebResponse res = req.GetResponse()) |
| 2878 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 2879 | { |
| 2880 | char[] buf = new char[8192]; |
| 2881 | int n = r.ReadBlock(buf, 0, buf.Length); |
| 2882 | return new string(buf, 0, n); |
| 2883 | } |
| 2884 | } |
| 2885 | |
| 2886 | public static bool Ping(string id) |
| 2887 | { |
| 2888 | if (!ValidId(id)) return false; |
| 2889 | return Fetch("/v1/ping?app=trainer&id=" + id + "&v=" + Program.Version + "&os=win").Contains("\"ok\":true"); |
| 2890 | } |
| 2891 | |
| 2892 | public static bool Forget(string id) |
| 2893 | { |
| 2894 | if (!ValidId(id)) return false; |
| 2895 | return Fetch("/v1/forget?app=trainer&id=" + id).Contains("\"ok\":true"); |
| 2896 | } |
| 2897 | |
| 2898 | public static string Board = "Loading..."; |
| 2899 | |
| 2900 | private static int Field(string s, string k) |
| 2901 | { |
| 2902 | System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, "\"" + k + "\":(\\d+)"); |
| 2903 | return m.Success ? int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) : 0; |
| 2904 | } |
| 2905 | |
| 2906 | public static string Stats() |
| 2907 | { |
| 2908 | string s = Fetch("/v1/users"); |
| 2909 | if (s.IndexOf("\"week\":", StringComparison.Ordinal) < 0) return null; |
| 2910 | int win = 0, lin = 0, mac = 0; |
| 2911 | int p = s.IndexOf("\"platforms30d\":", StringComparison.Ordinal); |
| 2912 | if (p >= 0) |
| 2913 | { |
| 2914 | int e = s.IndexOf('}', p); |
| 2915 | string ps = e > p ? s.Substring(p, e - p) : s.Substring(p); |
| 2916 | win = Field(ps, "win"); lin = Field(ps, "linux"); mac = Field(ps, "mac"); |
| 2917 | } |
| 2918 | string f = "N0"; |
| 2919 | CultureInfo c = CultureInfo.InvariantCulture; |
| 2920 | string r = "Today: " + Field(s, "today").ToString(f, c) + "\nThis week: " + Field(s, "week").ToString(f, c) + "\nThis month: " + Field(s, "month").ToString(f, c) + "\nLast 90 days: " + Field(s, "last90days").ToString(f, c); |
| 2921 | r += "\n\nLast 30 days: Windows " + win.ToString(f, c) + " · Linux / Steam Deck " + lin.ToString(f, c) + (mac > 0 ? " · macOS " + mac.ToString(f, c) : ""); |
| 2922 | return r; |
| 2923 | } |
| 2924 | |
| 2925 | public static string Count() |
| 2926 | { |
| 2927 | string s = Fetch("/v1/users"); |
| 2928 | System.Text.RegularExpressions.Match w = System.Text.RegularExpressions.Regex.Match(s, "\"week\":(\\d+)"); |
| 2929 | System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(s, "\"month\":(\\d+)"); |
| 2930 | if (!w.Success) return null; |
| 2931 | int week = int.Parse(w.Groups[1].Value, CultureInfo.InvariantCulture); |
| 2932 | int month = m.Success ? int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) : week; |
| 2933 | return week.ToString("N0", CultureInfo.InvariantCulture) + (week == 1 ? " person" : " people") + " used the trainer this week, " + month.ToString("N0", CultureInfo.InvariantCulture) + " this month."; |
| 2934 | } |
| 2935 | } |
| 2936 | |
| 2937 | internal static class Updater |
| 2938 | { |
| 2939 | private static readonly string Base = "https://updates.smellypawz.com"; |
| 2940 | private const long MaxBytes = 50L * 1024 * 1024; |
| 2941 | public static string Status = "Not checked yet."; |
| 2942 | public static UpdateInfo Ready; |
| 2943 | |
| 2944 | private static string Folder { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), "update"); } } |
| 2945 | |
| 2946 | public static int Compare(string a, string b) |
| 2947 | { |
| 2948 | string[] x = a.Split('.'), y = b.Split('.'); |
| 2949 | for (int i = 0; i < 3; i++) |
| 2950 | { |
| 2951 | int p = i < x.Length ? int.Parse(x[i], CultureInfo.InvariantCulture) : 0; |
| 2952 | int q = i < y.Length ? int.Parse(y[i], CultureInfo.InvariantCulture) : 0; |
| 2953 | if (p != q) return p.CompareTo(q); |
| 2954 | } |
| 2955 | return 0; |
| 2956 | } |
| 2957 | |
| 2958 | private static HttpWebRequest Get(string url) |
| 2959 | { |
| 2960 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 2961 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); |
| 2962 | req.Method = "GET"; |
| 2963 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 2964 | req.Timeout = 15000; |
| 2965 | req.ReadWriteTimeout = 30000; |
| 2966 | req.AllowAutoRedirect = false; |
| 2967 | return req; |
| 2968 | } |
| 2969 | |
| 2970 | public static UpdateInfo Check() |
| 2971 | { |
| 2972 | string json; |
| 2973 | using (WebResponse res = Get(Base + "/v1/latest?app=trainer&have=" + Program.Version).GetResponse()) |
| 2974 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 2975 | { |
| 2976 | char[] buf = new char[65536]; |
| 2977 | int n = r.ReadBlock(buf, 0, buf.Length); |
| 2978 | json = new string(buf, 0, n); |
| 2979 | } |
| 2980 | System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); |
| 2981 | Dictionary<string, object> d = js.DeserializeObject(json) as Dictionary<string, object>; |
| 2982 | if (d == null) throw new InvalidDataException("bad answer"); |
| 2983 | object v; |
| 2984 | string ver = d.TryGetValue("version", out v) && v != null ? v.ToString() : null; |
| 2985 | if (ver == null || !System.Text.RegularExpressions.Regex.IsMatch(ver, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$")) return null; |
| 2986 | if (Compare(ver, Program.Version) <= 0) return null; |
| 2987 | string sha = d.TryGetValue("sha256", out v) && v != null ? v.ToString().ToLowerInvariant() : null; |
| 2988 | if (sha == null || !System.Text.RegularExpressions.Regex.IsMatch(sha, "^[0-9a-f]{64}$")) return null; |
| 2989 | if (!d.TryGetValue("download", out v) || v == null) return null; |
| 2990 | UpdateInfo u = new UpdateInfo(); |
| 2991 | u.Version = ver; |
| 2992 | u.Sha = sha; |
| 2993 | u.Notes = d.TryGetValue("notes", out v) && v != null ? v.ToString() : ""; |
| 2994 | u.Notes = u.Notes.Replace("\\n", "\n").Replace("\r\n", "\n").Trim(); if (u.Notes.Length > 4000) u.Notes = u.Notes.Substring(0, 4000); |
| 2995 | try { u.Size = d.TryGetValue("size", out v) && v != null ? Convert.ToInt64(v, CultureInfo.InvariantCulture) : 0; } catch (Exception) { u.Size = 0; } |
| 2996 | if (u.Size <= 0 || u.Size > MaxBytes) return null; |
| 2997 | u.Required = d.TryGetValue("required", out v) && v is bool && (bool)v; |
| 2998 | try { u.Vt = VirusTotal.Lookup(u.Sha); } catch (Exception) { u.Vt = null; } |
| 2999 | return u; |
| 3000 | } |
| 3001 | |
| 3002 | private static string Fetch(UpdateInfo u, string part, Action<int> progress) |
| 3003 | { |
| 3004 | try |
| 3005 | { |
| 3006 | using (HttpWebResponse res = (HttpWebResponse)Get(Base + "/v1/download?app=trainer&version=" + u.Version).GetResponse()) |
| 3007 | { |
| 3008 | if (res.StatusCode != HttpStatusCode.OK) return "the update server said " + (int)res.StatusCode; |
| 3009 | using (Stream s = res.GetResponseStream()) |
| 3010 | using (FileStream fs = new FileStream(part, FileMode.Create, FileAccess.Write)) |
| 3011 | { |
| 3012 | byte[] buf = new byte[65536]; |
| 3013 | long total = 0; |
| 3014 | int n, last = -1; |
| 3015 | while ((n = s.Read(buf, 0, buf.Length)) > 0) |
| 3016 | { |
| 3017 | total += n; |
| 3018 | if (total > u.Size || total > MaxBytes) return "the download was bigger than expected"; |
| 3019 | fs.Write(buf, 0, n); |
| 3020 | int pc = (int)(total * 100 / u.Size); |
| 3021 | if (pc != last && progress != null) { last = pc; progress(pc); } |
| 3022 | } |
| 3023 | if (total != u.Size) return "the download was cut short"; |
| 3024 | } |
| 3025 | } |
| 3026 | } |
| 3027 | catch (WebException e) |
| 3028 | { |
| 3029 | HttpWebResponse r = e.Response as HttpWebResponse; |
| 3030 | return r != null ? "the update server said " + (int)r.StatusCode : "couldn't reach the update server"; |
| 3031 | } |
| 3032 | catch (IOException) { return "the download stalled"; } |
| 3033 | return null; |
| 3034 | } |
| 3035 | |
| 3036 | public static string Download(UpdateInfo u, Action<int> progress, out string file) |
| 3037 | { |
| 3038 | file = null; |
| 3039 | string dir = Folder; |
| 3040 | Directory.CreateDirectory(dir); |
| 3041 | foreach (string old in Directory.GetFiles(dir)) { try { File.Delete(old); } catch (Exception) { } } |
| 3042 | string part = Path.Combine(dir, "trainer-" + u.Version + ".part"); |
| 3043 | string got = null; |
| 3044 | for (int attempt = 1; attempt <= 3; attempt++) |
| 3045 | { |
| 3046 | got = Fetch(u, part, progress); |
| 3047 | if (got == null || got.StartsWith("the download was bigger", StringComparison.Ordinal) || got.StartsWith("the update server said 4", StringComparison.Ordinal)) break; |
| 3048 | if (attempt < 3) Thread.Sleep(2000 * attempt); |
| 3049 | else got += " (tried 3 times)"; |
| 3050 | } |
| 3051 | if (got != null) return got; |
| 3052 | string hash; |
| 3053 | using (System.Security.Cryptography.SHA256 h = System.Security.Cryptography.SHA256.Create()) |
| 3054 | using (FileStream fs = File.OpenRead(part)) |
| 3055 | { |
| 3056 | if (fs.ReadByte() != 'M' || fs.ReadByte() != 'Z') { return "the download isn't a program"; } |
| 3057 | fs.Position = 0; |
| 3058 | hash = BitConverter.ToString(h.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); |
| 3059 | } |
| 3060 | if (hash != u.Sha) { try { File.Delete(part); } catch (Exception) { } return "the download didn't match its fingerprint, so it was thrown away"; } |
| 3061 | int listed; |
| 3062 | try { listed = Nexus.HashListed(hash); } catch (Exception) { listed = 0; } |
| 3063 | if (listed == 0) return "couldn't reach Nexus Mods to double-check the update. Try again later"; |
| 3064 | if (listed < 0) { try { File.Delete(part); } catch (Exception) { } return "this update isn't listed on the official Nexus page yet, so it wasn't installed"; } |
| 3065 | string exe = Path.Combine(dir, "trainer-" + u.Version + ".exe"); |
| 3066 | if (File.Exists(exe)) File.Delete(exe); |
| 3067 | File.Move(part, exe); |
| 3068 | file = exe; |
| 3069 | return null; |
| 3070 | } |
| 3071 | |
| 3072 | public static string Apply(string newExe, string sha) |
| 3073 | { |
| 3074 | string cur = Application.ExecutablePath; |
| 3075 | string old = cur + ".old"; |
| 3076 | try { if (File.Exists(old)) File.Delete(old); } |
| 3077 | catch (Exception) { old = cur + "." + DateTime.UtcNow.Ticks + ".old"; } |
| 3078 | try { File.Move(cur, old); } |
| 3079 | catch (UnauthorizedAccessException) { return "Windows won't let the trainer replace itself in " + Path.GetDirectoryName(cur) + ". Move the trainer folder somewhere like Documents, or download the update from Nexus."; } |
| 3080 | catch (Exception e) { return "couldn't replace the trainer: " + e.Message; } |
| 3081 | try |
| 3082 | { |
| 3083 | File.Copy(newExe, cur, false); |
| 3084 | string h; |
| 3085 | using (System.Security.Cryptography.SHA256 s = System.Security.Cryptography.SHA256.Create()) |
| 3086 | using (FileStream fs = File.OpenRead(cur)) |
| 3087 | h = BitConverter.ToString(s.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); |
| 3088 | if (h != sha) throw new IOException("the copied file didn't match"); |
| 3089 | } |
| 3090 | catch (Exception e) |
| 3091 | { |
| 3092 | try { if (File.Exists(cur)) File.Delete(cur); File.Move(old, cur); } catch (Exception) { } |
| 3093 | return "couldn't install the update: " + e.Message; |
| 3094 | } |
| 3095 | try { File.Delete(newExe); } catch (Exception) { } |
| 3096 | try |
| 3097 | { |
| 3098 | ProcessStartInfo si = new ProcessStartInfo(cur, "--updated"); |
| 3099 | si.WorkingDirectory = Path.GetDirectoryName(cur); |
| 3100 | si.UseShellExecute = false; |
| 3101 | Process.Start(si); |
| 3102 | } |
| 3103 | catch (Exception e) { return "the update is installed, but the trainer couldn't restart itself (" + e.Message + "). Open it again by hand."; } |
| 3104 | return null; |
| 3105 | } |
| 3106 | |
| 3107 | public static void Cleanup() |
| 3108 | { |
| 3109 | Thread t = new Thread(delegate () |
| 3110 | { |
| 3111 | string cur = Application.ExecutablePath; |
| 3112 | for (int i = 0; i < 30; i++) |
| 3113 | { |
| 3114 | bool left = false; |
| 3115 | try |
| 3116 | { |
| 3117 | foreach (string f in Directory.GetFiles(Path.GetDirectoryName(cur), Path.GetFileName(cur) + "*.old")) |
| 3118 | { |
| 3119 | try { File.Delete(f); } catch (Exception) { left = true; } |
| 3120 | } |
| 3121 | } |
| 3122 | catch (Exception) { return; } |
| 3123 | if (!left) return; |
| 3124 | Thread.Sleep(1000); |
| 3125 | } |
| 3126 | }); |
| 3127 | t.IsBackground = true; |
| 3128 | t.Start(); |
| 3129 | } |
| 3130 | } |
| 3131 | |
| 3132 | internal static class Nexus |
| 3133 | { |
| 3134 | public const string Member = "casualexpie"; |
| 3135 | private const string MemberId = "94954933"; |
| 3136 | private const string Game = "scavprototype"; |
| 3137 | public const string ProfileUrl = "https://www.nexusmods.com/users/" + MemberId + "?tab=user+files"; |
| 3138 | public const string BananaUrl = "https://gamebanana.com/members/6222538"; |
| 3139 | private const string Api = "https://api.nexusmods.com/v2/graphql"; |
| 3140 | |
| 3141 | public static string ModUrl(int id) { return "https://www.nexusmods.com/" + Game + "/mods/" + id; } |
| 3142 | |
| 3143 | private static string Folder { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "UltraParadise"); } } |
| 3144 | private static string CacheFile { get { return Path.Combine(Folder, "nexus.json"); } } |
| 3145 | |
| 3146 | public static List<NexusMod> Load(out DateTime when) |
| 3147 | { |
| 3148 | when = DateTime.MinValue; |
| 3149 | try |
| 3150 | { |
| 3151 | if (!File.Exists(CacheFile)) return null; |
| 3152 | when = File.GetLastWriteTimeUtc(CacheFile); |
| 3153 | return Parse(File.ReadAllText(CacheFile)); |
| 3154 | } |
| 3155 | catch (Exception) { return null; } |
| 3156 | } |
| 3157 | |
| 3158 | public static List<NexusMod> Fetch() |
| 3159 | { |
| 3160 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 3161 | string q = "{ mods(filter:{ uploaderId:{ value:\\\"" + MemberId + "\\\" } }, sort:{ downloads:{ direction: DESC } }, count: 40) { nodes { modId name summary endorsements downloads updatedAt thumbnailUrl status adultContent game { domainName } } } }"; |
| 3162 | byte[] body = Encoding.UTF8.GetBytes("{\"query\":\"" + q + "\"}"); |
| 3163 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Api); |
| 3164 | req.Method = "POST"; |
| 3165 | req.ContentType = "application/json"; |
| 3166 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 3167 | req.Timeout = 15000; |
| 3168 | req.ReadWriteTimeout = 15000; |
| 3169 | using (Stream s = req.GetRequestStream()) s.Write(body, 0, body.Length); |
| 3170 | string json; |
| 3171 | using (WebResponse res = req.GetResponse()) |
| 3172 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 3173 | json = r.ReadToEnd(); |
| 3174 | List<NexusMod> list = Parse(json); |
| 3175 | if (list == null) return null; |
| 3176 | try { Directory.CreateDirectory(Folder); File.WriteAllText(CacheFile, json); } catch (Exception) { } |
| 3177 | return list; |
| 3178 | } |
| 3179 | |
| 3180 | public static string OwnHash() |
| 3181 | { |
| 3182 | using (System.Security.Cryptography.SHA256 h = System.Security.Cryptography.SHA256.Create()) |
| 3183 | using (FileStream fs = File.OpenRead(Application.ExecutablePath)) |
| 3184 | return BitConverter.ToString(h.ComputeHash(fs)).Replace("-", "").ToLowerInvariant(); |
| 3185 | } |
| 3186 | |
| 3187 | public const int TrainerModId = 1203; |
| 3188 | |
| 3189 | public static int VerifyOfficial(out string pageUrl) |
| 3190 | { |
| 3191 | pageUrl = ModUrl(TrainerModId); |
| 3192 | return HashListed(OwnHash()); |
| 3193 | } |
| 3194 | |
| 3195 | public static int HashListed(string hash) |
| 3196 | { |
| 3197 | if (hash == null || !System.Text.RegularExpressions.Regex.IsMatch(hash, "^[0-9a-f]{64}$")) return -1; |
| 3198 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 3199 | string q = "{ mods(filter:{ uploaderId:{ value:\\\"" + MemberId + "\\\" } }, count: 60) { nodes { modId name description status game { domainName } } } }"; |
| 3200 | byte[] body = Encoding.UTF8.GetBytes("{\"query\":\"" + q + "\"}"); |
| 3201 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Api); |
| 3202 | req.Method = "POST"; |
| 3203 | req.ContentType = "application/json"; |
| 3204 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 3205 | req.Timeout = 15000; |
| 3206 | req.ReadWriteTimeout = 15000; |
| 3207 | using (Stream s = req.GetRequestStream()) s.Write(body, 0, body.Length); |
| 3208 | string json; |
| 3209 | using (WebResponse res = req.GetResponse()) |
| 3210 | using (StreamReader r = new StreamReader(res.GetResponseStream(), Encoding.UTF8)) |
| 3211 | json = r.ReadToEnd(); |
| 3212 | System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); |
| 3213 | js.MaxJsonLength = 16 * 1024 * 1024; |
| 3214 | Dictionary<string, object> root = js.DeserializeObject(json) as Dictionary<string, object>; |
| 3215 | Dictionary<string, object> data = root != null && root.ContainsKey("data") ? root["data"] as Dictionary<string, object> : null; |
| 3216 | Dictionary<string, object> mods = data != null && data.ContainsKey("mods") ? data["mods"] as Dictionary<string, object> : null; |
| 3217 | object[] nodes = mods != null && mods.ContainsKey("nodes") ? mods["nodes"] as object[] : null; |
| 3218 | if (nodes == null) return 0; |
| 3219 | bool foundPage = false; |
| 3220 | foreach (object o in nodes) |
| 3221 | { |
| 3222 | Dictionary<string, object> n = o as Dictionary<string, object>; |
| 3223 | if (n == null) continue; |
| 3224 | Dictionary<string, object> g = n.ContainsKey("game") ? n["game"] as Dictionary<string, object> : null; |
| 3225 | if (g == null || Str(g, "domainName") != Game || Str(n, "status") != "published") continue; |
| 3226 | if ((int)Num(n, "modId") != TrainerModId) continue; |
| 3227 | foundPage = true; |
| 3228 | string desc = (Str(n, "description") ?? "").ToLowerInvariant(); |
| 3229 | if (desc.Contains(hash)) return 1; |
| 3230 | } |
| 3231 | return foundPage ? -1 : 0; |
| 3232 | } |
| 3233 | |
| 3234 | private static List<NexusMod> Parse(string json) |
| 3235 | { |
| 3236 | System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); |
| 3237 | js.MaxJsonLength = 8 * 1024 * 1024; |
| 3238 | Dictionary<string, object> root = js.DeserializeObject(json) as Dictionary<string, object>; |
| 3239 | if (root == null || !root.ContainsKey("data")) return null; |
| 3240 | Dictionary<string, object> data = root["data"] as Dictionary<string, object>; |
| 3241 | Dictionary<string, object> mods = data != null && data.ContainsKey("mods") ? data["mods"] as Dictionary<string, object> : null; |
| 3242 | object[] nodes = mods != null && mods.ContainsKey("nodes") ? mods["nodes"] as object[] : null; |
| 3243 | if (nodes == null) return null; |
| 3244 | List<NexusMod> list = new List<NexusMod>(); |
| 3245 | foreach (object o in nodes) |
| 3246 | { |
| 3247 | Dictionary<string, object> n = o as Dictionary<string, object>; |
| 3248 | if (n == null) continue; |
| 3249 | if (Str(n, "status") != "published") continue; |
| 3250 | Dictionary<string, object> g = n.ContainsKey("game") ? n["game"] as Dictionary<string, object> : null; |
| 3251 | if (g == null || Str(g, "domainName") != Game) continue; |
| 3252 | NexusMod m = new NexusMod(); |
| 3253 | m.Id = (int)Num(n, "modId"); |
| 3254 | m.Name = Str(n, "name") ?? ""; |
| 3255 | if (m.Id <= 0 || m.Name.Length == 0) continue; |
| 3256 | m.Self = m.Id == TrainerModId; |
| 3257 | m.Adult = n.ContainsKey("adultContent") && n["adultContent"] is bool && (bool)n["adultContent"]; |
| 3258 | m.Summary = (Str(n, "summary") ?? "").Replace("\r", " ").Replace("\n", " "); |
| 3259 | m.Downloads = (long)Num(n, "downloads"); |
| 3260 | m.Endorsements = (int)Num(n, "endorsements"); |
| 3261 | m.Thumb = m.Adult ? null : Str(n, "thumbnailUrl"); |
| 3262 | DateTime d; |
| 3263 | if (DateTime.TryParse(Str(n, "updatedAt") ?? "", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out d)) m.Updated = d; |
| 3264 | list.Add(m); |
| 3265 | } |
| 3266 | return list; |
| 3267 | } |
| 3268 | |
| 3269 | private static string Str(Dictionary<string, object> d, string k) |
| 3270 | { |
| 3271 | object v; |
| 3272 | return d.TryGetValue(k, out v) && v != null ? v.ToString() : null; |
| 3273 | } |
| 3274 | |
| 3275 | private static double Num(Dictionary<string, object> d, string k) |
| 3276 | { |
| 3277 | object v; |
| 3278 | if (!d.TryGetValue(k, out v) || v == null) return 0; |
| 3279 | try { return Convert.ToDouble(v, CultureInfo.InvariantCulture); } catch (Exception) { return 0; } |
| 3280 | } |
| 3281 | |
| 3282 | public static Bitmap Thumb(string url) |
| 3283 | { |
| 3284 | if (string.IsNullOrEmpty(url)) return null; |
| 3285 | Uri u; |
| 3286 | if (!Uri.TryCreate(url, UriKind.Absolute, out u) || u.Scheme != "https" || !(u.Host.EndsWith(".nexusmods.com", StringComparison.OrdinalIgnoreCase) || u.Host.EndsWith(".thunderstore.io", StringComparison.OrdinalIgnoreCase))) return null; |
| 3287 | string dir = Path.Combine(Folder, "thumbs"); |
| 3288 | string file = Path.Combine(dir, Hash(url) + ".img"); |
| 3289 | byte[] bytes = null; |
| 3290 | try { if (File.Exists(file)) bytes = File.ReadAllBytes(file); } catch (Exception) { } |
| 3291 | if (bytes == null) |
| 3292 | { |
| 3293 | try |
| 3294 | { |
| 3295 | using (WebClient wc = new WebClient()) |
| 3296 | { |
| 3297 | wc.Headers[HttpRequestHeader.UserAgent] = "UltraParadiseCUTrainer/" + Program.Version; |
| 3298 | bytes = wc.DownloadData(u); |
| 3299 | } |
| 3300 | if (bytes.Length > 4 * 1024 * 1024) return null; |
| 3301 | Directory.CreateDirectory(dir); |
| 3302 | File.WriteAllBytes(file, bytes); |
| 3303 | } |
| 3304 | catch (Exception) { return null; } |
| 3305 | } |
| 3306 | try |
| 3307 | { |
| 3308 | using (MemoryStream ms = new MemoryStream(bytes)) |
| 3309 | using (Image im = Image.FromStream(ms)) |
| 3310 | return new Bitmap(im); |
| 3311 | } |
| 3312 | catch (Exception) { } |
| 3313 | try { return Wic(bytes); } |
| 3314 | catch (Exception) { return null; } |
| 3315 | } |
| 3316 | |
| 3317 | private static Bitmap Wic(byte[] bytes) |
| 3318 | { |
| 3319 | using (MemoryStream ms = new MemoryStream(bytes)) |
| 3320 | { |
| 3321 | System.Windows.Media.Imaging.BitmapDecoder dec = System.Windows.Media.Imaging.BitmapDecoder.Create(ms, System.Windows.Media.Imaging.BitmapCreateOptions.PreservePixelFormat, System.Windows.Media.Imaging.BitmapCacheOption.OnLoad); |
| 3322 | System.Windows.Media.Imaging.BitmapSource src = dec.Frames[0]; |
| 3323 | System.Windows.Media.Imaging.FormatConvertedBitmap conv = new System.Windows.Media.Imaging.FormatConvertedBitmap(src, System.Windows.Media.PixelFormats.Pbgra32, null, 0); |
| 3324 | int w = conv.PixelWidth, h = conv.PixelHeight; |
| 3325 | if (w <= 0 || h <= 0 || w > 4096 || h > 4096) return null; |
| 3326 | int stride = w * 4; |
| 3327 | byte[] px = new byte[stride * h]; |
| 3328 | conv.CopyPixels(px, stride, 0); |
| 3329 | Bitmap bmp = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); |
| 3330 | System.Drawing.Imaging.BitmapData bd = bmp.LockBits(new Rectangle(0, 0, w, h), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); |
| 3331 | try |
| 3332 | { |
| 3333 | for (int y = 0; y < h; y++) Marshal.Copy(px, y * stride, IntPtr.Add(bd.Scan0, y * bd.Stride), stride); |
| 3334 | } |
| 3335 | finally { bmp.UnlockBits(bd); } |
| 3336 | return bmp; |
| 3337 | } |
| 3338 | } |
| 3339 | |
| 3340 | private static string Hash(string s) |
| 3341 | { |
| 3342 | using (System.Security.Cryptography.SHA1 h = System.Security.Cryptography.SHA1.Create()) |
| 3343 | return BitConverter.ToString(h.ComputeHash(Encoding.UTF8.GetBytes(s))).Replace("-", "").ToLowerInvariant(); |
| 3344 | } |
| 3345 | } |
| 3346 | |
| 3347 | internal class AboutPanel : Control |
| 3348 | { |
| 3349 | public List<NexusMod> Mods; |
| 3350 | public Dictionary<string, TsPackage> Ts; |
| 3351 | public const int RecommendedId = 885; |
| 3352 | public const string RecommendedTs = "SaveAnywhere"; |
| 3353 | public string Status = "Loading my mods from Nexus..."; |
| 3354 | public int OfficialState; |
| 3355 | public string OfficialUrl; |
| 3356 | private readonly Font checkFont = Theme.F("Segoe UI Semibold", 8.5f); |
| 3357 | private readonly List<KeyValuePair<Rectangle, string>> links = new List<KeyValuePair<Rectangle, string>>(); |
| 3358 | private string hover; |
| 3359 | private int scroll, contentH; |
| 3360 | private readonly Image tile; |
| 3361 | private readonly Font headFont = Theme.F("Segoe UI Semibold", 8f); |
| 3362 | private readonly Font nameFont = Theme.F("Segoe UI Black", 15f); |
| 3363 | private readonly Font textFont = Theme.F("Segoe UI", 9f); |
| 3364 | private readonly Font smallFont = Theme.F("Segoe UI", 8.5f); |
| 3365 | private readonly Font statFont = Theme.F("Segoe UI Semibold", 13f); |
| 3366 | private readonly Font titleFont = Theme.F("Segoe UI Semibold", 9.5f); |
| 3367 | private readonly Font linkFont = Theme.F("Segoe UI Semibold", 9f); |
| 3368 | |
| 3369 | public AboutPanel(Image tileImage) |
| 3370 | { |
| 3371 | tile = tileImage; |
| 3372 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); |
| 3373 | BackColor = Theme.Back; |
| 3374 | } |
| 3375 | |
| 3376 | private int Pad { get { return Theme.S(18); } } |
| 3377 | private int Gap { get { return Theme.S(22); } } |
| 3378 | private int HeadH { get { return Theme.S(34); } } |
| 3379 | private int LeftW { get { return Theme.S(290); } } |
| 3380 | |
| 3381 | private void Head(Graphics g, string title, int x, int y, int w) |
| 3382 | { |
| 3383 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; |
| 3384 | Theme.FillRound(g, Theme.Orange, new Rectangle(x, y + Theme.S(8) + (HeadH - Theme.S(12)) / 2 - Theme.S(6), Theme.S(3), Theme.S(12)), Theme.S(1)); |
| 3385 | string sp = Theme.Spaced(title); |
| 3386 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 3387 | g.DrawString(sp, headFont, orange, new RectangleF(x + Theme.S(9), y + Theme.S(8), w, HeadH - Theme.S(12)), mid); |
| 3388 | int tw = (int)g.MeasureString(sp, headFont).Width + Theme.S(16); |
| 3389 | int ly = y + Theme.S(8) + (HeadH - Theme.S(12)) / 2; |
| 3390 | using (LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(x + tw - 1, ly, Math.Max(2, w - tw + 2), 1), Theme.Line, Color.FromArgb(0, Theme.Line), LinearGradientMode.Horizontal)) |
| 3391 | g.FillRectangle(lb, x + tw, ly, Math.Max(1, w - tw), 1); |
| 3392 | } |
| 3393 | |
| 3394 | private static string Big(long n) |
| 3395 | { |
| 3396 | if (n >= 1000000) return (n / 1000000.0).ToString("0.#", CultureInfo.InvariantCulture) + "M"; |
| 3397 | if (n >= 10000) return (n / 1000.0).ToString("0.#", CultureInfo.InvariantCulture) + "k"; |
| 3398 | return n.ToString("#,0", CultureInfo.InvariantCulture); |
| 3399 | } |
| 3400 | |
| 3401 | protected override void OnPaint(PaintEventArgs e) |
| 3402 | { |
| 3403 | Graphics g = e.Graphics; |
| 3404 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 3405 | Theme.PaintBack(g, this); |
| 3406 | links.Clear(); |
| 3407 | |
| 3408 | int x = Pad, y = Theme.S(6); |
| 3409 | Head(g, "ABOUT ME", x, y, LeftW); |
| 3410 | y += HeadH + Theme.S(6); |
| 3411 | if (tile != null) |
| 3412 | { |
| 3413 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 3414 | g.DrawImage(tile, x, y, Theme.S(44), Theme.S(44)); |
| 3415 | } |
| 3416 | using (SolidBrush w = new SolidBrush(Theme.Bright)) g.DrawString(Nexus.Member, nameFont, w, x + Theme.S(54), y + Theme.S(2)); |
| 3417 | using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString("Modder for Casualties: Unknown", smallFont, o, x + Theme.S(57), y + Theme.S(28)); |
| 3418 | y += Theme.S(60); |
| 3419 | string bio = "Hi! I make mods for Casualties: Unknown, from cheats and quality-of-life fixes to a few silly ones. Thanks for using the trainer.\n\nIf you like it, an endorsement on Nexus really helps."; |
| 3420 | SizeF bs = g.MeasureString(bio, textFont, LeftW); |
| 3421 | using (SolidBrush t = new SolidBrush(Theme.Soft)) g.DrawString(bio, textFont, t, new RectangleF(x, y, LeftW, bs.Height + 4)); |
| 3422 | y += (int)bs.Height + Theme.S(18); |
| 3423 | |
| 3424 | if (Mods != null && Mods.Count > 0) |
| 3425 | { |
| 3426 | long dl = 0; int en = 0; |
| 3427 | foreach (NexusMod m in Mods) { dl += m.Downloads; en += m.Endorsements; } |
| 3428 | int sw = LeftW / 3; |
| 3429 | string[][] stats = { new[] { Mods.Count.ToString(), "mods" }, new[] { Big(dl), "downloads" }, new[] { Big(en), "endorsements" } }; |
| 3430 | for (int i = 0; i < 3; i++) |
| 3431 | { |
| 3432 | using (SolidBrush w = new SolidBrush(Theme.Text)) g.DrawString(stats[i][0], statFont, w, x + i * sw, y); |
| 3433 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString(stats[i][1], smallFont, d, x + i * sw + Theme.S(2), y + Theme.S(26)); |
| 3434 | } |
| 3435 | y += Theme.S(56); |
| 3436 | } |
| 3437 | |
| 3438 | Rectangle btn = new Rectangle(x, y, Theme.S(190), Theme.S(30)); |
| 3439 | bool hb = hover == Nexus.ProfileUrl; |
| 3440 | using (SolidBrush b = new SolidBrush(hb ? Theme.Hover : Theme.Panel)) g.FillRectangle(b, btn); |
| 3441 | using (Pen p = new Pen(hb ? Theme.Orange : Theme.Edge)) g.DrawRectangle(p, btn); |
| 3442 | StringFormat c = new StringFormat(); c.Alignment = StringAlignment.Center; c.LineAlignment = StringAlignment.Center; |
| 3443 | using (SolidBrush t = new SolidBrush(Theme.Text)) g.DrawString("All my mods on Nexus", linkFont, t, btn, c); |
| 3444 | links.Add(new KeyValuePair<Rectangle, string>(btn, Nexus.ProfileUrl)); |
| 3445 | y += Theme.S(38); |
| 3446 | Rectangle gb = new Rectangle(x, y, Theme.S(190), Theme.S(30)); |
| 3447 | bool hg = hover == Nexus.BananaUrl; |
| 3448 | using (SolidBrush b = new SolidBrush(hg ? Theme.Hover : Theme.Panel)) g.FillRectangle(b, gb); |
| 3449 | using (Pen p = new Pen(hg ? Theme.Orange : Theme.Edge)) g.DrawRectangle(p, gb); |
| 3450 | using (SolidBrush t = new SolidBrush(Theme.Text)) g.DrawString("My GameBanana page", linkFont, t, gb, c); |
| 3451 | links.Add(new KeyValuePair<Rectangle, string>(gb, Nexus.BananaUrl)); |
| 3452 | y += Theme.S(38); |
| 3453 | Rectangle tb = new Rectangle(x, y, Theme.S(190), Theme.S(30)); |
| 3454 | bool ht = hover == Thunderstore.TeamUrl; |
| 3455 | using (SolidBrush b = new SolidBrush(ht ? Theme.Hover : Theme.Panel)) g.FillRectangle(b, tb); |
| 3456 | using (Pen p = new Pen(ht ? Theme.Orange : Theme.Edge)) g.DrawRectangle(p, tb); |
| 3457 | using (SolidBrush t = new SolidBrush(Theme.Text)) g.DrawString("My Thunderstore page", linkFont, t, tb, c); |
| 3458 | links.Add(new KeyValuePair<Rectangle, string>(tb, Thunderstore.TeamUrl)); |
| 3459 | y += Theme.S(42); |
| 3460 | using (SolidBrush d = new SolidBrush(Theme.Faint)) |
| 3461 | g.DrawString(Status, smallFont, d, new RectangleF(x, y, LeftW, Theme.S(40))); |
| 3462 | |
| 3463 | string legal = "Open source: opensource.smellypawz.com\nCopyright (c) " + Nexus.Member + ".\nDon't reupload, sell or reuse it."; |
| 3464 | SizeF ls = g.MeasureString(legal, smallFont, LeftW); |
| 3465 | int ly = Height - (int)ls.Height - Theme.S(14); |
| 3466 | using (Pen p = new Pen(Theme.Line)) g.DrawLine(p, x, ly - Theme.S(10), x + LeftW, ly - Theme.S(10)); |
| 3467 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString(legal, smallFont, d, new RectangleF(x, ly, LeftW, ls.Height + 2)); |
| 3468 | |
| 3469 | string check = OfficialState == 1 ? "✓ Official copy, verified against casualexpie's Nexus page" |
| 3470 | : OfficialState == -1 ? "! Not an official copy. Get it from Nexus Mods or GameBanana (click here)" |
| 3471 | : "Official copy check isn't available right now"; |
| 3472 | Color cc = OfficialState == 1 ? Theme.On : OfficialState == -1 ? Theme.Bad : Theme.Faint; |
| 3473 | SizeF cs = g.MeasureString(check, checkFont, LeftW); |
| 3474 | Rectangle cr = new Rectangle(x, ly - Theme.S(18) - (int)cs.Height, LeftW, (int)cs.Height + 2); |
| 3475 | using (SolidBrush b = new SolidBrush(cc)) g.DrawString(check, checkFont, b, cr); |
| 3476 | if (OfficialState == -1 && OfficialUrl != null) links.Add(new KeyValuePair<Rectangle, string>(cr, OfficialUrl)); |
| 3477 | |
| 3478 | int rx = x + LeftW + Gap, rw = Width - rx - Pad; |
| 3479 | Head(g, "CHECK OUT MY OTHER MODS", rx, Theme.S(6), rw); |
| 3480 | int top = Theme.S(6) + HeadH + Theme.S(6); |
| 3481 | Region clip = g.Clip; |
| 3482 | g.SetClip(new Rectangle(rx, top, rw + Theme.S(8), Height - top)); |
| 3483 | int cols = 2, cg = Theme.S(14); |
| 3484 | int cw = (rw - cg) / cols, ch = Theme.S(96); |
| 3485 | int cy = top - scroll; |
| 3486 | |
| 3487 | NexusMod recN = null; |
| 3488 | if (Mods != null) foreach (NexusMod gm in Mods) if (gm.Id == RecommendedId) recN = gm; |
| 3489 | TsPackage recT = null; |
| 3490 | if (Ts != null) Ts.TryGetValue(RecommendedTs, out recT); |
| 3491 | cy = SubHead(g, "★ RECOMMENDED", rx, cy, rw); |
| 3492 | { |
| 3493 | Rectangle r = new Rectangle(rx, cy, rw, Theme.S(112)); |
| 3494 | string url = Nexus.ModUrl(RecommendedId); |
| 3495 | string tsUrl = recT != null ? recT.Url : Thunderstore.PageUrl(RecommendedTs); |
| 3496 | int bw = Theme.S(104), bh = Theme.S(24); |
| 3497 | Rectangle bn = new Rectangle(r.Right - Theme.S(10) - bw * 2 - Theme.S(6), r.Bottom - Theme.S(10) - bh, bw, bh); |
| 3498 | Rectangle bt = new Rectangle(bn.Right + Theme.S(6), bn.Y, bw, bh); |
| 3499 | if (r.Bottom > top && r.Top < Height) |
| 3500 | { |
| 3501 | links.Add(new KeyValuePair<Rectangle, string>(bn, url + "?tab=files")); |
| 3502 | links.Add(new KeyValuePair<Rectangle, string>(bt, tsUrl)); |
| 3503 | links.Add(new KeyValuePair<Rectangle, string>(r, url)); |
| 3504 | } |
| 3505 | bool h = hover == url; |
| 3506 | using (SolidBrush b = new SolidBrush(h ? Theme.Hover : Theme.Panel)) g.FillRectangle(b, r); |
| 3507 | using (Pen p = new Pen(Theme.Orange)) g.DrawRectangle(p, r); |
| 3508 | Theme.FillRound(g, Theme.Orange, new Rectangle(r.X, r.Y, Theme.S(4), r.Height), 0); |
| 3509 | Rectangle th = new Rectangle(r.X + Theme.S(12), r.Y + Theme.S(10), Theme.S(164), r.Height - Theme.S(20)); |
| 3510 | Image img = recN != null && recN.Image != null ? (Image)recN.Image : recT != null ? recT.Image : null; |
| 3511 | Thumb(g, img, th, false); |
| 3512 | int tx = th.Right + Theme.S(12), tw = r.Right - tx - Theme.S(10); |
| 3513 | StringFormat nw = new StringFormat(); nw.Trimming = StringTrimming.EllipsisCharacter; nw.FormatFlags = StringFormatFlags.NoWrap; |
| 3514 | using (SolidBrush t = new SolidBrush(Theme.Bright)) g.DrawString("Save Anywhere", statFont, t, new RectangleF(tx, r.Y + Theme.S(8), tw, Theme.S(24)), nw); |
| 3515 | StringFormat wrap = new StringFormat(); wrap.Trimming = StringTrimming.EllipsisWord; |
| 3516 | float lineH = smallFont.GetHeight(g); |
| 3517 | using (SolidBrush d = new SolidBrush(Theme.Soft)) g.DrawString("Save your run anywhere, not just at the usual spots. Cloud saves, auto-save and save slots, plus share codes to send a run to a friend.", smallFont, d, new RectangleF(tx, r.Y + Theme.S(34), tw, lineH * 2 + 1), wrap); |
| 3518 | List<string> meta = new List<string>(); |
| 3519 | if (recN != null) meta.Add(Big(recN.Downloads) + " on Nexus"); |
| 3520 | if (recT != null) meta.Add("v" + recT.Version + " on Thunderstore"); |
| 3521 | using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString(string.Join(" · ", meta.ToArray()), smallFont, o, new RectangleF(tx, r.Y + Theme.S(64), tw, Theme.S(18)), nw); |
| 3522 | MiniButton(g, bn, "Nexus Mods", url + "?tab=files"); |
| 3523 | MiniButton(g, bt, "Thunderstore", tsUrl); |
| 3524 | cy = r.Bottom + Theme.S(10); |
| 3525 | } |
| 3526 | |
| 3527 | List<NexusMod> grid = new List<NexusMod>(); |
| 3528 | if (Mods != null) foreach (NexusMod gm in Mods) if (!gm.Self && gm.Id != RecommendedId) grid.Add(gm); |
| 3529 | cy = SubHead(g, "ON NEXUS MODS", rx, cy, rw); |
| 3530 | if (grid.Count == 0) |
| 3531 | { |
| 3532 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString(Mods == null ? "Loading..." : "Nothing to show yet.", textFont, d, rx, cy + Theme.S(2)); |
| 3533 | cy += Theme.S(28); |
| 3534 | } |
| 3535 | for (int i = 0; i < grid.Count; i++) |
| 3536 | { |
| 3537 | NexusMod m = grid[i]; |
| 3538 | Rectangle r = new Rectangle(rx + (i % cols) * (cw + cg), cy + (i / cols) * (ch + cg), cw, ch); |
| 3539 | Card(g, r, top, m.Image, m.Adult, m.Name, m.Summary, Big(m.Downloads) + " downloads · " + m.Endorsements + " endorsements", Nexus.ModUrl(m.Id)); |
| 3540 | } |
| 3541 | if (grid.Count > 0) cy += ((grid.Count + cols - 1) / cols) * (ch + cg); |
| 3542 | |
| 3543 | List<TsPackage> tgrid = new List<TsPackage>(); |
| 3544 | if (Ts != null) foreach (TsPackage p in Ts.Values) if (!string.Equals(p.Name, RecommendedTs, StringComparison.OrdinalIgnoreCase)) tgrid.Add(p); |
| 3545 | tgrid.Sort(delegate (TsPackage a, TsPackage b) { int o = b.Downloads.CompareTo(a.Downloads); return o != 0 ? o : string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase); }); |
| 3546 | cy = SubHead(g, "ON THUNDERSTORE", rx, cy, rw); |
| 3547 | if (tgrid.Count == 0) |
| 3548 | { |
| 3549 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString(Ts == null ? "Loading..." : "Nothing to show yet.", textFont, d, rx, cy + Theme.S(2)); |
| 3550 | cy += Theme.S(28); |
| 3551 | } |
| 3552 | for (int i = 0; i < tgrid.Count; i++) |
| 3553 | { |
| 3554 | TsPackage p = tgrid[i]; |
| 3555 | Rectangle r = new Rectangle(rx + (i % cols) * (cw + cg), cy + (i / cols) * (ch + cg), cw, ch); |
| 3556 | Card(g, r, top, p.Image, false, TsName(p.Name), p.Description ?? "", p.Downloads.ToString("#,0", CultureInfo.InvariantCulture) + " downloads · v" + p.Version, p.Url); |
| 3557 | } |
| 3558 | if (tgrid.Count > 0) cy += ((tgrid.Count + cols - 1) / cols) * (ch + cg); |
| 3559 | contentH = cy + scroll - top; |
| 3560 | g.Clip = clip; |
| 3561 | int view = Height - top; |
| 3562 | if (contentH > view) |
| 3563 | { |
| 3564 | int tH = Math.Max(Theme.S(30), view * view / contentH); |
| 3565 | int tY = top + (view - tH) * scroll / Math.Max(1, contentH - view); |
| 3566 | using (SolidBrush sb = new SolidBrush(Theme.Scroll)) g.FillRectangle(sb, Width - Theme.S(6), tY, Theme.S(3), tH); |
| 3567 | } |
| 3568 | } |
| 3569 | |
| 3570 | private readonly Font subFont = Theme.F("Segoe UI Semibold", 7.5f); |
| 3571 | |
| 3572 | private int SubHead(Graphics g, string title, int x, int y, int w) |
| 3573 | { |
| 3574 | string sp = Theme.Spaced(title); |
| 3575 | using (SolidBrush b = new SolidBrush(Theme.Dim)) g.DrawString(sp, subFont, b, x, y + Theme.S(4)); |
| 3576 | int tw = (int)g.MeasureString(sp, subFont).Width + Theme.S(8); |
| 3577 | using (Pen p = new Pen(Theme.Line)) g.DrawLine(p, x + tw, y + Theme.S(11), x + w, y + Theme.S(11)); |
| 3578 | return y + Theme.S(24); |
| 3579 | } |
| 3580 | |
| 3581 | private void Thumb(Graphics g, Image img, Rectangle th, bool adult) |
| 3582 | { |
| 3583 | if (img != null) { DrawCover(g, img, th); return; } |
| 3584 | using (SolidBrush b = new SolidBrush(Theme.Thumb)) g.FillRectangle(b, th); |
| 3585 | if (adult) |
| 3586 | { |
| 3587 | StringFormat cf = new StringFormat(); cf.Alignment = StringAlignment.Center; cf.LineAlignment = StringAlignment.Center; |
| 3588 | using (SolidBrush b = new SolidBrush(Theme.Bad)) g.DrawString("18+", statFont, b, th, cf); |
| 3589 | } |
| 3590 | else if (tile != null) |
| 3591 | { |
| 3592 | int ts = Theme.S(32); |
| 3593 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 3594 | g.DrawImage(tile, th.X + (th.Width - ts) / 2, th.Y + (th.Height - ts) / 2, ts, ts); |
| 3595 | } |
| 3596 | } |
| 3597 | |
| 3598 | private void MiniButton(Graphics g, Rectangle r, string text, string url) |
| 3599 | { |
| 3600 | bool h = hover == url; |
| 3601 | using (SolidBrush b = new SolidBrush(h ? Theme.Orange : Theme.Back)) g.FillRectangle(b, r); |
| 3602 | using (Pen p = new Pen(h ? Theme.Orange : Theme.Edge)) g.DrawRectangle(p, r); |
| 3603 | StringFormat c = new StringFormat(); c.Alignment = StringAlignment.Center; c.LineAlignment = StringAlignment.Center; |
| 3604 | using (SolidBrush t = new SolidBrush(h ? Theme.OnAccent : Theme.Text)) g.DrawString(text, smallFont, t, r, c); |
| 3605 | } |
| 3606 | |
| 3607 | private void Card(Graphics g, Rectangle r, int top, Image img, bool adult, string name, string summary, string meta, string url) |
| 3608 | { |
| 3609 | bool h = hover == url; |
| 3610 | using (SolidBrush b = new SolidBrush(h ? Theme.Hover : Theme.Panel)) g.FillRectangle(b, r); |
| 3611 | using (Pen p = new Pen(h ? Theme.Orange : Theme.Line)) g.DrawRectangle(p, r); |
| 3612 | Rectangle th = new Rectangle(r.X + Theme.S(8), r.Y + Theme.S(8), Theme.S(104), r.Height - Theme.S(16)); |
| 3613 | Thumb(g, img, th, adult); |
| 3614 | int tx = th.Right + Theme.S(10), tw = r.Right - tx - Theme.S(8); |
| 3615 | StringFormat nw = new StringFormat(); nw.Trimming = StringTrimming.EllipsisCharacter; nw.FormatFlags = StringFormatFlags.NoWrap; |
| 3616 | using (SolidBrush t = new SolidBrush(h ? Theme.Bright : Theme.Text)) g.DrawString(name, titleFont, t, new RectangleF(tx, r.Y + Theme.S(6), tw, Theme.S(20)), nw); |
| 3617 | StringFormat wrap = new StringFormat(); wrap.Trimming = StringTrimming.EllipsisWord; |
| 3618 | float lineH = smallFont.GetHeight(g); |
| 3619 | using (SolidBrush d = new SolidBrush(Theme.Soft)) g.DrawString(summary, smallFont, d, new RectangleF(tx, r.Y + Theme.S(28), tw, lineH * 2 + 1), wrap); |
| 3620 | using (SolidBrush o = new SolidBrush(Theme.Orange)) g.DrawString(meta, smallFont, o, new RectangleF(tx, r.Bottom - Theme.S(22), tw, Theme.S(18)), nw); |
| 3621 | if (r.Bottom > top && r.Top < Height) links.Add(new KeyValuePair<Rectangle, string>(r, url)); |
| 3622 | } |
| 3623 | |
| 3624 | private static string TsName(string pkg) |
| 3625 | { |
| 3626 | foreach (KnownMod k in Installer.Mods) if (string.Equals(k.Ts, pkg, StringComparison.OrdinalIgnoreCase)) return k.Name; |
| 3627 | return System.Text.RegularExpressions.Regex.Replace(pkg, "(?<=[a-z])(?=[A-Z])", " "); |
| 3628 | } |
| 3629 | |
| 3630 | private static void DrawCover(Graphics g, Image img, Rectangle r) |
| 3631 | { |
| 3632 | float s = Math.Max(r.Width / (float)img.Width, r.Height / (float)img.Height); |
| 3633 | float sw = r.Width / s, sh = r.Height / s; |
| 3634 | RectangleF src = new RectangleF((img.Width - sw) / 2f, (img.Height - sh) / 2f, sw, sh); |
| 3635 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 3636 | g.DrawImage(img, r, src, GraphicsUnit.Pixel); |
| 3637 | } |
| 3638 | |
| 3639 | private string At(Point p) |
| 3640 | { |
| 3641 | foreach (KeyValuePair<Rectangle, string> l in links) if (l.Key.Contains(p)) return l.Value; |
| 3642 | return null; |
| 3643 | } |
| 3644 | |
| 3645 | protected override void OnMouseMove(MouseEventArgs e) |
| 3646 | { |
| 3647 | string h = At(e.Location); |
| 3648 | if (h != hover) { hover = h; Invalidate(); } |
| 3649 | Cursor = h != null ? Cursors.Hand : Cursors.Default; |
| 3650 | } |
| 3651 | |
| 3652 | protected override void OnMouseLeave(EventArgs e) { if (hover != null) { hover = null; Invalidate(); } } |
| 3653 | |
| 3654 | protected override void OnMouseDown(MouseEventArgs e) |
| 3655 | { |
| 3656 | Focus(); |
| 3657 | if (e.Button != MouseButtons.Left) return; |
| 3658 | string u = At(e.Location); |
| 3659 | if (u == null) return; |
| 3660 | if (!u.StartsWith("https://www.nexusmods.com/", StringComparison.Ordinal) && !u.StartsWith("https://gamebanana.com/", StringComparison.Ordinal) && !u.StartsWith("https://thunderstore.io/", StringComparison.Ordinal)) return; |
| 3661 | try { Process.Start(u); } catch (Exception) { } |
| 3662 | } |
| 3663 | |
| 3664 | protected override void OnMouseWheel(MouseEventArgs e) |
| 3665 | { |
| 3666 | int view = Height - (Theme.S(6) + HeadH + Theme.S(6)); |
| 3667 | int max = Math.Max(0, contentH - view); |
| 3668 | int s = Math.Max(0, Math.Min(max, scroll - e.Delta / 120 * Theme.S(60))); |
| 3669 | if (s != scroll) { scroll = s; Invalidate(); } |
| 3670 | } |
| 3671 | } |
| 3672 | |
| 3673 | internal class KnownMod |
| 3674 | { |
| 3675 | public int Id; |
| 3676 | public string Dll, Name, Ts; |
| 3677 | public KnownMod(int id, string dll, string name, string ts) { Id = id; Dll = dll; Name = name; Ts = ts; } |
| 3678 | } |
| 3679 | |
| 3680 | internal static class Piracy |
| 3681 | { |
| 3682 | public const string SteamPage = "https://store.steampowered.com/app/4576490/"; |
| 3683 | private static readonly string[] Files = { "steam_emu.ini", "SmartSteamEmu.ini", "cream_api.ini", "CODEX.ini", "steam_api64.cdx", "OnlineFix.ini", "OnlineFix64.dll", "ALI213.ini", "3DMGAME.ini", "TENOKE.ini", "unsteam.ini", "steam_interfaces.txt", "local_save.txt", "account_name.txt", "user_steam_id.txt", "ColdClientLoader.ini", "steamclient_loader_x64.exe", "EMPRESS.ini", "RUNE.ini", "SKIDROW.ini", "Goldberg SteamEmu Saves.lnk" }; |
| 3684 | private static readonly string[] Dirs = { "steam_settings", "SmartSteamEmu", "Goldberg SteamEmu Saves", "OnlineFix" }; |
| 3685 | |
| 3686 | public static bool Flagged(string game) |
| 3687 | { |
| 3688 | if (string.IsNullOrEmpty(game)) return false; |
| 3689 | try |
| 3690 | { |
| 3691 | string[] where = { game, Path.Combine(game, "CasualtiesUnknown_Data", "Plugins", "x86_64"), Path.Combine(game, "CasualtiesUnknown_Data", "Plugins") }; |
| 3692 | foreach (string w in where) |
| 3693 | { |
| 3694 | if (!Directory.Exists(w)) continue; |
| 3695 | foreach (string n in Files) if (File.Exists(Path.Combine(w, n))) return true; |
| 3696 | foreach (string n in Dirs) if (Directory.Exists(Path.Combine(w, n))) return true; |
| 3697 | } |
| 3698 | } |
| 3699 | catch (Exception) { } |
| 3700 | return false; |
| 3701 | } |
| 3702 | } |
| 3703 | |
| 3704 | internal class PiracyForm : Form |
| 3705 | { |
| 3706 | public bool Proceed; |
| 3707 | |
| 3708 | public PiracyForm() |
| 3709 | { |
| 3710 | Text = Program.Name; |
| 3711 | FormBorderStyle = FormBorderStyle.FixedDialog; |
| 3712 | MaximizeBox = false; |
| 3713 | MinimizeBox = false; |
| 3714 | ShowInTaskbar = false; |
| 3715 | StartPosition = FormStartPosition.CenterParent; |
| 3716 | BackColor = Theme.Back; |
| 3717 | ForeColor = Theme.Text; |
| 3718 | AutoScaleMode = AutoScaleMode.Dpi; |
| 3719 | ClientSize = new Size(Theme.S(460), Theme.S(250)); |
| 3720 | try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch (Exception) { } |
| 3721 | Label head = new Label(); |
| 3722 | head.Text = "This doesn't look like an official copy"; |
| 3723 | head.Font = Theme.F("Segoe UI Semibold", 12f); |
| 3724 | head.ForeColor = Theme.Orange; |
| 3725 | head.AutoSize = false; |
| 3726 | head.SetBounds(Theme.S(18), Theme.S(16), Theme.S(424), Theme.S(28)); |
| 3727 | Label body = new Label(); |
| 3728 | body.Text = "The trainer found files in your game folder that come from cracked copies of the game.\n\nUltra Paradise doesn't condone piracy. Casualties: Unknown is made by a small team, so please support Orsoniks and Oro Interactive by buying it on Steam.\n\nIf you think this is a mistake, you can pick the game's .exe yourself."; |
| 3729 | body.Font = Theme.F("Segoe UI", 9.5f); |
| 3730 | body.AutoSize = false; |
| 3731 | body.SetBounds(Theme.S(18), Theme.S(50), Theme.S(424), Theme.S(140)); |
| 3732 | Button steam = new Button(); |
| 3733 | steam.Text = "Open the Steam page"; |
| 3734 | steam.FlatStyle = FlatStyle.Flat; |
| 3735 | steam.BackColor = Theme.Orange; |
| 3736 | steam.ForeColor = Theme.OnAccent; |
| 3737 | steam.FlatAppearance.BorderSize = 0; |
| 3738 | steam.Font = Theme.F("Segoe UI Semibold", 9f); |
| 3739 | steam.SetBounds(Theme.S(18), Theme.S(200), Theme.S(190), Theme.S(34)); |
| 3740 | steam.Click += delegate { try { Process.Start(Piracy.SteamPage); } catch (Exception) { } Close(); }; |
| 3741 | Button go = new Button(); |
| 3742 | go.Text = "Proceed and pick the .exe"; |
| 3743 | go.FlatStyle = FlatStyle.Flat; |
| 3744 | go.BackColor = Theme.Panel; |
| 3745 | go.ForeColor = Theme.Text; |
| 3746 | go.FlatAppearance.BorderColor = Theme.Edge; |
| 3747 | go.Font = Theme.F("Segoe UI", 9f); |
| 3748 | go.SetBounds(Theme.S(222), Theme.S(200), Theme.S(220), Theme.S(34)); |
| 3749 | go.Click += delegate { Proceed = true; Close(); }; |
| 3750 | Controls.Add(head); |
| 3751 | Controls.Add(body); |
| 3752 | Controls.Add(steam); |
| 3753 | Controls.Add(go); |
| 3754 | AcceptButton = steam; |
| 3755 | } |
| 3756 | } |
| 3757 | |
| 3758 | internal static class Installer |
| 3759 | { |
| 3760 | public static readonly KnownMod[] Mods = |
| 3761 | { |
| 3762 | new KnownMod(874, "CUCheats.dll", "CU Cheats - Ultra Paradise", "CUCheats"), |
| 3763 | new KnownMod(885, "SaveAnywhere.dll", "Save Anywhere", "SaveAnywhere"), |
| 3764 | new KnownMod(894, "NoDurability.dll", "No Durability", "NoDurability"), |
| 3765 | new KnownMod(915, "PickYourNumber.dll", "Pick Your Number, Age and Height", "PickYourNumber"), |
| 3766 | new KnownMod(897, "GetStinky.dll", "Get Stinky", "GetStinky"), |
| 3767 | new KnownMod(1183, "ThighHighsRevamped.dll", "Thigh Highs Revamped", "ThighHighsRevamped"), |
| 3768 | new KnownMod(1059, "AlwaysGivenAChance.dll", "Always Given A Chance", "AlwaysGivenAChance"), |
| 3769 | new KnownMod(999, "CustomDeathScreen.dll", "Custom Death Screen", null), |
| 3770 | new KnownMod(998, "NoMoreSoundCannons.dll", "No More Sound Cannons", "NoMoreSoundCannons"), |
| 3771 | new KnownMod(1190, "ControllerSupport.dll", "Controller Support", "ControllerSupport"), |
| 3772 | new KnownMod(1200, "HatsHatsHats.dll", "Hats Hats Hats", "HatsHatsHats"), |
| 3773 | new KnownMod(1204, "SpeedrunCU.dll", "Speed Run CU", "SpeedRunCU"), |
| 3774 | new KnownMod(1214, "IRegretNothing.dll", "I Regret Nothing", "IRegretNothing"), |
| 3775 | new KnownMod(1233, "Interpretation.dll", "Interpretation - Expie and Milky Reskin", "Interpretation"), |
| 3776 | }; |
| 3777 | |
| 3778 | public static readonly KeyValuePair<int, string>[] Recommended = |
| 3779 | { |
| 3780 | new KeyValuePair<int, string>(885, "Save your run anywhere, not just at the usual spots"), |
| 3781 | new KeyValuePair<int, string>(1190, "Play with an Xbox or PlayStation controller"), |
| 3782 | new KeyValuePair<int, string>(894, "Your gear and tools stop wearing out"), |
| 3783 | new KeyValuePair<int, string>(915, "Pick your experiment number, age and height"), |
| 3784 | new KeyValuePair<int, string>(1059, "Your last stand always gets its chance"), |
| 3785 | new KeyValuePair<int, string>(1200, "A Santa hat on new runs, and a traffic cone to find"), |
| 3786 | }; |
| 3787 | |
| 3788 | public static string WhyRecommended(int id) |
| 3789 | { |
| 3790 | foreach (KeyValuePair<int, string> kv in Recommended) if (kv.Key == id) return kv.Value; |
| 3791 | return null; |
| 3792 | } |
| 3793 | |
| 3794 | public const string BepInExUrl = "https://github.com/BepInEx/BepInEx/releases"; |
| 3795 | public const string BepVersion = "5.4.23.6"; |
| 3796 | private const string BepZipUrl = "https://github.com/BepInEx/BepInEx/releases/download/v5.4.23.6/BepInEx_win_x64_5.4.23.6.zip"; |
| 3797 | private const string BepSha = "6c57a714a892efb4e9e1fef63d608a3391f30ec984031c465404e4ee381a0755"; |
| 3798 | private const long BepMaxBytes = 5L * 1024 * 1024; |
| 3799 | |
| 3800 | public static string InstallBepInEx(string game, Action<int> progress) |
| 3801 | { |
| 3802 | if (!IsGameDir(game)) return "Set the game folder first."; |
| 3803 | if (GameRunning()) return "Close the game first, then try again."; |
| 3804 | ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072; |
| 3805 | byte[] zip; |
| 3806 | try |
| 3807 | { |
| 3808 | HttpWebRequest req = (HttpWebRequest)WebRequest.Create(BepZipUrl); |
| 3809 | req.UserAgent = "UltraParadiseCUTrainer/" + Program.Version; |
| 3810 | req.Timeout = 20000; |
| 3811 | req.ReadWriteTimeout = 30000; |
| 3812 | using (WebResponse res = req.GetResponse()) |
| 3813 | using (Stream s = res.GetResponseStream()) |
| 3814 | using (MemoryStream ms = new MemoryStream()) |
| 3815 | { |
| 3816 | long len = res.ContentLength; |
| 3817 | byte[] buf = new byte[65536]; |
| 3818 | int n, last = -1; |
| 3819 | while ((n = s.Read(buf, 0, buf.Length)) > 0) |
| 3820 | { |
| 3821 | ms.Write(buf, 0, n); |
| 3822 | if (ms.Length > BepMaxBytes) return "the download was bigger than expected, so it was stopped."; |
| 3823 | if (len > 0 && progress != null) |
| 3824 | { |
| 3825 | int pc = (int)(ms.Length * 100 / len); |
| 3826 | if (pc != last) { last = pc; progress(pc); } |
| 3827 | } |
| 3828 | } |
| 3829 | zip = ms.ToArray(); |
| 3830 | } |
| 3831 | } |
| 3832 | catch (Exception) { return "couldn't download BepInEx from GitHub. Check your connection, or use the download page."; } |
| 3833 | string hash; |
| 3834 | using (System.Security.Cryptography.SHA256 h = System.Security.Cryptography.SHA256.Create()) |
| 3835 | hash = BitConverter.ToString(h.ComputeHash(zip)).Replace("-", "").ToLowerInvariant(); |
| 3836 | if (hash != BepSha) return "the BepInEx download didn't match its official fingerprint, so nothing was installed."; |
| 3837 | string root = Path.GetFullPath(game).TrimEnd('\\') + "\\"; |
| 3838 | int written = 0; |
| 3839 | try |
| 3840 | { |
| 3841 | using (MemoryStream ms = new MemoryStream(zip)) |
| 3842 | using (System.IO.Compression.ZipArchive za = new System.IO.Compression.ZipArchive(ms, System.IO.Compression.ZipArchiveMode.Read)) |
| 3843 | { |
| 3844 | foreach (System.IO.Compression.ZipArchiveEntry e in za.Entries) |
| 3845 | { |
| 3846 | string name = e.FullName.Replace('/', '\\'); |
| 3847 | if (name.Length == 0 || name.EndsWith("\\")) continue; |
| 3848 | if (name.Contains("..") || Path.IsPathRooted(name)) return "the BepInEx zip had an unsafe path, so nothing more was installed."; |
| 3849 | string dest = Path.GetFullPath(Path.Combine(root, name)); |
| 3850 | if (!dest.StartsWith(root, StringComparison.OrdinalIgnoreCase)) return "the BepInEx zip had an unsafe path, so nothing more was installed."; |
| 3851 | Directory.CreateDirectory(Path.GetDirectoryName(dest)); |
| 3852 | using (Stream src = e.Open()) |
| 3853 | using (FileStream fs = new FileStream(dest, FileMode.Create, FileAccess.Write)) |
| 3854 | src.CopyTo(fs); |
| 3855 | written++; |
| 3856 | } |
| 3857 | } |
| 3858 | Directory.CreateDirectory(Plugins(game)); |
| 3859 | } |
| 3860 | catch (UnauthorizedAccessException) { return "Windows wouldn't let the trainer write to the game folder. Try running the trainer as administrator once, or install BepInEx by hand."; } |
| 3861 | catch (Exception ex) { return "couldn't unpack BepInEx: " + ex.Message; } |
| 3862 | if (BepInExVersion(game) == null) return "BepInEx was unpacked (" + written + " files), but the trainer still can't see it."; |
| 3863 | return null; |
| 3864 | } |
| 3865 | public const string ExeName = "CasualtiesUnknown.exe"; |
| 3866 | |
| 3867 | public static KnownMod ById(int id) |
| 3868 | { |
| 3869 | foreach (KnownMod m in Mods) if (m.Id == id) return m; |
| 3870 | return null; |
| 3871 | } |
| 3872 | |
| 3873 | public static string CustomExe; |
| 3874 | public static string Current; |
| 3875 | |
| 3876 | public static bool IsGameDir(string d) |
| 3877 | { |
| 3878 | try |
| 3879 | { |
| 3880 | if (string.IsNullOrEmpty(d)) return false; |
| 3881 | if (File.Exists(Path.Combine(d, ExeName))) return true; |
| 3882 | return CustomExe != null && File.Exists(CustomExe) && SameDir(Path.GetDirectoryName(CustomExe), d); |
| 3883 | } |
| 3884 | catch (Exception) { return false; } |
| 3885 | } |
| 3886 | |
| 3887 | private static bool SameDir(string a, string b) |
| 3888 | { |
| 3889 | try { return string.Equals(Path.GetFullPath(a).TrimEnd('\\'), Path.GetFullPath(b).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase); } |
| 3890 | catch (Exception) { return false; } |
| 3891 | } |
| 3892 | |
| 3893 | public static string ExeIn(string dir) |
| 3894 | { |
| 3895 | if (string.IsNullOrEmpty(dir)) return null; |
| 3896 | if (CustomExe != null && File.Exists(CustomExe) && SameDir(Path.GetDirectoryName(CustomExe), dir)) return CustomExe; |
| 3897 | string e = Path.Combine(dir, ExeName); |
| 3898 | return File.Exists(e) ? e : null; |
| 3899 | } |
| 3900 | |
| 3901 | public static string CheckExe(string exe) |
| 3902 | { |
| 3903 | if (string.IsNullOrEmpty(exe) || !File.Exists(exe)) return "That file doesn't exist."; |
| 3904 | if (!exe.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) return "Pick the game's .exe file."; |
| 3905 | string name = Path.GetFileNameWithoutExtension(exe); |
| 3906 | if (name.StartsWith("UnityCrashHandler", StringComparison.OrdinalIgnoreCase) || name.StartsWith("Ultra Paradise", StringComparison.OrdinalIgnoreCase)) |
| 3907 | return "That's not the game. Pick the game's own .exe (usually CasualtiesUnknown.exe)."; |
| 3908 | string data = Path.Combine(Path.GetDirectoryName(exe), name + "_Data"); |
| 3909 | if (!File.Exists(Path.Combine(data, @"Managed\Assembly-CSharp.dll"))) |
| 3910 | return "That doesn't look like Casualties: Unknown. The game's .exe has a folder called " + name + "_Data next to it."; |
| 3911 | return null; |
| 3912 | } |
| 3913 | |
| 3914 | public static string[] ProcessNames() |
| 3915 | { |
| 3916 | if (CustomExe == null) return new string[] { Program.GameProcess }; |
| 3917 | string n = Path.GetFileNameWithoutExtension(CustomExe); |
| 3918 | if (string.Equals(n, Program.GameProcess, StringComparison.OrdinalIgnoreCase)) return new string[] { Program.GameProcess }; |
| 3919 | return new string[] { Program.GameProcess, n }; |
| 3920 | } |
| 3921 | |
| 3922 | public static Process[] GameProcesses() |
| 3923 | { |
| 3924 | List<Process> all = new List<Process>(); |
| 3925 | foreach (string n in ProcessNames()) |
| 3926 | { |
| 3927 | try { all.AddRange(Process.GetProcessesByName(n)); } catch (Exception) { } |
| 3928 | } |
| 3929 | return all.ToArray(); |
| 3930 | } |
| 3931 | |
| 3932 | public static string GameLabel() |
| 3933 | { |
| 3934 | string exe = ExeIn(Current); |
| 3935 | if (exe == null) return "Game not found. Use Pick Game .exe."; |
| 3936 | return (SteamAppId(Current) != null ? "Steam: " : "Found: ") + exe; |
| 3937 | } |
| 3938 | |
| 3939 | public static string SteamAppId(string dir) |
| 3940 | { |
| 3941 | try |
| 3942 | { |
| 3943 | if (string.IsNullOrEmpty(dir) || CustomExe != null && SameDir(Path.GetDirectoryName(CustomExe), dir) && !string.Equals(Path.GetFileName(CustomExe), ExeName, StringComparison.OrdinalIgnoreCase)) return null; |
| 3944 | DirectoryInfo common = Directory.GetParent(Path.GetFullPath(dir).TrimEnd('\\')); |
| 3945 | if (common == null || !string.Equals(common.Name, "common", StringComparison.OrdinalIgnoreCase) || common.Parent == null) return null; |
| 3946 | string folder = Path.GetFileName(Path.GetFullPath(dir).TrimEnd('\\')); |
| 3947 | foreach (string acf in Directory.GetFiles(common.Parent.FullName, "appmanifest_*.acf")) |
| 3948 | { |
| 3949 | string txt = File.ReadAllText(acf); |
| 3950 | System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(txt, "\"installdir\"\\s+\"([^\"]+)\""); |
| 3951 | if (!m.Success || !string.Equals(m.Groups[1].Value, folder, StringComparison.OrdinalIgnoreCase)) continue; |
| 3952 | System.Text.RegularExpressions.Match id = System.Text.RegularExpressions.Regex.Match(txt, "\"appid\"\\s+\"(\\d{1,10})\""); |
| 3953 | if (id.Success) return id.Groups[1].Value; |
| 3954 | } |
| 3955 | } |
| 3956 | catch (Exception) { } |
| 3957 | return null; |
| 3958 | } |
| 3959 | |
| 3960 | public static string Launch(string dir) |
| 3961 | { |
| 3962 | if (GameRunning()) return "The game is already running."; |
| 3963 | string exe = ExeIn(dir); |
| 3964 | if (exe == null) return "The trainer can't find the game. Use Pick Game .exe in the Settings tab."; |
| 3965 | string app = SteamAppId(dir); |
| 3966 | if (app != null) |
| 3967 | { |
| 3968 | try { Process.Start("steam://rungameid/" + app); return null; } catch (Exception) { } |
| 3969 | } |
| 3970 | try |
| 3971 | { |
| 3972 | ProcessStartInfo si = new ProcessStartInfo(exe); |
| 3973 | si.WorkingDirectory = Path.GetDirectoryName(exe); |
| 3974 | si.UseShellExecute = true; |
| 3975 | Process.Start(si); |
| 3976 | return null; |
| 3977 | } |
| 3978 | catch (Exception ex) { return "Couldn't start the game: " + ex.Message; } |
| 3979 | } |
| 3980 | |
| 3981 | public static string FindGame() |
| 3982 | { |
| 3983 | foreach (Process p in GameProcesses()) |
| 3984 | { |
| 3985 | try { string d = Path.GetDirectoryName(p.MainModule.FileName); if (IsGameDir(d)) return d; } catch (Exception) { } |
| 3986 | } |
| 3987 | if (CustomExe != null && File.Exists(CustomExe)) return Path.GetDirectoryName(CustomExe); |
| 3988 | List<string> libs = new List<string>(); |
| 3989 | try |
| 3990 | { |
| 3991 | string steam = Microsoft.Win32.Registry.GetValue(@"HKEY_CURRENT_USER\Software\Valve\Steam", "SteamPath", null) as string; |
| 3992 | if (!string.IsNullOrEmpty(steam)) |
| 3993 | { |
| 3994 | steam = steam.Replace('/', '\\'); |
| 3995 | libs.Add(steam); |
| 3996 | string vdf = Path.Combine(steam, @"steamapps\libraryfolders.vdf"); |
| 3997 | if (File.Exists(vdf)) |
| 3998 | foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(File.ReadAllText(vdf), "\"path\"\\s+\"([^\"]+)\"")) |
| 3999 | libs.Add(m.Groups[1].Value.Replace("\\\\", "\\")); |
| 4000 | } |
| 4001 | } |
| 4002 | catch (Exception) { } |
| 4003 | foreach (string lib in libs) |
| 4004 | { |
| 4005 | string d = Path.Combine(lib, @"steamapps\common\Casualties Unknown"); |
| 4006 | if (IsGameDir(d)) return d; |
| 4007 | } |
| 4008 | return null; |
| 4009 | } |
| 4010 | |
| 4011 | public static string BepInExVersion(string game) |
| 4012 | { |
| 4013 | if (!IsGameDir(game)) return null; |
| 4014 | string core = Path.Combine(game, @"BepInEx\core\BepInEx.dll"); |
| 4015 | if (!File.Exists(core)) core = Path.Combine(game, @"BepInEx\core\BepInEx.Core.dll"); |
| 4016 | if (!File.Exists(core) || !File.Exists(Path.Combine(game, "winhttp.dll"))) return null; |
| 4017 | try { return FileVersionInfo.GetVersionInfo(core).FileVersion ?? "?"; } catch (Exception) { return "?"; } |
| 4018 | } |
| 4019 | |
| 4020 | public static string Plugins(string game) { return Path.Combine(game, @"BepInEx\plugins"); } |
| 4021 | |
| 4022 | public static bool Installed(string game, KnownMod m) |
| 4023 | { |
| 4024 | try |
| 4025 | { |
| 4026 | string p = Plugins(game); |
| 4027 | return Directory.Exists(p) && Directory.GetFiles(p, m.Dll, SearchOption.AllDirectories).Length > 0; |
| 4028 | } |
| 4029 | catch (Exception) { return false; } |
| 4030 | } |
| 4031 | |
| 4032 | public static bool GameRunning() |
| 4033 | { |
| 4034 | return GameProcesses().Length > 0; |
| 4035 | } |
| 4036 | |
| 4037 | public static string DownloadsFolder() |
| 4038 | { |
| 4039 | IntPtr p; |
| 4040 | try |
| 4041 | { |
| 4042 | if (SHGetKnownFolderPath(new Guid("374DE290-123F-4565-9164-39C4925E467B"), 0, IntPtr.Zero, out p) == 0) |
| 4043 | { |
| 4044 | string s = Marshal.PtrToStringUni(p); |
| 4045 | Marshal.FreeCoTaskMem(p); |
| 4046 | if (Directory.Exists(s)) return s; |
| 4047 | } |
| 4048 | } |
| 4049 | catch (Exception) { } |
| 4050 | string d = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads"); |
| 4051 | return Directory.Exists(d) ? d : null; |
| 4052 | } |
| 4053 | |
| 4054 | [DllImport("shell32.dll")] |
| 4055 | private static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint flags, IntPtr token, out IntPtr path); |
| 4056 | |
| 4057 | public static KnownMod Identify(string zip) |
| 4058 | { |
| 4059 | try |
| 4060 | { |
| 4061 | FileInfo fi = new FileInfo(zip); |
| 4062 | if (!fi.Exists || fi.Length > 200L * 1024 * 1024) return null; |
| 4063 | using (System.IO.Compression.ZipArchive za = System.IO.Compression.ZipFile.OpenRead(zip)) |
| 4064 | { |
| 4065 | bool modLoader = false; |
| 4066 | KnownMod hit = null; |
| 4067 | foreach (System.IO.Compression.ZipArchiveEntry e in za.Entries) |
| 4068 | { |
| 4069 | if (e.FullName.Replace('\\', '/').IndexOf("ModLoader/", StringComparison.OrdinalIgnoreCase) >= 0) modLoader = true; |
| 4070 | foreach (KnownMod m in Mods) |
| 4071 | if (string.Equals(e.Name, m.Dll, StringComparison.OrdinalIgnoreCase)) hit = m; |
| 4072 | } |
| 4073 | return modLoader ? null : hit; |
| 4074 | } |
| 4075 | } |
| 4076 | catch (Exception) { return null; } |
| 4077 | } |
| 4078 | |
| 4079 | public static bool LooksLikeMine(string file) |
| 4080 | { |
| 4081 | string n = Path.GetFileNameWithoutExtension(file).Replace(" ", "").ToLowerInvariant(); |
| 4082 | foreach (KnownMod m in Mods) |
| 4083 | { |
| 4084 | if (n.Contains("-" + m.Id + "-")) return true; |
| 4085 | if (n.Contains(Path.GetFileNameWithoutExtension(m.Dll).ToLowerInvariant())) return true; |
| 4086 | if (n.Contains(m.Name.Replace(" ", "").Replace(",", "").ToLowerInvariant())) return true; |
| 4087 | } |
| 4088 | return n.Contains("nomorefuckingsoundcannons") || n.Contains("cucheats"); |
| 4089 | } |
| 4090 | |
| 4091 | private static int Segment(string p, string seg) |
| 4092 | { |
| 4093 | if (p.StartsWith(seg, StringComparison.OrdinalIgnoreCase)) return 0; |
| 4094 | int i = p.IndexOf("/" + seg, StringComparison.OrdinalIgnoreCase); |
| 4095 | return i < 0 ? -1 : i + 1; |
| 4096 | } |
| 4097 | |
| 4098 | public static string Install(string zip, string game, out KnownMod mod) |
| 4099 | { |
| 4100 | mod = Identify(zip); |
| 4101 | if (mod == null) return "That zip isn't one of casualexpie's BepInEx mods."; |
| 4102 | if (!IsGameDir(game)) return "Set the game folder first."; |
| 4103 | if (BepInExVersion(game) == null) return "Install BepInEx first."; |
| 4104 | if (GameRunning()) return "Close the game first, then install."; |
| 4105 | string root = Path.GetFullPath(game).TrimEnd('\\') + "\\"; |
| 4106 | List<KeyValuePair<System.IO.Compression.ZipArchiveEntry, string>> plan = new List<KeyValuePair<System.IO.Compression.ZipArchiveEntry, string>>(); |
| 4107 | using (System.IO.Compression.ZipArchive za = System.IO.Compression.ZipFile.OpenRead(zip)) |
| 4108 | { |
| 4109 | bool tsZip = za.GetEntry("manifest.json") != null; |
| 4110 | string tsDir = "BepInEx/plugins/" + Thunderstore.Owner + "-" + (mod.Ts ?? Path.GetFileNameWithoutExtension(mod.Dll)) + "/"; |
| 4111 | foreach (System.IO.Compression.ZipArchiveEntry e in za.Entries) |
| 4112 | { |
| 4113 | if (string.IsNullOrEmpty(e.Name)) continue; |
| 4114 | string p = e.FullName.Replace('\\', '/'); |
| 4115 | if (p.Contains("../") || p.StartsWith("/") || p.Contains(":")) return "That zip has unsafe file paths, so it wasn't installed."; |
| 4116 | if (e.Name.StartsWith("README", StringComparison.OrdinalIgnoreCase) && e.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)) continue; |
| 4117 | int bi = Segment(p, "BepInEx/plugins/"); |
| 4118 | string rel; |
| 4119 | if (bi >= 0) rel = p.Substring(bi); |
| 4120 | else if (Segment(p, "BepInEx/") >= 0) continue; |
| 4121 | else if (tsZip) rel = tsDir + p; |
| 4122 | else rel = "BepInEx/plugins/" + e.Name; |
| 4123 | string target = Path.GetFullPath(Path.Combine(game, rel.Replace('/', '\\'))); |
| 4124 | if (!target.StartsWith(root + "BepInEx\\plugins\\", StringComparison.OrdinalIgnoreCase)) continue; |
| 4125 | plan.Add(new KeyValuePair<System.IO.Compression.ZipArchiveEntry, string>(e, target)); |
| 4126 | } |
| 4127 | if (plan.Count == 0) return "There was nothing to install in that zip."; |
| 4128 | foreach (KeyValuePair<System.IO.Compression.ZipArchiveEntry, string> kv in plan) |
| 4129 | { |
| 4130 | Directory.CreateDirectory(Path.GetDirectoryName(kv.Value)); |
| 4131 | System.IO.Compression.ZipFileExtensions.ExtractToFile(kv.Key, kv.Value, true); |
| 4132 | } |
| 4133 | } |
| 4134 | string plugins = Plugins(game); |
| 4135 | foreach (string f in Directory.GetFiles(plugins, mod.Dll, SearchOption.AllDirectories)) |
| 4136 | { |
| 4137 | bool fresh = false; |
| 4138 | foreach (KeyValuePair<System.IO.Compression.ZipArchiveEntry, string> kv in plan) |
| 4139 | if (string.Equals(Path.GetFullPath(f), kv.Value, StringComparison.OrdinalIgnoreCase)) fresh = true; |
| 4140 | if (!fresh) { try { File.Delete(f); } catch (Exception) { } } |
| 4141 | } |
| 4142 | return null; |
| 4143 | } |
| 4144 | |
| 4145 | public static string Remove(string game, KnownMod m) |
| 4146 | { |
| 4147 | if (GameRunning()) return "Close the game first."; |
| 4148 | int n = 0; |
| 4149 | foreach (string f in Directory.GetFiles(Plugins(game), m.Dll, SearchOption.AllDirectories)) |
| 4150 | { |
| 4151 | File.Delete(f); |
| 4152 | n++; |
| 4153 | } |
| 4154 | return n == 0 ? m.Name + " wasn't installed." : null; |
| 4155 | } |
| 4156 | } |
| 4157 | |
| 4158 | internal static class SysInfo |
| 4159 | { |
| 4160 | [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] |
| 4161 | private class MemStatus |
| 4162 | { |
| 4163 | public uint dwLength = (uint)Marshal.SizeOf(typeof(MemStatus)); |
| 4164 | public uint dwMemoryLoad; |
| 4165 | public ulong ullTotalPhys, ullAvailPhys, ullTotalPageFile, ullAvailPageFile, ullTotalVirtual, ullAvailVirtual, ullAvailExtendedVirtual; |
| 4166 | } |
| 4167 | |
| 4168 | [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] |
| 4169 | [return: MarshalAs(UnmanagedType.Bool)] |
| 4170 | private static extern bool GlobalMemoryStatusEx([In, Out] MemStatus m); |
| 4171 | |
| 4172 | private static string Reg(string key, string name) |
| 4173 | { |
| 4174 | try |
| 4175 | { |
| 4176 | object v = Microsoft.Win32.Registry.GetValue(key, name, null); |
| 4177 | return v == null ? null : v.ToString().Trim(); |
| 4178 | } |
| 4179 | catch (Exception) { return null; } |
| 4180 | } |
| 4181 | |
| 4182 | public static string WindowsVersion() |
| 4183 | { |
| 4184 | const string k = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"; |
| 4185 | string name = Reg(k, "ProductName") ?? "Windows"; |
| 4186 | string build = Reg(k, "CurrentBuild") ?? Environment.OSVersion.Version.Build.ToString(); |
| 4187 | int b; |
| 4188 | if (int.TryParse(build, out b) && b >= 22000) name = name.Replace("Windows 10", "Windows 11"); |
| 4189 | string disp = Reg(k, "DisplayVersion") ?? Reg(k, "ReleaseId"); |
| 4190 | string ubr = Reg(k, "UBR"); |
| 4191 | return name + (disp != null ? " " + disp : "") + " (build " + build + (ubr != null ? "." + ubr : "") + ", " + (Environment.Is64BitOperatingSystem ? "64-bit" : "32-bit") + ")"; |
| 4192 | } |
| 4193 | |
| 4194 | public static string Cpu() |
| 4195 | { |
| 4196 | string n = Reg(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString"); |
| 4197 | return (n ?? Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER") ?? "?") + ", " + Environment.ProcessorCount + " threads"; |
| 4198 | } |
| 4199 | |
| 4200 | public static string Ram() |
| 4201 | { |
| 4202 | try |
| 4203 | { |
| 4204 | MemStatus m = new MemStatus(); |
| 4205 | if (GlobalMemoryStatusEx(m)) return (m.ullTotalPhys / 1073741824.0).ToString("0.0", CultureInfo.InvariantCulture) + " GB"; |
| 4206 | } |
| 4207 | catch (Exception) { } |
| 4208 | return "?"; |
| 4209 | } |
| 4210 | |
| 4211 | public static List<string> Gpus() |
| 4212 | { |
| 4213 | List<string> o = new List<string>(); |
| 4214 | try |
| 4215 | { |
| 4216 | using (Microsoft.Win32.RegistryKey cls = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}")) |
| 4217 | { |
| 4218 | if (cls != null) |
| 4219 | foreach (string sub in cls.GetSubKeyNames()) |
| 4220 | { |
| 4221 | if (sub.Length != 4) continue; |
| 4222 | using (Microsoft.Win32.RegistryKey k = cls.OpenSubKey(sub)) |
| 4223 | { |
| 4224 | if (k == null) continue; |
| 4225 | string desc = k.GetValue("DriverDesc") as string; |
| 4226 | if (string.IsNullOrEmpty(desc) || desc.IndexOf("Basic Display", StringComparison.OrdinalIgnoreCase) >= 0 || desc.IndexOf("Remote", StringComparison.OrdinalIgnoreCase) >= 0 || desc.IndexOf("Virtual", StringComparison.OrdinalIgnoreCase) >= 0) continue; |
| 4227 | string ver = k.GetValue("DriverVersion") as string; |
| 4228 | string line = desc + (ver != null ? " (driver " + ver + ")" : ""); |
| 4229 | if (!o.Contains(line)) o.Add(line); |
| 4230 | } |
| 4231 | } |
| 4232 | } |
| 4233 | } |
| 4234 | catch (Exception) { } |
| 4235 | if (o.Count == 0) o.Add("?"); |
| 4236 | return o; |
| 4237 | } |
| 4238 | |
| 4239 | public static string Device() |
| 4240 | { |
| 4241 | const string k = @"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\BIOS"; |
| 4242 | string s = ((Reg(k, "SystemManufacturer") ?? "") + " " + (Reg(k, "SystemProductName") ?? "")).Trim(); |
| 4243 | if (s.IndexOf("Valve", StringComparison.OrdinalIgnoreCase) >= 0) s += " (Steam Deck)"; |
| 4244 | return s.Length > 0 ? s : null; |
| 4245 | } |
| 4246 | |
| 4247 | public static List<KeyValuePair<string, string>> Collect(string game, string attached) |
| 4248 | { |
| 4249 | List<KeyValuePair<string, string>> o = new List<KeyValuePair<string, string>>(); |
| 4250 | Action<string, string> add = delegate (string a, string b) { o.Add(new KeyValuePair<string, string>(a, b)); }; |
| 4251 | add("Trainer", Program.Name + " v" + Program.Version + " (Windows)"); |
| 4252 | add("Attached", attached); |
| 4253 | add("Windows", WindowsVersion()); |
| 4254 | string dev = Device(); |
| 4255 | if (dev != null) add("Device", dev); |
| 4256 | add("CPU", Cpu()); |
| 4257 | add("RAM", Ram()); |
| 4258 | foreach (string g in Gpus()) add("GPU", g); |
| 4259 | add(".NET", Environment.Version.ToString()); |
| 4260 | if (game != null && Installer.IsGameDir(game)) |
| 4261 | { |
| 4262 | string bep = Installer.BepInExVersion(game); |
| 4263 | add("BepInEx", bep ?? "not installed"); |
| 4264 | List<string> mods = new List<string>(); |
| 4265 | foreach (KnownMod m in Installer.Mods) if (Installer.Installed(game, m)) mods.Add(m.Name); |
| 4266 | add("My mods", mods.Count == 0 ? "none" : string.Join(", ", mods.ToArray())); |
| 4267 | } |
| 4268 | else add("Game", "not found"); |
| 4269 | return o; |
| 4270 | } |
| 4271 | |
| 4272 | public static string LogFile(string game) |
| 4273 | { |
| 4274 | string company = "Orsoniks", product = "CasualtiesUnknown"; |
| 4275 | try |
| 4276 | { |
| 4277 | if (game != null) |
| 4278 | { |
| 4279 | string info = Path.Combine(game, @"CasualtiesUnknown_Data\app.info"); |
| 4280 | if (File.Exists(info)) |
| 4281 | { |
| 4282 | string[] l = File.ReadAllLines(info); |
| 4283 | if (l.Length >= 2 && l[0].Trim().Length > 0 && l[1].Trim().Length > 0 && l[0].IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && l[1].IndexOfAny(Path.GetInvalidFileNameChars()) < 0) |
| 4284 | { |
| 4285 | company = l[0].Trim(); |
| 4286 | product = l[1].Trim(); |
| 4287 | } |
| 4288 | } |
| 4289 | } |
| 4290 | } |
| 4291 | catch (Exception) { } |
| 4292 | string low = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData"), "LocalLow"); |
| 4293 | return Path.Combine(Path.Combine(Path.Combine(low, company), product), "Player.log"); |
| 4294 | } |
| 4295 | |
| 4296 | public static string Scrub(string s) |
| 4297 | { |
| 4298 | if (s == null) return ""; |
| 4299 | string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| 4300 | if (!string.IsNullOrEmpty(home) && home.Length > 3) |
| 4301 | { |
| 4302 | s = s.Replace(home, "%USERPROFILE%"); |
| 4303 | s = s.Replace(home.Replace('\\', '/'), "%USERPROFILE%"); |
| 4304 | } |
| 4305 | string user = Environment.UserName; |
| 4306 | if (!string.IsNullOrEmpty(user) && user.Length > 2) s = s.Replace("\\" + user + "\\", "\\<user>\\").Replace("/" + user + "/", "/<user>/"); |
| 4307 | return s; |
| 4308 | } |
| 4309 | } |
| 4310 | |
| 4311 | internal class ReportPanel : Control |
| 4312 | { |
| 4313 | public Func<string> GameDir; |
| 4314 | public Func<string> Attached; |
| 4315 | public Action<string, bool> Say; |
| 4316 | |
| 4317 | private readonly TextBox log = new TextBox(); |
| 4318 | private readonly Label state = new Label(); |
| 4319 | private readonly Label sys = new Label(); |
| 4320 | private readonly CheckBox errorsOnly = new CheckBox(); |
| 4321 | private readonly Button openFolder = new Button(), copy = new Button(), save = new Button(), bugs = new Button(), refresh = new Button(); |
| 4322 | private readonly List<string> lines = new List<string>(); |
| 4323 | private List<KeyValuePair<string, string>> info; |
| 4324 | private DateTime infoAt = DateTime.MinValue; |
| 4325 | private string file, partial = ""; |
| 4326 | private long pos; |
| 4327 | private bool loading; |
| 4328 | |
| 4329 | public ReportPanel() |
| 4330 | { |
| 4331 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw, true); |
| 4332 | BackColor = Theme.Back; |
| 4333 | log.Multiline = true; |
| 4334 | log.ReadOnly = true; |
| 4335 | log.WordWrap = false; |
| 4336 | log.ScrollBars = ScrollBars.Both; |
| 4337 | log.BorderStyle = BorderStyle.None; |
| 4338 | log.BackColor = Theme.Panel; |
| 4339 | log.ForeColor = Theme.Text; |
| 4340 | log.Font = Theme.F("Consolas", 9f); |
| 4341 | log.MaxLength = 0; |
| 4342 | Controls.Add(log); |
| 4343 | foreach (Label l in new Label[] { state, sys }) |
| 4344 | { |
| 4345 | l.BackColor = Theme.Panel; |
| 4346 | l.ForeColor = Theme.Dim; |
| 4347 | l.Font = Theme.F("Segoe UI", 9f); |
| 4348 | Controls.Add(l); |
| 4349 | } |
| 4350 | sys.ForeColor = Theme.Text; |
| 4351 | sys.Text = "Reading your system..."; |
| 4352 | errorsOnly.Text = "Only warnings and errors"; |
| 4353 | errorsOnly.ForeColor = Theme.Text; |
| 4354 | errorsOnly.BackColor = Theme.Panel; |
| 4355 | errorsOnly.Font = Theme.F("Segoe UI", 9f); |
| 4356 | errorsOnly.CheckedChanged += delegate { ShowAll(); }; |
| 4357 | Controls.Add(errorsOnly); |
| 4358 | Btn(openFolder, "Open log folder", delegate { if (file != null) { try { Process.Start("explorer.exe", "\"" + Path.GetDirectoryName(file) + "\""); } catch (Exception) { } } }); |
| 4359 | Btn(refresh, "Re-read system", delegate { infoAt = DateTime.MinValue; Poll(); }); |
| 4360 | Btn(copy, "Copy report", delegate |
| 4361 | { |
| 4362 | try { Clipboard.SetText(Build()); if (Say != null) Say("Report copied. Paste it on the Nexus Bugs page.", false); } |
| 4363 | catch (Exception) { if (Say != null) Say("Couldn't copy to the clipboard. Try Save report.", true); } |
| 4364 | }); |
| 4365 | Btn(save, "Save report...", delegate |
| 4366 | { |
| 4367 | using (SaveFileDialog d = new SaveFileDialog()) |
| 4368 | { |
| 4369 | d.Filter = "Text file (*.txt)|*.txt"; |
| 4370 | d.FileName = "UltraParadise-bug-report.txt"; |
| 4371 | if (d.ShowDialog(FindForm()) != DialogResult.OK) return; |
| 4372 | try { File.WriteAllText(d.FileName, Build()); if (Say != null) Say("Report saved.", false); } |
| 4373 | catch (Exception e) { if (Say != null) Say("Couldn't save it: " + e.Message, true); } |
| 4374 | } |
| 4375 | }); |
| 4376 | Btn(bugs, "Open Nexus Bugs page", delegate { try { Process.Start(Nexus.ModUrl(Nexus.TrainerModId) + "?tab=bugs"); } catch (Exception) { } }); |
| 4377 | copy.BackColor = Theme.Orange; |
| 4378 | copy.ForeColor = Theme.OnAccent; |
| 4379 | } |
| 4380 | |
| 4381 | private void Btn(Button b, string text, EventHandler click) |
| 4382 | { |
| 4383 | b.Text = text; |
| 4384 | b.FlatStyle = FlatStyle.Flat; |
| 4385 | b.FlatAppearance.BorderColor = Theme.Edge; |
| 4386 | b.FlatAppearance.MouseOverBackColor = Theme.Hover; |
| 4387 | b.BackColor = Theme.Back; |
| 4388 | b.ForeColor = Theme.Text; |
| 4389 | b.Font = Theme.F("Segoe UI", 9f); |
| 4390 | b.Cursor = Cursors.Hand; |
| 4391 | b.Click += click; |
| 4392 | Controls.Add(b); |
| 4393 | } |
| 4394 | |
| 4395 | private Rectangle Left_ { get { int g = Theme.S(18); return new Rectangle(g, g, (int)((Width - g * 3) * 0.64f), Height - g * 2); } } |
| 4396 | private Rectangle Right_ { get { int g = Theme.S(18); Rectangle l = Left_; return new Rectangle(l.Right + g, g, Width - l.Right - g * 2, Height - g * 2); } } |
| 4397 | |
| 4398 | protected override void OnLayout(LayoutEventArgs e) |
| 4399 | { |
| 4400 | base.OnLayout(e); |
| 4401 | int p = Theme.S(14), h = Theme.S(28), head = Theme.S(34); |
| 4402 | Rectangle l = Left_, r = Right_; |
| 4403 | state.Bounds = new Rectangle(l.X + p, l.Y + head, l.Width - p * 2, Theme.S(20)); |
| 4404 | int bottom = l.Bottom - p - h; |
| 4405 | log.Bounds = new Rectangle(l.X + p, state.Bottom + Theme.S(4), l.Width - p * 2, Math.Max(Theme.S(60), bottom - Theme.S(8) - state.Bottom - Theme.S(4))); |
| 4406 | errorsOnly.Bounds = new Rectangle(l.X + p, bottom, Theme.S(190), h); |
| 4407 | openFolder.Bounds = new Rectangle(l.Right - p - Theme.S(130), bottom, Theme.S(130), h); |
| 4408 | int bw = r.Width - p * 2; |
| 4409 | int y = r.Bottom - p - h; |
| 4410 | bugs.Bounds = new Rectangle(r.X + p, y, bw, h); y -= h + Theme.S(6); |
| 4411 | save.Bounds = new Rectangle(r.X + p, y, bw, h); y -= h + Theme.S(6); |
| 4412 | copy.Bounds = new Rectangle(r.X + p, y, bw, h); y -= h + Theme.S(6); |
| 4413 | refresh.Bounds = new Rectangle(r.X + p, y, bw, h); |
| 4414 | sys.Bounds = new Rectangle(r.X + p, r.Y + head, bw, Math.Max(Theme.S(40), refresh.Top - Theme.S(70) - r.Y - head)); |
| 4415 | } |
| 4416 | |
| 4417 | protected override void OnPaint(PaintEventArgs e) |
| 4418 | { |
| 4419 | Graphics g = e.Graphics; |
| 4420 | Theme.PaintBack(g, this); |
| 4421 | using (SolidBrush b = new SolidBrush(Theme.Panel)) |
| 4422 | { |
| 4423 | g.FillRectangle(b, Left_); |
| 4424 | g.FillRectangle(b, Right_); |
| 4425 | } |
| 4426 | using (Font f = Theme.F("Segoe UI", 9f, FontStyle.Bold)) |
| 4427 | using (SolidBrush o = new SolidBrush(Theme.Orange)) |
| 4428 | { |
| 4429 | g.DrawString("GAME LOG (LIVE)", f, o, Left_.X + Theme.S(14), Left_.Y + Theme.S(12)); |
| 4430 | g.DrawString("YOUR SYSTEM", f, o, Right_.X + Theme.S(14), Right_.Y + Theme.S(12)); |
| 4431 | } |
| 4432 | using (Font f = Theme.F("Segoe UI", 8.5f)) |
| 4433 | using (SolidBrush d = new SolidBrush(Theme.Dim)) |
| 4434 | { |
| 4435 | RectangleF t = new RectangleF(Right_.X + Theme.S(14), refresh.Top - Theme.S(64), Right_.Width - Theme.S(28), Theme.S(60)); |
| 4436 | g.DrawString("Copy the report, then paste it on the Nexus Bugs page with what you did and what happened. Your user folder and name are hidden.", f, d, t); |
| 4437 | } |
| 4438 | } |
| 4439 | |
| 4440 | public void Poll() |
| 4441 | { |
| 4442 | string game = GameDir != null ? GameDir() : null; |
| 4443 | if (!loading && DateTime.UtcNow - infoAt > TimeSpan.FromSeconds(30)) |
| 4444 | { |
| 4445 | loading = true; |
| 4446 | infoAt = DateTime.UtcNow; |
| 4447 | string att = Attached != null ? Attached() : "?"; |
| 4448 | ThreadPool.QueueUserWorkItem(delegate |
| 4449 | { |
| 4450 | List<KeyValuePair<string, string>> i = null; |
| 4451 | try { i = SysInfo.Collect(game, att); } catch (Exception) { } |
| 4452 | try |
| 4453 | { |
| 4454 | BeginInvoke(new Action(delegate |
| 4455 | { |
| 4456 | loading = false; |
| 4457 | if (i == null) return; |
| 4458 | info = i; |
| 4459 | StringBuilder sb = new StringBuilder(); |
| 4460 | foreach (KeyValuePair<string, string> kv in i) sb.Append(kv.Key).Append(": ").Append(SysInfo.Scrub(kv.Value)).Append("\r\n"); |
| 4461 | sys.Text = sb.ToString(); |
| 4462 | })); |
| 4463 | } |
| 4464 | catch (Exception) { loading = false; } |
| 4465 | }); |
| 4466 | } |
| 4467 | string f = SysInfo.LogFile(game); |
| 4468 | if (f != file) { file = f; pos = 0; partial = ""; lines.Clear(); ShowAll(); } |
| 4469 | if (!File.Exists(f)) { state.Text = "No game log yet. It appears once the game has been started."; return; } |
| 4470 | bool running = Installer.GameRunning(); |
| 4471 | try |
| 4472 | { |
| 4473 | using (FileStream fs = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) |
| 4474 | { |
| 4475 | if (fs.Length < pos) { pos = 0; partial = ""; lines.Clear(); ShowAll(); } |
| 4476 | if (pos == 0 && fs.Length > 2 * 1024 * 1024) pos = fs.Length - 2 * 1024 * 1024; |
| 4477 | if (fs.Length > pos) |
| 4478 | { |
| 4479 | fs.Position = pos; |
| 4480 | byte[] buf = new byte[(int)Math.Min(fs.Length - pos, 4 * 1024 * 1024)]; |
| 4481 | int n = fs.Read(buf, 0, buf.Length); |
| 4482 | pos += n; |
| 4483 | string text = partial + Encoding.UTF8.GetString(buf, 0, n); |
| 4484 | int last = text.LastIndexOf('\n'); |
| 4485 | if (last < 0) partial = text; |
| 4486 | else |
| 4487 | { |
| 4488 | partial = text.Substring(last + 1); |
| 4489 | List<string> fresh = new List<string>(); |
| 4490 | foreach (string line in text.Substring(0, last).Split('\n')) fresh.Add(line.TrimEnd('\r')); |
| 4491 | lines.AddRange(fresh); |
| 4492 | if (lines.Count > 3000) { lines.RemoveRange(0, lines.Count - 3000); ShowAll(); } |
| 4493 | else Append(fresh); |
| 4494 | } |
| 4495 | } |
| 4496 | } |
| 4497 | state.Text = (running ? "Live. " : "The game isn't running, so this is its last log. ") + lines.Count + " lines."; |
| 4498 | } |
| 4499 | catch (Exception e) { state.Text = "Couldn't read the log: " + e.Message; } |
| 4500 | } |
| 4501 | |
| 4502 | private static bool Problem(string l) |
| 4503 | { |
| 4504 | return l.IndexOf("Exception", StringComparison.Ordinal) >= 0 || l.IndexOf("Error", StringComparison.Ordinal) >= 0 || l.IndexOf("Warning", StringComparison.Ordinal) >= 0 || l.StartsWith("[Ultra Paradise]", StringComparison.Ordinal); |
| 4505 | } |
| 4506 | |
| 4507 | private void Append(List<string> fresh) |
| 4508 | { |
| 4509 | StringBuilder sb = new StringBuilder(); |
| 4510 | foreach (string l in fresh) if (!errorsOnly.Checked || Problem(l)) sb.Append(SysInfo.Scrub(l)).Append("\r\n"); |
| 4511 | if (sb.Length > 0) log.AppendText(sb.ToString()); |
| 4512 | } |
| 4513 | |
| 4514 | private void ShowAll() |
| 4515 | { |
| 4516 | StringBuilder sb = new StringBuilder(); |
| 4517 | int start = Math.Max(0, lines.Count - 1500); |
| 4518 | for (int i = start; i < lines.Count; i++) if (!errorsOnly.Checked || Problem(lines[i])) sb.Append(SysInfo.Scrub(lines[i])).Append("\r\n"); |
| 4519 | log.Text = sb.ToString(); |
| 4520 | log.SelectionStart = log.TextLength; |
| 4521 | log.ScrollToCaret(); |
| 4522 | } |
| 4523 | |
| 4524 | private string Build() |
| 4525 | { |
| 4526 | StringBuilder sb = new StringBuilder(); |
| 4527 | sb.Append("=== Ultra Paradise CU:Trainer bug report ===\r\n"); |
| 4528 | sb.Append("Made " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC\r\n"); |
| 4529 | List<KeyValuePair<string, string>> i = info ?? SysInfo.Collect(GameDir != null ? GameDir() : null, Attached != null ? Attached() : "?"); |
| 4530 | foreach (KeyValuePair<string, string> kv in i) sb.Append(kv.Key).Append(": ").Append(kv.Value).Append("\r\n"); |
| 4531 | sb.Append("\r\n=== Last log lines (Player.log) ===\r\n"); |
| 4532 | for (int k = Math.Max(0, lines.Count - 300); k < lines.Count; k++) sb.Append(lines[k]).Append("\r\n"); |
| 4533 | return SysInfo.Scrub(sb.ToString()); |
| 4534 | } |
| 4535 | } |
| 4536 | |
| 4537 | internal class ModsPanel : Control |
| 4538 | { |
| 4539 | public string Game; |
| 4540 | public string BepInEx; |
| 4541 | public bool GameOn; |
| 4542 | public Func<List<NexusMod>> NexusList; |
| 4543 | public readonly Dictionary<int, string> Pending = new Dictionary<int, string>(); |
| 4544 | public event Action ChangeFolder, InstallFromFile, OpenPlugins, InstallBepInEx; |
| 4545 | public string BepStatus; |
| 4546 | public event Action<KnownMod> InstallPending, RemoveMod, OpenPage; |
| 4547 | public Dictionary<string, TsPackage> Ts; |
| 4548 | public List<ModManager> Managers; |
| 4549 | public string Handler, TsStatus; |
| 4550 | |
| 4551 | private static void Open(string url) |
| 4552 | { |
| 4553 | if (string.IsNullOrEmpty(url) || !(url.StartsWith("https://thunderstore.io/", StringComparison.Ordinal) || url.StartsWith("ror2mm://v1/install/thunderstore.io/", StringComparison.Ordinal))) return; |
| 4554 | try { Process.Start(url); } catch (Exception) { } |
| 4555 | } |
| 4556 | private readonly List<KeyValuePair<Rectangle, Action>> hits = new List<KeyValuePair<Rectangle, Action>>(); |
| 4557 | private Rectangle hover = Rectangle.Empty; |
| 4558 | private int scroll, contentH; |
| 4559 | private readonly Font headFont = Theme.F("Segoe UI Semibold", 8f); |
| 4560 | private readonly Font textFont = Theme.F("Segoe UI", 9f); |
| 4561 | private readonly Font smallFont = Theme.F("Segoe UI", 8.5f); |
| 4562 | private readonly Font boldFont = Theme.F("Segoe UI Semibold", 9.5f); |
| 4563 | private readonly Font btnFont = Theme.F("Segoe UI Semibold", 8.5f); |
| 4564 | |
| 4565 | public ModsPanel() |
| 4566 | { |
| 4567 | SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); |
| 4568 | BackColor = Theme.Back; |
| 4569 | AllowDrop = true; |
| 4570 | } |
| 4571 | |
| 4572 | private int Pad { get { return Theme.S(18); } } |
| 4573 | private int HeadH { get { return Theme.S(34); } } |
| 4574 | private int LeftW { get { return Theme.S(300); } } |
| 4575 | |
| 4576 | private void Head(Graphics g, string title, int x, int y, int w) |
| 4577 | { |
| 4578 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; |
| 4579 | Theme.FillRound(g, Theme.Orange, new Rectangle(x, y + Theme.S(8) + (HeadH - Theme.S(12)) / 2 - Theme.S(6), Theme.S(3), Theme.S(12)), Theme.S(1)); |
| 4580 | string sp = Theme.Spaced(title); |
| 4581 | using (SolidBrush orange = new SolidBrush(Theme.Orange)) |
| 4582 | g.DrawString(sp, headFont, orange, new RectangleF(x + Theme.S(9), y + Theme.S(8), w, HeadH - Theme.S(12)), mid); |
| 4583 | int tw = (int)g.MeasureString(sp, headFont).Width + Theme.S(16); |
| 4584 | int ly = y + Theme.S(8) + (HeadH - Theme.S(12)) / 2; |
| 4585 | using (LinearGradientBrush lb = new LinearGradientBrush(new Rectangle(x + tw - 1, ly, Math.Max(2, w - tw + 2), 1), Theme.Line, Color.FromArgb(0, Theme.Line), LinearGradientMode.Horizontal)) |
| 4586 | g.FillRectangle(lb, x + tw, ly, Math.Max(1, w - tw), 1); |
| 4587 | } |
| 4588 | |
| 4589 | private int Button(Graphics g, int x, int y, string text, bool primary, Action a) |
| 4590 | { |
| 4591 | int w = (int)Math.Ceiling(g.MeasureString(text, btnFont).Width) + Theme.S(20); |
| 4592 | Rectangle r = new Rectangle(x, y, w, Theme.S(26)); |
| 4593 | bool h = r == hover; |
| 4594 | Color fill = primary ? (h ? Theme.AccentHover : Theme.Orange) : (h ? Theme.Hover : Theme.Panel); |
| 4595 | using (SolidBrush b = new SolidBrush(fill)) g.FillRectangle(b, r); |
| 4596 | using (Pen p = new Pen(primary ? Theme.Orange : (h ? Theme.Orange : Theme.Edge))) g.DrawRectangle(p, r); |
| 4597 | StringFormat c = new StringFormat(); c.Alignment = StringAlignment.Center; c.LineAlignment = StringAlignment.Center; |
| 4598 | using (SolidBrush t = new SolidBrush(primary ? Theme.OnAccent : Theme.Text)) g.DrawString(text, btnFont, t, r, c); |
| 4599 | hits.Add(new KeyValuePair<Rectangle, Action>(r, a)); |
| 4600 | return w; |
| 4601 | } |
| 4602 | |
| 4603 | private int Para(Graphics g, string s, Font f, Color c, int x, int y, int w) |
| 4604 | { |
| 4605 | SizeF sz = g.MeasureString(s, f, w); |
| 4606 | using (SolidBrush b = new SolidBrush(c)) g.DrawString(s, f, b, new RectangleF(x, y, w, sz.Height + 2)); |
| 4607 | return (int)Math.Ceiling(sz.Height); |
| 4608 | } |
| 4609 | |
| 4610 | protected override void OnPaint(PaintEventArgs e) |
| 4611 | { |
| 4612 | Graphics g = e.Graphics; |
| 4613 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 4614 | Theme.PaintBack(g, this); |
| 4615 | hits.Clear(); |
| 4616 | |
| 4617 | int x = Pad, y = Theme.S(6), w = LeftW; |
| 4618 | Head(g, "SETUP", x, y, w); |
| 4619 | y += HeadH + Theme.S(4); |
| 4620 | |
| 4621 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString("Game folder", smallFont, d, x, y); |
| 4622 | y += Theme.S(18); |
| 4623 | StringFormat ell = new StringFormat(); ell.Trimming = StringTrimming.EllipsisPath; ell.FormatFlags = StringFormatFlags.NoWrap; |
| 4624 | using (SolidBrush t = new SolidBrush(Game != null ? Theme.Text : Theme.Bad)) |
| 4625 | g.DrawString(Game ?? "Not found. Pick the game's .exe.", textFont, t, new RectangleF(x, y, w, Theme.S(20)), ell); |
| 4626 | y += Theme.S(24); |
| 4627 | Button(g, x, y, Game != null ? "Change" : "Pick game .exe", Game == null, delegate { if (ChangeFolder != null) ChangeFolder(); }); |
| 4628 | y += Theme.S(40); |
| 4629 | |
| 4630 | using (SolidBrush d = new SolidBrush(Theme.Dim)) g.DrawString("BepInEx", smallFont, d, x, y); |
| 4631 | y += Theme.S(18); |
| 4632 | if (Game == null) |
| 4633 | { |
| 4634 | y += Para(g, "Find the game folder first.", textFont, Theme.Dim, x, y, w) + Theme.S(10); |
| 4635 | } |
| 4636 | else if (BepInEx != null) |
| 4637 | { |
| 4638 | y += Para(g, "\u2713 Installed (v" + BepInEx + ")", boldFont, Theme.On, x, y, w) + Theme.S(12); |
| 4639 | } |
| 4640 | else |
| 4641 | { |
| 4642 | y += Para(g, "\u2717 Not installed. My mods need BepInEx 5 to run.", boldFont, Theme.Bad, x, y, w) + Theme.S(6); |
| 4643 | y += Para(g, BepStatus ?? "The trainer can download BepInEx " + Installer.BepVersion + " from its official GitHub page, check it, and install it into your game folder for you.", smallFont, Theme.Soft, x, y, w) + Theme.S(8); |
| 4644 | int gx = x; |
| 4645 | gx += Button(g, gx, y, "Install BepInEx for me", true, delegate { if (InstallBepInEx != null) InstallBepInEx(); }) + Theme.S(8); |
| 4646 | Button(g, gx, y, "Download page", false, delegate { try { Process.Start(Installer.BepInExUrl); } catch (Exception) { } }); |
| 4647 | y += Theme.S(40); |
| 4648 | } |
| 4649 | |
| 4650 | if (GameOn) { y += Para(g, "The game is running. Close it before installing or removing mods.", smallFont, Theme.Orange, x, y, w) + Theme.S(10); } |
| 4651 | |
| 4652 | int bx = x; |
| 4653 | bx += Button(g, bx, y, "Install from a zip...", false, delegate { if (InstallFromFile != null) InstallFromFile(); }) + Theme.S(8); |
| 4654 | if (Game != null && BepInEx != null) Button(g, bx, y, "Open plugins folder", false, delegate { if (OpenPlugins != null) OpenPlugins(); }); |
| 4655 | y += Theme.S(40); |
| 4656 | y += Para(g, "Download any of my mods from Nexus or Thunderstore and the trainer spots it in your Downloads folder and offers to install it. You can also drag a zip onto this tab.", smallFont, Theme.Dim, x, y, w) + Theme.S(8); |
| 4657 | |
| 4658 | Head(g, "MOD MANAGERS", x, y, w); |
| 4659 | y += HeadH + Theme.S(2); |
| 4660 | if (Managers == null) y += Para(g, "Looking for mod managers...", smallFont, Theme.Dim, x, y, w) + Theme.S(6); |
| 4661 | else if (Managers.Count == 0) y += Para(g, "None found. r2modman, Gale and the Thunderstore Mod Manager can install all my mods from Thunderstore, with BepInEx set up for you.", smallFont, Theme.Soft, x, y, w) + Theme.S(6); |
| 4662 | else |
| 4663 | { |
| 4664 | foreach (ModManager m in Managers) |
| 4665 | { |
| 4666 | int mine = ModManagers.Count(m); |
| 4667 | string line = "✓ " + m.Name + " · " + m.Profiles.Count + (m.Profiles.Count == 1 ? " profile" : " profiles") + ", " + mine + " of my mods"; |
| 4668 | y += Para(g, line, textFont, Theme.On, x, y, w) + Theme.S(2); |
| 4669 | } |
| 4670 | y += Theme.S(4); |
| 4671 | if (Handler != null) y += Para(g, "\"Get with\" buttons send the mod to " + Handler + ". Mods in a mod manager only load when you start the game from it.", smallFont, Theme.Dim, x, y, w) + Theme.S(6); |
| 4672 | else y += Para(g, "Mods in a mod manager only load when you start the game from it.", smallFont, Theme.Dim, x, y, w) + Theme.S(6); |
| 4673 | } |
| 4674 | Button(g, x, y, "My Thunderstore page", false, delegate { Open(Thunderstore.TeamUrl); }); |
| 4675 | y += Theme.S(32); |
| 4676 | if (TsStatus != null) Para(g, TsStatus, smallFont, Theme.Faint, x, y, w); |
| 4677 | |
| 4678 | int rx = x + w + Theme.S(22), rw = Width - rx - Pad; |
| 4679 | Head(g, "MY MODS", rx, Theme.S(6), rw); |
| 4680 | int top = Theme.S(6) + HeadH + Theme.S(4); |
| 4681 | Region clip = g.Clip; |
| 4682 | g.SetClip(new Rectangle(rx, top, rw + Theme.S(8), Height - top)); |
| 4683 | |
| 4684 | List<KnownMod> order = new List<KnownMod>(); |
| 4685 | Dictionary<int, NexusMod> nx = new Dictionary<int, NexusMod>(); |
| 4686 | List<NexusMod> live = NexusList != null ? NexusList() : null; |
| 4687 | if (live != null) foreach (NexusMod m in live) { nx[m.Id] = m; KnownMod k = Installer.ById(m.Id); if (k != null) order.Add(k); } |
| 4688 | foreach (KnownMod k in Installer.Mods) if (!order.Contains(k)) order.Add(k); |
| 4689 | List<KnownMod> rec = new List<KnownMod>(); |
| 4690 | foreach (KeyValuePair<int, string> kv in Installer.Recommended) |
| 4691 | { |
| 4692 | KnownMod k = Installer.ById(kv.Key); |
| 4693 | if (k != null && !Pending.ContainsKey(k.Id) && !(Game != null && Installer.Installed(Game, k)) && ModManagers.Find(Managers, k) == null) rec.Add(k); |
| 4694 | } |
| 4695 | foreach (KnownMod k in rec) order.Remove(k); |
| 4696 | order.InsertRange(0, rec); |
| 4697 | |
| 4698 | int rh = Theme.S(84), ry = top - scroll; |
| 4699 | foreach (KnownMod k in order) |
| 4700 | { |
| 4701 | Rectangle r = new Rectangle(rx, ry, rw, rh - Theme.S(6)); |
| 4702 | using (SolidBrush b = new SolidBrush(Theme.Panel)) g.FillRectangle(b, r); |
| 4703 | using (Pen p = new Pen(Theme.Line)) g.DrawRectangle(p, r); |
| 4704 | NexusMod n; |
| 4705 | nx.TryGetValue(k.Id, out n); |
| 4706 | Rectangle th = new Rectangle(r.X + Theme.S(6), r.Y + Theme.S(6), Theme.S(128), r.Height - Theme.S(12)); |
| 4707 | if (n != null && n.Image != null) |
| 4708 | { |
| 4709 | float s = Math.Max(th.Width / (float)n.Image.Width, th.Height / (float)n.Image.Height); |
| 4710 | float sw = th.Width / s, sh = th.Height / s; |
| 4711 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 4712 | g.DrawImage(n.Image, th, new RectangleF((n.Image.Width - sw) / 2f, (n.Image.Height - sh) / 2f, sw, sh), GraphicsUnit.Pixel); |
| 4713 | } |
| 4714 | else |
| 4715 | { |
| 4716 | using (SolidBrush b = new SolidBrush(Theme.Thumb)) g.FillRectangle(b, th); |
| 4717 | if (n != null && n.Adult) |
| 4718 | { |
| 4719 | StringFormat cf = new StringFormat(); cf.Alignment = StringAlignment.Center; cf.LineAlignment = StringAlignment.Center; |
| 4720 | using (SolidBrush b = new SolidBrush(Theme.Bad)) g.DrawString("18+", boldFont, b, th, cf); |
| 4721 | } |
| 4722 | } |
| 4723 | |
| 4724 | bool inst = Game != null && Installer.Installed(Game, k); |
| 4725 | bool pend = Pending.ContainsKey(k.Id); |
| 4726 | TsPackage tp = null; |
| 4727 | if (Ts != null && k.Ts != null) Ts.TryGetValue(k.Ts, out tp); |
| 4728 | MgrProfile mp = ModManagers.Find(Managers, k); |
| 4729 | string mv = null; |
| 4730 | if (mp != null && k.Ts != null) mp.Versions.TryGetValue(k.Ts, out mv); |
| 4731 | bool mgrOld = mp != null && tp != null && mv != null && Thunderstore.Compare(mv, tp.Version) < 0; |
| 4732 | bool any = inst || mp != null; |
| 4733 | string status = pend ? (inst ? "Update downloaded, ready to install" : "Downloaded, ready to install") : inst ? "Installed" : "Not installed"; |
| 4734 | Color sc = pend ? Theme.Orange : inst ? Theme.On : Theme.Dim; |
| 4735 | if (k.Id == 874 && inst && !pend) { status = "Installed. It has the same cheats as this trainer, so you only need one."; sc = Theme.Orange; } |
| 4736 | if (!pend && mp != null) |
| 4737 | { |
| 4738 | string where = mp.Manager + " (" + mp.Name + ")"; |
| 4739 | if (mgrOld) { status = "Update on Thunderstore: v" + mv + " \u2192 v" + tp.Version + " in " + where; sc = Theme.Orange; } |
| 4740 | else if (inst) status += ", and in " + where; |
| 4741 | else { status = "Installed in " + where + (mv != null ? ", v" + mv : ""); sc = Theme.On; } |
| 4742 | } |
| 4743 | string why = !any && !pend ? Installer.WhyRecommended(k.Id) : null; |
| 4744 | if (why != null) { status = "\u2605 Recommended: " + why; sc = Theme.Warn; } |
| 4745 | else if (!any && !pend && tp != null) status = "Not installed \u00b7 v" + tp.Version + " on Thunderstore"; |
| 4746 | |
| 4747 | KnownMod kk = k; |
| 4748 | int bxr = r.Right - Theme.S(8); |
| 4749 | List<KeyValuePair<string, KeyValuePair<bool, Action>>> btns = new List<KeyValuePair<string, KeyValuePair<bool, Action>>>(); |
| 4750 | if (pend) btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>(inst ? "Update" : "Install", new KeyValuePair<bool, Action>(true, delegate { if (InstallPending != null) InstallPending(kk); }))); |
| 4751 | string link = tp != null ? Thunderstore.InstallLink(tp) : null; |
| 4752 | string page = tp != null ? tp.Url : null; |
| 4753 | if (mgrOld && !pend) btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>("Update", new KeyValuePair<bool, Action>(true, delegate { Open(Handler != null ? link : page); }))); |
| 4754 | btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>(any || pend ? "Nexus" : "Get it on Nexus", new KeyValuePair<bool, Action>(!any && !pend, delegate { if (OpenPage != null) OpenPage(kk); }))); |
| 4755 | if (tp != null) |
| 4756 | { |
| 4757 | if (!any && !pend && Handler != null) btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>("Get with " + Handler, new KeyValuePair<bool, Action>(false, delegate { Open(link); }))); |
| 4758 | else btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>("Thunderstore", new KeyValuePair<bool, Action>(false, delegate { Open(page); }))); |
| 4759 | } |
| 4760 | if (inst) btns.Add(new KeyValuePair<string, KeyValuePair<bool, Action>>("Remove", new KeyValuePair<bool, Action>(false, delegate { if (RemoveMod != null) RemoveMod(kk); }))); |
| 4761 | int by = r.Bottom - Theme.S(34); |
| 4762 | for (int i = btns.Count - 1; i >= 0; i--) |
| 4763 | { |
| 4764 | int bw = (int)Math.Ceiling(g.MeasureString(btns[i].Key, btnFont).Width) + Theme.S(20); |
| 4765 | bxr -= bw; |
| 4766 | Button(g, bxr, by, btns[i].Key, btns[i].Value.Key, btns[i].Value.Value); |
| 4767 | bxr -= Theme.S(6); |
| 4768 | } |
| 4769 | |
| 4770 | int tx = th.Right + Theme.S(12), tw = r.Right - Theme.S(10) - tx; |
| 4771 | StringFormat nw = new StringFormat(); nw.Trimming = StringTrimming.EllipsisCharacter; nw.FormatFlags = StringFormatFlags.NoWrap; |
| 4772 | using (SolidBrush t = new SolidBrush(Theme.Text)) g.DrawString(n != null ? n.Name : k.Name, boldFont, t, new RectangleF(tx, r.Y + Theme.S(9), tw, Theme.S(20)), nw); |
| 4773 | using (SolidBrush t = new SolidBrush(sc)) g.DrawString(status, smallFont, t, new RectangleF(tx, r.Y + Theme.S(28), tw, Theme.S(18)), nw); |
| 4774 | ry += rh; |
| 4775 | } |
| 4776 | contentH = order.Count * rh; |
| 4777 | g.Clip = clip; |
| 4778 | int view = Height - top; |
| 4779 | if (contentH > view) |
| 4780 | { |
| 4781 | int tH = Math.Max(Theme.S(30), view * view / contentH); |
| 4782 | int tY = top + (view - tH) * scroll / Math.Max(1, contentH - view); |
| 4783 | using (SolidBrush sb = new SolidBrush(Theme.Scroll)) g.FillRectangle(sb, Width - Theme.S(6), tY, Theme.S(3), tH); |
| 4784 | } |
| 4785 | for (int i = hits.Count - 1; i >= 0; i--) |
| 4786 | if (hits[i].Key.X >= rx && (hits[i].Key.Bottom <= top || hits[i].Key.Top >= Height)) hits.RemoveAt(i); |
| 4787 | } |
| 4788 | |
| 4789 | protected override void OnMouseMove(MouseEventArgs e) |
| 4790 | { |
| 4791 | Rectangle h = Rectangle.Empty; |
| 4792 | foreach (KeyValuePair<Rectangle, Action> kv in hits) if (kv.Key.Contains(e.Location)) h = kv.Key; |
| 4793 | if (h != hover) { hover = h; Invalidate(); } |
| 4794 | Cursor = h != Rectangle.Empty ? Cursors.Hand : Cursors.Default; |
| 4795 | } |
| 4796 | |
| 4797 | protected override void OnMouseLeave(EventArgs e) { if (hover != Rectangle.Empty) { hover = Rectangle.Empty; Invalidate(); } } |
| 4798 | |
| 4799 | protected override void OnMouseDown(MouseEventArgs e) |
| 4800 | { |
| 4801 | Focus(); |
| 4802 | if (e.Button != MouseButtons.Left) return; |
| 4803 | foreach (KeyValuePair<Rectangle, Action> kv in hits) |
| 4804 | if (kv.Key.Contains(e.Location)) { kv.Value(); return; } |
| 4805 | } |
| 4806 | |
| 4807 | protected override void OnMouseWheel(MouseEventArgs e) |
| 4808 | { |
| 4809 | int view = Height - (Theme.S(6) + HeadH + Theme.S(4)); |
| 4810 | int max = Math.Max(0, contentH - view); |
| 4811 | int s = Math.Max(0, Math.Min(max, scroll - e.Delta / 120 * Theme.S(60))); |
| 4812 | if (s != scroll) { scroll = s; Invalidate(); } |
| 4813 | } |
| 4814 | |
| 4815 | public event Action<string> ZipDropped; |
| 4816 | |
| 4817 | protected override void OnDragEnter(DragEventArgs e) |
| 4818 | { |
| 4819 | string[] f = e.Data.GetDataPresent(DataFormats.FileDrop) ? e.Data.GetData(DataFormats.FileDrop) as string[] : null; |
| 4820 | e.Effect = f != null && f.Length == 1 && f[0].EndsWith(".zip", StringComparison.OrdinalIgnoreCase) ? DragDropEffects.Copy : DragDropEffects.None; |
| 4821 | } |
| 4822 | |
| 4823 | protected override void OnDragDrop(DragEventArgs e) |
| 4824 | { |
| 4825 | string[] f = e.Data.GetData(DataFormats.FileDrop) as string[]; |
| 4826 | if (f != null && f.Length == 1 && ZipDropped != null) ZipDropped(f[0]); |
| 4827 | } |
| 4828 | } |
| 4829 | |
| 4830 | internal partial class MainForm : Form |
| 4831 | { |
| 4832 | private readonly Image splash; |
| 4833 | private readonly Image tile = Res.Image("tile.png"); |
| 4834 | private readonly List<Tab> tabs; |
| 4835 | private readonly List<Option> options; |
| 4836 | private readonly Dictionary<string, Option> byId = new Dictionary<string, Option>(); |
| 4837 | private readonly SideBar side = new SideBar(); |
| 4838 | private readonly TabView view = new TabView(); |
| 4839 | private readonly SpawnerPanel spawner = new SpawnerPanel(); |
| 4840 | private readonly HealthPanel health = new HealthPanel(); |
| 4841 | private AboutPanel about; |
| 4842 | private readonly ModsPanel mods = new ModsPanel(); |
| 4843 | private readonly ReportPanel report = new ReportPanel(); |
| 4844 | private readonly MyModsPanel mymods = new MyModsPanel(); |
| 4845 | private FileSystemWatcher downloads; |
| 4846 | private readonly Dictionary<string, int> zipQueue = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); |
| 4847 | private DateTime nextModsRefresh; |
| 4848 | private DateTime nexusFetched = DateTime.MinValue; |
| 4849 | private bool nexusBusy; |
| 4850 | private readonly HashSet<string> lastDangers = new HashSet<string>(); |
| 4851 | private readonly OverlayForm overlay = new OverlayForm(); |
| 4852 | private readonly System.Windows.Forms.Timer tick = new System.Windows.Forms.Timer(); |
| 4853 | private readonly Button attachBtn = new Button(); |
| 4854 | private readonly Button allOffBtn = new Button(); |
| 4855 | private readonly Button launchBtn = new Button(); |
| 4856 | private DateTime launchedAt = DateTime.MinValue; |
| 4857 | private Dictionary<string, string> settings; |
| 4858 | private readonly LinkServer link; |
| 4859 | private readonly int bannerH, sideW, footerH; |
| 4860 | private readonly Font titleFont = Theme.F("Segoe UI Black", 17f); |
| 4861 | private readonly Font subFont = Theme.F("Segoe UI Semibold", 9f); |
| 4862 | private readonly Font statusFont = Theme.F("Segoe UI Semibold", 9f); |
| 4863 | private readonly Font msgFont = Theme.F("Segoe UI", 9f); |
| 4864 | |
| 4865 | private Process game; |
| 4866 | private int gamePid; |
| 4867 | private DateTime foundAt; |
| 4868 | private bool injectTried; |
| 4869 | private string statusText = "Looking for the game..."; |
| 4870 | private Color statusColor = Theme.Dim; |
| 4871 | private string where = ""; |
| 4872 | private string message = "Click a cheat to switch it on or off. Click its key box to change the key."; |
| 4873 | private bool messageBad; |
| 4874 | private string hint; |
| 4875 | private string blocked; |
| 4876 | private bool hotkeysOn; |
| 4877 | private readonly Dictionary<int, Option> hotkeyIds = new Dictionary<int, Option>(); |
| 4878 | private DateTime nextScan, nextItemsAsk; |
| 4879 | private Rectangle lastOverlayBounds; |
| 4880 | private readonly List<KeyValuePair<string, string>> incomingItems = new List<KeyValuePair<string, string>>(); |
| 4881 | private bool itemsLoading; |
| 4882 | private DebugForm debug; |
| 4883 | private bool screenTipShown; |
| 4884 | |
| 4885 | public MainForm(Image splashImage) |
| 4886 | { |
| 4887 | splash = splashImage; |
| 4888 | using (Graphics g = CreateGraphics()) Theme.Scale = g.DpiX / 96f * Theme.UiScale; |
| 4889 | AutoScaleMode = AutoScaleMode.None; |
| 4890 | Text = Program.Name; |
| 4891 | Font = Theme.F("Segoe UI", 9f); |
| 4892 | BackColor = Theme.Back; |
| 4893 | ForeColor = Theme.Text; |
| 4894 | FormBorderStyle = FormBorderStyle.Sizable; |
| 4895 | MaximizeBox = true; |
| 4896 | StartPosition = FormStartPosition.CenterScreen; |
| 4897 | DoubleBuffered = true; |
| 4898 | KeyPreview = true; |
| 4899 | try { Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); } catch (Exception) { } |
| 4900 | bannerH = Theme.S(86); |
| 4901 | sideW = Theme.S(176); |
| 4902 | footerH = Theme.S(60); |
| 4903 | ClientSize = new Size(Theme.S(1180), Theme.S(690)); |
| 4904 | MinimumSize = SizeFromClientSize(new Size(Theme.S(960), Theme.S(680))); |
| 4905 | |
| 4906 | tabs = Catalog.Build(out options); |
| 4907 | foreach (Option o in options) byId[o.Id] = o; |
| 4908 | |
| 4909 | settings = Settings.Load(); |
| 4910 | foreach (Option o in options) |
| 4911 | { |
| 4912 | string v; |
| 4913 | if (o.Bindable && settings.TryGetValue("key." + o.Id, out v)) |
| 4914 | { |
| 4915 | int k; |
| 4916 | if (int.TryParse(v, out k)) o.Key = (Keys)k; |
| 4917 | } |
| 4918 | if (o.Kind == Kind.Slider && settings.TryGetValue("val." + o.Id, out v)) |
| 4919 | { |
| 4920 | float f; |
| 4921 | if (float.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out f)) o.Value = Math.Max(o.Min, Math.Min(o.Max, f)); |
| 4922 | } |
| 4923 | } |
| 4924 | byId["overlay"].On = Get("overlay", "1") == "1"; |
| 4925 | byId["autoattach"].On = Get("autoattach", "1") == "1"; |
| 4926 | byId["remember"].On = Get("remember", "1") == "1"; |
| 4927 | byId["launchwith"].On = Get("launchwith", "0") == "1"; |
| 4928 | byId["closewithgame"].On = Get("closewithgame", "1") == "1"; |
| 4929 | byId["autoupdate"].On = Get("autoupdate", "1") == "1"; |
| 4930 | byId["trayhide"].On = Get("trayhide", "0") == "1"; |
| 4931 | byId["bark"].On = Get("bark", "1") == "1"; |
| 4932 | byId["silentupdate"].On = Get("silentupdate", "0") == "1"; |
| 4933 | byId["debugwithgame"].On = Get("debugwithgame", "0") == "1"; |
| 4934 | byId["usagecount"].On = Get("usage", "1") == "1"; |
| 4935 | SyncThemeSliders(); |
| 4936 | Theme.Changed += OnThemeChanged; |
| 4937 | if (byId["remember"].On) |
| 4938 | { |
| 4939 | foreach (string id in Get("cheats.on", "").Split(',')) |
| 4940 | { |
| 4941 | Option o; |
| 4942 | if (id.Length > 0 && byId.TryGetValue(id, out o) && o.Kind == Kind.Toggle && !o.Local) o.On = true; |
| 4943 | } |
| 4944 | } |
| 4945 | else |
| 4946 | { |
| 4947 | byId["GameSpeed"].Value = 1f; |
| 4948 | byId["CameraZoom"].Value = 1f; |
| 4949 | } |
| 4950 | string ce = Get("gameexe", ""); |
| 4951 | if (ce.Length > 0 && Installer.CheckExe(ce) == null) Installer.CustomExe = ce; |
| 4952 | |
| 4953 | int bodyH = ClientSize.Height - bannerH - footerH; |
| 4954 | side.Tabs = tabs; |
| 4955 | side.Bounds = new Rectangle(0, bannerH, sideW, bodyH); |
| 4956 | side.ActiveCount = delegate (Tab t) |
| 4957 | { |
| 4958 | if (t.Health) return health.Issues.Count; |
| 4959 | if (t.Mods) return mods.Pending.Count; |
| 4960 | int n = 0; |
| 4961 | foreach (Option o in t.All()) if (o.Kind == Kind.Toggle && o.On && !o.Local) n++; |
| 4962 | return n; |
| 4963 | }; |
| 4964 | side.Alert = delegate (Tab t) |
| 4965 | { |
| 4966 | if (!t.Health) return false; |
| 4967 | foreach (Issue i in health.Issues) if (i.Danger) return true; |
| 4968 | return false; |
| 4969 | }; |
| 4970 | side.TabSelected += SelectTab; |
| 4971 | Controls.Add(side); |
| 4972 | |
| 4973 | view.Bounds = new Rectangle(sideW, bannerH, ClientSize.Width - sideW, bodyH); |
| 4974 | view.Clicked += RunOption; |
| 4975 | view.Rebind += delegate (Option o) |
| 4976 | { |
| 4977 | view.Capturing = view.Capturing == o ? null : o; |
| 4978 | SetMessage(view.Capturing != null ? "Press a key for " + o.Name + ". Esc cancels, Delete clears it." : "", false); |
| 4979 | view.Invalidate(); |
| 4980 | }; |
| 4981 | view.HoverChanged += delegate (Option o) { hint = o != null ? o.Hint : null; InvalidateFooter(); }; |
| 4982 | view.SliderChanged += SetSlider; |
| 4983 | view.StarClicked += ToggleFav; |
| 4984 | SetupSearch(); |
| 4985 | SetupMusic(); |
| 4986 | view.ButtonClicked += delegate (Btn b) |
| 4987 | { |
| 4988 | if (b.Act == "@theme") { RunTheme(b.Arg); return; } |
| 4989 | if (b.Act == "@barktest") { string why = PlayBark(true); SetMessage(why ?? "Woof.", why != null); return; } |
| 4990 | if (b.Act.StartsWith("@m:", StringComparison.Ordinal)) { MusicButton(b); return; } |
| 4991 | if (b.Act.StartsWith("@x:", StringComparison.Ordinal)) { ToolsButton(b); return; } |
| 4992 | if (b.Act == "@url") { try { Process.Start(new ProcessStartInfo(b.Arg) { UseShellExecute = true }); } catch (Exception) { SetMessage("Couldn't open your browser.", true); } return; } |
| 4993 | if (b.Act.StartsWith("@", StringComparison.Ordinal)) { RunGameButton(b.Act); return; } |
| 4994 | if (!link.IsConnected) { SetMessage("Attach to the game first.", true); return; } |
| 4995 | link.Send("ACT " + b.Act + (b.Arg != null ? " " + b.Arg : "")); |
| 4996 | }; |
| 4997 | Controls.Add(view); |
| 4998 | |
| 4999 | spawner.Visible = false; |
| 5000 | spawner.Spawn += delegate (string id, int n) |
| 5001 | { |
| 5002 | if (!link.IsConnected) { SetMessage("Attach to the game first.", true); return; } |
| 5003 | link.Send("SPAWN " + id + " " + n); |
| 5004 | spawner.NoteSpawn(id); |
| 5005 | }; |
| 5006 | view.Controls.Add(spawner); |
| 5007 | |
| 5008 | health.Visible = false; |
| 5009 | health.FixClicked += delegate (Fix f) |
| 5010 | { |
| 5011 | if (f.Opt != null) |
| 5012 | { |
| 5013 | if (f.Opt.Kind == Kind.Toggle && f.Opt.On) return; |
| 5014 | RunOption(f.Opt); |
| 5015 | } |
| 5016 | else |
| 5017 | { |
| 5018 | if (!link.IsConnected) { SetMessage("Attach to the game first.", true); return; } |
| 5019 | link.Send("ACT " + f.Act); |
| 5020 | } |
| 5021 | health.Invalidate(); |
| 5022 | }; |
| 5023 | view.Controls.Add(health); |
| 5024 | |
| 5025 | about = new AboutPanel(tile); |
| 5026 | about.Visible = false; |
| 5027 | DateTime cachedAt; |
| 5028 | List<NexusMod> cached = Nexus.Load(out cachedAt); |
| 5029 | if (cached != null) |
| 5030 | { |
| 5031 | about.Mods = cached; |
| 5032 | about.Status = "Saved list from " + cachedAt.ToLocalTime().ToString("d MMM, HH:mm", CultureInfo.InvariantCulture) + ". Updating..."; |
| 5033 | } |
| 5034 | view.Controls.Add(about); |
| 5035 | |
| 5036 | mods.Visible = false; |
| 5037 | string gd = Get("gamedir", ""); |
| 5038 | mods.Game = Installer.IsGameDir(gd) ? gd : Installer.FindGame(); |
| 5039 | Installer.Current = mods.Game; |
| 5040 | mods.NexusList = delegate { return about.Mods; }; |
| 5041 | DateTime tsAt; |
| 5042 | mods.Ts = Thunderstore.Load(out tsAt); |
| 5043 | about.Ts = mods.Ts; |
| 5044 | if (mods.Ts != null) mods.TsStatus = "Thunderstore: saved list from " + tsAt.ToLocalTime().ToString("d MMM, HH:mm", CultureInfo.InvariantCulture) + "."; |
| 5045 | mods.ChangeFolder += delegate { PickGameExe(); }; |
| 5046 | mods.InstallBepInEx += delegate { DoInstallBepInEx(null); }; |
| 5047 | mods.OpenPlugins += delegate |
| 5048 | { |
| 5049 | try { string p = Installer.Plugins(mods.Game); Directory.CreateDirectory(p); Process.Start("explorer.exe", "\"" + p + "\""); } catch (Exception) { } |
| 5050 | }; |
| 5051 | mods.OpenPage += delegate (KnownMod k) { try { Process.Start(Nexus.ModUrl(k.Id) + "?tab=files"); } catch (Exception) { } }; |
| 5052 | mods.InstallFromFile += delegate |
| 5053 | { |
| 5054 | using (OpenFileDialog d = new OpenFileDialog()) |
| 5055 | { |
| 5056 | d.Filter = "Mod zip (*.zip)|*.zip"; |
| 5057 | d.Title = "Pick one of casualexpie's mod zips"; |
| 5058 | string dl = Installer.DownloadsFolder(); |
| 5059 | if (dl != null) d.InitialDirectory = dl; |
| 5060 | if (d.ShowDialog(this) == DialogResult.OK) InstallZip(d.FileName); |
| 5061 | } |
| 5062 | }; |
| 5063 | mods.ZipDropped += InstallZip; |
| 5064 | mods.InstallPending += delegate (KnownMod k) |
| 5065 | { |
| 5066 | string z; |
| 5067 | if (mods.Pending.TryGetValue(k.Id, out z)) InstallZip(z); |
| 5068 | }; |
| 5069 | mods.RemoveMod += delegate (KnownMod k) |
| 5070 | { |
| 5071 | if (mods.Game == null) return; |
| 5072 | if (MessageBox.Show(this, "Remove " + k.Name + " from the game?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; |
| 5073 | string err; |
| 5074 | try { err = Installer.Remove(mods.Game, k); } catch (Exception ex) { err = "Couldn't remove it: " + ex.Message; } |
| 5075 | if (err != null) MessageBox.Show(this, err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 5076 | else SetMessage(k.Name + " removed.", false); |
| 5077 | RefreshMods(); |
| 5078 | }; |
| 5079 | view.Controls.Add(mods); |
| 5080 | RefreshMods(); |
| 5081 | |
| 5082 | report.Visible = false; |
| 5083 | report.GameDir = delegate { return mods.Game; }; |
| 5084 | report.Attached = delegate { return link.IsConnected ? "yes" : "no"; }; |
| 5085 | report.Say = SetMessage; |
| 5086 | view.Controls.Add(report); |
| 5087 | mymods.Visible = false; |
| 5088 | mymods.Send = delegate (string s) { link.Send(s); }; |
| 5089 | mymods.Say = SetMessage; |
| 5090 | mymods.TakeChanged = delegate (string g, bool on) { settings["take." + g] = on ? "1" : "0"; Settings.Save(settings); link.Send("MODTAKE " + g + " " + (on ? "1" : "0")); }; |
| 5091 | view.Controls.Add(mymods); |
| 5092 | |
| 5093 | int fy = ClientSize.Height - footerH; |
| 5094 | Style(attachBtn, "Attach now"); |
| 5095 | attachBtn.Bounds = new Rectangle(ClientSize.Width - Theme.S(16) - Theme.S(104), fy + Theme.S(16), Theme.S(104), Theme.S(28)); |
| 5096 | attachBtn.Click += delegate { injectTried = false; foundAt = DateTime.MinValue; TryAttach(true); }; |
| 5097 | Controls.Add(attachBtn); |
| 5098 | Style(allOffBtn, "All off"); |
| 5099 | allOffBtn.Bounds = new Rectangle(attachBtn.Left - Theme.S(8) - Theme.S(80), fy + Theme.S(16), Theme.S(80), Theme.S(28)); |
| 5100 | allOffBtn.Click += delegate { AllOff(); }; |
| 5101 | Controls.Add(allOffBtn); |
| 5102 | Style(launchBtn, "Start game"); |
| 5103 | launchBtn.Bounds = new Rectangle(allOffBtn.Left - Theme.S(8) - Theme.S(96), fy + Theme.S(16), Theme.S(96), Theme.S(28)); |
| 5104 | launchBtn.Click += delegate { LaunchGame(); }; |
| 5105 | Controls.Add(launchBtn); |
| 5106 | attachBtn.Anchor = allOffBtn.Anchor = launchBtn.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; |
| 5107 | side.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left; |
| 5108 | view.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; |
| 5109 | ResizeRedraw = true; |
| 5110 | view.Resize += delegate |
| 5111 | { |
| 5112 | Rectangle full = new Rectangle(0, 0, view.Width, view.Height); |
| 5113 | if (spawner.Visible) spawner.Bounds = view.SpawnerBounds(); |
| 5114 | if (mods != null && mods.Visible) mods.Bounds = full; |
| 5115 | if (about != null && about.Visible) about.Bounds = full; |
| 5116 | if (health.Visible) health.Bounds = full; |
| 5117 | if (report.Visible) report.Bounds = full; |
| 5118 | if (mymods.Visible) mymods.Bounds = full; |
| 5119 | view.Invalidate(); |
| 5120 | }; |
| 5121 | RestoreWindow(); |
| 5122 | |
| 5123 | overlay.Options = options; |
| 5124 | |
| 5125 | int start = -1; |
| 5126 | if (Get("welcomed", "0") != "1") |
| 5127 | { |
| 5128 | start = 0; |
| 5129 | settings["welcomed"] = "1"; |
| 5130 | Settings.Save(settings); |
| 5131 | } |
| 5132 | else |
| 5133 | { |
| 5134 | string tn = Get("tabname", ""); |
| 5135 | for (int i = 0; i < tabs.Count; i++) if (tabs[i].Name == tn) start = i; |
| 5136 | if (start < 0) start = 1; |
| 5137 | } |
| 5138 | side.Selected = start; |
| 5139 | SelectTab(start); |
| 5140 | |
| 5141 | link = new LinkServer(); |
| 5142 | link.Connected += delegate { Ui(OnLinked); }; |
| 5143 | link.Disconnected += delegate { Ui(OnUnlinked); }; |
| 5144 | link.Line += delegate (string s) { Ui(delegate { OnLine(s); }); }; |
| 5145 | SetupTools(); |
| 5146 | |
| 5147 | tick.Interval = 100; |
| 5148 | tick.Tick += delegate { Tick(); }; |
| 5149 | tick.Start(); |
| 5150 | try { Microsoft.Win32.SystemEvents.DisplaySettingsChanged += OnScreensChanged; } catch (Exception) { } |
| 5151 | } |
| 5152 | |
| 5153 | private int lastScreens = Monitors.Count; |
| 5154 | |
| 5155 | private void OnScreensChanged(object sender, EventArgs e) |
| 5156 | { |
| 5157 | Ui(delegate |
| 5158 | { |
| 5159 | int n = Monitors.Count; |
| 5160 | if (n != lastScreens) SetMessage(n > lastScreens ? "New screen found: you have " + n + " now. The Debug tab can move the trainer or the Debug window onto it." : "A screen was unplugged. You have " + n + " now.", false); |
| 5161 | lastScreens = n; |
| 5162 | view.Invalidate(); |
| 5163 | }); |
| 5164 | } |
| 5165 | |
| 5166 | private void ScreenTip() |
| 5167 | { |
| 5168 | if (screenTipShown || Monitors.Count < 2) return; |
| 5169 | Screen gs = Monitors.GameScreen(game); |
| 5170 | if (gs == null || gs.DeviceName != Screen.FromControl(this).DeviceName) return; |
| 5171 | screenTipShown = true; |
| 5172 | SetMessage("Tip: you have " + Monitors.Count + " screens and the trainer is on the same one as the game. Move Trainer (Debug tab) puts it on the other one.", false); |
| 5173 | } |
| 5174 | |
| 5175 | private void MoveTrainerToOther() |
| 5176 | { |
| 5177 | if (Monitors.Count < 2) { SetMessage("Only one screen is plugged in. A second screen is recommended so the trainer never covers the game.", false); return; } |
| 5178 | Screen s = Monitors.Spare(Monitors.GameScreen(game), this); |
| 5179 | if (s == null || s.DeviceName == Screen.FromControl(this).DeviceName) s = Monitors.Next(this); |
| 5180 | Monitors.MoveTo(this, s, false); |
| 5181 | SetMessage("Moved to " + Monitors.Name(s) + ".", false); |
| 5182 | } |
| 5183 | |
| 5184 | private void OpenDebug(bool other) |
| 5185 | { |
| 5186 | bool fresh = debug == null; |
| 5187 | if (fresh) |
| 5188 | { |
| 5189 | debug = new DebugForm(); |
| 5190 | debug.Game = delegate { return game; }; |
| 5191 | debug.Say = SetMessage; |
| 5192 | debug.Live = delegate (bool on) { if (link != null && link.IsConnected) link.Send("DEBUG " + (on ? "1" : "0")); if (!on) SaveDebugWindow(); }; |
| 5193 | debug.SetLinked(link != null && link.IsConnected); |
| 5194 | if (!RestoreDebugWindow() && Monitors.Count > 1) |
| 5195 | { |
| 5196 | Screen s = Monitors.Spare(Monitors.GameScreen(game), this); |
| 5197 | if (s != null) Monitors.MoveTo(debug, s, true); |
| 5198 | } |
| 5199 | } |
| 5200 | if (!debug.Visible) debug.Show(); |
| 5201 | if (debug.WindowState == FormWindowState.Minimized) debug.WindowState = FormWindowState.Normal; |
| 5202 | if (other) debug.MoveToOther(); |
| 5203 | debug.Activate(); |
| 5204 | if (fresh && Monitors.Count < 2) SetMessage("Debug window open. Tip: a second screen is recommended, so the game and the Debug window can sit side by side.", false); |
| 5205 | } |
| 5206 | |
| 5207 | private bool RestoreDebugWindow() |
| 5208 | { |
| 5209 | string[] p = Get("debugwindow", "").Split(','); |
| 5210 | if (p.Length != 5) return false; |
| 5211 | int x, y, w, h; |
| 5212 | if (!int.TryParse(p[0], out x) || !int.TryParse(p[1], out y) || !int.TryParse(p[2], out w) || !int.TryParse(p[3], out h)) return false; |
| 5213 | Rectangle r = new Rectangle(x, y, Math.Max(w, debug.MinimumSize.Width), Math.Max(h, debug.MinimumSize.Height)); |
| 5214 | bool onScreen = false; |
| 5215 | foreach (Screen s in Screen.AllScreens) |
| 5216 | { |
| 5217 | Rectangle i = Rectangle.Intersect(s.WorkingArea, r); |
| 5218 | if (i.Width >= Theme.S(200) && i.Height >= Theme.S(100)) { onScreen = true; break; } |
| 5219 | } |
| 5220 | if (!onScreen) return false; |
| 5221 | debug.StartPosition = FormStartPosition.Manual; |
| 5222 | debug.Bounds = r; |
| 5223 | if (p[4] == "1") debug.WindowState = FormWindowState.Maximized; |
| 5224 | return true; |
| 5225 | } |
| 5226 | |
| 5227 | private void SaveDebugWindow() |
| 5228 | { |
| 5229 | if (debug == null || debug.WindowState == FormWindowState.Minimized) return; |
| 5230 | Rectangle r = debug.WindowState == FormWindowState.Normal ? debug.Bounds : debug.RestoreBounds; |
| 5231 | if (r.Width <= 0 || r.Height <= 0) return; |
| 5232 | settings["debugwindow"] = r.X + "," + r.Y + "," + r.Width + "," + r.Height + "," + (debug.WindowState == FormWindowState.Maximized ? "1" : "0"); |
| 5233 | Settings.Save(settings); |
| 5234 | } |
| 5235 | |
| 5236 | private string Get(string k, string def) |
| 5237 | { |
| 5238 | string v; |
| 5239 | return settings.TryGetValue(k, out v) ? v : def; |
| 5240 | } |
| 5241 | |
| 5242 | private static void Style(Button b, string text) |
| 5243 | { |
| 5244 | b.Text = text; |
| 5245 | b.FlatStyle = FlatStyle.Flat; |
| 5246 | b.FlatAppearance.BorderColor = Theme.Edge; |
| 5247 | b.FlatAppearance.MouseOverBackColor = Theme.Hover; |
| 5248 | b.FlatAppearance.MouseDownBackColor = Theme.Line; |
| 5249 | b.BackColor = Theme.Panel; |
| 5250 | b.ForeColor = Theme.Text; |
| 5251 | b.Cursor = Cursors.Hand; |
| 5252 | } |
| 5253 | |
| 5254 | private void Ui(Action a) |
| 5255 | { |
| 5256 | if (IsDisposed) return; |
| 5257 | try { BeginInvoke(a); } catch (Exception) { } |
| 5258 | } |
| 5259 | |
| 5260 | private void SelectTab(int i) |
| 5261 | { |
| 5262 | if (tabs[i].Favs) RebuildFavs(); |
| 5263 | view.ShowTab(tabs[i]); |
| 5264 | ShowSearchBox(tabs[i].Search); |
| 5265 | if (tabs[i].Music) RebuildMusic(); |
| 5266 | ShowNowPlaying(tabs[i].Music); |
| 5267 | MusicTabShown(tabs[i].Music); |
| 5268 | settings["tabname"] = tabs[i].Name; |
| 5269 | Settings.Save(settings); |
| 5270 | spawner.Visible = tabs[i].Spawner; |
| 5271 | if (spawner.Visible) |
| 5272 | { |
| 5273 | spawner.Bounds = view.SpawnerBounds(); |
| 5274 | nextItemsAsk = DateTime.MinValue; |
| 5275 | } |
| 5276 | if (mods != null) |
| 5277 | { |
| 5278 | mods.Visible = tabs[i].Mods; |
| 5279 | if (mods.Visible) |
| 5280 | { |
| 5281 | mods.Bounds = new Rectangle(0, 0, view.Width, view.Height); |
| 5282 | mods.Focus(); |
| 5283 | mgrScanned = DateTime.MinValue; |
| 5284 | RefreshMods(); |
| 5285 | RefreshNexus(); |
| 5286 | RefreshThunderstore(); |
| 5287 | } |
| 5288 | } |
| 5289 | if (about != null) |
| 5290 | { |
| 5291 | about.Visible = tabs[i].About; |
| 5292 | if (about.Visible) |
| 5293 | { |
| 5294 | about.Bounds = new Rectangle(0, 0, view.Width, view.Height); |
| 5295 | about.Focus(); |
| 5296 | RefreshThunderstore(); |
| 5297 | RefreshNexus(); |
| 5298 | } |
| 5299 | } |
| 5300 | health.Visible = tabs[i].Health; |
| 5301 | if (health.Visible) health.Bounds = new Rectangle(0, 0, view.Width, view.Height); |
| 5302 | report.Visible = tabs[i].Report; |
| 5303 | if (report.Visible) { report.Bounds = new Rectangle(0, 0, view.Width, view.Height); report.Poll(); } |
| 5304 | mymods.Visible = tabs[i].MyMods; |
| 5305 | if (mymods.Visible) { mymods.Bounds = new Rectangle(0, 0, view.Width, view.Height); mymods.Outdated = UltraPara.State(GameDir()) == "old"; if (link != null && link.IsConnected) link.Send("MODS"); } |
| 5306 | SendHealthMode(); |
| 5307 | } |
| 5308 | |
| 5309 | protected override void OnShown(EventArgs e) |
| 5310 | { |
| 5311 | base.OnShown(e); |
| 5312 | if (about != null && about.Visible) { RefreshNexus(); RefreshThunderstore(); } |
| 5313 | if (Program.Quiet) return; |
| 5314 | SetupTray(); |
| 5315 | CheckOfficial(); |
| 5316 | BeginInvoke(new Action(StartupPrompts)); |
| 5317 | } |
| 5318 | |
| 5319 | private NotifyIcon tray; |
| 5320 | private ToolStripMenuItem trayStart, trayAttach; |
| 5321 | private string lastTip; |
| 5322 | |
| 5323 | private void SetupTray() |
| 5324 | { |
| 5325 | ContextMenuStrip menu = new ContextMenuStrip(); |
| 5326 | ToolStripMenuItem open = new ToolStripMenuItem("Open Trainer", null, delegate { ShowFromTray(); }); |
| 5327 | open.Font = new Font(open.Font, FontStyle.Bold); |
| 5328 | menu.Items.Add(open); |
| 5329 | menu.Items.Add(new ToolStripSeparator()); |
| 5330 | trayStart = new ToolStripMenuItem("Start Game", null, delegate { LaunchGame(); }); |
| 5331 | trayAttach = new ToolStripMenuItem("Attach Now", null, delegate { injectTried = false; foundAt = DateTime.MinValue; TryAttach(true); }); |
| 5332 | menu.Items.Add(trayStart); |
| 5333 | menu.Items.Add(trayAttach); |
| 5334 | menu.Items.Add(new ToolStripMenuItem("All Cheats Off", null, delegate { AllOff(); })); |
| 5335 | menu.Items.Add(new ToolStripMenuItem("Check for Updates", null, delegate { CheckForUpdate(true); })); |
| 5336 | menu.Items.Add(new ToolStripSeparator()); |
| 5337 | menu.Items.Add(new ToolStripMenuItem("Exit", null, delegate { Close(); })); |
| 5338 | menu.Opening += delegate |
| 5339 | { |
| 5340 | trayStart.Enabled = !Installer.GameRunning(); |
| 5341 | trayAttach.Enabled = game != null && !link.IsConnected; |
| 5342 | }; |
| 5343 | tray = new NotifyIcon(); |
| 5344 | tray.Icon = Icon; |
| 5345 | tray.ContextMenuStrip = menu; |
| 5346 | tray.DoubleClick += delegate { ShowFromTray(); }; |
| 5347 | tray.BalloonTipClicked += delegate { ShowFromTray(); }; |
| 5348 | UpdateTrayTip(); |
| 5349 | tray.Visible = true; |
| 5350 | } |
| 5351 | |
| 5352 | private void UpdateTrayTip() |
| 5353 | { |
| 5354 | if (tray == null) return; |
| 5355 | int n = 0; |
| 5356 | foreach (Option o in options) if (o.Kind == Kind.Toggle && !o.Local && o.On) n++; |
| 5357 | string state = blocked != null ? "Cheats are off (multiplayer)" : link.IsConnected ? "Attached to the game" : game != null ? "Game found, not attached" : "Game isn't running"; |
| 5358 | string tip = "CU:Trainer v" + Program.Version + "\n" + state + "\n" + n + " cheat" + (n == 1 ? "" : "s") + " on"; |
| 5359 | if (Updater.Ready != null) tip += "\nUpdate: v" + Updater.Ready.Version; |
| 5360 | if (tip.Length > 63) tip = tip.Substring(0, 63); |
| 5361 | if (tip == lastTip) return; |
| 5362 | lastTip = tip; |
| 5363 | tray.Text = tip; |
| 5364 | } |
| 5365 | |
| 5366 | private void ShowFromTray() |
| 5367 | { |
| 5368 | Show(); |
| 5369 | if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; |
| 5370 | Activate(); |
| 5371 | BringToFront(); |
| 5372 | } |
| 5373 | |
| 5374 | private void TrayNotice(string title, string text) |
| 5375 | { |
| 5376 | if (tray == null || (Visible && WindowState != FormWindowState.Minimized)) return; |
| 5377 | try { tray.ShowBalloonTip(5000, title, text, ToolTipIcon.Info); } catch (Exception) { } |
| 5378 | } |
| 5379 | |
| 5380 | private void UpdatesNotice() |
| 5381 | { |
| 5382 | if (Get("notice.updates", "0") == "1") return; |
| 5383 | settings["notice.updates"] = "1"; |
| 5384 | Settings.Save(settings); |
| 5385 | MessageBox.Show(this, |
| 5386 | "Heads up: Ultra Paradise gets updates regularly.\n\n" + |
| 5387 | "Some are big (new features), some are small (bug fixes and tweaks). Sometimes there'll be a lot of updates close together, and sometimes very few.\n\n" + |
| 5388 | "You don't need to do anything: the trainer checks for updates when it starts and asks before installing one. Turn on Update Without Asking in the Settings tab if you'd rather it just updates.\n\n" + |
| 5389 | "Every update is checked against the official fingerprints on the Nexus page before it's installed.", |
| 5390 | Program.Name + " - About updates", MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 5391 | } |
| 5392 | |
| 5393 | private void UsageNotice() |
| 5394 | { |
| 5395 | if (Get("notice.usage", "0") == "1") return; |
| 5396 | DialogResult r = MessageBox.Show(this, |
| 5397 | "Can the trainer count you as a user?\n\n" + |
| 5398 | "Once a day it would tell casualexpie's update server that it's being used, so casualexpie can see how many people use the trainer.\n\n" + |
| 5399 | "It only sends a random ID made on this PC, the trainer version and that you're on Windows. No name, no account, nothing about your PC or game, and the server doesn't keep your IP address.\n\n" + |
| 5400 | "You can change this any time with Count Me as a User in the Settings tab. Turning it off also deletes what was sent.", |
| 5401 | Program.Name + " - User count", MessageBoxButtons.YesNo, MessageBoxIcon.Question); |
| 5402 | settings["notice.usage"] = "1"; |
| 5403 | settings["usage"] = r == DialogResult.Yes ? "1" : "0"; |
| 5404 | Settings.Save(settings); |
| 5405 | byId["usagecount"].On = r == DialogResult.Yes; |
| 5406 | view.Invalidate(); |
| 5407 | } |
| 5408 | |
| 5409 | private System.Windows.Forms.Timer usageTimer; |
| 5410 | private bool usageBusy; |
| 5411 | |
| 5412 | private void SetUsageStatus(string s) |
| 5413 | { |
| 5414 | Usage.Status = s; |
| 5415 | view.Invalidate(); |
| 5416 | } |
| 5417 | |
| 5418 | private bool vtBusy; |
| 5419 | |
| 5420 | private void CheckVirusTotal(bool manual) |
| 5421 | { |
| 5422 | if (vtBusy) return; |
| 5423 | vtBusy = true; |
| 5424 | VirusTotal.Status = "Checking VirusTotal..."; |
| 5425 | view.Invalidate(); |
| 5426 | System.Threading.ThreadPool.QueueUserWorkItem(delegate |
| 5427 | { |
| 5428 | VtResult v = null; |
| 5429 | string fail = null; |
| 5430 | try { v = VirusTotal.Lookup(VirusTotal.SelfSha); } |
| 5431 | catch (Exception) { fail = "VirusTotal: couldn't reach the update server. Try Check Again later."; } |
| 5432 | try |
| 5433 | { |
| 5434 | BeginInvoke(new Action(delegate |
| 5435 | { |
| 5436 | vtBusy = false; |
| 5437 | if (v != null) VirusTotal.Self = v; |
| 5438 | if (v != null && v.Status == "queued") |
| 5439 | { |
| 5440 | System.Windows.Forms.Timer again = new System.Windows.Forms.Timer(); |
| 5441 | again.Interval = 90 * 1000; |
| 5442 | again.Tick += delegate { again.Stop(); again.Dispose(); CheckVirusTotal(false); }; |
| 5443 | again.Start(); |
| 5444 | } |
| 5445 | VirusTotal.Status = "v" + Program.Version + ". " + (fail ?? (v != null ? v.Line : "VirusTotal: no result.")); |
| 5446 | view.Invalidate(); |
| 5447 | if (manual) SetMessage(fail ?? (v != null ? v.Line : "No result."), fail != null || (v != null && v.Status == "done" && v.Flagged > 0)); |
| 5448 | })); |
| 5449 | } |
| 5450 | catch (Exception) { vtBusy = false; } |
| 5451 | }); |
| 5452 | } |
| 5453 | |
| 5454 | private void StartUsage() |
| 5455 | { |
| 5456 | CheckVirusTotal(false); |
| 5457 | UsageTick(); |
| 5458 | if (usageTimer != null) return; |
| 5459 | usageTimer = new System.Windows.Forms.Timer(); |
| 5460 | usageTimer.Interval = 60 * 60 * 1000; |
| 5461 | usageTimer.Tick += delegate { UsageTick(); }; |
| 5462 | usageTimer.Start(); |
| 5463 | } |
| 5464 | |
| 5465 | private bool boardBusy; |
| 5466 | |
| 5467 | private void RefreshBoard() |
| 5468 | { |
| 5469 | if (boardBusy) return; |
| 5470 | boardBusy = true; |
| 5471 | System.Threading.ThreadPool.QueueUserWorkItem(delegate |
| 5472 | { |
| 5473 | string s = null; |
| 5474 | try { s = Usage.Stats(); } catch (Exception) { } |
| 5475 | try |
| 5476 | { |
| 5477 | BeginInvoke(new Action(delegate |
| 5478 | { |
| 5479 | boardBusy = false; |
| 5480 | if (s != null) Usage.Board = s; |
| 5481 | else if (Usage.Board == "Loading...") Usage.Board = "Couldn't reach the update server. Tries again in an hour."; |
| 5482 | view.Invalidate(); |
| 5483 | })); |
| 5484 | } |
| 5485 | catch (Exception) { boardBusy = false; } |
| 5486 | }); |
| 5487 | } |
| 5488 | |
| 5489 | private void UsageTick() |
| 5490 | { |
| 5491 | if (usageBusy || Get("notice.usage", "0") != "1") { RefreshBoard(); return; } |
| 5492 | bool on = byId["usagecount"].On; |
| 5493 | if (!on) |
| 5494 | { |
| 5495 | if (!Usage.Status.StartsWith("You're not counted", StringComparison.Ordinal)) SetUsageStatus("You're not counted. Turn on Count Me as a User to be counted."); |
| 5496 | RefreshBoard(); |
| 5497 | return; |
| 5498 | } |
| 5499 | string id = Get("usage.id", ""); |
| 5500 | if (!Usage.ValidId(id)) |
| 5501 | { |
| 5502 | id = Usage.NewId(); |
| 5503 | settings["usage.id"] = id; |
| 5504 | Settings.Save(settings); |
| 5505 | } |
| 5506 | string day = Usage.Day.ToString(CultureInfo.InvariantCulture); |
| 5507 | bool send = Get("usage.day", "") != day; |
| 5508 | usageBusy = true; |
| 5509 | System.Threading.ThreadPool.QueueUserWorkItem(delegate |
| 5510 | { |
| 5511 | bool sent = false; |
| 5512 | string count = null; |
| 5513 | try { if (send) sent = Usage.Ping(id); } catch (Exception) { } |
| 5514 | try { count = Usage.Count(); } catch (Exception) { } |
| 5515 | try |
| 5516 | { |
| 5517 | BeginInvoke(new Action(delegate |
| 5518 | { |
| 5519 | usageBusy = false; |
| 5520 | if (sent) { settings["usage.day"] = day; Settings.Save(settings); } |
| 5521 | RefreshBoard(); |
| 5522 | if (!byId["usagecount"].On) return; |
| 5523 | SetUsageStatus(count != null ? count + " You're counted." : "Couldn't reach the server. You're counted once it's back."); |
| 5524 | })); |
| 5525 | } |
| 5526 | catch (Exception) { usageBusy = false; } |
| 5527 | }); |
| 5528 | } |
| 5529 | |
| 5530 | private void UsageOff() |
| 5531 | { |
| 5532 | string id = Get("usage.id", ""); |
| 5533 | settings.Remove("usage.id"); |
| 5534 | settings.Remove("usage.day"); |
| 5535 | Settings.Save(settings); |
| 5536 | SetUsageStatus("You're not counted. Asking the server to delete what this PC sent..."); |
| 5537 | System.Threading.ThreadPool.QueueUserWorkItem(delegate |
| 5538 | { |
| 5539 | bool ok = false; |
| 5540 | try { ok = !Usage.ValidId(id) || Usage.Forget(id); } catch (Exception) { } |
| 5541 | try |
| 5542 | { |
| 5543 | BeginInvoke(new Action(delegate |
| 5544 | { |
| 5545 | if (ok) SetUsageStatus("You're not counted. Anything this PC sent has been deleted."); |
| 5546 | else SetUsageStatus("You're not counted. The server couldn't be reached to delete the old data; it's removed after 90 days anyway."); |
| 5547 | })); |
| 5548 | } |
| 5549 | catch (Exception) { } |
| 5550 | }); |
| 5551 | } |
| 5552 | |
| 5553 | private void StartupPrompts() |
| 5554 | { |
| 5555 | if (!Program.JustUpdated && !Program.JustInstalled && OfferInstall()) return; |
| 5556 | UpdatesNotice(); |
| 5557 | UsageNotice(); |
| 5558 | StartUsage(); |
| 5559 | StartDownloadWatch(); |
| 5560 | OfferRemoveCuCheats(); |
| 5561 | OfferBepInEx(); |
| 5562 | if (Program.JustInstalled) SetMessage("Installed on this PC. Open it from the Start Menu or your desktop. You can delete the copy you downloaded.", false); |
| 5563 | if (byId["remember"].On) |
| 5564 | { |
| 5565 | int n = 0; |
| 5566 | foreach (Option o in options) if (o.Kind == Kind.Toggle && !o.Local && o.On) n++; |
| 5567 | if (n > 0) SetMessage(n + " cheat" + (n == 1 ? " is" : "s are") + " on from last time. They kick in once the trainer is attached.", false); |
| 5568 | } |
| 5569 | if (byId["launchwith"].On && !Installer.GameRunning() && !Program.JustUpdated) BeginInvoke(new Action(LaunchGame)); |
| 5570 | if (Program.JustUpdated) |
| 5571 | { |
| 5572 | SetUpdateStatus("Updated to v" + Program.Version + "."); |
| 5573 | SetMessage("Updated to v" + Program.Version + ".", false); |
| 5574 | } |
| 5575 | else if (LauncherForm.Result != null) |
| 5576 | { |
| 5577 | SetUpdateStatus(LauncherForm.Result); |
| 5578 | if (LauncherForm.Later != null) |
| 5579 | { |
| 5580 | Updater.Ready = LauncherForm.Later; |
| 5581 | SetMessage("Update available: v" + LauncherForm.Later.Version + ". Update Now is in the Settings tab.", false); |
| 5582 | UpdateTrayTip(); |
| 5583 | } |
| 5584 | } |
| 5585 | else if (byId["autoupdate"].On) CheckForUpdate(false); |
| 5586 | } |
| 5587 | |
| 5588 | private bool OfferInstall() |
| 5589 | { |
| 5590 | if (Setup.RunningInstalled) return false; |
| 5591 | string iv = Setup.InstalledVersion(); |
| 5592 | if (iv != null) |
| 5593 | { |
| 5594 | if (Updater.Compare(Program.Version, iv) <= 0) |
| 5595 | { |
| 5596 | if (MessageBox.Show(this, Program.Name + " v" + iv + " is already installed on this PC.\n\nOpen the installed one instead of this copy?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return false; |
| 5597 | return SwitchToInstalled(); |
| 5598 | } |
| 5599 | if (MessageBox.Show(this, "v" + iv + " is installed on this PC, and this copy is newer (v" + Program.Version + ").\n\nUpdate the installed one to v" + Program.Version + "?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return false; |
| 5600 | return DoInstall(); |
| 5601 | } |
| 5602 | if (Get("install.ask", "1") == "0") return false; |
| 5603 | DialogResult r = MessageBox.Show(this, |
| 5604 | "Install " + Program.Name + " on this PC?\n\n" + |
| 5605 | "It goes in your user folder (no admin needed), with Start Menu and desktop shortcuts, and shows in Windows' Installed apps so you can uninstall it there. It keeps updating itself.\n\n" + |
| 5606 | "Yes: install it\nNo: keep running it from here, and don't ask again", |
| 5607 | Program.Name, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); |
| 5608 | if (r == DialogResult.No) |
| 5609 | { |
| 5610 | settings["install.ask"] = "0"; |
| 5611 | Settings.Save(settings); |
| 5612 | return false; |
| 5613 | } |
| 5614 | return r == DialogResult.Yes && DoInstall(); |
| 5615 | } |
| 5616 | |
| 5617 | private bool DoInstall() |
| 5618 | { |
| 5619 | string err = Setup.Install(true); |
| 5620 | if (err != null) |
| 5621 | { |
| 5622 | MessageBox.Show(this, "Couldn't install it: " + err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 5623 | view.Invalidate(); |
| 5624 | return false; |
| 5625 | } |
| 5626 | return SwitchToInstalled(); |
| 5627 | } |
| 5628 | |
| 5629 | private bool SwitchToInstalled() |
| 5630 | { |
| 5631 | try { Setup.Launch(Program.JustInstalled ? "" : "--installed"); } |
| 5632 | catch (Exception e) |
| 5633 | { |
| 5634 | MessageBox.Show(this, "Installed, but couldn't open it: " + e.Message + "\n\nOpen it from the Start Menu.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 5635 | return false; |
| 5636 | } |
| 5637 | Close(); |
| 5638 | return true; |
| 5639 | } |
| 5640 | |
| 5641 | private void OfferRemoveCuCheats() |
| 5642 | { |
| 5643 | KnownMod cc = Installer.ById(874); |
| 5644 | if (mods.Game == null || cc == null || !Installer.Installed(mods.Game, cc) || Get("cucheats.keep", "0") == "1") return; |
| 5645 | DialogResult d = MessageBox.Show(this, |
| 5646 | "CU Cheats (my in-game cheat mod) is installed in your game.\n\n" + |
| 5647 | "This trainer already has every CU Cheats cheat, and having both can make the same cheats fight each other. Remove CU Cheats now?\n\n" + |
| 5648 | "Yes: remove it (you can reinstall it any time from the Install My Mods tab)\n" + |
| 5649 | "No: keep it and don't ask again", |
| 5650 | Program.Name, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); |
| 5651 | if (d == DialogResult.No) |
| 5652 | { |
| 5653 | settings["cucheats.keep"] = "1"; |
| 5654 | Settings.Save(settings); |
| 5655 | return; |
| 5656 | } |
| 5657 | if (d != DialogResult.Yes) return; |
| 5658 | if (Installer.GameRunning()) |
| 5659 | { |
| 5660 | MessageBox.Show(this, "Close the game first, then remove CU Cheats from the Install My Mods tab.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 5661 | return; |
| 5662 | } |
| 5663 | string err; |
| 5664 | try { err = Installer.Remove(mods.Game, cc); } catch (Exception ex) { err = "Couldn't remove it: " + ex.Message; } |
| 5665 | if (err != null) MessageBox.Show(this, err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 5666 | else SetMessage("CU Cheats removed. The trainer has all of its cheats.", false); |
| 5667 | RefreshMods(); |
| 5668 | } |
| 5669 | |
| 5670 | private void CheckOfficial() |
| 5671 | { |
| 5672 | Thread t = new Thread(delegate () |
| 5673 | { |
| 5674 | int r = 0; |
| 5675 | string url = Nexus.ModUrl(Nexus.TrainerModId); |
| 5676 | try { r = Nexus.VerifyOfficial(out url); } catch (Exception) { r = 0; } |
| 5677 | Ui(delegate |
| 5678 | { |
| 5679 | about.OfficialState = r; |
| 5680 | about.OfficialUrl = url; |
| 5681 | about.Invalidate(); |
| 5682 | if (r == -1) |
| 5683 | { |
| 5684 | SetMessage("This copy doesn't match the official release. Download it only from casualexpie's Nexus page.", true); |
| 5685 | DialogResult d = MessageBox.Show(this, |
| 5686 | "This copy of " + Program.Name + " doesn't match any official release listed on casualexpie's Nexus Mods page.\n\n" + |
| 5687 | "It may have been modified or repackaged by someone else, and could be unsafe. The only official downloads are on Nexus Mods and GameBanana, uploaded by casualexpie.\n\n" + |
| 5688 | "Open the official page now?", |
| 5689 | Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); |
| 5690 | if (d == DialogResult.Yes && url.StartsWith("https://www.nexusmods.com/", StringComparison.Ordinal)) |
| 5691 | { |
| 5692 | try { Process.Start(url); } catch (Exception) { } |
| 5693 | } |
| 5694 | } |
| 5695 | }); |
| 5696 | }); |
| 5697 | t.IsBackground = true; |
| 5698 | t.Start(); |
| 5699 | } |
| 5700 | |
| 5701 | private DateTime tsFetched = DateTime.MinValue, mgrScanned = DateTime.MinValue; |
| 5702 | private bool tsBusy; |
| 5703 | |
| 5704 | private void RefreshThunderstore() |
| 5705 | { |
| 5706 | if (!IsHandleCreated || tsBusy || (DateTime.UtcNow - tsFetched).TotalMinutes < 10) return; |
| 5707 | tsBusy = true; |
| 5708 | Thread t = new Thread(delegate () |
| 5709 | { |
| 5710 | Dictionary<string, TsPackage> list = null; |
| 5711 | try { list = Thunderstore.Fetch(); } catch (Exception) { } |
| 5712 | Ui(delegate |
| 5713 | { |
| 5714 | tsBusy = false; |
| 5715 | if (list != null && list.Count > 0) |
| 5716 | { |
| 5717 | tsFetched = DateTime.UtcNow; |
| 5718 | mods.Ts = list; |
| 5719 | about.Ts = list; |
| 5720 | about.Invalidate(); |
| 5721 | LoadTsThumbs(list); |
| 5722 | mods.TsStatus = "Thunderstore: " + list.Count + " of my mods, updated " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + "."; |
| 5723 | } |
| 5724 | else |
| 5725 | { |
| 5726 | tsFetched = DateTime.UtcNow.AddMinutes(-8); |
| 5727 | mods.TsStatus = mods.Ts != null ? "Couldn't reach Thunderstore, showing the saved list." : "Couldn't reach Thunderstore."; |
| 5728 | if (about.Ts == null) about.Ts = new Dictionary<string, TsPackage>(); |
| 5729 | LoadTsThumbs(about.Ts); |
| 5730 | about.Invalidate(); |
| 5731 | } |
| 5732 | mods.Invalidate(); |
| 5733 | }); |
| 5734 | }); |
| 5735 | t.IsBackground = true; |
| 5736 | t.Start(); |
| 5737 | } |
| 5738 | |
| 5739 | private void ScanManagers() |
| 5740 | { |
| 5741 | if ((DateTime.UtcNow - mgrScanned).TotalSeconds < 15) return; |
| 5742 | mgrScanned = DateTime.UtcNow; |
| 5743 | try { mods.Managers = ModManagers.Scan(); } catch (Exception) { mods.Managers = new List<ModManager>(); } |
| 5744 | mods.Handler = ModManagers.Handler(); |
| 5745 | } |
| 5746 | |
| 5747 | private void RefreshNexus() |
| 5748 | { |
| 5749 | if (!IsHandleCreated || nexusBusy || (DateTime.UtcNow - nexusFetched).TotalMinutes < 10) return; |
| 5750 | nexusBusy = true; |
| 5751 | Thread t = new Thread(delegate () |
| 5752 | { |
| 5753 | List<NexusMod> list = null; |
| 5754 | try { list = Nexus.Fetch(); } catch (Exception) { } |
| 5755 | Ui(delegate |
| 5756 | { |
| 5757 | nexusBusy = false; |
| 5758 | if (list != null) |
| 5759 | { |
| 5760 | nexusFetched = DateTime.UtcNow; |
| 5761 | about.Mods = list; |
| 5762 | about.Status = "Live from Nexus, updated " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + "."; |
| 5763 | } |
| 5764 | else |
| 5765 | { |
| 5766 | nexusFetched = DateTime.UtcNow.AddMinutes(-8); |
| 5767 | about.Status = about.Mods != null ? "Couldn't reach Nexus, showing the saved list." : "Couldn't reach Nexus. Check your connection."; |
| 5768 | if (about.Mods == null) about.Mods = new List<NexusMod>(); |
| 5769 | } |
| 5770 | about.Invalidate(); |
| 5771 | LoadThumbs(about.Mods); |
| 5772 | }); |
| 5773 | }); |
| 5774 | t.IsBackground = true; |
| 5775 | t.Start(); |
| 5776 | } |
| 5777 | |
| 5778 | private void LoadTsThumbs(Dictionary<string, TsPackage> list) |
| 5779 | { |
| 5780 | if (list == null) return; |
| 5781 | List<TsPackage> todo = new List<TsPackage>(); |
| 5782 | foreach (TsPackage p in list.Values) if (p.Image == null && p.Icon != null) todo.Add(p); |
| 5783 | if (todo.Count == 0) return; |
| 5784 | Thread t = new Thread(delegate () |
| 5785 | { |
| 5786 | foreach (TsPackage p in todo) |
| 5787 | { |
| 5788 | Bitmap b = Nexus.Thumb(p.Icon); |
| 5789 | if (b == null) continue; |
| 5790 | TsPackage pp = p; |
| 5791 | Ui(delegate { pp.Image = b; about.Invalidate(); }); |
| 5792 | } |
| 5793 | }); |
| 5794 | t.IsBackground = true; |
| 5795 | t.Start(); |
| 5796 | } |
| 5797 | |
| 5798 | private void LoadThumbs(List<NexusMod> list) |
| 5799 | { |
| 5800 | List<NexusMod> todo = new List<NexusMod>(); |
| 5801 | foreach (NexusMod m in list) if (m.Image == null && m.Thumb != null) todo.Add(m); |
| 5802 | if (todo.Count == 0) return; |
| 5803 | Thread t = new Thread(delegate () |
| 5804 | { |
| 5805 | foreach (NexusMod m in todo) |
| 5806 | { |
| 5807 | Bitmap b = Nexus.Thumb(m.Thumb); |
| 5808 | if (b == null) continue; |
| 5809 | NexusMod mm = m; |
| 5810 | Ui(delegate { mm.Image = b; about.Invalidate(); }); |
| 5811 | } |
| 5812 | }); |
| 5813 | t.IsBackground = true; |
| 5814 | t.Start(); |
| 5815 | } |
| 5816 | |
| 5817 | private void RefreshMods() |
| 5818 | { |
| 5819 | if (mods.Game != null && !Installer.IsGameDir(mods.Game)) mods.Game = null; |
| 5820 | if (mods.Game == null) mods.Game = Installer.FindGame(); |
| 5821 | if (mods.Game != null && !PiracyOk(mods.Game)) |
| 5822 | { |
| 5823 | string flagged = mods.Game; |
| 5824 | mods.Game = null; |
| 5825 | if (!piracyShown) |
| 5826 | { |
| 5827 | piracyShown = true; |
| 5828 | BeginInvoke((Action)delegate { ShowPiracy(flagged); }); |
| 5829 | } |
| 5830 | } |
| 5831 | Installer.Current = mods.Game; |
| 5832 | mods.BepInEx = mods.Game != null ? Installer.BepInExVersion(mods.Game) : null; |
| 5833 | mods.GameOn = Installer.GameRunning(); |
| 5834 | if (mods.Visible || mods.Managers == null) ScanManagers(); |
| 5835 | List<int> stale = new List<int>(); |
| 5836 | foreach (KeyValuePair<int, string> kv in mods.Pending) if (!File.Exists(kv.Value)) stale.Add(kv.Key); |
| 5837 | foreach (int id in stale) mods.Pending.Remove(id); |
| 5838 | mods.Invalidate(); |
| 5839 | side.Invalidate(); |
| 5840 | } |
| 5841 | |
| 5842 | private bool piracyShown; |
| 5843 | |
| 5844 | private bool PiracyOk(string dir) |
| 5845 | { |
| 5846 | string ok; |
| 5847 | return !Piracy.Flagged(dir) || (settings.TryGetValue("piracy.ok", out ok) && string.Equals(ok, dir, StringComparison.OrdinalIgnoreCase)); |
| 5848 | } |
| 5849 | |
| 5850 | private void ShowPiracy(string dir) |
| 5851 | { |
| 5852 | bool go; |
| 5853 | using (PiracyForm p = new PiracyForm()) { p.ShowDialog(this); go = p.Proceed; } |
| 5854 | if (!go) { SetMessage("The game in " + dir + " wasn't used. Use Pick Game .exe if you want to choose it anyway.", true); return; } |
| 5855 | PickGameExe(true); |
| 5856 | } |
| 5857 | |
| 5858 | private bool PickGameExe() |
| 5859 | { |
| 5860 | return PickGameExe(false); |
| 5861 | } |
| 5862 | |
| 5863 | private bool PickGameExe(bool proceeded) |
| 5864 | { |
| 5865 | using (OpenFileDialog d = new OpenFileDialog()) |
| 5866 | { |
| 5867 | d.Title = "Pick the Casualties: Unknown game .exe (usually CasualtiesUnknown.exe)"; |
| 5868 | d.Filter = "Game (*.exe)|*.exe"; |
| 5869 | if (mods.Game != null && Directory.Exists(mods.Game)) d.InitialDirectory = mods.Game; |
| 5870 | if (d.ShowDialog(this) != DialogResult.OK) return false; |
| 5871 | string err = Installer.CheckExe(d.FileName); |
| 5872 | if (err != null) |
| 5873 | { |
| 5874 | MessageBox.Show(this, err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 5875 | return false; |
| 5876 | } |
| 5877 | string dir = Path.GetDirectoryName(d.FileName); |
| 5878 | if (Piracy.Flagged(dir)) |
| 5879 | { |
| 5880 | if (!proceeded && !PiracyOk(dir)) |
| 5881 | { |
| 5882 | bool go; |
| 5883 | using (PiracyForm p = new PiracyForm()) { p.ShowDialog(this); go = p.Proceed; } |
| 5884 | if (!go) return false; |
| 5885 | } |
| 5886 | settings["piracy.ok"] = dir; |
| 5887 | } |
| 5888 | bool std = string.Equals(Path.GetFileName(d.FileName), Installer.ExeName, StringComparison.OrdinalIgnoreCase); |
| 5889 | Installer.CustomExe = std ? null : d.FileName; |
| 5890 | if (std) settings.Remove("gameexe"); else settings["gameexe"] = d.FileName; |
| 5891 | settings["gamedir"] = dir; |
| 5892 | Settings.Save(settings); |
| 5893 | mods.Game = dir; |
| 5894 | RefreshMods(); |
| 5895 | view.Invalidate(); |
| 5896 | SetMessage("Game set to " + d.FileName, false); |
| 5897 | return true; |
| 5898 | } |
| 5899 | } |
| 5900 | |
| 5901 | private void SyncThemeSliders() |
| 5902 | { |
| 5903 | byId["theme.bgop"].Value = Theme.BgOpacity; |
| 5904 | byId["theme.scale"].Value = (float)Math.Round(Theme.Values.ContainsKey("scale") ? Theme.UiScale * 100 : 100); |
| 5905 | byId["theme.ovop"].Value = Theme.OverlayOpacity; |
| 5906 | byId["theme.ovsize"].Value = Theme.OverlaySize; |
| 5907 | } |
| 5908 | |
| 5909 | private void SetThemeSlider(Option o, float v) |
| 5910 | { |
| 5911 | o.Value = v; |
| 5912 | string s = ((int)Math.Round(v)).ToString(CultureInfo.InvariantCulture); |
| 5913 | if (o.Id == "theme.bgop") Theme.Set("image.opacity", s); |
| 5914 | else if (o.Id == "theme.ovop") Theme.Set("overlay.opacity", s); |
| 5915 | else if (o.Id == "theme.ovsize") { Theme.Set("overlay.size", s); overlay.Invalidate(); } |
| 5916 | else if (o.Id == "theme.scale") |
| 5917 | { |
| 5918 | Theme.Values["scale"] = s; |
| 5919 | Theme.Save(); |
| 5920 | SetMessage("Size " + s + "%: click Restart Now to see it.", false); |
| 5921 | } |
| 5922 | view.Invalidate(); |
| 5923 | } |
| 5924 | |
| 5925 | private void OnThemeChanged(Color[] before) |
| 5926 | { |
| 5927 | Color[] after = Theme.Tokens(); |
| 5928 | for (int i = 0; i < before.Length; i++) if (before[i].ToArgb() == statusColor.ToArgb()) { statusColor = after[i]; break; } |
| 5929 | Theme.Recolor(this, before, after); |
| 5930 | overlay.Opacity = Theme.OverlayOpacity / 100.0; |
| 5931 | overlay.Invalidate(); |
| 5932 | SyncThemeSliders(); |
| 5933 | Invalidate(); |
| 5934 | } |
| 5935 | |
| 5936 | private void RunTheme(string arg) |
| 5937 | { |
| 5938 | int c = arg.IndexOf(':'); |
| 5939 | string cmd = c < 0 ? arg : arg.Substring(0, c), val = c < 0 ? "" : arg.Substring(c + 1); |
| 5940 | switch (cmd) |
| 5941 | { |
| 5942 | case "preset": |
| 5943 | Theme.UsePreset(val); |
| 5944 | SetMessage("Theme: " + Theme.PresetName, false); |
| 5945 | break; |
| 5946 | case "pick": |
| 5947 | using (ColorDialog cd = new ColorDialog()) |
| 5948 | { |
| 5949 | cd.FullOpen = true; |
| 5950 | cd.AnyColor = true; |
| 5951 | cd.Color = Theme.ColorOf(val); |
| 5952 | if (cd.ShowDialog(this) == DialogResult.OK) Theme.Set(val, Theme.Hex(cd.Color)); |
| 5953 | } |
| 5954 | break; |
| 5955 | case "reset": |
| 5956 | if (val.Length > 0) Theme.Set(val, null); |
| 5957 | else if (MessageBox.Show(this, "Put the trainer back to the standard dark theme? Your picture, font, size and colours are cleared.", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) |
| 5958 | { |
| 5959 | bool restart = Theme.Values.ContainsKey("scale") || Theme.Values.ContainsKey("font"); |
| 5960 | Theme.ResetAll(); |
| 5961 | SetMessage(restart ? "Theme reset. Restart the trainer to reset the font and size." : "Theme reset.", false); |
| 5962 | } |
| 5963 | break; |
| 5964 | case "img": |
| 5965 | if (val == "none") { Theme.Set("image", null); break; } |
| 5966 | using (OpenFileDialog od = new OpenFileDialog()) |
| 5967 | { |
| 5968 | od.Title = "Pick a background picture"; |
| 5969 | od.Filter = "Pictures|*.png;*.jpg;*.jpeg;*.gif;*.bmp|All files|*.*"; |
| 5970 | if (od.ShowDialog(this) != DialogResult.OK) break; |
| 5971 | Theme.Set("image", od.FileName); |
| 5972 | if (Theme.BgImage == null) { Theme.Set("image", null); SetMessage("That picture couldn't be opened.", true); } |
| 5973 | else if (Theme.BgOpacity == 0) Theme.Set("image.opacity", "30"); |
| 5974 | } |
| 5975 | break; |
| 5976 | case "fit": Theme.Set("image.fit", val); break; |
| 5977 | case "banner": Theme.Set("banner", val); break; |
| 5978 | case "corner": Theme.Set("overlay.corner", val); break; |
| 5979 | case "font": |
| 5980 | if (val == "none") { Theme.Values.Remove("font"); Theme.Save(); SetMessage("Default font: click Restart Now to see it.", false); break; } |
| 5981 | try |
| 5982 | { |
| 5983 | using (FontDialog fd = new FontDialog()) |
| 5984 | { |
| 5985 | fd.ShowEffects = false; |
| 5986 | fd.ShowColor = false; |
| 5987 | fd.FontMustExist = true; |
| 5988 | fd.AllowVerticalFonts = false; |
| 5989 | try { fd.Font = new Font(Theme.FontName ?? "Segoe UI", 10f); } catch (Exception) { } |
| 5990 | if (fd.ShowDialog(this) != DialogResult.OK) break; |
| 5991 | Theme.Values["font"] = fd.Font.FontFamily.Name; |
| 5992 | Theme.Save(); |
| 5993 | SetMessage(fd.Font.FontFamily.Name + ": click Restart Now to see it.", false); |
| 5994 | } |
| 5995 | } |
| 5996 | catch (Exception e) { SetMessage("Couldn't use that font: " + e.Message, true); } |
| 5997 | break; |
| 5998 | case "restart": |
| 5999 | Program.Relaunch = true; |
| 6000 | Close(); |
| 6001 | break; |
| 6002 | case "file": |
| 6003 | if (val == "open") |
| 6004 | { |
| 6005 | Theme.Save(); |
| 6006 | try { Process.Start("notepad.exe", "\"" + Theme.FilePath + "\""); } catch (Exception e) { SetMessage("Couldn't open it: " + e.Message, true); } |
| 6007 | } |
| 6008 | else if (val == "reload") { Theme.Reload(); SetMessage("Theme file reloaded. Font and size changes need a restart.", false); } |
| 6009 | else if (val == "import") |
| 6010 | { |
| 6011 | using (OpenFileDialog od = new OpenFileDialog()) |
| 6012 | { |
| 6013 | od.Title = "Import a theme"; |
| 6014 | od.Filter = "Theme files|*.ini;*.txt;*.theme|All files|*.*"; |
| 6015 | if (od.ShowDialog(this) != DialogResult.OK) break; |
| 6016 | string err = Theme.Import(od.FileName); |
| 6017 | SetMessage(err ?? "Theme imported. Font and size changes need a restart.", err != null); |
| 6018 | } |
| 6019 | } |
| 6020 | else if (val == "export") |
| 6021 | { |
| 6022 | using (SaveFileDialog sd = new SaveFileDialog()) |
| 6023 | { |
| 6024 | sd.Title = "Export your theme"; |
| 6025 | sd.Filter = "Theme files|*.ini|All files|*.*"; |
| 6026 | sd.FileName = "my-theme.ini"; |
| 6027 | if (sd.ShowDialog(this) != DialogResult.OK) break; |
| 6028 | string err = Theme.Export(sd.FileName); |
| 6029 | SetMessage(err ?? "Saved " + Path.GetFileName(sd.FileName) + ".", err != null); |
| 6030 | } |
| 6031 | } |
| 6032 | break; |
| 6033 | } |
| 6034 | view.Invalidate(); |
| 6035 | } |
| 6036 | |
| 6037 | private void RunGameButton(string act) |
| 6038 | { |
| 6039 | switch (act) |
| 6040 | { |
| 6041 | case "@launch": |
| 6042 | LaunchGame(); |
| 6043 | break; |
| 6044 | case "@debug": |
| 6045 | OpenDebug(false); |
| 6046 | break; |
| 6047 | case "@debugother": |
| 6048 | OpenDebug(true); |
| 6049 | break; |
| 6050 | case "@upinstall": |
| 6051 | InstallUltraPara(true); |
| 6052 | break; |
| 6053 | case "@upremove": |
| 6054 | { |
| 6055 | string gd = GameDir(); |
| 6056 | string err = gd == null ? "the game folder wasn't found" : UltraPara.Remove(gd); |
| 6057 | SetMessage(err == null ? "UltraPara.dll removed. The trainer can't attach until it's installed again." : "Couldn't remove it: " + err + ".", err != null); |
| 6058 | upAutoTried = true; |
| 6059 | RefreshUltraPara(); |
| 6060 | } |
| 6061 | break; |
| 6062 | case "@upfolder": |
| 6063 | { |
| 6064 | string gd = GameDir(); |
| 6065 | if (gd != null) try { Process.Start("explorer.exe", "\"" + gd + "\""); } catch (Exception) { } |
| 6066 | } |
| 6067 | break; |
| 6068 | case "@uplog": |
| 6069 | { |
| 6070 | string gd = GameDir(); |
| 6071 | string f = gd == null ? null : Path.Combine(Path.Combine(gd, "UltraParadise"), "UltraPara.log"); |
| 6072 | if (f != null && File.Exists(f)) try { Process.Start("notepad.exe", "\"" + f + "\""); } catch (Exception) { } |
| 6073 | else SetMessage("There's no loader log yet. It's written when the game starts with UltraPara.dll installed.", false); |
| 6074 | } |
| 6075 | break; |
| 6076 | case "@discord": |
| 6077 | SetMessage("The Discord server isn't open yet. It's coming later.", false); |
| 6078 | break; |
| 6079 | case "@trainerother": |
| 6080 | MoveTrainerToOther(); |
| 6081 | break; |
| 6082 | case "@pickexe": |
| 6083 | PickGameExe(); |
| 6084 | break; |
| 6085 | case "@updcheck": |
| 6086 | CheckForUpdate(true); |
| 6087 | break; |
| 6088 | case "@updnow": |
| 6089 | if (Updater.Ready != null) |
| 6090 | { |
| 6091 | if (Updater.Ready.VtFlagged && MessageBox.Show(this, Updater.Ready.VtLine + "\n\nInstall v" + Updater.Ready.Version + " anyway?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) break; |
| 6092 | InstallUpdate(Updater.Ready); |
| 6093 | } |
| 6094 | else CheckForUpdate(true); |
| 6095 | break; |
| 6096 | case "@vtopen": |
| 6097 | { |
| 6098 | string link = VirusTotal.Self != null ? VirusTotal.Self.Link : null; |
| 6099 | if (link == null) { try { link = "https://www.virustotal.com/gui/file/" + VirusTotal.SelfSha; } catch (Exception) { } } |
| 6100 | if (link != null) { try { Process.Start(link); } catch (Exception) { SetMessage("Couldn't open the browser.", true); } } |
| 6101 | } |
| 6102 | break; |
| 6103 | case "@vtcheck": |
| 6104 | CheckVirusTotal(true); |
| 6105 | break; |
| 6106 | case "@vtcopy": |
| 6107 | try { Clipboard.SetText(VirusTotal.SelfSha); SetMessage("Fingerprint copied.", false); } |
| 6108 | catch (Exception) { SetMessage("Couldn't copy the fingerprint.", true); } |
| 6109 | break; |
| 6110 | case "@install": |
| 6111 | if (Setup.RunningInstalled) { Setup.Install(true); SetMessage("Shortcuts and the Installed apps entry are fixed.", false); break; } |
| 6112 | if (Setup.InstalledVersion() != null && Updater.Compare(Program.Version, Setup.InstalledVersion()) <= 0) { SwitchToInstalled(); break; } |
| 6113 | DoInstall(); |
| 6114 | break; |
| 6115 | case "@uninstall": |
| 6116 | if (Setup.InstalledVersion() == null && !Setup.RunningInstalled) { SetMessage("It isn't installed on this PC.", false); break; } |
| 6117 | if (Setup.Uninstall() && Setup.RunningInstalled) Close(); |
| 6118 | break; |
| 6119 | case "@findgame": |
| 6120 | Installer.CustomExe = null; |
| 6121 | settings.Remove("gameexe"); |
| 6122 | settings.Remove("gamedir"); |
| 6123 | Settings.Save(settings); |
| 6124 | mods.Game = null; |
| 6125 | RefreshMods(); |
| 6126 | SetMessage(mods.Game != null ? "Found the game in " + mods.Game : "Couldn't find the game. Use Pick Game .exe.", mods.Game == null); |
| 6127 | break; |
| 6128 | } |
| 6129 | view.Invalidate(); |
| 6130 | } |
| 6131 | |
| 6132 | private void LaunchGame() |
| 6133 | { |
| 6134 | if (Installer.GameRunning()) { SetMessage("The game is already running.", false); return; } |
| 6135 | if (Installer.ExeIn(mods.Game) == null) |
| 6136 | { |
| 6137 | RefreshMods(); |
| 6138 | if (Installer.ExeIn(mods.Game) == null) |
| 6139 | { |
| 6140 | if (MessageBox.Show(this, "The trainer can't find Casualties: Unknown on this PC.\n\nPick the game's .exe now?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; |
| 6141 | if (!PickGameExe()) return; |
| 6142 | } |
| 6143 | } |
| 6144 | string err = Installer.Launch(mods.Game); |
| 6145 | if (err != null) { SetMessage(err, true); return; } |
| 6146 | launchedAt = DateTime.UtcNow; |
| 6147 | injectTried = false; |
| 6148 | SetStatus("Starting the game...", Theme.Orange); |
| 6149 | SetMessage("Starting Casualties: Unknown. The trainer attaches once it has loaded.", false); |
| 6150 | } |
| 6151 | |
| 6152 | private bool updateBusy; |
| 6153 | |
| 6154 | private void SetUpdateStatus(string s) |
| 6155 | { |
| 6156 | Updater.Status = s; |
| 6157 | view.Invalidate(); |
| 6158 | } |
| 6159 | |
| 6160 | private void CheckForUpdate(bool manual) |
| 6161 | { |
| 6162 | if (updateBusy) return; |
| 6163 | updateBusy = true; |
| 6164 | SetUpdateStatus("Checking for updates..."); |
| 6165 | Thread t = new Thread(delegate () |
| 6166 | { |
| 6167 | UpdateInfo u = null; |
| 6168 | string fail = null; |
| 6169 | try { u = Updater.Check(); } catch (Exception) { fail = "Couldn't reach the update server."; } |
| 6170 | Ui(delegate |
| 6171 | { |
| 6172 | updateBusy = false; |
| 6173 | Updater.Ready = u; |
| 6174 | if (fail != null) |
| 6175 | { |
| 6176 | SetUpdateStatus(fail + " You have v" + Program.Version + "."); |
| 6177 | if (manual) SetMessage(fail, true); |
| 6178 | return; |
| 6179 | } |
| 6180 | if (u == null) |
| 6181 | { |
| 6182 | SetUpdateStatus("You're up to date (v" + Program.Version + "). Checked " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + "."); |
| 6183 | if (manual) SetMessage("You have the newest version.", false); |
| 6184 | return; |
| 6185 | } |
| 6186 | SetUpdateStatus("v" + u.Version + " is out (you have v" + Program.Version + "). Click Update Now."); |
| 6187 | SetMessage("Update available: v" + u.Version + ". See the Settings tab.", false); |
| 6188 | UpdateTrayTip(); |
| 6189 | TrayNotice("Update available", "v" + u.Version + " is out. Click here to open the trainer."); |
| 6190 | bool gameOn = Installer.GameRunning(); |
| 6191 | if (!manual && byId["silentupdate"].On && !gameOn && u.VtClean) { InstallUpdate(u); return; } |
| 6192 | if (!manual && Get("update.skip", "") == u.Version && !u.Required && !u.VtFlagged) return; |
| 6193 | Native.FlashWindow(Handle, true); |
| 6194 | string msg = "Version " + u.Version + " of " + Program.Name + " is out. You have " + Program.Version + "." + |
| 6195 | (u.Notes.Length > 0 ? "\n\nWhat's new: " + u.Notes : "") + |
| 6196 | "\n\n" + u.VtLine + (u.VtFlagged ? "\nLook at the report (Settings tab > VIRUSTOTAL > Open Report) before you install it." : "") + |
| 6197 | (u.Required ? "\n\nThis update is required. Older versions may stop working." : "") + |
| 6198 | "\n\nUpdate now? The trainer downloads it, checks it against the official Nexus page, and restarts." + |
| 6199 | (gameOn ? "\n\nThe game is open: your cheats switch off for a moment. Restart the game afterwards to get all of the new version's changes." : "") + |
| 6200 | (u.Required ? "" : "\n\nNo: skip this version (you can still update from the Settings tab)."); |
| 6201 | DialogResult r = MessageBox.Show(this, msg, Program.Name, u.Required ? MessageBoxButtons.YesNo : MessageBoxButtons.YesNoCancel, u.VtFlagged ? MessageBoxIcon.Warning : MessageBoxIcon.Information); |
| 6202 | if (r == DialogResult.Yes) InstallUpdate(u); |
| 6203 | else if (r == DialogResult.No && !u.Required) |
| 6204 | { |
| 6205 | settings["update.skip"] = u.Version; |
| 6206 | Settings.Save(settings); |
| 6207 | } |
| 6208 | }); |
| 6209 | }); |
| 6210 | t.IsBackground = true; |
| 6211 | t.Start(); |
| 6212 | } |
| 6213 | |
| 6214 | private void InstallUpdate(UpdateInfo u) |
| 6215 | { |
| 6216 | if (updateBusy) return; |
| 6217 | updateBusy = true; |
| 6218 | SetUpdateStatus("Downloading v" + u.Version + "..."); |
| 6219 | Thread t = new Thread(delegate () |
| 6220 | { |
| 6221 | string file = null, err; |
| 6222 | try |
| 6223 | { |
| 6224 | err = Updater.Download(u, delegate (int pc) { Ui(delegate { SetUpdateStatus("Downloading v" + u.Version + "... " + pc + "%"); }); }, out file); |
| 6225 | } |
| 6226 | catch (Exception e) { err = e.Message; } |
| 6227 | Ui(delegate |
| 6228 | { |
| 6229 | if (err == null) |
| 6230 | { |
| 6231 | SetUpdateStatus("Installing v" + u.Version + "..."); |
| 6232 | err = Updater.Apply(file, u.Sha); |
| 6233 | } |
| 6234 | updateBusy = false; |
| 6235 | if (err != null) |
| 6236 | { |
| 6237 | SetUpdateStatus("Update failed. You still have v" + Program.Version + "."); |
| 6238 | if (MessageBox.Show(this, "The update didn't install: " + err + "\n\nOpen the Nexus page to download it by hand?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) |
| 6239 | { |
| 6240 | try { Process.Start(Nexus.ModUrl(Nexus.TrainerModId) + "?tab=files"); } catch (Exception) { } |
| 6241 | } |
| 6242 | return; |
| 6243 | } |
| 6244 | Close(); |
| 6245 | }); |
| 6246 | }); |
| 6247 | t.IsBackground = true; |
| 6248 | t.Start(); |
| 6249 | } |
| 6250 | |
| 6251 | private void SaveCheats() |
| 6252 | { |
| 6253 | if (!byId["remember"].On) return; |
| 6254 | List<string> on = new List<string>(); |
| 6255 | foreach (Option o in options) if (o.Kind == Kind.Toggle && !o.Local && o.On) on.Add(o.Id); |
| 6256 | settings["cheats.on"] = string.Join(",", on.ToArray()); |
| 6257 | Settings.Save(settings); |
| 6258 | } |
| 6259 | |
| 6260 | private bool bepBusy; |
| 6261 | |
| 6262 | private void DoInstallBepInEx(string thenZip) |
| 6263 | { |
| 6264 | if (bepBusy) return; |
| 6265 | if (mods.Game == null) { PickGameExe(); if (mods.Game == null) return; } |
| 6266 | if (Installer.GameRunning()) { MessageBox.Show(this, "Close the game first, then install BepInEx.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } |
| 6267 | bepBusy = true; |
| 6268 | string game = mods.Game; |
| 6269 | mods.BepStatus = "Downloading BepInEx " + Installer.BepVersion + "..."; |
| 6270 | mods.Invalidate(); |
| 6271 | Thread t = new Thread(delegate () |
| 6272 | { |
| 6273 | string err; |
| 6274 | try { err = Installer.InstallBepInEx(game, delegate (int pc) { Ui(delegate { mods.BepStatus = "Downloading BepInEx " + Installer.BepVersion + "... " + pc + "%"; mods.Invalidate(); }); }); } |
| 6275 | catch (Exception e) { err = e.Message; } |
| 6276 | Ui(delegate |
| 6277 | { |
| 6278 | bepBusy = false; |
| 6279 | mods.BepStatus = null; |
| 6280 | RefreshMods(); |
| 6281 | if (err != null) |
| 6282 | { |
| 6283 | MessageBox.Show(this, "BepInEx didn't install: " + err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 6284 | return; |
| 6285 | } |
| 6286 | SetMessage("BepInEx " + Installer.BepVersion + " installed.", false); |
| 6287 | if (thenZip != null && File.Exists(thenZip)) { InstallZip(thenZip); return; } |
| 6288 | MessageBox.Show(this, "BepInEx " + Installer.BepVersion + " is installed. You can install my mods now.\n\nThe first time you start the game with BepInEx it takes a little longer to load.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 6289 | }); |
| 6290 | }); |
| 6291 | t.IsBackground = true; |
| 6292 | t.Start(); |
| 6293 | } |
| 6294 | |
| 6295 | private void OfferBepInEx() |
| 6296 | { |
| 6297 | if (mods.Game == null || mods.BepInEx != null || Get("bep.ask", "1") == "0") return; |
| 6298 | DialogResult r = MessageBox.Show(this, |
| 6299 | "BepInEx isn't installed in your game. You don't need it for this trainer, but my other mods need it.\n\n" + |
| 6300 | "Download and install BepInEx " + Installer.BepVersion + " now? It comes from the official BepInEx GitHub page and is checked before it's installed.\n\n" + |
| 6301 | "Yes: install it\nNo: don't ask again (you can install it any time from the Install My Mods tab)", |
| 6302 | Program.Name, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question); |
| 6303 | if (r == DialogResult.No) { settings["bep.ask"] = "0"; Settings.Save(settings); return; } |
| 6304 | if (r == DialogResult.Yes) DoInstallBepInEx(null); |
| 6305 | } |
| 6306 | |
| 6307 | private void InstallZip(string zip) |
| 6308 | { |
| 6309 | if (mods.Game == null) { PickGameExe(); if (mods.Game == null) return; } |
| 6310 | if (mods.BepInEx == null) |
| 6311 | { |
| 6312 | if (MessageBox.Show(this, "BepInEx isn't installed in your game folder, and my mods need it.\n\nInstall BepInEx " + Installer.BepVersion + " now? The trainer downloads it from the official GitHub page, checks it, and installs it, then installs this mod.", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; |
| 6313 | DoInstallBepInEx(zip); |
| 6314 | return; |
| 6315 | } |
| 6316 | KnownMod mod; |
| 6317 | string err; |
| 6318 | try { err = Installer.Install(zip, mods.Game, out mod); } |
| 6319 | catch (Exception ex) { mod = null; err = "Couldn't install it: " + ex.Message; } |
| 6320 | if (err != null) |
| 6321 | { |
| 6322 | MessageBox.Show(this, err, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); |
| 6323 | } |
| 6324 | else |
| 6325 | { |
| 6326 | mods.Pending.Remove(mod.Id); |
| 6327 | string extra = mod.Id == 874 ? "\n\nCU Cheats does the same things as this trainer. Don't switch on the same cheats in both." : ""; |
| 6328 | MessageBox.Show(this, mod.Name + " is installed. Start the game to use it." + extra, Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Information); |
| 6329 | SetMessage(mod.Name + " installed.", false); |
| 6330 | } |
| 6331 | RefreshMods(); |
| 6332 | } |
| 6333 | |
| 6334 | private void StartDownloadWatch() |
| 6335 | { |
| 6336 | string dl = Installer.DownloadsFolder(); |
| 6337 | if (dl == null) return; |
| 6338 | try |
| 6339 | { |
| 6340 | downloads = new FileSystemWatcher(dl, "*.zip"); |
| 6341 | downloads.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size; |
| 6342 | FileSystemEventHandler h = delegate (object s, FileSystemEventArgs e) { string p = e.FullPath; Ui(delegate { zipQueue[p] = 0; }); }; |
| 6343 | downloads.Created += h; |
| 6344 | downloads.Changed += h; |
| 6345 | downloads.Renamed += delegate (object s, RenamedEventArgs e) { string p = e.FullPath; if (p.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) Ui(delegate { zipQueue[p] = 0; }); }; |
| 6346 | downloads.EnableRaisingEvents = true; |
| 6347 | } |
| 6348 | catch (Exception) { downloads = null; } |
| 6349 | |
| 6350 | Thread t = new Thread(delegate () |
| 6351 | { |
| 6352 | Dictionary<int, KeyValuePair<DateTime, string>> found = new Dictionary<int, KeyValuePair<DateTime, string>>(); |
| 6353 | try |
| 6354 | { |
| 6355 | foreach (string f in Directory.GetFiles(dl, "*.zip")) |
| 6356 | { |
| 6357 | FileInfo fi = new FileInfo(f); |
| 6358 | if (fi.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-30) || !Installer.LooksLikeMine(f)) continue; |
| 6359 | KnownMod m = Installer.Identify(f); |
| 6360 | if (m == null) continue; |
| 6361 | KeyValuePair<DateTime, string> cur; |
| 6362 | if (!found.TryGetValue(m.Id, out cur) || cur.Key < fi.LastWriteTimeUtc) found[m.Id] = new KeyValuePair<DateTime, string>(fi.LastWriteTimeUtc, f); |
| 6363 | } |
| 6364 | } |
| 6365 | catch (Exception) { } |
| 6366 | Ui(delegate |
| 6367 | { |
| 6368 | foreach (KeyValuePair<int, KeyValuePair<DateTime, string>> kv in found) |
| 6369 | { |
| 6370 | KnownMod m = Installer.ById(kv.Key); |
| 6371 | if (m != null && !SameAsInstalled(kv.Value.Value, m)) mods.Pending[kv.Key] = kv.Value.Value; |
| 6372 | } |
| 6373 | RefreshMods(); |
| 6374 | }); |
| 6375 | }); |
| 6376 | t.IsBackground = true; |
| 6377 | t.Start(); |
| 6378 | } |
| 6379 | |
| 6380 | private bool SameAsInstalled(string zip, KnownMod m) |
| 6381 | { |
| 6382 | if (mods.Game == null) return false; |
| 6383 | try |
| 6384 | { |
| 6385 | string[] inst = Directory.GetFiles(Installer.Plugins(mods.Game), m.Dll, SearchOption.AllDirectories); |
| 6386 | if (inst.Length == 0) return false; |
| 6387 | byte[] a = File.ReadAllBytes(inst[0]); |
| 6388 | using (System.IO.Compression.ZipArchive za = System.IO.Compression.ZipFile.OpenRead(zip)) |
| 6389 | foreach (System.IO.Compression.ZipArchiveEntry e in za.Entries) |
| 6390 | if (string.Equals(e.Name, m.Dll, StringComparison.OrdinalIgnoreCase)) |
| 6391 | using (Stream s = e.Open()) |
| 6392 | using (MemoryStream ms = new MemoryStream()) |
| 6393 | { |
| 6394 | s.CopyTo(ms); |
| 6395 | byte[] b = ms.ToArray(); |
| 6396 | if (b.Length != a.Length) return false; |
| 6397 | for (int i = 0; i < a.Length; i++) if (a[i] != b[i]) return false; |
| 6398 | return true; |
| 6399 | } |
| 6400 | } |
| 6401 | catch (Exception) { } |
| 6402 | return false; |
| 6403 | } |
| 6404 | |
| 6405 | private void CheckZipQueue() |
| 6406 | { |
| 6407 | if (zipQueue.Count == 0) return; |
| 6408 | List<string> keys = new List<string>(zipQueue.Keys); |
| 6409 | foreach (string z in keys) |
| 6410 | { |
| 6411 | int tries = zipQueue[z]; |
| 6412 | if (!File.Exists(z) || tries > 60) { zipQueue.Remove(z); continue; } |
| 6413 | try { using (FileStream fs = File.Open(z, FileMode.Open, FileAccess.Read, FileShare.Read)) { } } |
| 6414 | catch (Exception) { zipQueue[z] = tries + 1; continue; } |
| 6415 | zipQueue.Remove(z); |
| 6416 | KnownMod m = Installer.Identify(z); |
| 6417 | if (m == null || SameAsInstalled(z, m)) continue; |
| 6418 | string old; |
| 6419 | if (mods.Pending.TryGetValue(m.Id, out old) && string.Equals(old, z, StringComparison.OrdinalIgnoreCase)) continue; |
| 6420 | mods.Pending[m.Id] = z; |
| 6421 | RefreshMods(); |
| 6422 | Native.FlashWindow(Handle, true); |
| 6423 | bool inst = mods.Game != null && Installer.Installed(mods.Game, m); |
| 6424 | if (MessageBox.Show(this, "You downloaded " + m.Name + ".\n\n" + (inst ? "Update it" : "Install it") + " into the game now?", Program.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) |
| 6425 | InstallZip(z); |
| 6426 | } |
| 6427 | } |
| 6428 | |
| 6429 | private int healthMode = -1; |
| 6430 | |
| 6431 | private void SendHealthMode() |
| 6432 | { |
| 6433 | if (link == null || !link.IsConnected) { healthMode = -1; return; } |
| 6434 | int m = 1; |
| 6435 | if (m == healthMode) return; |
| 6436 | healthMode = m; |
| 6437 | link.Send("HEALTH " + m); |
| 6438 | } |
| 6439 | |
| 6440 | protected override void OnResize(EventArgs e) |
| 6441 | { |
| 6442 | base.OnResize(e); |
| 6443 | SendHealthMode(); |
| 6444 | if (tray != null && WindowState == FormWindowState.Minimized && byId["trayhide"].On && Visible) |
| 6445 | { |
| 6446 | Hide(); |
| 6447 | if (Get("tray.told", "0") != "1") |
| 6448 | { |
| 6449 | settings["tray.told"] = "1"; |
| 6450 | Settings.Save(settings); |
| 6451 | TrayNotice(Program.Name, "Still running here. Double-click to open, right-click for options."); |
| 6452 | } |
| 6453 | } |
| 6454 | } |
| 6455 | |
| 6456 | private static string SoundDir { get { return Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UltraParadise"), "sounds"); } } |
| 6457 | |
| 6458 | private static bool SafeName(string n) |
| 6459 | { |
| 6460 | return n != null && System.Text.RegularExpressions.Regex.IsMatch(n, "^[A-Za-z0-9_-]{1,40}$"); |
| 6461 | } |
| 6462 | |
| 6463 | private void OnIcon(string rest) |
| 6464 | { |
| 6465 | int sp = rest.IndexOf(' '); |
| 6466 | if (sp <= 0) return; |
| 6467 | string id = rest.Substring(0, sp); |
| 6468 | if (!System.Text.RegularExpressions.Regex.IsMatch(id, "^-?\\d{1,11}$")) return; |
| 6469 | try |
| 6470 | { |
| 6471 | byte[] png = Convert.FromBase64String(rest.Substring(sp + 1)); |
| 6472 | if (png.Length > 2000000) return; |
| 6473 | using (MemoryStream ms = new MemoryStream(png)) |
| 6474 | using (Image im = Image.FromStream(ms)) |
| 6475 | { |
| 6476 | if (im.Width > 512 || im.Height > 512) return; |
| 6477 | health.AddIcon(id, new Bitmap(im)); |
| 6478 | } |
| 6479 | } |
| 6480 | catch (Exception) { } |
| 6481 | } |
| 6482 | |
| 6483 | private void OnBarkSet(string rest) |
| 6484 | { |
| 6485 | string[] p = rest.Split(' '); |
| 6486 | if (p.Length < 2) return; |
| 6487 | float pitch; |
| 6488 | if (!float.TryParse(p[0], NumberStyles.Float, CultureInfo.InvariantCulture, out pitch) || float.IsNaN(pitch)) pitch = 1f; |
| 6489 | pitch = Math.Max(0.5f, Math.Min(2f, pitch)); |
| 6490 | List<string> names = new List<string>(); |
| 6491 | foreach (string n in p[1].Split(',')) if (SafeName(n) && !names.Contains(n) && names.Count < 8) names.Add(n); |
| 6492 | if (names.Count == 0) return; |
| 6493 | settings["bark.set"] = string.Join(",", names.ToArray()); |
| 6494 | settings["bark.pitch"] = pitch.ToString("0.###", CultureInfo.InvariantCulture); |
| 6495 | Settings.Save(settings); |
| 6496 | foreach (string n in names) |
| 6497 | if (!File.Exists(Path.Combine(SoundDir, n + ".wav"))) link.Send("GETSFX " + n); |
| 6498 | } |
| 6499 | |
| 6500 | private void OnSfx(string rest) |
| 6501 | { |
| 6502 | int sp = rest.IndexOf(' '); |
| 6503 | if (sp <= 0) return; |
| 6504 | string name = rest.Substring(0, sp); |
| 6505 | if (!SafeName(name)) return; |
| 6506 | try |
| 6507 | { |
| 6508 | byte[] wav = Convert.FromBase64String(rest.Substring(sp + 1)); |
| 6509 | if (!IsWav(wav)) return; |
| 6510 | Directory.CreateDirectory(SoundDir); |
| 6511 | File.WriteAllBytes(Path.Combine(SoundDir, name + ".wav"), wav); |
| 6512 | } |
| 6513 | catch (Exception) { } |
| 6514 | } |
| 6515 | |
| 6516 | private static bool IsWav(byte[] w) |
| 6517 | { |
| 6518 | return w != null && w.Length > 44 && w.Length < 8000000 && |
| 6519 | w[0] == 'R' && w[1] == 'I' && w[2] == 'F' && w[3] == 'F' && w[8] == 'W' && w[9] == 'A' && w[10] == 'V' && w[11] == 'E' && |
| 6520 | w[12] == 'f' && w[13] == 'm' && w[14] == 't' && w[15] == ' ' && w[20] == 1 && w[21] == 0; |
| 6521 | } |
| 6522 | |
| 6523 | [DllImport("winmm.dll", EntryPoint = "PlaySoundW", SetLastError = true)] |
| 6524 | private static extern bool WinPlaySound(IntPtr sound, IntPtr module, uint flags); |
| 6525 | |
| 6526 | private IntPtr barkMem = IntPtr.Zero; |
| 6527 | private DateTime lastBark = DateTime.MinValue; |
| 6528 | private readonly Random barkRng = new Random(); |
| 6529 | |
| 6530 | private void StopBark() |
| 6531 | { |
| 6532 | try { WinPlaySound(IntPtr.Zero, IntPtr.Zero, 0); } catch (Exception) { } |
| 6533 | if (barkMem != IntPtr.Zero) { Marshal.FreeHGlobal(barkMem); barkMem = IntPtr.Zero; } |
| 6534 | } |
| 6535 | |
| 6536 | private void PlayBark() |
| 6537 | { |
| 6538 | if (!byId["bark"].On) return; |
| 6539 | PlayBark(false); |
| 6540 | } |
| 6541 | |
| 6542 | private string PlayBark(bool test) |
| 6543 | { |
| 6544 | if (!test && (DateTime.UtcNow - lastBark).TotalMilliseconds < 300) return null; |
| 6545 | List<string> have = new List<string>(); |
| 6546 | foreach (string n in Get("bark.set", "").Split(',')) |
| 6547 | if (SafeName(n) && File.Exists(Path.Combine(SoundDir, n + ".wav"))) have.Add(n); |
| 6548 | if (have.Count == 0) return "No bark sounds yet. Start a run with the trainer attached once, and it picks your runner's barks up from the game."; |
| 6549 | try |
| 6550 | { |
| 6551 | byte[] w = File.ReadAllBytes(Path.Combine(SoundDir, have[barkRng.Next(have.Count)] + ".wav")); |
| 6552 | if (!IsWav(w)) return "That bark sound file is damaged. It gets fetched again next run."; |
| 6553 | float pitch; |
| 6554 | if (!float.TryParse(Get("bark.pitch", "1"), NumberStyles.Float, CultureInfo.InvariantCulture, out pitch)) pitch = 1f; |
| 6555 | double f = Math.Max(0.5, Math.Min(2.0, pitch + (barkRng.NextDouble() * 0.3 - 0.15))); |
| 6556 | int rate = BitConverter.ToInt32(w, 24); |
| 6557 | int align = BitConverter.ToInt16(w, 32); |
| 6558 | if (rate < 8000 || rate > 96000 || align < 1 || align > 8) return "That bark sound file has an odd format."; |
| 6559 | int nr = (int)(rate * f); |
| 6560 | Array.Copy(BitConverter.GetBytes(nr), 0, w, 24, 4); |
| 6561 | Array.Copy(BitConverter.GetBytes(nr * align), 0, w, 28, 4); |
| 6562 | StopBark(); |
| 6563 | barkMem = Marshal.AllocHGlobal(w.Length); |
| 6564 | Marshal.Copy(w, 0, barkMem, w.Length); |
| 6565 | lastBark = DateTime.UtcNow; |
| 6566 | if (!WinPlaySound(barkMem, IntPtr.Zero, 0x0001 | 0x0002 | 0x0004)) |
| 6567 | { |
| 6568 | int err = Marshal.GetLastWin32Error(); |
| 6569 | StopBark(); |
| 6570 | return "Windows couldn't play the bark (error " + err + "). Check that a sound output device is on."; |
| 6571 | } |
| 6572 | return null; |
| 6573 | } |
| 6574 | catch (Exception e) |
| 6575 | { |
| 6576 | return "The bark couldn't play: " + e.Message; |
| 6577 | } |
| 6578 | } |
| 6579 | |
| 6580 | private void OnVitals(string rest) |
| 6581 | { |
| 6582 | Dictionary<string, string> d = null; |
| 6583 | if (rest != "none") |
| 6584 | { |
| 6585 | d = new Dictionary<string, string>(); |
| 6586 | foreach (string part in rest.Split('|')) |
| 6587 | { |
| 6588 | int eq = part.IndexOf('='); |
| 6589 | if (eq > 0) d[part.Substring(0, eq)] = part.Substring(eq + 1); |
| 6590 | } |
| 6591 | } |
| 6592 | health.Vitals = d; |
| 6593 | if (d == null) health.Moodles.Clear(); |
| 6594 | health.Issues = Advisor.Check(d, byId); |
| 6595 | HashSet<string> now = new HashSet<string>(); |
| 6596 | foreach (Issue i in health.Issues) |
| 6597 | { |
| 6598 | if (!i.Danger) continue; |
| 6599 | now.Add(i.Title); |
| 6600 | if (lastDangers.Contains(i.Title)) continue; |
| 6601 | string tip = i.Title; |
| 6602 | foreach (Fix f in i.Fixes) |
| 6603 | { |
| 6604 | if (f.Opt == null || (f.Opt.Kind == Kind.Toggle && f.Opt.On)) continue; |
| 6605 | tip += ": try " + f.Opt.Name + (f.Opt.Key != Keys.None ? " (" + KeyText.Of(f.Opt.Key) + ")" : ""); |
| 6606 | break; |
| 6607 | } |
| 6608 | overlay.Toast(tip, false); |
| 6609 | } |
| 6610 | lastDangers.Clear(); |
| 6611 | foreach (string t in now) lastDangers.Add(t); |
| 6612 | if (health.Visible) health.Invalidate(); |
| 6613 | side.Invalidate(); |
| 6614 | } |
| 6615 | |
| 6616 | protected override void OnPaint(PaintEventArgs e) |
| 6617 | { |
| 6618 | Graphics g = e.Graphics; |
| 6619 | g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; |
| 6620 | Rectangle hr = new Rectangle(0, 0, ClientSize.Width, bannerH); |
| 6621 | if (splash != null && Theme.BannerArt) |
| 6622 | { |
| 6623 | float sx = splash.Width / (float)hr.Width; |
| 6624 | int srcH = (int)(hr.Height * sx); |
| 6625 | Rectangle src = new Rectangle(0, (int)(splash.Height * 0.47f) - srcH / 2, splash.Width, srcH); |
| 6626 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 6627 | g.DrawImage(splash, hr, src, GraphicsUnit.Pixel); |
| 6628 | using (LinearGradientBrush lg = new LinearGradientBrush(new Rectangle(0, 0, Theme.S(620), bannerH), Color.FromArgb(235, Theme.Side), Color.FromArgb(0, Theme.Side), LinearGradientMode.Horizontal)) |
| 6629 | g.FillRectangle(lg, 0, 0, Theme.S(620), bannerH); |
| 6630 | } |
| 6631 | else |
| 6632 | { |
| 6633 | using (SolidBrush b = new SolidBrush(Theme.Side)) g.FillRectangle(b, hr); |
| 6634 | } |
| 6635 | int x = Theme.S(22); |
| 6636 | if (tile != null) |
| 6637 | { |
| 6638 | int ts = Theme.S(46); |
| 6639 | g.InterpolationMode = InterpolationMode.HighQualityBicubic; |
| 6640 | g.DrawImage(tile, x, (bannerH - ts) / 2, ts, ts); |
| 6641 | x += ts + Theme.S(14); |
| 6642 | } |
| 6643 | using (SolidBrush w = new SolidBrush(Theme.Bright)) |
| 6644 | g.DrawString("ULTRA PARADISE", titleFont, w, x - Theme.S(3), bannerH / 2 - Theme.S(30)); |
| 6645 | using (SolidBrush o = new SolidBrush(Theme.Orange)) |
| 6646 | g.DrawString(Theme.Spaced("CU:TRAINER") + " · CASUALTIES: UNKNOWN", subFont, o, x, bannerH / 2 + Theme.S(6)); |
| 6647 | using (Pen line = new Pen(Theme.Line)) g.DrawLine(line, 0, bannerH - 1, ClientSize.Width, bannerH - 1); |
| 6648 | |
| 6649 | int fy = ClientSize.Height - footerH; |
| 6650 | using (SolidBrush panel = new SolidBrush(Theme.Side)) g.FillRectangle(panel, 0, fy, ClientSize.Width, footerH); |
| 6651 | using (Pen line = new Pen(Theme.Line)) g.DrawLine(line, 0, fy, ClientSize.Width, fy); |
| 6652 | Theme.FillRound(g, Color.FromArgb(60, statusColor), new Rectangle(Theme.S(15), fy + Theme.S(12), Theme.S(14), Theme.S(14)), Theme.S(7)); |
| 6653 | Theme.FillRound(g, statusColor, new Rectangle(Theme.S(18), fy + Theme.S(15), Theme.S(8), Theme.S(8)), Theme.S(4)); |
| 6654 | StringFormat mid = new StringFormat(); mid.LineAlignment = StringAlignment.Center; mid.FormatFlags = StringFormatFlags.NoWrap; mid.Trimming = StringTrimming.EllipsisCharacter; |
| 6655 | int textW = launchBtn.Left - Theme.S(34) - Theme.S(16); |
| 6656 | string top = statusText + (where.Length > 0 ? " · " + where : ""); |
| 6657 | using (SolidBrush t = new SolidBrush(Theme.Text)) |
| 6658 | g.DrawString(top, statusFont, t, new RectangleF(Theme.S(34), fy + Theme.S(8), textW, Theme.S(22)), mid); |
| 6659 | string bottom = hint ?? message; |
| 6660 | using (SolidBrush m = new SolidBrush(hint == null && messageBad ? Theme.Bad : Theme.Dim)) |
| 6661 | g.DrawString(bottom ?? "", msgFont, m, new RectangleF(Theme.S(34), fy + Theme.S(30), textW, Theme.S(22)), mid); |
| 6662 | } |
| 6663 | |
| 6664 | private void InvalidateFooter() |
| 6665 | { |
| 6666 | Invalidate(new Rectangle(0, ClientSize.Height - footerH, ClientSize.Width, footerH)); |
| 6667 | } |
| 6668 | |
| 6669 | private void SetStatus(string text, Color c) |
| 6670 | { |
| 6671 | if (statusText == text && statusColor == c) return; |
| 6672 | statusText = text; |
| 6673 | statusColor = c; |
| 6674 | InvalidateFooter(); |
| 6675 | } |
| 6676 | |
| 6677 | private void SetWhere(string w) |
| 6678 | { |
| 6679 | if (where == w) return; |
| 6680 | where = w; |
| 6681 | InvalidateFooter(); |
| 6682 | } |
| 6683 | |
| 6684 | private void SetMessage(string s, bool bad) |
| 6685 | { |
| 6686 | message = s; |
| 6687 | messageBad = bad; |
| 6688 | InvalidateFooter(); |
| 6689 | } |
| 6690 | |
| 6691 | protected override bool ProcessCmdKey(ref Message msg, Keys keyData) |
| 6692 | { |
| 6693 | if (keyData == (Keys.Control | Keys.F) && view.Capturing == null && searchTab != null) |
| 6694 | { |
| 6695 | int si = tabs.IndexOf(searchTab); |
| 6696 | if (si >= 0) { side.Selected = si; side.Invalidate(); SelectTab(si); } |
| 6697 | return true; |
| 6698 | } |
| 6699 | if (view.Capturing != null) |
| 6700 | { |
| 6701 | Keys code = keyData & Keys.KeyCode; |
| 6702 | if (code == Keys.ControlKey || code == Keys.ShiftKey || code == Keys.Menu || code == Keys.LWin || code == Keys.RWin) return true; |
| 6703 | Option o = view.Capturing; |
| 6704 | view.Capturing = null; |
| 6705 | if (code == Keys.Escape) SetMessage("", false); |
| 6706 | else if (code == Keys.Delete || code == Keys.Back) { Bind(o, Keys.None); SetMessage(o.Name + " has no key now.", false); } |
| 6707 | else |
| 6708 | { |
| 6709 | string moved = null; |
| 6710 | foreach (Option other in options) |
| 6711 | if (other != o && other.Bindable && other.Key == keyData) { Bind(other, Keys.None); moved = other.Name; } |
| 6712 | Bind(o, keyData); |
| 6713 | SetMessage(moved != null ? KeyText.Of(keyData) + " moved from " + moved + " to " + o.Name + "." : o.Name + " is on " + KeyText.Of(keyData) + ".", false); |
| 6714 | } |
| 6715 | view.Invalidate(); |
| 6716 | overlay.Invalidate(); |
| 6717 | return true; |
| 6718 | } |
| 6719 | return base.ProcessCmdKey(ref msg, keyData); |
| 6720 | } |
| 6721 | |
| 6722 | private void Bind(Option o, Keys k) |
| 6723 | { |
| 6724 | o.Key = k; |
| 6725 | settings["key." + o.Id] = ((int)k).ToString(); |
| 6726 | Settings.Save(settings); |
| 6727 | if (hotkeysOn) { UnregisterKeys(); RegisterKeys(); } |
| 6728 | } |
| 6729 | |
| 6730 | private void SetSlider(Option o, float v) |
| 6731 | { |
| 6732 | if (o.Id.StartsWith("theme.", StringComparison.Ordinal)) { SetThemeSlider(o, v); return; } |
| 6733 | o.Value = v; |
| 6734 | if ((o.Id != "GameSpeed" && o.Id != "CameraZoom") || byId["remember"].On) |
| 6735 | { |
| 6736 | settings["val." + o.Id] = v.ToString(CultureInfo.InvariantCulture); |
| 6737 | Settings.Save(settings); |
| 6738 | } |
| 6739 | if (link.IsConnected && blocked == null) link.Send("VAL " + o.Id + " " + v.ToString(CultureInfo.InvariantCulture)); |
| 6740 | view.Invalidate(); |
| 6741 | } |
| 6742 | |
| 6743 | private void RunOption(Option o) |
| 6744 | { |
| 6745 | if (o.Local) |
| 6746 | { |
| 6747 | RunLocal(o); |
| 6748 | return; |
| 6749 | } |
| 6750 | if (o.Kind == Kind.Toggle) |
| 6751 | { |
| 6752 | o.On = !o.On; |
| 6753 | if (link.IsConnected && blocked == null) link.Send("SET " + o.Id + " " + (o.On ? "1" : "0")); |
| 6754 | if (o.On) PlayBark(); |
| 6755 | SaveCheats(); |
| 6756 | overlay.Toast(o.Name + (o.On ? " ON" : " OFF"), true); |
| 6757 | SetMessage(o.Name + (o.On ? " on." : " off.") + (link.IsConnected ? "" : " It kicks in once the trainer is attached."), false); |
| 6758 | view.Invalidate(); |
| 6759 | side.Invalidate(); |
| 6760 | overlay.Invalidate(); |
| 6761 | } |
| 6762 | else |
| 6763 | { |
| 6764 | if (!link.IsConnected) { SetMessage("Attach to the game first.", true); return; } |
| 6765 | link.Send("ACT " + o.Id); |
| 6766 | overlay.Toast(o.Name, true); |
| 6767 | } |
| 6768 | } |
| 6769 | |
| 6770 | private void RunLocal(Option o) |
| 6771 | { |
| 6772 | switch (o.Id) |
| 6773 | { |
| 6774 | case "overlay": |
| 6775 | case "autoattach": |
| 6776 | case "launchwith": |
| 6777 | case "closewithgame": |
| 6778 | case "autoupdate": |
| 6779 | case "silentupdate": |
| 6780 | case "trayhide": |
| 6781 | case "bark": |
| 6782 | case "debugwithgame": |
| 6783 | o.On = !o.On; |
| 6784 | settings[o.Id] = o.On ? "1" : "0"; |
| 6785 | Settings.Save(settings); |
| 6786 | if (o.Id == "overlay") overlay.Toast(o.On ? "Overlay on" : "Overlay hidden", true); |
| 6787 | SetMessage(o.Name + (o.On ? " on." : " off."), false); |
| 6788 | break; |
| 6789 | case "usagecount": |
| 6790 | o.On = !o.On; |
| 6791 | settings["usage"] = o.On ? "1" : "0"; |
| 6792 | settings["notice.usage"] = "1"; |
| 6793 | Settings.Save(settings); |
| 6794 | if (o.On) { SetMessage("Thanks! You're counted as a user.", false); UsageTick(); } |
| 6795 | else { SetMessage("You're no longer counted.", false); UsageOff(); } |
| 6796 | break; |
| 6797 | case "remember": |
| 6798 | o.On = !o.On; |
| 6799 | settings["remember"] = o.On ? "1" : "0"; |
| 6800 | if (o.On) |
| 6801 | { |
| 6802 | settings["val.GameSpeed"] = byId["GameSpeed"].Value.ToString(CultureInfo.InvariantCulture); |
| 6803 | settings["val.CameraZoom"] = byId["CameraZoom"].Value.ToString(CultureInfo.InvariantCulture); |
| 6804 | SaveCheats(); |
| 6805 | } |
| 6806 | else |
| 6807 | { |
| 6808 | settings.Remove("cheats.on"); |
| 6809 | settings.Remove("val.GameSpeed"); |
| 6810 | settings.Remove("val.CameraZoom"); |
| 6811 | } |
| 6812 | Settings.Save(settings); |
| 6813 | SetMessage(o.On ? "The cheats you have on now will come back next time you open the trainer." : "Cheats start off every time you open the trainer.", false); |
| 6814 | break; |
| 6815 | case "speedcycle": |
| 6816 | { |
| 6817 | Option s = byId["GameSpeed"]; |
| 6818 | float next = Math.Abs(s.Value - 1f) < 0.01f ? 1.5f : Math.Abs(s.Value - 1.5f) < 0.01f ? 2f : Math.Abs(s.Value - 2f) < 0.01f ? 0.5f : 1f; |
| 6819 | SetSlider(s, next); |
| 6820 | string txt = "Game speed x" + next.ToString("0.#", CultureInfo.InvariantCulture); |
| 6821 | overlay.Toast(txt, true); |
| 6822 | SetMessage(txt, false); |
| 6823 | break; |
| 6824 | } |
| 6825 | case "alloff": |
| 6826 | AllOff(); |
| 6827 | break; |
| 6828 | case "debugwin": |
| 6829 | if (debug != null && debug.Visible) debug.Hide(); |
| 6830 | else OpenDebug(false); |
| 6831 | break; |
| 6832 | case "resetkeys": |
| 6833 | foreach (Option x in options) |
| 6834 | { |
| 6835 | if (!x.Bindable) continue; |
| 6836 | x.Key = x.DefaultKey; |
| 6837 | settings.Remove("key." + x.Id); |
| 6838 | } |
| 6839 | Settings.Save(settings); |
| 6840 | if (hotkeysOn) { UnregisterKeys(); RegisterKeys(); } |
| 6841 | SetMessage("Every key is back to its default.", false); |
| 6842 | break; |
| 6843 | } |
| 6844 | view.Invalidate(); |
| 6845 | overlay.Invalidate(); |
| 6846 | } |
| 6847 | |
| 6848 | private void AllOff() |
| 6849 | { |
| 6850 | foreach (Option o in options) |
| 6851 | { |
| 6852 | if (o.Kind != Kind.Toggle || o.Local || !o.On) continue; |
| 6853 | o.On = false; |
| 6854 | if (link.IsConnected) link.Send("SET " + o.Id + " 0"); |
| 6855 | } |
| 6856 | Option gs = byId["GameSpeed"], cz = byId["CameraZoom"]; |
| 6857 | if (gs.Value != 1f) SetSlider(gs, 1f); |
| 6858 | if (cz.Value != 1f) SetSlider(cz, 1f); |
| 6859 | SaveCheats(); |
| 6860 | view.Invalidate(); |
| 6861 | side.Invalidate(); |
| 6862 | overlay.Invalidate(); |
| 6863 | SetMessage("Everything is off.", false); |
| 6864 | } |
| 6865 | |
| 6866 | private void PushAll() |
| 6867 | { |
| 6868 | foreach (Option o in options) |
| 6869 | { |
| 6870 | if (o.Local) continue; |
| 6871 | if (o.Kind == Kind.Toggle) link.Send("SET " + o.Id + " " + (o.On ? "1" : "0")); |
| 6872 | else if (o.Kind == Kind.Slider) link.Send("VAL " + o.Id + " " + o.Value.ToString(CultureInfo.InvariantCulture)); |
| 6873 | } |
| 6874 | } |
| 6875 | |
| 6876 | private void OnLinked() |
| 6877 | { |
| 6878 | blocked = null; |
| 6879 | mymods.Linked = true; |
| 6880 | foreach (KeyValuePair<string, string> kv in settings) if (kv.Key.StartsWith("take.", StringComparison.Ordinal) && kv.Value == "1") link.Send("MODTAKE " + kv.Key.Substring(5) + " 1"); |
| 6881 | link.Send("MODS"); |
| 6882 | MusicLinked(); |
| 6883 | PushAll(); |
| 6884 | view.Linked = true; |
| 6885 | view.Invalidate(); |
| 6886 | if (link.GameCode != LinkServer.CodeVersion) |
| 6887 | { |
| 6888 | SetStatus("Attached, but restart the game to finish updating", Theme.Orange); |
| 6889 | SetMessage("The game still has an older trainer version loaded. Your cheats work, but restart the game to get everything new in v" + Program.Version + ".", true); |
| 6890 | } |
| 6891 | else |
| 6892 | { |
| 6893 | SetStatus("Attached to Casualties: Unknown", Theme.On); |
| 6894 | SetMessage("Attached. Your keys work while the game window is in front.", false); |
| 6895 | } |
| 6896 | nextItemsAsk = DateTime.MinValue; |
| 6897 | health.Linked = true; |
| 6898 | healthMode = -1; |
| 6899 | SendHealthMode(); |
| 6900 | health.Invalidate(); |
| 6901 | if (byId["debugwithgame"].On && (debug == null || !debug.Visible)) OpenDebug(false); |
| 6902 | if (debug != null) |
| 6903 | { |
| 6904 | debug.SetLinked(true); |
| 6905 | if (debug.Visible) link.Send("DEBUG 1"); |
| 6906 | } |
| 6907 | ScreenTip(); |
| 6908 | } |
| 6909 | |
| 6910 | private void OnUnlinked() |
| 6911 | { |
| 6912 | mymods.Linked = false; |
| 6913 | mymods.Clear(); |
| 6914 | MusicUnlinked(); |
| 6915 | view.Linked = false; |
| 6916 | view.Invalidate(); |
| 6917 | SetWhere(""); |
| 6918 | UnregisterKeys(); |
| 6919 | itemsLoading = false; |
| 6920 | healthMode = -1; |
| 6921 | health.Linked = false; |
| 6922 | health.Reset(); |
| 6923 | lastDangers.Clear(); |
| 6924 | if (debug != null) debug.SetLinked(false); |
| 6925 | side.Invalidate(); |
| 6926 | if (game != null && !HasExited(game)) SetStatus("Lost the connection to the game", Theme.Bad); |
| 6927 | } |
| 6928 | |
| 6929 | private void OnLine(string s) |
| 6930 | { |
| 6931 | int sp = s.IndexOf(' '); |
| 6932 | string cmd = sp < 0 ? s : s.Substring(0, sp); |
| 6933 | string rest = sp < 0 ? "" : s.Substring(sp + 1); |
| 6934 | HistoryLine(cmd, rest); |
| 6935 | switch (cmd) |
| 6936 | { |
| 6937 | case "LOADER": |
| 6938 | UltraPara.GameVersion = rest == "none" ? "" : rest; |
| 6939 | return; |
| 6940 | case "INFO": |
| 6941 | { |
| 6942 | Dictionary<string, string> d = new Dictionary<string, string>(); |
| 6943 | foreach (string part in rest.Split('|')) |
| 6944 | { |
| 6945 | int eq = part.IndexOf('='); |
| 6946 | if (eq > 0) d[part.Substring(0, eq)] = part.Substring(eq + 1); |
| 6947 | } |
| 6948 | string w = d.ContainsKey("where") ? d["where"] : ""; |
| 6949 | if (d.ContainsKey("alive") && d["alive"] == "0") w += ", dead"; |
| 6950 | if (d.ContainsKey("paused")) w += " · God Mode paused: " + d["paused"]; |
| 6951 | SetWhere(w); |
| 6952 | view.Info = d; |
| 6953 | view.Invalidate(); |
| 6954 | break; |
| 6955 | } |
| 6956 | case "VITALS": |
| 6957 | OnVitals(rest); |
| 6958 | break; |
| 6959 | case "DLOG": |
| 6960 | if (debug != null) debug.OnLog(rest); |
| 6961 | break; |
| 6962 | case "DSNAP": |
| 6963 | if (debug != null) debug.OnSnapshot(rest); |
| 6964 | break; |
| 6965 | case "MODS": |
| 6966 | mymods.Parse(rest); |
| 6967 | break; |
| 6968 | case "MODSTAT": |
| 6969 | mymods.Stats(rest); |
| 6970 | break; |
| 6971 | case "MUSIC": |
| 6972 | OnMusicLine(rest); |
| 6973 | break; |
| 6974 | case "MUSICLIST": |
| 6975 | OnMusicList(rest); |
| 6976 | break; |
| 6977 | case "MODERR": |
| 6978 | { |
| 6979 | int sp2 = rest.IndexOf(' '); |
| 6980 | SetMessage(sp2 > 0 ? rest.Substring(sp2 + 1) : rest, true); |
| 6981 | } |
| 6982 | break; |
| 6983 | case "DSYS": |
| 6984 | if (debug != null) debug.OnSystem(rest); |
| 6985 | break; |
| 6986 | case "MOODLES": |
| 6987 | health.SetMoodles(rest); |
| 6988 | break; |
| 6989 | case "MICON": |
| 6990 | OnIcon(rest); |
| 6991 | break; |
| 6992 | case "BARKSET": |
| 6993 | OnBarkSet(rest); |
| 6994 | break; |
| 6995 | case "SFX": |
| 6996 | OnSfx(rest); |
| 6997 | break; |
| 6998 | case "MSG": |
| 6999 | SetMessage(rest, false); |
| 7000 | overlay.Toast(rest, true); |
| 7001 | break; |
| 7002 | case "READY": |
| 7003 | { |
| 7004 | int n; |
| 7005 | if (int.TryParse(rest, out n)) |
| 7006 | { |
| 7007 | if (n == -1) SetMessage("The trainer's patch library didn't load, so many cheats won't work. Try restarting the game.", true); |
| 7008 | else if (n > 0) SetMessage(n + " cheat hook" + (n == 1 ? "" : "s") + " couldn't load. A game update may have changed something.", true); |
| 7009 | } |
| 7010 | break; |
| 7011 | } |
| 7012 | case "BLOCKED": |
| 7013 | blocked = rest; |
| 7014 | SetStatus("Cheats are off: " + rest, Theme.Bad); |
| 7015 | SetMessage(Program.Name + " doesn't run alongside multiplayer mods.", true); |
| 7016 | break; |
| 7017 | case "ITEM": |
| 7018 | { |
| 7019 | int tab = rest.IndexOf('\t'); |
| 7020 | if (tab > 0) incomingItems.Add(new KeyValuePair<string, string>(rest.Substring(0, tab), rest.Substring(tab + 1))); |
| 7021 | break; |
| 7022 | } |
| 7023 | case "ITEMSEND": |
| 7024 | itemsLoading = false; |
| 7025 | if (incomingItems.Count > 0) |
| 7026 | { |
| 7027 | spawner.SetItems(new List<KeyValuePair<string, string>>(incomingItems)); |
| 7028 | incomingItems.Clear(); |
| 7029 | } |
| 7030 | else spawner.SetStatus("Start a run to load the item list."); |
| 7031 | break; |
| 7032 | } |
| 7033 | } |
| 7034 | |
| 7035 | private static bool HasExited(Process p) |
| 7036 | { |
| 7037 | try { return p.HasExited; } catch (Exception) { return true; } |
| 7038 | } |
| 7039 | |
| 7040 | private void Tick() |
| 7041 | { |
| 7042 | if (DateTime.UtcNow >= nextModsRefresh) |
| 7043 | { |
| 7044 | nextModsRefresh = DateTime.UtcNow.AddSeconds(1); |
| 7045 | CheckZipQueue(); |
| 7046 | if (mods.Visible) RefreshMods(); |
| 7047 | } |
| 7048 | if (DateTime.UtcNow >= nextScan) |
| 7049 | { |
| 7050 | nextScan = DateTime.UtcNow.AddSeconds(1); |
| 7051 | Scan(); |
| 7052 | UpdateTrayTip(); |
| 7053 | if (report.Visible) report.Poll(); |
| 7054 | } |
| 7055 | if (spawner.Visible && link.IsConnected && !spawner.HasItems && !itemsLoading && DateTime.UtcNow >= nextItemsAsk) |
| 7056 | { |
| 7057 | nextItemsAsk = DateTime.UtcNow.AddSeconds(5); |
| 7058 | itemsLoading = true; |
| 7059 | incomingItems.Clear(); |
| 7060 | spawner.SetStatus("Loading the item list..."); |
| 7061 | link.Send("ITEMS"); |
| 7062 | } |
| 7063 | if (link.IsConnected) attachedThisRun = true; |
| 7064 | Monitors.GameProc = game; |
| 7065 | UltraParaTick(); |
| 7066 | MusicTick(); |
| 7067 | ToolsTick(); |
| 7068 | bool focused = GameFocused(); |
| 7069 | bool want = focused && link.IsConnected; |
| 7070 | if (want && !hotkeysOn) RegisterKeys(); |
| 7071 | else if (!want && hotkeysOn) UnregisterKeys(); |
| 7072 | PlaceOverlay(focused); |
| 7073 | } |
| 7074 | |
| 7075 | private bool attachedThisRun; |
| 7076 | private DateTime closeWithGameAt = DateTime.MaxValue; |
| 7077 | |
| 7078 | private void Scan() |
| 7079 | { |
| 7080 | if (game != null && HasExited(game)) |
| 7081 | { |
| 7082 | if (attachedThisRun && byId["closewithgame"].On) closeWithGameAt = DateTime.UtcNow.AddSeconds(3); |
| 7083 | attachedThisRun = false; |
| 7084 | LinkServer.DeleteLinkFile(gamePid); |
| 7085 | game = null; |
| 7086 | gamePid = 0; |
| 7087 | injectTried = false; |
| 7088 | SetWhere(""); |
| 7089 | } |
| 7090 | if (game == null) |
| 7091 | { |
| 7092 | Process[] ps = Installer.GameProcesses(); |
| 7093 | if (ps.Length == 0) |
| 7094 | { |
| 7095 | if (closeWithGameAt != DateTime.MaxValue) |
| 7096 | { |
| 7097 | if (DateTime.UtcNow >= closeWithGameAt) { closeWithGameAt = DateTime.MaxValue; Close(); return; } |
| 7098 | SetStatus("The game closed, so the trainer is closing too", Theme.Dim); |
| 7099 | return; |
| 7100 | } |
| 7101 | if ((DateTime.UtcNow - launchedAt).TotalSeconds < 60) SetStatus("Starting the game...", Theme.Orange); |
| 7102 | else SetStatus("Waiting for Casualties: Unknown to start", Theme.Dim); |
| 7103 | return; |
| 7104 | } |
| 7105 | closeWithGameAt = DateTime.MaxValue; |
| 7106 | game = ps[0]; |
| 7107 | gamePid = game.Id; |
| 7108 | foundAt = DateTime.UtcNow; |
| 7109 | } |
| 7110 | if (link.IsConnected) return; |
| 7111 | TryAttach(false); |
| 7112 | } |
| 7113 | |
| 7114 | private void TryAttach(bool manual) |
| 7115 | { |
| 7116 | if (game == null || HasExited(game)) |
| 7117 | { |
| 7118 | if (manual) SetMessage("Start the game first.", true); |
| 7119 | return; |
| 7120 | } |
| 7121 | if (link.IsConnected) return; |
| 7122 | bool launched = (DateTime.UtcNow - launchedAt).TotalMinutes < 5; |
| 7123 | if (!manual && !injectTried && !byId["autoattach"].On && !launched) |
| 7124 | { |
| 7125 | SetStatus("Game found. Click Attach now when you're ready", Theme.Orange); |
| 7126 | return; |
| 7127 | } |
| 7128 | if (!injectTried) |
| 7129 | { |
| 7130 | try { link.WriteLinkFile(gamePid); injectTried = true; attachAskedAt = DateTime.UtcNow; } |
| 7131 | catch (Exception e) { SetStatus("Couldn't prepare the link: " + e.Message, Theme.Bad); return; } |
| 7132 | } |
| 7133 | double uptime = 99; |
| 7134 | try { uptime = (DateTime.Now - game.StartTime).TotalSeconds; } catch (Exception) { } |
| 7135 | if (UltraPara.LoadedIn(game)) |
| 7136 | { |
| 7137 | if ((DateTime.UtcNow - attachAskedAt).TotalSeconds < 25 || uptime < 40) SetStatus("Attaching... (UltraPara.dll is starting the trainer code)", Theme.Orange); |
| 7138 | else |
| 7139 | { |
| 7140 | string gd = GameDir(); |
| 7141 | string last = gd == null ? null : UltraPara.LastLog(gd); |
| 7142 | SetStatus("UltraPara.dll is loaded but the trainer code hasn't connected" + (last != null && last.Contains("FAILED") ? ": " + last.Substring(last.IndexOf("FAILED", StringComparison.Ordinal)) : " yet"), Theme.Bad); |
| 7143 | } |
| 7144 | return; |
| 7145 | } |
| 7146 | if (uptime < 15) { SetStatus("Game found, waiting for it to finish loading", Theme.Orange); return; } |
| 7147 | string st = UltraPara.State(GameDir()); |
| 7148 | if (st == "missing" || st == "nogame") SetStatus("UltraPara.dll isn't installed. Close the game; the trainer installs it (UltraPara tab)", Theme.Bad); |
| 7149 | else if (st == "foreign") SetStatus("Another program's version.dll is in the game folder, so UltraPara.dll can't load (UltraPara tab)", Theme.Bad); |
| 7150 | else SetStatus("UltraPara.dll is installed but the game was started before it. Restart the game", Theme.Bad); |
| 7151 | } |
| 7152 | |
| 7153 | private readonly TextBox searchBox = new TextBox(); |
| 7154 | private Tab searchTab, favTab; |
| 7155 | |
| 7156 | private void SetupSearch() |
| 7157 | { |
| 7158 | foreach (Tab x in tabs) { if (x.Search) searchTab = x; if (x.Favs) favTab = x; } |
| 7159 | string fv; |
| 7160 | if (settings.TryGetValue("favs", out fv)) |
| 7161 | foreach (string id in fv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) |
| 7162 | { |
| 7163 | Option o; |
| 7164 | if (byId.TryGetValue(id, out o)) o.Fav = true; |
| 7165 | } |
| 7166 | searchBox.Visible = false; |
| 7167 | searchBox.BorderStyle = BorderStyle.FixedSingle; |
| 7168 | searchBox.Font = Theme.F("Segoe UI", 11f); |
| 7169 | searchBox.BackColor = Theme.Sunk; |
| 7170 | searchBox.ForeColor = Theme.Text; |
| 7171 | searchBox.TextChanged += delegate { RebuildSearch(); view.Invalidate(); }; |
| 7172 | searchBox.KeyDown += delegate (object s, KeyEventArgs e) |
| 7173 | { |
| 7174 | if (e.KeyCode == Keys.Escape) { searchBox.Text = ""; e.SuppressKeyPress = true; } |
| 7175 | }; |
| 7176 | view.Controls.Add(searchBox); |
| 7177 | view.Resize += delegate { PlaceSearch(); }; |
| 7178 | RebuildSearch(); |
| 7179 | RebuildFavs(); |
| 7180 | } |
| 7181 | |
| 7182 | private void PlaceSearch() |
| 7183 | { |
| 7184 | int pad = Theme.S(18); |
| 7185 | searchBox.Bounds = new Rectangle(pad, Theme.S(12), Math.Max(Theme.S(200), Math.Min(Theme.S(560), view.Width - pad * 2)), Theme.S(28)); |
| 7186 | } |
| 7187 | |
| 7188 | private bool Searchable(Option o) |
| 7189 | { |
| 7190 | return (o.Kind == Kind.Toggle || o.Kind == Kind.Action || o.Kind == Kind.Slider) && o.Origin != null && o.Origin != "Search" && o.Origin != "Favorites"; |
| 7191 | } |
| 7192 | |
| 7193 | private static void Spread(Tab t, List<Section> secs) |
| 7194 | { |
| 7195 | foreach (List<Section> c in t.Cols) c.Clear(); |
| 7196 | int[] load = new int[3]; |
| 7197 | foreach (Section s in secs) |
| 7198 | { |
| 7199 | int best = 0; |
| 7200 | for (int c = 1; c < 3; c++) if (load[c] < load[best]) best = c; |
| 7201 | t.Cols[best].Add(s); |
| 7202 | load[best] += s.Rows.Count + 2; |
| 7203 | } |
| 7204 | } |
| 7205 | |
| 7206 | private static Option NoteRow(string text) |
| 7207 | { |
| 7208 | Option o = new Option(); o.Kind = Kind.Note; o.Id = "note:dyn"; o.Name = text; |
| 7209 | return o; |
| 7210 | } |
| 7211 | |
| 7212 | private void RebuildSearch() |
| 7213 | { |
| 7214 | if (searchTab == null) return; |
| 7215 | string q = searchBox.Text.Trim(); |
| 7216 | List<Section> secs = new List<Section>(); |
| 7217 | if (q.Length == 0) |
| 7218 | { |
| 7219 | int n = 0; |
| 7220 | foreach (Option o in options) if (Searchable(o)) n++; |
| 7221 | Section s = new Section("SEARCH"); |
| 7222 | s.Rows.Add(NoteRow("Type above to search all " + n + " cheats and settings by name or description. Ctrl+F jumps here from any tab, Esc clears it.\n\nClick a result to use it, give it a key, or click its star to add it to Favorites.")); |
| 7223 | secs.Add(s); |
| 7224 | } |
| 7225 | else |
| 7226 | { |
| 7227 | string[] words = q.ToLowerInvariant().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); |
| 7228 | Dictionary<string, Section> by = new Dictionary<string, Section>(); |
| 7229 | int found = 0; |
| 7230 | foreach (Option o in options) |
| 7231 | { |
| 7232 | if (!Searchable(o)) continue; |
| 7233 | string hay = (o.Name + " " + (o.Hint ?? "") + " " + o.Origin).ToLowerInvariant(); |
| 7234 | bool all = true; |
| 7235 | foreach (string wd in words) if (!hay.Contains(wd)) { all = false; break; } |
| 7236 | if (!all) continue; |
| 7237 | Section s; |
| 7238 | if (!by.TryGetValue(o.Origin, out s)) { s = new Section(o.Origin.ToUpperInvariant()); by[o.Origin] = s; secs.Add(s); } |
| 7239 | s.Rows.Add(o); |
| 7240 | found++; |
| 7241 | } |
| 7242 | if (found == 0) |
| 7243 | { |
| 7244 | Section s = new Section("NO RESULTS"); |
| 7245 | s.Rows.Add(NoteRow("Nothing matches \"" + q + "\". Try a shorter word, like \"heal\", \"jump\" or \"loot\".")); |
| 7246 | secs.Add(s); |
| 7247 | } |
| 7248 | } |
| 7249 | Spread(searchTab, secs); |
| 7250 | } |
| 7251 | |
| 7252 | private void RebuildFavs() |
| 7253 | { |
| 7254 | if (favTab == null) return; |
| 7255 | List<Section> secs = new List<Section>(); |
| 7256 | List<string> ids = new List<string>(); |
| 7257 | string fv; |
| 7258 | if (settings.TryGetValue("favs", out fv)) ids.AddRange(fv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); |
| 7259 | Dictionary<string, Section> by = new Dictionary<string, Section>(); |
| 7260 | foreach (string id in ids) |
| 7261 | { |
| 7262 | Option o; |
| 7263 | if (!byId.TryGetValue(id, out o) || !o.Fav || o.Origin == null) continue; |
| 7264 | Section s; |
| 7265 | if (!by.TryGetValue(o.Origin, out s)) { s = new Section(o.Origin.ToUpperInvariant()); by[o.Origin] = s; secs.Add(s); } |
| 7266 | s.Rows.Add(o); |
| 7267 | } |
| 7268 | if (secs.Count == 0) |
| 7269 | { |
| 7270 | Section s = new Section("FAVORITES"); |
| 7271 | s.Rows.Add(NoteRow("Your favorite cheats, all in one place.\n\nHover any cheat on any tab and click the star next to it to pin it here. Click the star again to take it off.")); |
| 7272 | secs.Add(s); |
| 7273 | } |
| 7274 | Spread(favTab, secs); |
| 7275 | } |
| 7276 | |
| 7277 | private void ToggleFav(Option o) |
| 7278 | { |
| 7279 | o.Fav = !o.Fav; |
| 7280 | List<string> ids = new List<string>(); |
| 7281 | string fv; |
| 7282 | if (settings.TryGetValue("favs", out fv)) ids.AddRange(fv.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); |
| 7283 | ids.Remove(o.Id); |
| 7284 | if (o.Fav) ids.Add(o.Id); |
| 7285 | settings["favs"] = string.Join(",", ids.ToArray()); |
| 7286 | Settings.Save(settings); |
| 7287 | RebuildFavs(); |
| 7288 | SetMessage(o.Fav ? o.Name + " is in Favorites now." : o.Name + " was taken out of Favorites.", false); |
| 7289 | view.Invalidate(); |
| 7290 | } |
| 7291 | |
| 7292 | private void ShowSearchBox(bool on) |
| 7293 | { |
| 7294 | searchBox.Visible = on; |
| 7295 | view.TopPad = on ? Theme.S(48) : 0; |
| 7296 | if (on) { PlaceSearch(); RebuildSearch(); searchBox.Focus(); searchBox.SelectAll(); } |
| 7297 | } |
| 7298 | |
| 7299 | private DateTime attachAskedAt = DateTime.MinValue; |
| 7300 | private bool upAutoTried, upBusy; |
| 7301 | private DateTime upNext = DateTime.MinValue; |
| 7302 | |
| 7303 | private string GameDir() |
| 7304 | { |
| 7305 | if (game != null) |
| 7306 | { |
| 7307 | try { return Path.GetDirectoryName(game.MainModule.FileName); } catch (Exception) { } |
| 7308 | } |
| 7309 | return mods != null && mods.Game != null && Installer.IsGameDir(mods.Game) ? mods.Game : Installer.FindGame(); |
| 7310 | } |
| 7311 | |
| 7312 | private void RefreshUltraPara() |
| 7313 | { |
| 7314 | string gd = GameDir(); |
| 7315 | string st = UltraPara.State(gd); |
| 7316 | string iv = gd == null ? null : UltraPara.InstalledVersion(gd); |
| 7317 | StringBuilder sb = new StringBuilder(); |
| 7318 | sb.Append("Installed: "); |
| 7319 | if (st == "ok") sb.Append("✓ Yes, v").Append(UltraParaInfo.Version); |
| 7320 | else if (st == "old") sb.Append("Older copy (v").Append(iv ?? "?").Append("), needs v").Append(UltraParaInfo.Version); |
| 7321 | else if (st == "foreign") sb.Append("✗ Blocked: another program's version.dll is in the game folder"); |
| 7322 | else if (st == "nogame") sb.Append("✗ Game folder not found"); |
| 7323 | else sb.Append("✗ Not installed"); |
| 7324 | sb.Append("\nIn the game: "); |
| 7325 | if (game == null) sb.Append("Game isn't running"); |
| 7326 | else if (UltraPara.LoadedIn(game)) sb.Append("✓ DLL loaded"); |
| 7327 | else sb.Append("✗ Not loaded (restart the game)"); |
| 7328 | sb.Append("\nTrainer code: ").Append(link.IsConnected ? "✓ Connected" + (UltraPara.GameVersion.Length > 0 ? " (UltraPara " + UltraPara.GameVersion + ")" : "") : "Not connected"); |
| 7329 | string last = gd == null ? null : UltraPara.LastLog(gd); |
| 7330 | if (last != null) sb.Append("\nLast start: ").Append(last.Length > 20 ? last.Substring(20) : last); |
| 7331 | if (upBusy) sb.Append("\n").Append(upStatusExtra); |
| 7332 | UltraPara.Status = sb.ToString(); |
| 7333 | } |
| 7334 | |
| 7335 | private string upStatusExtra = ""; |
| 7336 | |
| 7337 | private void InstallUltraPara(bool manual) |
| 7338 | { |
| 7339 | if (upBusy) return; |
| 7340 | string gd = GameDir(); |
| 7341 | if (gd == null) { if (manual) SetMessage("The trainer can't find your game folder. Use Pick Game .exe on the Welcome tab.", true); return; } |
| 7342 | if (Installer.GameRunning()) |
| 7343 | { |
| 7344 | if (manual) SetMessage("Close the game first. UltraPara.dll can't be replaced while the game has it open.", true); |
| 7345 | return; |
| 7346 | } |
| 7347 | upBusy = true; |
| 7348 | upStatusExtra = "Downloading UltraPara.dll..."; |
| 7349 | RefreshUltraPara(); |
| 7350 | Thread t = new Thread(delegate () |
| 7351 | { |
| 7352 | string err; |
| 7353 | try { err = UltraPara.Install(gd, delegate (int pc) { Ui(delegate { upStatusExtra = "Downloading UltraPara.dll... " + pc + "%"; RefreshUltraPara(); view.Invalidate(); }); }); } |
| 7354 | catch (Exception e) { err = e.Message; } |
| 7355 | Ui(delegate |
| 7356 | { |
| 7357 | upBusy = false; |
| 7358 | upStatusExtra = ""; |
| 7359 | if (err == null) SetMessage("UltraPara.dll v" + UltraParaInfo.Version + " is installed. Start the game and the trainer attaches by itself.", false); |
| 7360 | else SetMessage("UltraPara.dll didn't install: " + err + ".", true); |
| 7361 | RefreshUltraPara(); |
| 7362 | view.Invalidate(); |
| 7363 | }); |
| 7364 | }); |
| 7365 | t.IsBackground = true; |
| 7366 | t.Start(); |
| 7367 | } |
| 7368 | |
| 7369 | private void UltraParaTick() |
| 7370 | { |
| 7371 | if (DateTime.UtcNow < upNext) return; |
| 7372 | upNext = DateTime.UtcNow.AddSeconds(2); |
| 7373 | RefreshUltraPara(); |
| 7374 | if (!upAutoTried && !upBusy && !Installer.GameRunning()) |
| 7375 | { |
| 7376 | string st = UltraPara.State(GameDir()); |
| 7377 | if (st == "missing" || st == "old") { upAutoTried = true; InstallUltraPara(false); } |
| 7378 | } |
| 7379 | } |
| 7380 | |
| 7381 | private bool GameFocused() |
| 7382 | { |
| 7383 | if (game == null) return false; |
| 7384 | IntPtr fg = Native.GetForegroundWindow(); |
| 7385 | if (fg == IntPtr.Zero) return false; |
| 7386 | uint pid; |
| 7387 | Native.GetWindowThreadProcessId(fg, out pid); |
| 7388 | return pid == (uint)gamePid && !Native.IsIconic(fg); |
| 7389 | } |
| 7390 | |
| 7391 | private void PlaceOverlay(bool focused) |
| 7392 | { |
| 7393 | bool panel = byId["overlay"].On; |
| 7394 | bool show = focused && link.IsConnected && (panel || overlay.ToastActive); |
| 7395 | if (!show) |
| 7396 | { |
| 7397 | if (overlay.Visible) overlay.Hide(); |
| 7398 | return; |
| 7399 | } |
| 7400 | IntPtr hwnd = Native.GetForegroundWindow(); |
| 7401 | Native.RECT rc; |
| 7402 | if (!Native.GetClientRect(hwnd, out rc)) return; |
| 7403 | Native.POINT pt = new Native.POINT(); |
| 7404 | Native.ClientToScreen(hwnd, ref pt); |
| 7405 | Rectangle b = new Rectangle(pt.X, pt.Y, rc.Right - rc.Left, rc.Bottom - rc.Top); |
| 7406 | if (b.Width < 50 || b.Height < 50) return; |
| 7407 | overlay.ShowPanel = panel; |
| 7408 | if (b != lastOverlayBounds) |
| 7409 | { |
| 7410 | lastOverlayBounds = b; |
| 7411 | overlay.Bounds = b; |
| 7412 | } |
| 7413 | if (!overlay.Visible) overlay.Show(); |
| 7414 | overlay.Invalidate(); |
| 7415 | } |
| 7416 | |
| 7417 | private void RegisterKeys() |
| 7418 | { |
| 7419 | hotkeyIds.Clear(); |
| 7420 | int id = 0x5100; |
| 7421 | foreach (Option o in options) |
| 7422 | { |
| 7423 | if (!o.Bindable || o.Key == Keys.None) continue; |
| 7424 | uint mods = 0x4000; |
| 7425 | if ((o.Key & Keys.Alt) != 0) mods |= 1; |
| 7426 | if ((o.Key & Keys.Control) != 0) mods |= 2; |
| 7427 | if ((o.Key & Keys.Shift) != 0) mods |= 4; |
| 7428 | if (Native.RegisterHotKey(Handle, id, mods, (uint)(o.Key & Keys.KeyCode))) hotkeyIds[id] = o; |
| 7429 | id++; |
| 7430 | } |
| 7431 | RegisterToolKeys(); |
| 7432 | hotkeysOn = true; |
| 7433 | } |
| 7434 | |
| 7435 | private void UnregisterKeys() |
| 7436 | { |
| 7437 | foreach (int id in hotkeyIds.Keys) Native.UnregisterHotKey(Handle, id); |
| 7438 | hotkeyIds.Clear(); |
| 7439 | UnregisterToolKeys(); |
| 7440 | hotkeysOn = false; |
| 7441 | } |
| 7442 | |
| 7443 | protected override void WndProc(ref Message m) |
| 7444 | { |
| 7445 | if (m.Msg == 0x0312) |
| 7446 | { |
| 7447 | Option o; |
| 7448 | if (hotkeyIds.TryGetValue(m.WParam.ToInt32(), out o)) RunOption(o); |
| 7449 | else ToolHotkey(m.WParam.ToInt32()); |
| 7450 | return; |
| 7451 | } |
| 7452 | base.WndProc(ref m); |
| 7453 | } |
| 7454 | |
| 7455 | private void RestoreWindow() |
| 7456 | { |
| 7457 | string[] p = Get("window", "").Split(','); |
| 7458 | if (p.Length != 5) return; |
| 7459 | int x, y, w, h; |
| 7460 | if (!int.TryParse(p[0], out x) || !int.TryParse(p[1], out y) || !int.TryParse(p[2], out w) || !int.TryParse(p[3], out h)) return; |
| 7461 | Rectangle r = new Rectangle(x, y, Math.Max(w, MinimumSize.Width), Math.Max(h, MinimumSize.Height)); |
| 7462 | bool onScreen = false; |
| 7463 | foreach (Screen s in Screen.AllScreens) |
| 7464 | { |
| 7465 | Rectangle i = Rectangle.Intersect(s.WorkingArea, r); |
| 7466 | if (i.Width >= Theme.S(200) && i.Height >= Theme.S(100)) { onScreen = true; break; } |
| 7467 | } |
| 7468 | if (!onScreen) return; |
| 7469 | StartPosition = FormStartPosition.Manual; |
| 7470 | Bounds = r; |
| 7471 | if (p[4] == "1") WindowState = FormWindowState.Maximized; |
| 7472 | } |
| 7473 | |
| 7474 | private void SaveWindow() |
| 7475 | { |
| 7476 | if (WindowState == FormWindowState.Minimized && !Visible) return; |
| 7477 | Rectangle r = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; |
| 7478 | if (r.Width <= 0 || r.Height <= 0) return; |
| 7479 | settings["window"] = r.X + "," + r.Y + "," + r.Width + "," + r.Height + "," + (WindowState == FormWindowState.Maximized ? "1" : "0"); |
| 7480 | Settings.Save(settings); |
| 7481 | } |
| 7482 | |
| 7483 | protected override void OnFormClosing(FormClosingEventArgs e) |
| 7484 | { |
| 7485 | try { SaveWindow(); } catch (Exception) { } |
| 7486 | if (debug != null) |
| 7487 | { |
| 7488 | SaveDebugWindow(); |
| 7489 | debug.Quitting = true; |
| 7490 | try { debug.Close(); } catch (Exception) { } |
| 7491 | } |
| 7492 | try { Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= OnScreensChanged; } catch (Exception) { } |
| 7493 | UnregisterKeys(); |
| 7494 | if (link.IsConnected) |
| 7495 | foreach (Option o in options) |
| 7496 | if (o.Kind == Kind.Toggle && o.On && !o.Local) link.Send("SET " + o.Id + " 0"); |
| 7497 | if (link.IsConnected) |
| 7498 | { |
| 7499 | link.Send("VAL GameSpeed 1"); |
| 7500 | link.Send("VAL CameraZoom 1"); |
| 7501 | } |
| 7502 | if (gamePid != 0) LinkServer.DeleteLinkFile(gamePid); |
| 7503 | if (tray != null) { tray.Visible = false; tray.Dispose(); tray = null; } |
| 7504 | overlay.Close(); |
| 7505 | base.OnFormClosing(e); |
| 7506 | } |
| 7507 | } |
| 7508 | } |