casualexpiesource

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

1910 lines · 107.4 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Globalization;
4using System.IO;
5using System.Linq;
6using System.Threading.Tasks;
7using Avalonia;
8using Avalonia.Controls;
9using Avalonia.Controls.Primitives;
10using Avalonia.Controls.Shapes;
11using Avalonia.Input;
12using Avalonia.Interactivity;
13using Avalonia.Layout;
14using Avalonia.Media;
15using Avalonia.Media.Imaging;
16using Avalonia.Platform.Storage;
17using Avalonia.Threading;
18using UltraParadise.Shared;
19using Path = System.IO.Path;
20using SPath = Avalonia.Controls.Shapes.Path;
21
22namespace UltraParadise.Linux
23{
24 internal sealed partial class MainWindow : Window
25 {
26 private readonly LinkServer link = new();
27 private readonly List<CTab> tabs = Cheats.Build();
28 private readonly Dictionary<string, COpt> byId = new();
29 private readonly Dictionary<string, Action<string>> stateSetters = new();
30 private readonly Dictionary<string, Button> keyButtons = new();
31 private readonly Dictionary<string, string> binds = new();
32 private readonly List<(TextBlock tb, COpt o)> infoRows = new();
33 private Dictionary<string, string> info;
34
35 private readonly ContentControl view = new();
36 private readonly StackPanel sideList = new() { Spacing = 1, Margin = new Thickness(10, 4, 10, 12) };
37 private readonly Panel bgLayer = new() { ClipToBounds = true, IsHitTestVisible = false };
38 private readonly LayoutTransformControl scaleHost = new();
39 private Image bannerArt;
40 private Border bannerFade;
41 private readonly List<Border> cards = new();
42 private readonly List<Action> themeRefresh = new();
43 private readonly Dictionary<string, (SPath icon, TextBlock label)> sideParts = new();
44 private string lastGroup;
45 private readonly Dictionary<string, Control> pages = new();
46 private readonly Dictionary<string, Button> sideButtons = new();
47 private string page;
48
49 private readonly Ellipse dot = new() { Width = 10, Height = 10 };
50 private readonly TextBlock statusText = new() { FontSize = 14, VerticalAlignment = VerticalAlignment.Center };
51 private readonly TextBlock messageText = new() { FontSize = 13, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis };
52
53 private string gameDir;
54 private string game { get => gameDir; set { gameDir = value; Game.Current = value; } }
55 private string bindingId;
56 private DateTime gameSeenSince = DateTime.MinValue;
57 private string pluginVersion;
58 private string blocked;
59 private bool autoPluginTried;
60
61 public MainWindow()
62 {
63 Title = Program.Name;
64 Width = 1200;
65 Height = 720;
66 MinWidth = 980;
67 MinHeight = 620;
68 Background = Ui.B(Ui.Back);
69 WindowStartupLocation = WindowStartupLocation.CenterScreen;
70 Bitmap icon = Program.Image("icon.png");
71 if (icon != null) Icon = new WindowIcon(icon);
72
73 foreach (CTab t in tabs)
74 foreach (CSection s in t.Sections)
75 foreach (COpt o in s.Rows)
76 {
77 byId[o.Id] = o;
78 if (o.Kind == CKind.Toggle || o.Kind == CKind.Action) binds[o.Id] = Settings.Get("bind." + o.Id, o.Key);
79 }
80 binds["menu"] = Settings.Get("bind.menu", Cheats.MenuKey);
81 binds["overlay"] = Settings.Get("bind.overlay", Cheats.OverlayKey);
82
83 Grid root = new() { RowDefinitions = new RowDefinitions("86,*,60"), ColumnDefinitions = new ColumnDefinitions("190,*") };
84
85 Panel banner = new();
86 Bitmap splashArt = Program.Image("splash.jpg");
87 banner.Background = Ui.B(Ui.Side);
88 if (splashArt != null)
89 {
90 bannerArt = new Image { Source = splashArt, Stretch = Stretch.UniformToFill, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, IsVisible = Ui.BannerArt };
91 banner.Children.Add(bannerArt);
92 }
93 bannerFade = new Border { BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(0, 0, 0, 1), Background = BannerFade() };
94 banner.Children.Add(bannerFade);
95 banner.ClipToBounds = true;
96 StackPanel bp = new() { Orientation = Orientation.Horizontal, Margin = new Thickness(22, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, Spacing = 14 };
97 if (icon != null) bp.Children.Add(new Image { Source = icon, Width = 46, Height = 46 });
98 StackPanel titles = new() { VerticalAlignment = VerticalAlignment.Center };
99 titles.Children.Add(new TextBlock { Text = "ULTRA PARADISE", FontSize = 24, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Bright) });
100 titles.Children.Add(new TextBlock { Text = "C U : T R A I N E R · " + string.Join(" ", Program.Platform.ToUpperInvariant().ToCharArray()) + " · v" + Program.Version, FontSize = 11, Foreground = Ui.B(Ui.Orange) });
101 bp.Children.Add(titles);
102 banner.Children.Add(bp);
103 Grid.SetColumnSpan(banner, 2);
104 root.Children.Add(banner);
105
106 Border side = new() { Background = Ui.B(Ui.Side), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(0, 0, 1, 0), Child = new ScrollViewer { Content = sideList } };
107 Grid.SetRow(side, 1);
108 root.Children.Add(side);
109
110 Grid.SetRow(bgLayer, 1);
111 Grid.SetColumn(bgLayer, 1);
112 root.Children.Add(bgLayer);
113 view.Margin = new Thickness(0);
114 Grid.SetRow(view, 1);
115 Grid.SetColumn(view, 1);
116 root.Children.Add(view);
117
118 Border footer = new() { Background = Ui.B(Ui.Side), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(0, 1, 0, 0) };
119 Grid fg = new() { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), Margin = new Thickness(24, 0, 16, 0) };
120 dot.VerticalAlignment = VerticalAlignment.Center;
121 dot.Margin = new Thickness(0, 0, 10, 0);
122 fg.Children.Add(dot);
123 Grid.SetColumn(statusText, 1);
124 fg.Children.Add(statusText);
125 messageText.Margin = new Thickness(24, 0, 12, 0);
126 messageText.Foreground = Ui.B(Ui.Dim);
127 Grid.SetColumn(messageText, 2);
128 fg.Children.Add(messageText);
129 Button start = Btn("Start Game", () => StartGame(), true);
130 start.VerticalAlignment = VerticalAlignment.Center;
131 Grid.SetColumn(start, 3);
132 fg.Children.Add(start);
133 footer.Child = fg;
134 Grid.SetRow(footer, 2);
135 Grid.SetColumnSpan(footer, 2);
136 root.Children.Add(footer);
137 scaleHost.Child = root;
138 scaleHost.LayoutTransform = new ScaleTransform(Ui.Scale, Ui.Scale);
139 Content = scaleHost;
140 FontFamily = Ui.Font;
141 RefreshBackground();
142
143 SetupTools();
144 AddPage("Welcome", WelcomePage(), "START");
145 AddPage("Search", SearchPage(), "CHEATS");
146 AddPage("Favorites", FavsPage(), "CHEATS");
147 foreach (CTab t in tabs)
148 {
149 AddPage(t.Name, t.Name == "Items" ? ItemsPage(t) : CheatPage(t), "CHEATS");
150 if (t.Name == "Player") AddPage("Health", HealthPage(), "CHEATS");
151 }
152 AddPage("Profiles", ProfilesPage(), "TOOLS");
153 AddPage("Tools", ToolsPage(), "TOOLS");
154 AddPage("Watchlist", WatchPage(), "TOOLS");
155 AddPage("Run Stats", StatsPage(), "TOOLS");
156 AddPage("Game Setup", SetupPage(), "TRAINER");
157 AddPage("Settings", TrainerPage(), "TRAINER");
158 AddPage("Appearance", AppearancePage(), "TRAINER");
159 if (!Mac.On) AddPage("Debug", DebugPage(), "TRAINER");
160 AddPage("VirusTotal", VirusTotalPage(), "TRAINER");
161 AddPage("My Mods", MyModsPage(), "EXTRAS");
162 AddPage("Music", MusicPage(), "EXTRAS");
163 AddPage("Install My Mods", ModsPage(), "EXTRAS");
164 AddPage("Report a Bug", ReportPage(), "EXTRAS");
165 AddPage("About Me", AboutPage(), "EXTRAS");
166 Ui.Changed += OnThemeChanged;
167 Closed += (_, _) => Ui.Changed -= OnThemeChanged;
168 if (Application.Current?.PlatformSettings is { } ps)
169 {
170 EventHandler<Avalonia.Platform.PlatformColorValues> h = (_, _) => Dispatcher.UIThread.Post(Ui.SystemChanged);
171 ps.ColorValuesChanged += h;
172 Closed += (_, _) => ps.ColorValuesChanged -= h;
173 }
174
175 AddHandler(KeyDownEvent, OnKey, RoutingStrategies.Tunnel);
176 link.Line += l => Dispatcher.UIThread.Post(() => OnLine(l));
177 link.Connected += () => Dispatcher.UIThread.Post(OnConnected);
178 link.Disconnected += () => Dispatcher.UIThread.Post(OnDisconnected);
179 link.Start();
180
181 string saved = Settings.Get("game", "");
182 game = Game.IsGameDir(saved) ? saved : Game.Find();
183 if (game != null && !Piracy.Ok(game))
184 {
185 string flagged = game;
186 game = null;
187 Opened += (_, _) => Dispatcher.UIThread.Post(() => _ = ShowPiracy(flagged));
188 }
189 if (game != null) link.WriteLinkFile(game);
190
191 if (Settings.Get("welcomed", "0") != "1") { Settings.Set("welcomed", "1"); Show("Welcome"); }
192 else Show(SetupDone() ? "Player" : "Game Setup");
193 if (Settings.Get("notice.updates", "0") != "1" || Settings.Get("notice.usage", "0") != "1") Opened += (_, _) => Dispatcher.UIThread.Post(async () => { await UpdatesNotice(); await UsageNotice(); });
194 StartUsage();
195 DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(1) };
196 timer.Tick += (_, _) => Tick();
197 timer.Start();
198 Tick();
199 if (LauncherWindow.Checked)
200 {
201 updStatus.Text = LauncherWindow.Result;
202 updNow.IsEnabled = Updater.Ready != null;
203 }
204 else if (Settings.On("autoupdate", true)) _ = CheckUpdate(false);
205 if (!OperatingSystem.IsWindows() && !Mac.On && !Setup.RunningInstalled && !Setup.Installed && Settings.Get("install.told", "0") != "1")
206 {
207 Settings.Set("install.told", "1");
208 Message("Tip: install the trainer to your PC (app menu entry and desktop shortcut) from the Settings tab.", false);
209 }
210 if (Program.Args.Contains("--updated")) Message("Updated to v" + Program.Version + ".", false);
211 else if (Settings.On("launchwith", false) && game != null && SetupDone() && !Game.GameRunning()) StartGame();
212 }
213
214 protected override void OnClosed(EventArgs e)
215 {
216 CloseDebug();
217 link.RemoveLinkFile();
218 base.OnClosed(e);
219 }
220
221 private bool SetupDone() => Game.PluginState(game) is "ok" or "old" && Game.LaunchOptionState() != "unset";
222
223 private static TextBlock T(string text, double size, IBrush fg, bool bold = false, bool wrap = false) =>
224 new() { Text = text, FontSize = size, Foreground = fg, FontWeight = bold ? FontWeight.Bold : FontWeight.Normal, TextWrapping = wrap ? TextWrapping.Wrap : TextWrapping.NoWrap };
225
226 private static Button Btn(string text, Action click, bool accent = false)
227 {
228 Button b = new() { Content = text, Padding = new Thickness(14, 6), MinHeight = 32 };
229 b.CornerRadius = new CornerRadius(6);
230 if (accent) { b.Background = Ui.B(Ui.Orange); b.Foreground = Ui.B(Ui.OnAccent); b.FontWeight = FontWeight.SemiBold; }
231 b.Click += (_, _) => click();
232 return b;
233 }
234
235 private static void AddLogo(Button b)
236 {
237 string label = b.Content as string;
238 string file = label switch { "Nexus Mods" or "Nexus Page" => "logo-nexus.png", "GameBanana" => "logo-gamebanana.png", "Discord" => "logo-discord.png", _ => null };
239 if (file == null) return;
240 Avalonia.Media.Imaging.Bitmap bmp = Program.Image(file);
241 if (bmp == null) return;
242 StackPanel sp = new() { Orientation = Orientation.Horizontal, Spacing = 7 };
243 Image img = new() { Source = bmp, Width = 16, Height = 16, VerticalAlignment = VerticalAlignment.Center };
244 if (file == "logo-gamebanana.png") RenderOptions.SetBitmapInterpolationMode(img, Avalonia.Media.Imaging.BitmapInterpolationMode.None);
245 sp.Children.Add(img);
246 sp.Children.Add(new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center });
247 b.Content = sp;
248 }
249
250 private Border Section(string title, out StackPanel body)
251 {
252 body = new StackPanel { Spacing = 6 };
253 StackPanel all = new() { Spacing = 10 };
254 if (!string.IsNullOrWhiteSpace(title))
255 {
256 StackPanel head = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
257 head.Children.Add(new Border { Width = 3, Height = 13, CornerRadius = new CornerRadius(2), Background = Ui.B(Ui.Orange), VerticalAlignment = VerticalAlignment.Center });
258 TextBlock tt = T(string.Join(" ", title.ToCharArray()), 11, Ui.B(Ui.Orange), true);
259 tt.VerticalAlignment = VerticalAlignment.Center;
260 head.Children.Add(tt);
261 all.Children.Add(head);
262 }
263 all.Children.Add(body);
264 Border card = new() { Background = Ui.B(Ui.Card), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(10), Padding = new Thickness(16, 14), Margin = new Thickness(0, 0, 0, 14), Child = all };
265 cards.Add(card);
266 return card;
267 }
268
269 private static readonly Dictionary<string, string> Icons = new()
270 {
271 ["Welcome"] = "M4,11 L12,4 L20,11 M6,9.5 V20 H18 V9.5",
272 ["Player"] = "M8,8 A4,4 0 1,0 16,8 A4,4 0 1,0 8,8 Z M5,20 C5,15.5 8,13.5 12,13.5 C16,13.5 19,15.5 19,20",
273 ["Health"] = "M12,20 C12,20 3,14.5 3,8.8 C3,6.1 5.1,4 7.6,4 C9.4,4 11,5 12,6.6 C13,5 14.6,4 16.4,4 C18.9,4 21,6.1 21,8.8 C21,14.5 12,20 12,20 Z",
274 ["Movement"] = "M5,6 L11,12 L5,18 M12,6 L18,12 L12,18",
275 ["Items"] = "M4,8 L12,4 L20,8 L20,17 L12,21 L4,17 Z M4,8 L12,12 L20,8 M12,12 L12,21",
276 ["Combat"] = "M13,3 L5,14 H12 L11,21 L19,10 H12 Z",
277 ["World"] = "M3,12 A9,9 0 1,0 21,12 A9,9 0 1,0 3,12 Z M3,12 H21 M12,3 C9,6 9,18 12,21 M12,3 C15,6 15,18 12,21",
278 ["Traders"] = "M5,8 H19 L18,20 H6 Z M9,8 V6.5 A3,3 0 0,1 15,6.5 V8",
279 ["Challenges"] = "M6,21 V4 M6,4 H17 L15,8 L17,12 H6",
280 ["Game Setup"] = "M4,7 H20 M4,17 H20 M9,4.5 V9.5 M15,14.5 V19.5",
281 ["Settings"] = "M9,12 A3,3 0 1,0 15,12 A3,3 0 1,0 9,12 Z M12,3 V6 M12,18 V21 M3,12 H6 M18,12 H21 M5.6,5.6 L7.8,7.8 M16.2,16.2 L18.4,18.4 M5.6,18.4 L7.8,16.2 M16.2,7.8 L18.4,5.6",
282 ["Appearance"] = "M12,3 A9,9 0 1,0 12,21 C13.5,21 13.5,19 12.8,18 C12,17 12.5,15 14.5,15 H17 A4,4 0 0,0 21,11 C21,6.5 17,3 12,3 Z M7.5,11 A1,1 0 1,0 9.5,11 A1,1 0 1,0 7.5,11 Z M10.5,7.5 A1,1 0 1,0 12.5,7.5 A1,1 0 1,0 10.5,7.5 Z M14.5,8.5 A1,1 0 1,0 16.5,8.5 A1,1 0 1,0 14.5,8.5 Z",
283 ["Debug"] = "M3,5 H21 V16 H3 Z M7,9 L9.5,11 L7,13 M11,13 H15 M9,20 H15 M12,16 V20",
284 ["Music"] = "M9,18 A2.5,2.5 0 1,1 9,17.9 Z M9,17.5 V5 L19,3 V15.5 M19,15.5 A2.5,2.5 0 1,1 19,15.4 Z M9,9 L19,7",
285 ["My Mods"] = "M4,6 H20 M4,12 H20 M4,18 H20 M8,4 V8 M16,10 V14 M11,16 V20",
286 ["Install My Mods"] = "M12,4 V15 M7,10.5 L12,15.5 L17,10.5 M5,20 H19",
287 ["Report a Bug"] = "M8,9 A4,4 0 0,1 16,9 V15 A4,4 0 0,1 8,15 Z M12,9 V19 M4,11 H8 M16,11 H20 M4,17 L8,15.5 M20,17 L16,15.5 M9,5 L7.5,3.5 M15,5 L16.5,3.5",
288 ["Search"] = "M4,10.5 A6.5,6.5 0 1,0 17,10.5 A6.5,6.5 0 1,0 4,10.5 Z M15.3,15.3 L20,20",
289 ["Favorites"] = "M12,3 L14.6,8.6 L20.6,9.3 L16.1,13.4 L17.3,19.4 L12,16.4 L6.7,19.4 L7.9,13.4 L3.4,9.3 L9.4,8.6 Z",
290 ["About Me"] = "M3,12 A9,9 0 1,0 21,12 A9,9 0 1,0 3,12 Z M12,11 V16.5 M12,7.5 V8",
291 ["Profiles"] = "M4,5 H20 V19 H4 Z M8,9 H16 M8,13 H16 M8,17 H12",
292 ["Tools"] = "M14,4 A4,4 0 0,0 10,9 L4,15 L7,18 L13,12 A4,4 0 0,0 18,8 L16,10 L14,8 L16,6 Z",
293 ["Watchlist"] = "M2,12 C5,6 9,4 12,4 C15,4 19,6 22,12 C19,18 15,20 12,20 C9,20 5,18 2,12 Z M9,12 A3,3 0 1,0 15,12 A3,3 0 1,0 9,12 Z",
294 ["Run Stats"] = "M4,20 V4 M4,20 H20 M8,16 V11 M12,16 V7 M16,16 V13",
295 };
296
297 private void AddPage(string name, Control c, string group)
298 {
299 pages[name] = c;
300 if (group != lastGroup)
301 {
302 lastGroup = group;
303 TextBlock gh = T(string.Join(" ", group.ToCharArray()), 10, Ui.B(Ui.Faint), true);
304 gh.Margin = new Thickness(10, sideList.Children.Count == 0 ? 8 : 14, 0, 4);
305 sideList.Children.Add(gh);
306 }
307 SPath icon = new()
308 {
309 Data = StreamGeometry.Parse(Icons.GetValueOrDefault(name, "M4,12 H20")),
310 Stroke = Ui.B(Ui.Dim),
311 StrokeThickness = 1.7,
312 StrokeLineCap = PenLineCap.Round,
313 StrokeJoin = PenLineJoin.Round,
314 Width = 18,
315 Height = 18,
316 Stretch = Stretch.Uniform,
317 VerticalAlignment = VerticalAlignment.Center,
318 };
319 TextBlock label = T(name, 13.5, Ui.B(Ui.Soft));
320 label.VerticalAlignment = VerticalAlignment.Center;
321 StackPanel content = new() { Orientation = Orientation.Horizontal, Spacing = 11 };
322 content.Children.Add(icon);
323 content.Children.Add(label);
324 Button b = new()
325 {
326 Content = content,
327 HorizontalAlignment = HorizontalAlignment.Stretch,
328 HorizontalContentAlignment = HorizontalAlignment.Left,
329 Background = Brushes.Transparent,
330 Padding = new Thickness(12, 7),
331 CornerRadius = new CornerRadius(8),
332 };
333 if (name == "VirusTotal")
334 {
335 icon.Data = StreamGeometry.Parse("F0 " + VtLogo);
336 icon.Stroke = null;
337 icon.StrokeThickness = 0;
338 icon.Fill = new SolidColorBrush(Color.FromRgb(0x3d, 0x7b, 0xff));
339 icon.Width = 16;
340 icon.Height = 16;
341 icon.Margin = new Thickness(1, 0, 1, 0);
342 }
343 b.Click += (_, _) => Show(name);
344 sideButtons[name] = b;
345 sideParts[name] = (icon, label);
346 sideList.Children.Add(b);
347 }
348
349 private void PaintSide()
350 {
351 foreach (var kv in sideButtons)
352 {
353 bool on = kv.Key == page;
354 kv.Value.Background = on ? Ui.B(Ui.Select) : Brushes.Transparent;
355 var (icon, label) = sideParts[kv.Key];
356 if (kv.Key == "VirusTotal") icon.Opacity = on ? 1 : 0.85;
357 else icon.Stroke = Ui.B(on ? Ui.Orange : Ui.Dim);
358 label.Foreground = Ui.B(on ? Ui.Text : Ui.Soft);
359 label.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal;
360 }
361 }
362
363 private IBrush BannerFade() => new LinearGradientBrush
364 {
365 StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
366 EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative),
367 GradientStops = { new GradientStop(Ui.Alpha(Ui.Side, 240), 0), new GradientStop(Ui.Alpha(Ui.Side, 200), 0.45), new GradientStop(Ui.Alpha(Ui.Side, Ui.BannerArt ? (byte)90 : (byte)255), 1) },
368 };
369
370 private void RefreshBackground()
371 {
372 bgLayer.Children.Clear();
373 if (Ui.BgImage == null || Ui.BgOpacity <= 0) return;
374 double op = Ui.BgOpacity / 100.0;
375 if (Ui.BgFit == "tile")
376 {
377 Size s = Ui.BgImage.Size;
378 bgLayer.Children.Add(new Border { Opacity = op, Background = new ImageBrush(Ui.BgImage) { TileMode = TileMode.Tile, Stretch = Stretch.None, DestinationRect = new RelativeRect(0, 0, s.Width, s.Height, RelativeUnit.Absolute) } });
379 return;
380 }
381 Stretch st = Ui.BgFit switch { "fit" => Stretch.Uniform, "stretch" => Stretch.Fill, "center" => Stretch.None, _ => Stretch.UniformToFill };
382 bgLayer.Children.Add(new Image { Source = Ui.BgImage, Stretch = st, Opacity = op, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center });
383 }
384
385 private void OnThemeChanged(Color[] before)
386 {
387 foreach (Border b in cards) b.Background = Ui.B(Ui.Card);
388 if (bannerArt != null) bannerArt.IsVisible = Ui.BannerArt;
389 if (bannerFade != null) bannerFade.Background = BannerFade();
390 scaleHost.LayoutTransform = new ScaleTransform(Ui.Scale, Ui.Scale);
391 FontFamily = Ui.Font;
392 RefreshBackground();
393 PaintSide();
394 foreach (Action a in themeRefresh) a();
395 if (link.IsConnected) link.Send(Ui.OverlayMessage);
396 }
397
398 private void Show(string name)
399 {
400 page = name;
401 if (name == "Favorites") RebuildFavs();
402 else if (name == "Search") RebuildSearch();
403 else if (name == "Music") RebuildSongs();
404 view.Content = pages[name];
405 MusicShown();
406 PaintSide();
407 if (name == "Game Setup") RefreshSetup();
408 if (name == "Install My Mods") { mgrScanned = DateTime.MinValue; RefreshMods(true); _ = RefreshThunderstore(); }
409 if (name == "Items") AskItems();
410 if (name == "Report a Bug") RefreshReport();
411 if (name == "About Me") { _ = LoadAbout(); _ = RefreshThunderstore(); }
412 }
413
414 private static ScrollViewer Scroll(Control c) => new() { Content = c, Padding = new Thickness(22, 18, 22, 8), HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled };
415
416 private Control CheatPage(CTab t)
417 {
418 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
419 for (int c = 0; c < 3; c++)
420 {
421 StackPanel col = new() { Margin = new Thickness(c == 0 ? 0 : 7, 0, c == 2 ? 0 : 7, 0) };
422 foreach (CSection s in t.Sections.Where(x => x.Col == c)) col.Children.Add(BuildSection(s));
423 Grid.SetColumn(col, c);
424 g.Children.Add(col);
425 }
426 return Scroll(g);
427 }
428
429 private Border BuildSection(CSection s)
430 {
431 Border b = Section(s.Title, out StackPanel body);
432 foreach (COpt o in s.Rows)
433 {
434 Control row = BuildRow(o);
435 if (row != null) body.Children.Add(row);
436 }
437 return b;
438 }
439
440 private Button KeyButton(string id)
441 {
442 Button k = new() { Width = 100, MinHeight = 32, HorizontalContentAlignment = HorizontalAlignment.Center, FontSize = 12, Foreground = Ui.B(Ui.Dim), Background = Ui.B(Ui.Sunk), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(6) };
443 k.Content = Cheats.KeyLabel(binds.GetValueOrDefault(id, ""));
444 ToolTip.SetTip(k, "Click, then press a key. Esc cancels, Delete clears it.");
445 k.Click += (_, _) => StartBind(id);
446 keyButtons[id] = k;
447 return k;
448 }
449
450 private Control BuildRow(COpt o)
451 {
452 switch (o.Kind)
453 {
454 case CKind.Toggle:
455 {
456 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };
457 ToggleSwitch tb = new() { OnContent = o.Name, OffContent = o.Name, HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 34, Margin = new Thickness(0, 0, 6, 0) };
458 if (o.Hint != null) ToolTip.SetTip(tb, o.Hint);
459 tb.ContextMenu = CheatContext(o);
460 tb.Click += (_, _) =>
461 {
462 bool on = tb.IsChecked == true;
463 if (!Linked()) { tb.IsChecked = !on; return; }
464 link.Send("SET " + o.Id + (on ? " 1" : " 0"));
465 if (on && Settings.On("bark", true)) Bark.Play();
466 };
467 RegisterSetter(o.Id, v => tb.IsChecked = v == "1");
468 g.Children.Add(tb);
469 Button st = StarButton(o);
470 Grid.SetColumn(st, 1);
471 g.Children.Add(st);
472 if (!buildingExtra)
473 {
474 Button k = KeyButton(o.Id);
475 Grid.SetColumn(k, 2);
476 g.Children.Add(k);
477 }
478 return g;
479 }
480 case CKind.Action:
481 {
482 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };
483 Button b = new() { Content = o.Name, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Left, MinHeight = 32, Margin = new Thickness(0, 0, 6, 0), CornerRadius = new CornerRadius(6) };
484 if (o.Hint != null) ToolTip.SetTip(b, o.Hint);
485 b.Click += (_, _) => { if (Linked()) link.Send("ACT " + o.Id); };
486 g.Children.Add(b);
487 Button st = StarButton(o);
488 Grid.SetColumn(st, 1);
489 g.Children.Add(st);
490 if (!buildingExtra)
491 {
492 Button k = KeyButton(o.Id);
493 Grid.SetColumn(k, 2);
494 g.Children.Add(k);
495 }
496 return g;
497 }
498 case CKind.Slider:
499 {
500 StackPanel sp = new() { Spacing = 0 };
501 Grid top = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") };
502 top.Children.Add(T(o.Name, 13, Ui.B(Ui.Text)));
503 TextBlock val = T(string.Format(CultureInfo.InvariantCulture, o.Format, o.Default), 13, Ui.B(Ui.Orange), true);
504 val.Margin = new Thickness(0, 0, 8, 0);
505 val.VerticalAlignment = VerticalAlignment.Center;
506 Grid.SetColumn(val, 1);
507 top.Children.Add(val);
508 Slider s = new() { Minimum = o.Min, Maximum = o.Max, TickFrequency = o.Step, IsSnapToTickEnabled = true, Value = o.Default };
509 Button reset = new() { Content = "Reset", FontSize = 11, Padding = new Thickness(8, 2), MinHeight = 22 };
510 Grid.SetColumn(reset, 2);
511 top.Children.Add(reset);
512 sp.Children.Add(top);
513 sp.Children.Add(s);
514 if (o.Hint != null) ToolTip.SetTip(sp, o.Hint);
515 bool quiet = false;
516 s.PropertyChanged += (_, e) =>
517 {
518 if (e.Property != RangeBase.ValueProperty) return;
519 val.Text = string.Format(CultureInfo.InvariantCulture, o.Format, s.Value);
520 if (quiet || !link.IsConnected) return;
521 link.Send("VAL " + o.Id + " " + s.Value.ToString("0.###", CultureInfo.InvariantCulture));
522 };
523 reset.Click += (_, _) => { if (Linked()) s.Value = o.Default; };
524 RegisterSetter(o.Id, v =>
525 {
526 if (!double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) return;
527 quiet = true;
528 s.Value = Math.Clamp(d, o.Min, o.Max);
529 quiet = false;
530 });
531 return sp;
532 }
533 case CKind.Buttons:
534 {
535 WrapPanel w = new() { Orientation = Orientation.Horizontal };
536 TextBlock label = T(o.Name ?? "", 13, Ui.B(Ui.Text));
537 label.Width = 130;
538 label.VerticalAlignment = VerticalAlignment.Center;
539 if (o.Text != null) infoRows.Add((label, o));
540 w.Children.Add(label);
541 foreach (CBtn cb in o.Buttons)
542 {
543 Button b = new() { Content = cb.Label, Margin = new Thickness(0, 0, 4, 4), Padding = new Thickness(10, 4), MinHeight = 30, CornerRadius = new CornerRadius(6) };
544 b.Click += (_, _) => { if (Linked()) link.Send("ACT " + cb.Act + (cb.Arg != null ? " " + cb.Arg : "")); };
545 w.Children.Add(b);
546 }
547 if (o.Hint != null) ToolTip.SetTip(w, o.Hint);
548 return w;
549 }
550 case CKind.Info:
551 {
552 TextBlock tb = T("", 13, Ui.B(Ui.Text), false, true);
553 infoRows.Add((tb, o));
554 return tb;
555 }
556 case CKind.Note:
557 return T(o.Name, 13, Ui.B(Ui.Dim), false, true);
558 }
559 return null;
560 }
561
562 private bool Linked()
563 {
564 if (link.IsConnected) return true;
565 Message(game == null ? "Set up the game first (Game Setup tab)." : "Start the game first. The cheats run inside the game.", true);
566 return false;
567 }
568
569 private void RefreshInfo()
570 {
571 foreach (var (tb, o) in infoRows) tb.Text = o.Text(info) ?? "";
572 }
573
574 private void StartBind(string id)
575 {
576 if (!Linked()) return;
577 if (bindingId != null && keyButtons.TryGetValue(bindingId, out Button old)) old.Content = Cheats.KeyLabel(binds.GetValueOrDefault(bindingId, ""));
578 bindingId = id;
579 if (keyButtons.TryGetValue(id, out Button b)) b.Content = "press a key";
580 Message("Press the key for " + (byId.TryGetValue(id, out COpt o) ? o.Name : id) + ". Esc cancels, Delete clears it.", false);
581 }
582
583 private void OnKey(object sender, KeyEventArgs e)
584 {
585 if (bindingId == null)
586 {
587 if (e.Key == Key.F && e.KeyModifiers.HasFlag(KeyModifiers.Control)) { OpenSearch(); e.Handled = true; }
588 return;
589 }
590 e.Handled = true;
591 Key k = e.Key;
592 if (k is Key.LeftCtrl or Key.RightCtrl or Key.LeftShift or Key.RightShift or Key.LeftAlt or Key.RightAlt or Key.LWin or Key.RWin) return;
593 string id = bindingId;
594 bindingId = null;
595 string v;
596 if (k == Key.Escape) v = null;
597 else if (k is Key.Delete or Key.Back) v = "none";
598 else
599 {
600 string u = KeyMap.Unity(k);
601 if (u == null) { Message("That key can't be used. Pick another.", true); v = null; }
602 else if (id == "menu") v = u;
603 else v = (e.KeyModifiers.HasFlag(KeyModifiers.Control) ? "Ctrl+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? "Shift+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Alt) ? "Alt+" : "") + u;
604 }
605 if (v != null)
606 {
607 binds[id] = v;
608 Settings.Set("bind." + id, v);
609 link.Send("BIND " + id + " " + v);
610 Message("Key set: " + Cheats.KeyLabel(v), false);
611 }
612 if (keyButtons.TryGetValue(id, out Button b)) b.Content = Cheats.KeyLabel(binds.GetValueOrDefault(id, ""));
613 }
614
615 private void Message(string s, bool bad)
616 {
617 messageText.Text = s;
618 messageText.Foreground = bad ? Ui.B(Ui.Bad) : Ui.B(Ui.Dim);
619 }
620
621 private void Status(string s, Color c)
622 {
623 statusText.Text = s;
624 statusText.Foreground = Ui.B(Ui.Text);
625 dot.Fill = Ui.B(c);
626 }
627
628 private DateTime startAsked = DateTime.MinValue;
629
630 private async void StartGame()
631 {
632 if (Game.GameRunning()) { Message("The game is already running.", false); return; }
633 if (game == null) { Show("Game Setup"); Message("Set the game folder first.", true); return; }
634 Message("Asking Steam to start Casualties: Unknown...", false);
635 string e = await Game.Start();
636 if (e != null) { Message("Couldn't start the game: " + e, true); return; }
637 startAsked = DateTime.UtcNow;
638 Message("Steam is starting Casualties: Unknown. If Steam was closed, it opens first, which can take a minute.", false);
639 }
640
641 private bool attachedThisRun;
642 private DateTime gameGoneSince = DateTime.MinValue;
643
644 private void Tick()
645 {
646 MusicTick();
647 ToolsTick();
648 if (game != null && !Game.IsGameDir(game)) game = null;
649 if (game != null) link.WriteLinkFile(game);
650 bool running = game != null && Game.GameRunning();
651 if (running) startAsked = DateTime.MinValue;
652 else if (startAsked != DateTime.MinValue && (DateTime.UtcNow - startAsked).TotalSeconds > 90)
653 {
654 startAsked = DateTime.MinValue;
655 Message("The game still hasn't started. Start it from your Steam library, and check Steam is logged in.", true);
656 }
657 if (running && gameSeenSince == DateTime.MinValue) gameSeenSince = DateTime.UtcNow;
658 if (!running) gameSeenSince = DateTime.MinValue;
659
660 if (!running && game != null && !autoPluginTried && !busy && Game.PluginState(game) is "old" or "missing")
661 {
662 autoPluginTried = true;
663 _ = AutoUltraPara();
664 }
665
666 if (link.IsConnected) attachedThisRun = true;
667 if (running) gameGoneSince = DateTime.MinValue;
668 else if (attachedThisRun && !link.IsConnected)
669 {
670 if (gameGoneSince == DateTime.MinValue) gameGoneSince = DateTime.UtcNow;
671 else if ((DateTime.UtcNow - gameGoneSince).TotalSeconds >= 3)
672 {
673 attachedThisRun = false;
674 gameGoneSince = DateTime.MinValue;
675 if (Settings.On("closewithgame", true)) { Close(); return; }
676 }
677 }
678
679 if (link.IsConnected)
680 {
681 if (blocked != null) Status("Cheats are off: " + blocked, Ui.Bad);
682 else if (link.GameCode != LinkServer.CodeVersion) Status("Attached, but UltraPara.dll is a different version. Close the game and the trainer updates it.", Ui.Warn);
683 else Status("Attached · " + Cheats.Get(info, "where", "loading"), Ui.Good);
684 }
685 else if (game == null) Status("Couldn't find Casualties: Unknown. Set the game folder in Game Setup.", Ui.Bad);
686 else if (Game.PluginState(game) is "missing" or "foreign") Status("UltraPara.dll isn't in the game folder. Finish Game Setup to use the trainer.", Ui.Warn);
687 else if (running && (DateTime.UtcNow - gameSeenSince).TotalSeconds > 40) Status(LinkProblem(), Ui.Warn);
688 else if (running) Status("Waiting for the game to load...", Ui.Warn);
689 else Status("Ready. Start the game and the trainer attaches by itself.", Ui.Dim);
690
691 if (page == "Game Setup") RefreshSetup();
692 if (page == "Install My Mods") RefreshMods(false);
693 if (page == "Items") AskItems();
694 if (page == "Report a Bug") RefreshReport();
695 DebugTick();
696 }
697
698 private DateTime barkAfter = DateTime.MinValue;
699
700 private void OnConnected()
701 {
702 barkAfter = DateTime.UtcNow.AddSeconds(4);
703 blocked = null;
704 pluginVersion = null;
705 items.Clear();
706 itemsLoading = false;
707 link.Send("HEALTH 1");
708 link.Send(Ui.OverlayMessage);
709 DebugConnected();
710 myModsLoaded = false;
711 RebuildMyMods();
712 MyModsConnected();
713 MusicConnected();
714 lastOvExtra = "";
715 SendXBinds();
716 Message("Attached to the game.", false);
717 }
718
719 private void OnDisconnected()
720 {
721 vitals = null;
722 UpdateHealth();
723 SetMoodles("");
724 blocked = null;
725 debugWin?.SetLinked(false);
726 MyModsDisconnected();
727 MusicDisconnected();
728 Message("The game closed or unlinked.", false);
729 }
730
731 private void OnLine(string s)
732 {
733 int sp = s.IndexOf(' ');
734 string cmd = sp < 0 ? s : s[..sp];
735 string rest = sp < 0 ? "" : s[(sp + 1)..];
736 switch (cmd)
737 {
738 case "INFO":
739 info = ParseDict(rest);
740 RefreshInfo();
741 break;
742 case "VITALS":
743 vitals = rest == "none" ? null : ParseDict(rest);
744 UpdateHealth();
745 break;
746 case "MOODLES": SetMoodles(rest); break;
747 case "MICON": OnIcon(rest); break;
748 case "BARKSET":
749 foreach (string n in Bark.OnSet(rest)) link.Send("GETSFX " + n);
750 break;
751 case "SFX": Bark.OnSfx(rest); break;
752 case "MSG": Message(rest, false); ToolsLine(cmd, rest); break;
753 case "HOTKEY": ToolsLine(cmd, rest); break;
754 case "READY":
755 if (int.TryParse(rest, out int n2))
756 {
757 if (n2 == -1) Message("The trainer's patch library didn't load, so many cheats won't work. Try restarting the game.", true);
758 else if (n2 > 0) Message(n2 + " cheat hook" + (n2 == 1 ? "" : "s") + " couldn't load. A game update may have changed something.", true);
759 }
760 break;
761 case "BLOCKED":
762 blocked = rest;
763 Message(Program.Name + " doesn't run alongside multiplayer mods.", true);
764 break;
765 case "STATE":
766 {
767 int p = rest.IndexOf(' ');
768 if (p > 0 && rest[(p + 1)..] == "1" && DateTime.UtcNow > barkAfter && lastState.TryGetValue(rest[..p], out string wasV) && wasV == "0"
769 && byId.TryGetValue(rest[..p], out COpt bo) && bo.Kind == CKind.Toggle && Settings.On("bark", true)) Bark.Play();
770 if (p > 0 && stateSetters.TryGetValue(rest[..p], out Action<string> set)) set(rest[(p + 1)..]);
771 if (p > 0) NoteState(rest[..p], rest[(p + 1)..]);
772 break;
773 }
774 case "BIND":
775 {
776 int p = rest.IndexOf(' ');
777 if (p <= 0) break;
778 string id = rest[..p], v = rest[(p + 1)..];
779 binds[id] = v;
780 if (Settings.Get("bind." + id, "") != v) Settings.Set("bind." + id, v);
781 if (bindingId != id && keyButtons.TryGetValue(id, out Button b)) b.Content = Cheats.KeyLabel(v);
782 break;
783 }
784 case "OPTS":
785 {
786 Dictionary<string, string> d = ParseDict(rest);
787 foreach (var kv in d) if (optSetters.TryGetValue(kv.Key, out Action<bool> set)) set(kv.Value == "1");
788 break;
789 }
790 case "PLUGIN": pluginVersion = rest; break;
791 case "LOADER": loaderVersion = rest == "none" ? null : rest; break;
792 case "DLOG": debugWin?.OnLog(rest); break;
793 case "DSNAP": debugWin?.OnSnapshot(rest); break;
794 case "DSYS": debugWin?.OnSystem(rest); break;
795 case "MODS": MyModsParse(rest); break;
796 case "MODSTAT": MyModsStats(rest); break;
797 case "MUSIC": OnMusicLine(rest); break;
798 case "MUSICLIST": OnMusicList(rest); break;
799 case "MODERR": { int sp2 = rest.IndexOf(' '); Message(sp2 > 0 ? rest[(sp2 + 1)..] : rest, true); } break;
800 case "ITEM":
801 {
802 int tab = rest.IndexOf('\t');
803 if (tab > 0) items.Add((rest[..tab], rest[(tab + 1)..]));
804 break;
805 }
806 case "ITEMSEND":
807 itemsLoading = false;
808 items.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase));
809 FilterItems();
810 spawnStatus.Text = items.Count > 0 ? items.Count + " items. Pick one and click Spawn." : "Start a run to load the item list.";
811 break;
812 }
813 }
814
815 private static Dictionary<string, string> ParseDict(string rest)
816 {
817 Dictionary<string, string> d = new();
818 foreach (string part in rest.Split('|'))
819 {
820 int eq = part.IndexOf('=');
821 if (eq > 0) d[part[..eq]] = part[(eq + 1)..];
822 }
823 return d;
824 }
825
826 private Dictionary<string, string> vitals;
827 private readonly List<Action> vitalUpdaters = new();
828 private readonly WrapPanel moodlePanel = new() { Orientation = Orientation.Horizontal };
829 private readonly StackPanel issuePanel = new() { Spacing = 8 };
830 private readonly TextBlock healthNote = T("", 13, Ui.B(Ui.Dim), false, true);
831 private readonly Dictionary<string, Bitmap> icons = new();
832 private string moodlesRaw = "", issuesKey = "";
833
834 private Control HealthPage()
835 {
836 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*") };
837 StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) };
838 Border vs = Section("VITALS", out StackPanel vb);
839 vb.Children.Add(healthNote);
840 Vital(vb, "Heart rate", "hr", 0, 200, v => v.ToString("0", CultureInfo.InvariantCulture) + " bpm", false);
841 Vital(vb, "Blood", "blood", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false);
842 Vital(vb, "Bleeding", "bleed", 0, 1, v => v.ToString("0.00", CultureInfo.InvariantCulture) + " L/min", true);
843 Vital(vb, "Oxygen", "oxy", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false);
844 Vital(vb, "Brain", "brain", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false);
845 Vital(vb, "Consciousness", "consc", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false);
846 Vital(vb, "Pain", "pain", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", true);
847 Vital(vb, "Temperature", "temp", 25, 45, v => v.ToString("0.0", CultureInfo.InvariantCulture) + " °C", false);
848 Vital(vb, "Hunger", "hunger", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false);
849 Vital(vb, "Thirst", "thirst", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false);
850 Vital(vb, "Energy", "energy", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false);
851 Vital(vb, "Sickness", "sick", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", true);
852 Vital(vb, "Infection", "infect", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), true);
853 Vital(vb, "Radiation", "rad", 0, 10, v => v.ToString("0.0", CultureInfo.InvariantCulture) + " gy", true);
854 Vital(vb, "Mood", "mood", -100, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false);
855 left.Children.Add(vs);
856 g.Children.Add(left);
857
858 StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) };
859 Border ms = Section("MOODLES", out StackPanel mb);
860 mb.Children.Add(moodlePanel);
861 right.Children.Add(ms);
862 Border ws = Section("WHAT TO DO", out StackPanel wb);
863 wb.Children.Add(issuePanel);
864 right.Children.Add(ws);
865 Grid.SetColumn(right, 1);
866 g.Children.Add(right);
867 UpdateHealth();
868 return Scroll(g);
869 }
870
871 private void Vital(StackPanel host, string label, string key, double min, double max, Func<double, string> fmt, bool badHigh)
872 {
873 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("120,*,90") };
874 g.Children.Add(T(label, 13, Ui.B(Ui.Text)));
875 ProgressBar bar = new() { Minimum = min, Maximum = max, Height = 8, MinHeight = 8, MinWidth = 0, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0) };
876 Grid.SetColumn(bar, 1);
877 g.Children.Add(bar);
878 TextBlock val = T("-", 13, Ui.B(Ui.Dim));
879 val.HorizontalAlignment = HorizontalAlignment.Right;
880 Grid.SetColumn(val, 2);
881 g.Children.Add(val);
882 host.Children.Add(g);
883 vitalUpdaters.Add(() =>
884 {
885 if (vitals == null || !vitals.ContainsKey(key)) { bar.Value = min; val.Text = "-"; return; }
886 double v = Advisor.F(vitals, key, 0);
887 bar.Value = Math.Clamp(v, min, max);
888 double frac = (v - min) / (max - min);
889 bool bad = badHigh ? frac > 0.5 : frac < 0.3;
890 bar.Foreground = Ui.B(bad ? Ui.Bad : Ui.Orange);
891 val.Text = fmt(v);
892 });
893 }
894
895 private void UpdateHealth()
896 {
897 foreach (Action a in vitalUpdaters) a();
898 healthNote.Text = !link.IsConnected ? "Start the game to see your character's health here." : vitals == null ? "Start a run to see your character's health." : Advisor.F(vitals, "alive", 1) < 0.5f ? "Your character is dead." : "";
899 healthNote.IsVisible = healthNote.Text.Length > 0;
900 List<Issue> issues = Advisor.Check(vitals, byId);
901 string key = string.Join("|", issues.Select(i => i.Title + i.Detail));
902 if (key == issuesKey) return;
903 issuesKey = key;
904 issuePanel.Children.Clear();
905 if (issues.Count == 0)
906 {
907 issuePanel.Children.Add(T(vitals == null ? "Nothing to show yet." : "All good. Nothing needs fixing right now.", 13, Ui.B(Ui.Dim), false, true));
908 return;
909 }
910 foreach (Issue i in issues)
911 {
912 StackPanel sp = new() { Spacing = 4 };
913 sp.Children.Add(T(i.Title, 14, Ui.B(i.Danger ? Ui.Bad : Ui.Text), true));
914 sp.Children.Add(T(i.Detail, 12, Ui.B(Ui.Dim), false, true));
915 WrapPanel fixes = new();
916 foreach (Fix f in i.Fixes)
917 {
918 Fix fx = f;
919 Button b = new() { Content = fx.Label, FontSize = 12, Padding = new Thickness(10, 3), Margin = new Thickness(0, 2, 6, 0), MinHeight = 26 };
920 b.Click += (_, _) =>
921 {
922 if (!Linked()) return;
923 if (fx.Act != null) link.Send("ACT " + fx.Act);
924 else if (fx.Opt.Kind == CKind.Toggle) { link.Send("SET " + fx.Opt.Id + " 1"); if (Settings.On("bark", true)) Bark.Play(); }
925 else link.Send("ACT " + fx.Opt.Id);
926 };
927 fixes.Children.Add(b);
928 }
929 if (fixes.Children.Count > 0) sp.Children.Add(fixes);
930 issuePanel.Children.Add(new Border { Background = Ui.B(Ui.Back), CornerRadius = new CornerRadius(6), Padding = new Thickness(10, 8), BorderBrush = Ui.B(i.Danger ? Ui.Bad : Ui.Line), BorderThickness = new Thickness(1), Child = sp });
931 }
932 }
933
934 private void OnIcon(string rest)
935 {
936 int sp = rest.IndexOf(' ');
937 if (sp <= 0) return;
938 string id = rest[..sp];
939 if (!int.TryParse(id, out _)) return;
940 try
941 {
942 byte[] b = Convert.FromBase64String(rest[(sp + 1)..]);
943 if (b.Length > 512 * 1024) return;
944 using MemoryStream ms = new(b);
945 icons[id] = new Bitmap(ms);
946 SetMoodles(moodlesRaw, true);
947 }
948 catch (Exception) { }
949 }
950
951 private void SetMoodles(string raw, bool force = false)
952 {
953 if (raw == moodlesRaw && !force) return;
954 moodlesRaw = raw;
955 moodlePanel.Children.Clear();
956 if (raw.Length == 0)
957 {
958 moodlePanel.Children.Add(T(link.IsConnected ? "No moodles right now." : "Start the game to see moodles.", 13, Ui.B(Ui.Dim)));
959 return;
960 }
961 foreach (string row in raw.Split('\u001e'))
962 {
963 string[] f = row.Split('\u001f');
964 if (f.Length < 6) continue;
965 Panel stack = new() { Width = 46, Height = 46 };
966 foreach (string id in new[] { f[0], f[1] })
967 {
968 if (id.Length == 0 || !icons.TryGetValue(id, out Bitmap bmp)) continue;
969 Image img = new() { Source = bmp, Width = 46, Height = 46, Stretch = Stretch.Uniform };
970 RenderOptions.SetBitmapInterpolationMode(img, BitmapInterpolationMode.None);
971 stack.Children.Add(img);
972 }
973 Border b = new() { Child = stack, Margin = new Thickness(0, 0, 6, 6), CornerRadius = new CornerRadius(4), BorderThickness = new Thickness(f[2] == "1" ? 2 : 0), BorderBrush = Ui.B(Ui.Bad), Background = Ui.B(Ui.Back) };
974 ToolTip.SetTip(b, f[4] + (f[5].Length > 0 ? "\n" + f[5] : ""));
975 moodlePanel.Children.Add(b);
976 }
977 }
978
979 private readonly List<(string key, string name)> items = new();
980 private List<(string key, string name)> shown = new();
981 private bool itemsLoading;
982 private DateTime nextItemsAsk;
983 private readonly TextBox itemSearch = new() { Watermark = "Search items" };
984 private readonly ListBox itemList = new() { Height = 380 };
985 private readonly NumericUpDown itemCount = new() { Minimum = 1, Maximum = 50, Increment = 1, Value = 1, FormatString = "0", Width = 130 };
986 private readonly TextBlock spawnStatus = T("Start a run to load the item list.", 12, Ui.B(Ui.Dim), false, true);
987
988 private Control ItemsPage(CTab t)
989 {
990 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,2*") };
991 StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) };
992 foreach (CSection s in t.Sections) left.Children.Add(BuildSection(s));
993 g.Children.Add(left);
994
995 Border sb = Section("ITEM SPAWNER", out StackPanel body);
996 body.Children.Add(itemSearch);
997 itemSearch.TextChanged += (_, _) => FilterItems();
998 body.Children.Add(itemList);
999 itemList.SelectionMode = SelectionMode.Multiple;
1000 itemList.DoubleTapped += (_, _) => Spawn();
1001 StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
1002 row.Children.Add(T("How many", 13, Ui.B(Ui.Text)));
1003 ((TextBlock)row.Children[0]).VerticalAlignment = VerticalAlignment.Center;
1004 row.Children.Add(itemCount);
1005 row.Children.Add(Btn("Spawn", Spawn, true));
1006 row.Children.Add(Btn("Favorite", ToggleItemFav));
1007 row.Children.Add(Btn("Reload List", () => { items.Clear(); FilterItems(); nextItemsAsk = DateTime.MinValue; AskItems(); }));
1008 body.Children.Add(row);
1009 body.Children.Add(spawnStatus);
1010 body.Children.Add(T("Favorites (star) and recently spawned items (arrow) are listed first. Ctrl+click several items to spawn them all at once.", 12, Ui.B(Ui.Dim), false, true));
1011 StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) };
1012 right.Children.Add(sb);
1013 Grid.SetColumn(right, 1);
1014 g.Children.Add(right);
1015 return Scroll(g);
1016 }
1017
1018 private void AskItems()
1019 {
1020 if (!link.IsConnected || items.Count > 0 || itemsLoading || DateTime.UtcNow < nextItemsAsk) return;
1021 nextItemsAsk = DateTime.UtcNow.AddSeconds(5);
1022 itemsLoading = true;
1023 spawnStatus.Text = "Loading the item list...";
1024 link.Send("ITEMS");
1025 }
1026
1027 private void FilterItems()
1028 {
1029 string q = (itemSearch.Text ?? "").Trim();
1030 List<(string key, string name)> match = q.Length == 0 ? items.ToList() : items.Where(i => i.name.Contains(q, StringComparison.OrdinalIgnoreCase) || i.key.Contains(q, StringComparison.OrdinalIgnoreCase)).ToList();
1031 List<(string key, string name)> favs = match.Where(i => itemFavs.Contains(i.key)).ToList();
1032 List<(string key, string name)> recent = q.Length == 0 ? itemRecent.Select(r => match.FirstOrDefault(i => i.key == r)).Where(i => i.key != null && !itemFavs.Contains(i.key)).ToList() : new();
1033 shown = favs.Concat(recent).Concat(match.Where(i => !itemFavs.Contains(i.key) && !recent.Any(r => r.key == i.key))).ToList();
1034 itemList.ItemsSource = shown.Select(i => (itemFavs.Contains(i.key) ? "\u2605 " : recent.Any(r => r.key == i.key) ? "\u21BA " : "") + i.name).ToList();
1035 }
1036
1037 private void Spawn()
1038 {
1039 if (!Linked()) return;
1040 List<int> picked = itemList.Selection.SelectedIndexes.Where(i => i >= 0 && i < shown.Count).ToList();
1041 if (picked.Count == 0) { spawnStatus.Text = "Pick an item first."; return; }
1042 int n = (int)(itemCount.Value ?? 1);
1043 List<string> keys = picked.Select(i => shown[i].key).ToList();
1044 foreach (string k in keys)
1045 {
1046 link.Send("SPAWN " + k + " " + Math.Clamp(n, 1, 50));
1047 itemRecent.Remove(k);
1048 itemRecent.Insert(0, k);
1049 }
1050 if (itemRecent.Count > 12) itemRecent.RemoveRange(12, itemRecent.Count - 12);
1051 Settings.Set("items.recent", string.Join(",", itemRecent));
1052 }
1053
1054 private readonly HashSet<string> itemFavs = new(Settings.Get("items.fav", "").Split(',', StringSplitOptions.RemoveEmptyEntries));
1055 private readonly List<string> itemRecent = Settings.Get("items.recent", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Take(12).ToList();
1056
1057 private void ToggleItemFav()
1058 {
1059 List<int> picked = itemList.Selection.SelectedIndexes.Where(i => i >= 0 && i < shown.Count).ToList();
1060 if (picked.Count == 0) { spawnStatus.Text = "Pick an item first."; return; }
1061 foreach (int i in picked) if (!itemFavs.Remove(shown[i].key)) itemFavs.Add(shown[i].key);
1062 Settings.Set("items.fav", string.Join(",", itemFavs));
1063 FilterItems();
1064 }
1065
1066 private readonly TextBlock gamePath = T("", 13, Ui.B(Ui.Text), false, true);
1067 private readonly TextBlock bepStatus = T("", 13, Ui.B(Ui.Text), false, true);
1068 private readonly TextBlock pluginStatus = T("", 13, Ui.B(Ui.Text), false, true);
1069 private readonly TextBlock launchStatus = T("", 13, Ui.B(Ui.Text), false, true);
1070 private readonly TextBlock setupWarn = T("", 13, Ui.B(Ui.Warn), false, true);
1071 private Button bepBtn, pluginBtn;
1072 private bool busy;
1073
1074 private Control SetupPage()
1075 {
1076 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*") };
1077 StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) };
1078
1079 Border all = Section("QUICK SETUP", out StackPanel ab);
1080 ab.Children.Add(T("Downloads UltraPara.dll (the trainer's loader) into the game folder, checks it, and sets the Steam launch option Proton needs to load it. The trainer doesn't need BepInEx; install it below only if you want my other mods. Close the game and quit Steam first.", 13, Ui.B(Ui.Dim), false, true));
1081 ab.Children.Add(Btn("Set Everything Up", () => _ = SetupAll(), true));
1082 left.Children.Add(all);
1083
1084 Border gs = Section("GAME", out StackPanel gb);
1085 gb.Children.Add(gamePath);
1086 WrapPanel gbtn = new();
1087 foreach (Button b in new[]
1088 {
1089 Btn("Find Again", () =>
1090 {
1091 game = Game.Find();
1092 if (game != null && !Piracy.Ok(game)) { string fl = game; game = null; RefreshSetup(); _ = ShowPiracy(fl); return; }
1093 if (game != null) Settings.Set("game", game);
1094 RefreshSetup();
1095 Message(game == null ? (Mac.On ? "Couldn't find the game in your CrossOver, Whisky or Wine bottles." : "Couldn't find the game in your Steam libraries.") : "Found the game.", game == null);
1096 }),
1097 Btn("Pick Game .exe", () => _ = PickGame(false)),
1098 Btn("Open Folder", () => { if (game != null) Game.Open(game); }),
1099 Btn("Start Game", () => StartGame()),
1100 })
1101 { b.Margin = new Thickness(0, 4, 6, 0); gbtn.Children.Add(b); }
1102 gb.Children.Add(gbtn);
1103 left.Children.Add(gs);
1104
1105 Border ps = Section("1 ULTRAPARA.DLL (REQUIRED)", out StackPanel pb);
1106 pb.Children.Add(T("The trainer's loader. It goes next to CasualtiesUnknown.exe as two files, UltraPara.dll and version.dll, and loads the cheats when the game starts. It comes from casualexpie's update server and is checked against the fingerprint built into this app. It doesn't need BepInEx.", 13, Ui.B(Ui.Dim), false, true));
1107 pb.Children.Add(pluginStatus);
1108 WrapPanel pbtn = new();
1109 pluginBtn = Btn("Install UltraPara.dll", () => _ = InstallUltraPara(true));
1110 pluginBtn.Margin = new Thickness(0, 4, 6, 0);
1111 pbtn.Children.Add(pluginBtn);
1112 Button rm = Btn("Remove", () => { if (game == null) return; string e = Game.RemovePlugin(game); Message(e == null ? "UltraPara.dll was removed. The trainer can't attach until it's installed again." : "Couldn't remove it: " + e, e != null); autoPluginTried = true; RefreshSetup(); });
1113 rm.Margin = new Thickness(0, 4, 6, 0);
1114 pbtn.Children.Add(rm);
1115 pb.Children.Add(pbtn);
1116 left.Children.Add(ps);
1117
1118 Border bs = Section("BEPINEX " + Game.BepVersion + " (OPTIONAL, FOR MY OTHER MODS)", out StackPanel bb);
1119 bb.Children.Add(T("The trainer doesn't need it. My other mods (Install My Mods tab) do. When it's installed, both work together.", 13, Ui.B(Ui.Dim), false, true));
1120 bb.Children.Add(bepStatus);
1121 bepBtn = Btn("Install BepInEx", () => _ = InstallBep());
1122 bb.Children.Add(bepBtn);
1123 left.Children.Add(bs);
1124 g.Children.Add(left);
1125
1126 StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) };
1127 Border ls = Section(Mac.On ? "2 WINE SETTING" : "2 STEAM LAUNCH OPTION", out StackPanel lb);
1128 WrapPanel lbtn = new();
1129 if (Mac.On)
1130 {
1131 lb.Children.Add(T("Wine only loads BepInEx if it's allowed to use the game's own winhttp.dll. The trainer can set that in the game's bottle for you (quit Steam in the bottle first). To do it by hand in CrossOver or Whisky: Wine Configuration > Libraries > add winhttp, set to Native then Builtin.", 13, Ui.B(Ui.Dim), false, true));
1132 lb.Children.Add(new TextBox { Text = "winhttp (native, builtin)", IsReadOnly = true, FontFamily = new FontFamily("monospace") });
1133 lbtn.Children.Add(Btn("Set It For Me", () => { string e = Game.SetLaunchOption(); Message(e == null ? "Wine setting done. You can start the game again." : "Couldn't set it: " + e, e != null); RefreshSetup(); }));
1134 }
1135 else
1136 {
1137 lb.Children.Add(T("Proton only loads UltraPara.dll (and BepInEx, if you use my other mods) with this launch option. Right-click the game in Steam > Properties > Launch Options. If you set the older one (winhttp=n,b), Set It For Me updates it:", 13, Ui.B(Ui.Dim), false, true));
1138 lb.Children.Add(new TextBox { Text = Game.LaunchOption, IsReadOnly = true, FontFamily = new FontFamily("monospace") });
1139 Button copy = Btn("Copy", async () => { if (Clipboard != null) await Clipboard.SetTextAsync(Game.LaunchOption); Message("Copied. Paste it into the game's Launch Options in Steam.", false); });
1140 copy.Margin = new Thickness(0, 0, 6, 0);
1141 lbtn.Children.Add(copy);
1142 lbtn.Children.Add(Btn("Set It For Me", () => { string e = Game.SetLaunchOption(); Message(e == null ? "Launch option set. You can start Steam again." : e, e != null); RefreshSetup(); }));
1143 }
1144 lb.Children.Add(lbtn);
1145 lb.Children.Add(launchStatus);
1146 right.Children.Add(ls);
1147
1148 Border ws = Section("NOTES", out StackPanel wb);
1149 wb.Children.Add(setupWarn);
1150 if (Mac.On) wb.Children.Add(T("On a Mac, " + Cheats.KeyLabel(Cheats.MenuKey) + " is fn + " + Cheats.KeyLabel(Cheats.MenuKey) + " on most keyboards, and Macs have no Insert key or number pad. Set your own keys in the cheat tabs, or press both sticks (L3 + R3) on a controller for the in-game menu.", 13, Ui.B(Ui.Dim), false, true));
1151 else wb.Children.Add(T("Steam Deck: do the setup here in Desktop Mode. In Gaming Mode, press both sticks (L3 + R3) or " + Cheats.KeyLabel(Cheats.MenuKey) + " in game to open the trainer's own menu. This app doesn't need to be open for that.", 13, Ui.B(Ui.Dim), false, true));
1152 wb.Children.Add(T("The first start after installing BepInEx takes a little longer while it sets itself up.", 13, Ui.B(Ui.Dim), false, true));
1153 right.Children.Add(ws);
1154
1155 Border lk = Section("LINKS", out StackPanel lkb);
1156 lkb.Children.Add(T("The official pages for this trainer. Not affiliated with Nexus Mods, GameBanana or Discord. Logos belong to their owners.", 13, Ui.B(Ui.Dim), false, true));
1157 WrapPanel lkw = new();
1158 foreach (Button b in new[]
1159 {
1160 Btn("Nexus Mods", () => Game.Open("https://www.nexusmods.com/scavprototype/mods/1203")),
1161 Btn("GameBanana", () => Game.Open("https://gamebanana.com/mods/749667")),
1162 Btn("Discord", () => Message("The Discord server isn't open yet. It's coming later.", false)),
1163 })
1164 { b.Margin = new Thickness(0, 4, 6, 0); AddLogo(b); lkw.Children.Add(b); }
1165 lkb.Children.Add(lkw);
1166 right.Children.Add(lk);
1167 Grid.SetColumn(right, 1);
1168 g.Children.Add(right);
1169 return Scroll(g);
1170 }
1171
1172 private async Task UpdatesNotice()
1173 {
1174 if (Settings.Get("notice.updates", "0") == "1") return;
1175 Settings.Set("notice.updates", "1");
1176 Window w = new()
1177 {
1178 Title = Program.Name + " - About updates",
1179 Width = 460,
1180 SizeToContent = SizeToContent.Height,
1181 CanResize = false,
1182 WindowStartupLocation = WindowStartupLocation.CenterOwner,
1183 Background = Ui.B(Ui.Back),
1184 };
1185 StackPanel sp = new() { Margin = new Thickness(20), Spacing = 12 };
1186 sp.Children.Add(new TextBlock { Text = "Heads up: Ultra Paradise gets updates regularly", FontSize = 18, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Orange), TextWrapping = TextWrapping.Wrap });
1187 sp.Children.Add(new TextBlock { Text = "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.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Text) });
1188 sp.Children.Add(new TextBlock { Text = "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.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Text) });
1189 sp.Children.Add(new TextBlock { Text = "Every update is checked against the official fingerprints on the Nexus page before it's installed.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Dim) });
1190 Button ok = new() { Content = "Got it", Padding = new Thickness(20, 6), HorizontalAlignment = HorizontalAlignment.Right, Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent) };
1191 ok.Click += (_, _) => w.Close();
1192 sp.Children.Add(ok);
1193 w.Content = sp;
1194 await w.ShowDialog(this);
1195 }
1196
1197 private async Task ShowPiracy(string dir)
1198 {
1199 PiracyDialog d = new();
1200 await d.ShowDialog(this);
1201 if (!d.Proceed) { Message("The game in " + dir + " wasn't used. Use Pick Game .exe in Game Setup if you want to choose it anyway.", true); return; }
1202 await PickGame(true);
1203 }
1204
1205 private async Task PickGame(bool proceeded)
1206 {
1207 IReadOnlyList<IStorageFile> r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
1208 {
1209 Title = "Pick the Casualties: Unknown game .exe (CasualtiesUnknown.exe)",
1210 AllowMultiple = false,
1211 FileTypeFilter = new[] { new FilePickerFileType("Game (.exe)") { Patterns = new[] { "*.exe", "*.EXE" } } },
1212 });
1213 string f = r.Count > 0 ? r[0].TryGetLocalPath() : null;
1214 if (f == null) return;
1215 string p = Path.GetDirectoryName(f);
1216 if (!Game.IsGameDir(p)) { Message("That isn't CasualtiesUnknown.exe. Pick the game's own .exe.", true); return; }
1217 if (Piracy.Flagged(p))
1218 {
1219 if (!proceeded && !Piracy.Ok(p))
1220 {
1221 PiracyDialog d = new();
1222 await d.ShowDialog(this);
1223 if (!d.Proceed) return;
1224 }
1225 Settings.Set("piracy.ok", p);
1226 }
1227 game = p;
1228 Settings.Set("game", p);
1229 link.WriteLinkFile(p);
1230 RefreshSetup();
1231 Message("Game folder set.", false);
1232 }
1233
1234 private async Task<bool> InstallBep()
1235 {
1236 if (busy || game == null) return false;
1237 busy = true;
1238 bepBtn.IsEnabled = false;
1239 string e = await Game.InstallBepInEx(game, pc => Dispatcher.UIThread.Post(() => bepStatus.Text = "Downloading BepInEx... " + pc + "%"));
1240 busy = false;
1241 bepBtn.IsEnabled = true;
1242 Message(e == null ? "BepInEx is installed." : "Couldn't install BepInEx: " + e, e != null);
1243 RefreshSetup();
1244 return e == null;
1245 }
1246
1247 private string upProgress, loaderVersion;
1248
1249 private async Task<bool> InstallUltraPara(bool tell)
1250 {
1251 if (busy || game == null) return false;
1252 busy = true;
1253 upProgress = "Downloading UltraPara.dll...";
1254 RefreshSetup();
1255 string e = await Game.InstallPlugin(game, pc => Dispatcher.UIThread.Post(() => { upProgress = "Downloading UltraPara.dll... " + pc + "%"; RefreshSetup(); }));
1256 busy = false;
1257 upProgress = null;
1258 if (e != null || tell) Message(e == null ? "UltraPara.dll v" + UltraParaInfo.Version + " is installed." : "Couldn't install UltraPara.dll: " + e, e != null);
1259 RefreshSetup();
1260 return e == null;
1261 }
1262
1263 private async Task AutoUltraPara()
1264 {
1265 string before = Game.PluginState(game);
1266 if (await InstallUltraPara(false)) Message(before == "old" ? "UltraPara.dll was updated to v" + UltraParaInfo.Version + "." : "UltraPara.dll v" + UltraParaInfo.Version + " was installed in the game folder.", false);
1267 }
1268
1269 private string LinkProblem()
1270 {
1271 string log = game != null ? Game.LoaderLog(game) : null;
1272 if (log == null) return "The game is running but UltraPara.dll didn't start. Check the launch option in Game Setup, then restart the game.";
1273 if (log.Contains("FAILED")) return "UltraPara.dll couldn't start the trainer: " + log.Substring(log.IndexOf("FAILED", StringComparison.Ordinal));
1274 return "UltraPara.dll is loaded but the trainer code hasn't connected yet.";
1275 }
1276
1277 private async Task SetupAll()
1278 {
1279 if (game == null) { Message("Find or pick the game folder first.", true); return; }
1280 if (Game.GameRunning()) { Message("Close the game first.", true); return; }
1281 if (!await InstallUltraPara(false)) return;
1282 if (Game.LaunchOptionState() != "set")
1283 {
1284 string e = Game.SetLaunchOption();
1285 if (e != null) { Message("UltraPara.dll is in. Last step: " + e, true); RefreshSetup(); return; }
1286 }
1287 RefreshSetup();
1288 Message(Mac.On ? "All set. Start the game through Steam in CrossOver/Whisky." : "All set. Start the game through Steam.", false);
1289 }
1290
1291 private void RefreshSetup()
1292 {
1293 gamePath.Text = game ?? "Not found. Use Find Again, or Pick Game .exe.";
1294 gamePath.Foreground = Ui.B(game == null ? Ui.Bad : Ui.Text);
1295 bool running = Game.GameRunning();
1296 if (!busy)
1297 {
1298 bool bep = Game.BepInstalled(game);
1299 bepStatus.Text = game == null ? "Waiting for the game folder." : bep ? (Game.BepRan(game) ? "Installed, and it has run." : "Installed. It hasn't run yet: start the game once with the launch option set.") : "Not installed.";
1300 bepStatus.Foreground = Ui.B(bep ? Ui.Good : Ui.Warn);
1301 bepBtn.Content = bep ? "Reinstall BepInEx" : "Install BepInEx";
1302 bepBtn.IsEnabled = game != null && !running;
1303 }
1304 string ps = Game.PluginState(game);
1305 string loaderLog = game != null ? Game.LoaderLog(game) : null;
1306 string st = ps switch
1307 {
1308 "ok" => "✓ Installed (v" + UltraParaInfo.Version + ").",
1309 "old" => running ? "An update is ready. It installs when the game is closed." : "An older version is installed. Update it.",
1310 "missing" => "✗ Not installed.",
1311 "foreign" => "✗ Blocked: the game folder has a version.dll from another program. Move it out first.",
1312 _ => "Waiting for the game folder.",
1313 };
1314 if (link.IsConnected && loaderVersion != null) st += "\n✓ DLL loaded in the game (UltraPara " + loaderVersion + ").";
1315 else if (running && loaderLog != null && loaderLog.Contains("LOADED")) st += "\n✓ DLL loaded in the game.";
1316 else if (running) st += "\nIn the game: not loaded yet. If it stays like this, restart the game and check the launch option.";
1317 if (loaderLog != null && loaderLog.Contains("FAILED")) st += "\nLast start: " + loaderLog;
1318 if (upProgress != null) st += "\n" + upProgress;
1319 pluginStatus.Text = st;
1320 pluginStatus.Foreground = Ui.B(ps == "ok" ? Ui.Good : Ui.Warn);
1321 pluginBtn.Content = ps == "old" ? "Update UltraPara.dll" : ps == "ok" ? "Reinstall UltraPara.dll" : "Install UltraPara.dll";
1322 pluginBtn.IsEnabled = game != null && !running && !busy;
1323 string ls = Game.LaunchOptionState();
1324 launchStatus.Text = ls == "set" ? "It's set." : ls == "unset" ? "Not set yet." : (Mac.On ? "Couldn't read the bottle's settings, so the trainer can't tell." : "Couldn't read Steam's settings, so the trainer can't tell. Check it in Steam.");
1325 launchStatus.Foreground = Ui.B(ls == "set" ? Ui.Good : Ui.Warn);
1326 List<string> warn = new();
1327 string other = game != null ? Game.OtherCheats(game) : null;
1328 if (other != null) warn.Add("CU Cheats is installed too. It has the same cheats and also uses " + Cheats.KeyLabel(Cheats.MenuKey) + ", so they clash. Remove one of them (Install My Mods tab).");
1329 if (running) warn.Add("The game is running. Close it to install or update anything.");
1330 setupWarn.Text = string.Join("\n\n", warn);
1331 setupWarn.IsVisible = warn.Count > 0;
1332 }
1333
1334 private readonly StackPanel modRows = new() { Spacing = 8 };
1335 private readonly TextBlock modsNote = T("", 13, Ui.B(Ui.Dim), false, true);
1336 private readonly Dictionary<int, string> pendingZips = new();
1337 private readonly Dictionary<string, (long size, DateTime time, KnownMod mod)> zipCache = new();
1338 private readonly HashSet<string> announced = new();
1339 private DateTime nextModScan;
1340 private string modsKey = "";
1341 private Dictionary<string, TsPackage> tsMods;
1342 private List<ModManager> managers;
1343 private string mgrHandler;
1344 private DateTime tsFetched = DateTime.MinValue, mgrScanned = DateTime.MinValue;
1345 private bool tsBusy;
1346 private readonly StackPanel mgrRows = new() { Spacing = 4 };
1347 private readonly TextBlock tsStatus = T("", 12, Ui.B(Ui.Dim), false, true);
1348
1349 private static void OpenTs(string url) { if (Thunderstore.SafeUrl(url)) Game.Open(url); }
1350
1351 private async Task RefreshThunderstore()
1352 {
1353 if (tsBusy || (DateTime.UtcNow - tsFetched).TotalMinutes < 10) return;
1354 tsBusy = true;
1355 Dictionary<string, TsPackage> d = null;
1356 try { d = await Thunderstore.Fetch(); } catch (Exception) { }
1357 tsBusy = false;
1358 if (d != null && d.Count > 0)
1359 {
1360 tsFetched = DateTime.UtcNow;
1361 tsMods = d;
1362 tsStatus.Text = "Thunderstore: " + d.Count + " of my mods, updated " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + ".";
1363 }
1364 else
1365 {
1366 tsFetched = DateTime.UtcNow.AddMinutes(-8);
1367 tsStatus.Text = tsMods != null ? "Couldn't reach Thunderstore, showing the saved list." : "Couldn't reach Thunderstore.";
1368 }
1369 RefreshMods(true);
1370 ShowTsAbout();
1371 }
1372
1373 private void ScanManagers(bool force)
1374 {
1375 if (!force && (DateTime.UtcNow - mgrScanned).TotalSeconds < 15) return;
1376 mgrScanned = DateTime.UtcNow;
1377 try { managers = ModManagers.Scan(); } catch (Exception) { managers = new(); }
1378 mgrHandler = ModManagers.Handler();
1379 mgrRows.Children.Clear();
1380 if (managers.Count == 0)
1381 mgrRows.Children.Add(T("None found. r2modman and Gale can install all my mods from Thunderstore, with BepInEx set up for you.", 13, Ui.B(Ui.Soft), false, true));
1382 else
1383 {
1384 foreach (ModManager m in managers)
1385 mgrRows.Children.Add(T("✓ " + m.Name + " · " + m.Profiles.Count + (m.Profiles.Count == 1 ? " profile" : " profiles") + ", " + ModManagers.Count(m) + " of my mods", 13, Ui.B(Ui.Good)));
1386 mgrRows.Children.Add(T((mgrHandler != null ? "\"Get with\" buttons send the mod to " + mgrHandler + ". " : "") + "Mods in a mod manager only load when you start the game from it.", 12, Ui.B(Ui.Dim), false, true));
1387 }
1388 }
1389
1390 private Control ModsPage()
1391 {
1392 StackPanel sp = new();
1393 Border hs = Section("INSTALL MY MODS", out StackPanel hb);
1394 hb.Children.Add(T("casualexpie's mods are on Nexus Mods and Thunderstore. Click Get on Nexus, download the file there (Manual download), and the trainer picks the zip up from your Downloads folder. Then click Install. You can also pick a zip yourself.", 13, Ui.B(Ui.Dim), false, true));
1395 WrapPanel w = new();
1396 Button pick = Btn("Install From Zip...", () => _ = PickZip());
1397 pick.Margin = new Thickness(0, 0, 6, 0);
1398 w.Children.Add(pick);
1399 w.Children.Add(Btn("Open Downloads", () => { string d = Mods.Downloads; if (d != null) Game.Open(d); }));
1400 hb.Children.Add(w);
1401 hb.Children.Add(modsNote);
1402 sp.Children.Add(hs);
1403 Border mg = Section("MOD MANAGERS", out StackPanel mgb);
1404 mgb.Children.Add(mgrRows);
1405 Button tsb = Btn("My Thunderstore page", () => OpenTs(Thunderstore.TeamUrl));
1406 tsb.Margin = new Thickness(0, 6, 0, 0);
1407 tsb.HorizontalAlignment = HorizontalAlignment.Left;
1408 mgb.Children.Add(tsb);
1409 mgb.Children.Add(tsStatus);
1410 sp.Children.Add(mg);
1411 tsMods = Thunderstore.Load(out DateTime tsAt);
1412 if (tsMods != null) tsStatus.Text = "Thunderstore: saved list from " + tsAt.ToLocalTime().ToString("d MMM, HH:mm", CultureInfo.InvariantCulture) + ".";
1413 Border ms = Section("MODS", out StackPanel mb);
1414 mb.Children.Add(modRows);
1415 sp.Children.Add(ms);
1416 return Scroll(sp);
1417 }
1418
1419 private async Task PickZip()
1420 {
1421 IReadOnlyList<IStorageFile> r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
1422 {
1423 Title = "Pick a mod zip from Nexus",
1424 AllowMultiple = false,
1425 FileTypeFilter = new[] { new FilePickerFileType("Zip files") { Patterns = new[] { "*.zip" } } },
1426 });
1427 string p = r.Count > 0 ? r[0].TryGetLocalPath() : null;
1428 if (p != null) InstallZip(p);
1429 }
1430
1431 private void InstallZip(string zip)
1432 {
1433 string e = Mods.Install(zip, game, out KnownMod m);
1434 if (e == null) { Message(m.Name + " is installed.", false); if (m != null) pendingZips.Remove(m.Id); }
1435 else Message("Couldn't install it: " + e, true);
1436 RefreshMods(true);
1437 }
1438
1439 private void ScanDownloads()
1440 {
1441 string d = Mods.Downloads;
1442 if (d == null || game == null) return;
1443 List<FileInfo> zips;
1444 try { zips = new DirectoryInfo(d).EnumerateFiles("*.zip").OrderByDescending(f => f.LastWriteTimeUtc).Take(150).ToList(); }
1445 catch (Exception) { return; }
1446 Dictionary<int, (string path, DateTime time)> best = new();
1447 foreach (FileInfo f in zips)
1448 {
1449 if (!zipCache.TryGetValue(f.FullName, out var c) || c.size != f.Length || c.time != f.LastWriteTimeUtc)
1450 {
1451 c = (f.Length, f.LastWriteTimeUtc, Mods.Identify(f.FullName));
1452 zipCache[f.FullName] = c;
1453 }
1454 if (c.mod == null) continue;
1455 if (!best.TryGetValue(c.mod.Id, out var b) || f.LastWriteTimeUtc > b.time) best[c.mod.Id] = (f.FullName, f.LastWriteTimeUtc);
1456 }
1457 pendingZips.Clear();
1458 foreach (var kv in best)
1459 {
1460 KnownMod m = Mods.All.First(x => x.Id == kv.Key);
1461 if (Mods.SameAsInstalled(game, kv.Value.path, m)) continue;
1462 pendingZips[kv.Key] = kv.Value.path;
1463 if (announced.Add(kv.Value.path + kv.Value.time.Ticks)) Message("You downloaded " + m.Name + ". Install it from the Install My Mods tab.", false);
1464 }
1465 }
1466
1467 private void RefreshMods(bool force)
1468 {
1469 if (DateTime.UtcNow >= nextModScan || force)
1470 {
1471 nextModScan = DateTime.UtcNow.AddSeconds(3);
1472 ScanDownloads();
1473 }
1474 bool running = Game.GameRunning();
1475 bool bep = Game.BepInstalled(game);
1476 modsNote.Text = game == null ? "Set the game folder in Game Setup first." : !bep ? "Install BepInEx first (Game Setup tab)." : running ? "Close the game to install or remove mods." : "";
1477 modsNote.IsVisible = modsNote.Text.Length > 0;
1478 ScanManagers(false);
1479 string mgrKey = managers == null ? "" : string.Join(";", managers.SelectMany(x => x.Profiles).Select(p => p.Manager + p.Name + ":" + string.Join(",", p.Dlls.OrderBy(d => d)) + string.Join(",", p.Versions.Select(v => v.Key + v.Value))));
1480 string key = (game ?? "") + running + bep + string.Join(",", pendingZips.Select(p => p.Key + p.Value)) + string.Join(",", Mods.All.Select(m => Mods.Installed(game, m) ? "1" : "0")) + mgrKey + mgrHandler;
1481 if (key == modsKey && !force) return;
1482 modsKey = key;
1483 modRows.Children.Clear();
1484 IEnumerable<int> recIds = Mods.Recommended.Select(r => r.id);
1485 if (Mods.SteamDeck) recIds = new[] { 1190 }.Concat(recIds.Where(i => i != 1190));
1486 List<KnownMod> rec = recIds.Select(i => Mods.All.FirstOrDefault(x => x.Id == i)).Where(x => x != null && !pendingZips.ContainsKey(x.Id) && !Mods.Installed(game, x) && ModManagers.Find(managers, x) == null).ToList();
1487 foreach (KnownMod m in rec.Concat(Mods.All.Where(x => !rec.Contains(x))))
1488 {
1489 bool inst = Mods.Installed(game, m);
1490 pendingZips.TryGetValue(m.Id, out string zip);
1491 string why = rec.Contains(m) ? Mods.Why(m.Id) : null;
1492 TsPackage tp = null;
1493 if (tsMods != null && m.Ts != null) tsMods.TryGetValue(m.Ts, out tp);
1494 MgrProfile mp = ModManagers.Find(managers, m);
1495 string mv = null;
1496 if (mp != null && m.Ts != null) mp.Versions.TryGetValue(m.Ts, out mv);
1497 bool mgrOld = mp != null && tp != null && mv != null && Thunderstore.Compare(mv, tp.Version) < 0;
1498 bool any = inst || mp != null;
1499 string status = zip != null ? (inst ? "Update ready: " : "Downloaded: ") + Path.GetFileName(zip) : inst ? "Installed" : why != null ? (why.StartsWith("Recommended", StringComparison.Ordinal) ? "\u2605 " + why : "\u2605 Recommended: " + why) : "Not installed";
1500 IBrush sc = Ui.B(zip != null ? Ui.Orange : inst ? Ui.Good : why != null ? Ui.Warn : Ui.Dim);
1501 if (zip == null && mp != null)
1502 {
1503 string where = mp.Manager + " (" + mp.Name + ")";
1504 if (mgrOld) { status = "Update on Thunderstore: v" + mv + " \u2192 v" + tp.Version + " in " + where; sc = Ui.B(Ui.Orange); }
1505 else if (inst) status += ", and in " + where;
1506 else { status = "Installed in " + where + (mv != null ? ", v" + mv : ""); sc = Ui.B(Ui.Good); }
1507 }
1508 else if (zip == null && !any && why == null && tp != null) status = "Not installed \u00b7 v" + tp.Version + " on Thunderstore";
1509 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
1510 StackPanel info = new() { VerticalAlignment = VerticalAlignment.Center };
1511 info.Children.Add(T(m.Name, 14, Ui.B(Ui.Text), true));
1512 info.Children.Add(T(status, 12, sc, false, true));
1513 g.Children.Add(info);
1514 StackPanel btns = new() { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center };
1515 if (zip != null)
1516 {
1517 Button ib = Btn(inst ? "Update" : "Install", () => InstallZip(zip), true);
1518 ib.IsEnabled = bep && !running;
1519 btns.Children.Add(ib);
1520 }
1521 string link = tp != null ? Thunderstore.InstallLink(tp) : null, page = tp?.Url;
1522 if (mgrOld && zip == null) btns.Children.Add(Btn("Update", () => OpenTs(mgrHandler != null ? link : page), true));
1523 btns.Children.Add(Btn(any || zip != null ? "Nexus" : "Get on Nexus", () => Game.Open(m.Page + "?tab=files")));
1524 if (tp != null)
1525 {
1526 if (!any && zip == null && mgrHandler != null) btns.Children.Add(Btn("Get with " + mgrHandler, () => OpenTs(link)));
1527 else btns.Children.Add(Btn("Thunderstore", () => OpenTs(page)));
1528 }
1529 if (inst)
1530 {
1531 Button rb = Btn("Remove", () => { string e = Mods.Remove(game, m); Message(e == null ? m.Name + " was removed." : "Couldn't remove it: " + e, e != null); RefreshMods(true); });
1532 rb.IsEnabled = !running;
1533 btns.Children.Add(rb);
1534 }
1535 Grid.SetColumn(btns, 1);
1536 g.Children.Add(btns);
1537 modRows.Children.Add(new Border { Background = Ui.B(Ui.Sunk), CornerRadius = new CornerRadius(6), Padding = new Thickness(12, 8), Child = g });
1538 }
1539 }
1540
1541 private readonly Dictionary<string, Action<bool>> optSetters = new();
1542 private readonly TextBlock updStatus = T("Not checked yet.", 13, Ui.B(Ui.Text), false, true);
1543 private Button updNow;
1544 private readonly TextBlock vtStatus = T("Not checked yet.", 13, Ui.B(Ui.Text), false, true);
1545 private readonly TextBlock usageStatus = T("Not counted yet.", 13, Ui.B(Ui.Text), false, true);
1546 private ToggleButton usageSwitch;
1547 private bool usageBusy, vtBusy, updateFlagOk;
1548
1549 private readonly TextBlock vtDetail = T("Engine breakdown: not checked yet.", 13, Ui.B(Ui.Dim), false, true);
1550 private readonly TextBlock vtNewest = T("Checking for updates...", 13, Ui.B(Ui.Text), false, true);
1551
1552 private const string VtLogo = "M45.292,44.5 L0,89 H100 V0 H0 Z M90,80 H22 L57.987,44.8 L22,9 H90 Z";
1553
1554 private Control VirusTotalPage()
1555 {
1556 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
1557 StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) };
1558 Border vs = Section("THIS VERSION", out StackPanel vb);
1559 vb.Children.Add(vtStatus);
1560 vb.Children.Add(vtDetail);
1561 WrapPanel vw = new();
1562 Button vo = Btn("Open Report", () => { string l = VirusTotal.Self?.Link; if (l != null) Game.Open(l); else Message("There's no VirusTotal report for this version yet.", false); }, true);
1563 vo.Margin = new Thickness(0, 4, 6, 0);
1564 vw.Children.Add(vo);
1565 Button va = Btn("Check Again", () => _ = CheckVirusTotal(true));
1566 va.Margin = new Thickness(0, 4, 0, 0);
1567 vw.Children.Add(va);
1568 vb.Children.Add(vw);
1569 vb.Children.Add(T("Open Report shows the full VirusTotal page: every engine and what it said. Check Again asks for the newest result.", 12, Ui.B(Ui.Dim), false, true));
1570 c0.Children.Add(vs);
1571 Border ns = Section("NEWEST VERSION", out StackPanel nb);
1572 nb.Children.Add(vtNewest);
1573 nb.Children.Add(T("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.", 12, Ui.B(Ui.Dim), false, true));
1574 c0.Children.Add(ns);
1575 g.Children.Add(c0);
1576
1577 StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) };
1578 Border ws = Section("WHAT IT IS", out StackPanel wb);
1579 wb.Children.Add(T("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 result here is for the official download of the version you're running.", 13, Ui.B(Ui.Dim), false, true));
1580 c1.Children.Add(ws);
1581 Border ms = Section("WHAT THE NUMBERS MEAN", out StackPanel mb);
1582 mb.Children.Add(T("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.", 13, Ui.B(Ui.Dim), false, true));
1583 c1.Children.Add(ms);
1584 Grid.SetColumn(c1, 1);
1585 g.Children.Add(c1);
1586
1587 StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) };
1588 Border ys = Section("WHY TRAINERS GET FLAGGED", out StackPanel yb);
1589 yb.Children.Add(T("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.", 13, Ui.B(Ui.Dim), false, true));
1590 c2.Children.Add(ys);
1591 Border os = Section("ON NEXUS", out StackPanel ob);
1592 ob.Children.Add(T("The official fingerprints for every download are on the Nexus page, under \"Official SHA-256 fingerprints\".", 13, Ui.B(Ui.Dim), false, true));
1593 ob.Children.Add(Btn("Nexus Page", () => Game.Open(Nexus.PageUrl)));
1594 c2.Children.Add(os);
1595 Grid.SetColumn(c2, 2);
1596 g.Children.Add(c2);
1597 return Scroll(g);
1598 }
1599
1600 private async Task CheckVirusTotal(bool manual)
1601 {
1602 if (vtBusy) return;
1603 vtBusy = true;
1604 vtStatus.Text = "Checking VirusTotal...";
1605 try
1606 {
1607 VtResult v = await VirusTotal.ForThisVersion();
1608 VirusTotal.Self = v;
1609 vtStatus.Text = "v" + Program.Version + ". " + v.Line;
1610 vtDetail.Text = v.Detail;
1611 if (v.Status == "queued") DispatcherTimer.RunOnce(() => _ = CheckVirusTotal(false), TimeSpan.FromSeconds(90));
1612 if (manual) Message(v.Line, v.Status == "done" && v.Flagged > 0);
1613 }
1614 catch (Exception)
1615 {
1616 vtStatus.Text = "VirusTotal: couldn't reach the update server. Try Check Again later.";
1617 if (manual) Message("Couldn't reach the update server.", true);
1618 }
1619 vtBusy = false;
1620 }
1621
1622 private async Task UsageNotice()
1623 {
1624 if (Settings.Get("notice.usage", "0") == "1") return;
1625 bool yes = false;
1626 Window w = new()
1627 {
1628 Title = Program.Name + " - User count",
1629 Width = 460,
1630 SizeToContent = SizeToContent.Height,
1631 CanResize = false,
1632 WindowStartupLocation = WindowStartupLocation.CenterOwner,
1633 Background = Ui.B(Ui.Back),
1634 };
1635 StackPanel sp = new() { Margin = new Thickness(20), Spacing = 12 };
1636 sp.Children.Add(new TextBlock { Text = "Can the trainer count you as a user?", FontSize = 18, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Orange), TextWrapping = TextWrapping.Wrap });
1637 sp.Children.Add(new TextBlock { Text = "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.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Text) });
1638 sp.Children.Add(new TextBlock { Text = "It only sends a random ID made on this computer, the trainer version and that you're on " + Program.Platform + ". No name, no account, nothing about your computer or game, and the server doesn't keep your IP address.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Text) });
1639 sp.Children.Add(new TextBlock { Text = "You can change this any time with Count Me as a User in the Settings tab. Turning it off also deletes what was sent.", TextWrapping = TextWrapping.Wrap, Foreground = Ui.B(Ui.Dim) });
1640 StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right };
1641 Button no = new() { Content = "No thanks", Padding = new Thickness(16, 6) };
1642 no.Click += (_, _) => w.Close();
1643 Button ok = new() { Content = "Yes, count me", Padding = new Thickness(20, 6), Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent) };
1644 ok.Click += (_, _) => { yes = true; w.Close(); };
1645 row.Children.Add(no);
1646 row.Children.Add(ok);
1647 sp.Children.Add(row);
1648 w.Content = sp;
1649 await w.ShowDialog(this);
1650 Settings.Set("notice.usage", "1");
1651 Settings.Set("usage", yes ? "1" : "0");
1652 if (usageSwitch != null) usageSwitch.IsChecked = yes;
1653 await UsageTick();
1654 }
1655
1656 private void StartUsage()
1657 {
1658 _ = CheckVirusTotal(false);
1659 if (Settings.Get("notice.usage", "0") == "1") _ = UsageTick();
1660 DispatcherTimer t = new() { Interval = TimeSpan.FromHours(1) };
1661 t.Tick += (_, _) => _ = UsageTick();
1662 t.Start();
1663 }
1664
1665 private readonly TextBlock usageBoard = T("Loading...", 13, Ui.B(Ui.Text), false, true);
1666 private bool boardBusy;
1667
1668 private async Task RefreshBoard()
1669 {
1670 if (boardBusy) return;
1671 boardBusy = true;
1672 string s = null;
1673 try { s = await Usage.Stats(); } catch (Exception) { }
1674 boardBusy = false;
1675 if (s != null) usageBoard.Text = s;
1676 else if (usageBoard.Text == "Loading...") usageBoard.Text = "Couldn't reach the update server. Tries again in an hour.";
1677 }
1678
1679 private async Task UsageTick()
1680 {
1681 if (usageBusy || Settings.Get("notice.usage", "0") != "1") { await RefreshBoard(); return; }
1682 if (!Settings.On("usage", true))
1683 {
1684 if (!usageStatus.Text.StartsWith("You're not counted", StringComparison.Ordinal)) usageStatus.Text = "You're not counted. Turn on Count Me as a User to be counted.";
1685 await RefreshBoard();
1686 return;
1687 }
1688 usageBusy = true;
1689 string id = Settings.Get("usage.id", "");
1690 if (!Usage.ValidId(id)) { id = Usage.NewId(); Settings.Set("usage.id", id); }
1691 string day = Usage.Day.ToString(CultureInfo.InvariantCulture);
1692 try { if (Settings.Get("usage.day", "") != day && await Usage.Ping(id)) Settings.Set("usage.day", day); } catch (Exception) { }
1693 string count = null;
1694 try { count = await Usage.Count(); } catch (Exception) { }
1695 usageBusy = false;
1696 await RefreshBoard();
1697 if (!Settings.On("usage", true)) return;
1698 usageStatus.Text = count != null ? count + " You're counted." : "Couldn't reach the server. You're counted once it's back.";
1699 }
1700
1701 private void UsageToggled(bool on)
1702 {
1703 Settings.Set("usage", on ? "1" : "0");
1704 Settings.Set("notice.usage", "1");
1705 if (on) { Message("Thanks! You're counted as a user.", false); _ = UsageTick(); return; }
1706 Message("You're no longer counted.", false);
1707 string id = Settings.Get("usage.id", "");
1708 Settings.Set("usage.id", null);
1709 Settings.Set("usage.day", null);
1710 usageStatus.Text = "You're not counted. Asking the server to delete what this computer sent...";
1711 _ = Task.Run(async () =>
1712 {
1713 bool ok = false;
1714 try { ok = await Usage.Forget(id); } catch (Exception) { }
1715 Dispatcher.UIThread.Post(() => usageStatus.Text = ok ? "You're not counted. Anything this computer sent has been deleted." : "You're not counted. The server couldn't be reached to delete the old data; it's removed after 90 days anyway.");
1716 });
1717 }
1718
1719 private ToggleButton Switch(string name, string hint, bool on, Action<bool> changed)
1720 {
1721 ToggleSwitch tb = new() { OnContent = name, OffContent = name, IsChecked = on, HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 34 };
1722 if (hint != null) ToolTip.SetTip(tb, hint);
1723 tb.Click += (_, _) => changed(tb.IsChecked == true);
1724 return tb;
1725 }
1726
1727 private void PluginOpt(StackPanel host, string key, string name, string hint)
1728 {
1729 ToggleButton tb = null;
1730 tb = Switch(name, hint, true, on =>
1731 {
1732 if (!Linked()) { tb.IsChecked = !on; return; }
1733 link.Send("OPT " + key + (on ? " 1" : " 0"));
1734 });
1735 optSetters[key] = v => tb.IsChecked = v;
1736 host.Children.Add(tb);
1737 }
1738
1739 private Control TrainerPage()
1740 {
1741 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") };
1742 StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) };
1743 Border ts = Section("SETTINGS", out StackPanel tb);
1744 tb.Children.Add(Switch("Bark When a Cheat Turns On", "Plays your runner's own bark when you switch a cheat on, here or with your in-game keys (Dune's sound for Dune). The sounds come from your game the first time it attaches.", Settings.On("bark", true), on => Settings.Set("bark", on ? "1" : "0")));
1745 Button testBark = Btn("Test Bark", () => { string why = Bark.Play(true); Message(why ?? "Woof.", why != null); });
1746 testBark.Margin = new Thickness(0, 4, 0, 6);
1747 testBark.HorizontalAlignment = HorizontalAlignment.Left;
1748 tb.Children.Add(testBark);
1749 tb.Children.Add(Switch("Start Game With Trainer", "Opens the game through Steam when you open the trainer, if it isn't running yet.", Settings.On("launchwith", false), on => Settings.Set("launchwith", on ? "1" : "0")));
1750 tb.Children.Add(Switch("Close With the Game", "Closes the trainer when you quit the game, if it was attached to it.", Settings.On("closewithgame", true), on => Settings.Set("closewithgame", on ? "1" : "0")));
1751 tb.Children.Add(Btn("Start Game", () => StartGame()));
1752 tb.Children.Add(Btn("Switch Everything Off", () => { if (Linked()) link.Send("ACT alloff"); }));
1753 tb.Children.Add(Btn("Reset All Keys", () =>
1754 {
1755 if (!Linked()) return;
1756 foreach (CTab t in tabs) foreach (CSection s in t.Sections) foreach (COpt o in s.Rows)
1757 if (o.Kind == CKind.Toggle || o.Kind == CKind.Action) link.Send("BIND " + o.Id + " " + (o.Key.Length > 0 ? o.Key : "none"));
1758 link.Send("BIND menu " + Cheats.MenuKey);
1759 link.Send("BIND overlay " + Cheats.OverlayKey);
1760 Message("Keys reset.", false);
1761 }));
1762 c0.Children.Add(ts);
1763 Border gs = Section("IN GAME", out StackPanel gb);
1764 Grid ov = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
1765 StackPanel ovs = new();
1766 PluginOpt(ovs, "overlay", "In-Game Overlay", "Shows what's on in the top-left corner of the game.");
1767 ovs.Margin = new Thickness(0, 0, 6, 0);
1768 ov.Children.Add(ovs);
1769 Button ok = KeyButton("overlay");
1770 Grid.SetColumn(ok, 1);
1771 ov.Children.Add(ok);
1772 gb.Children.Add(ov);
1773 Grid mk = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
1774 TextBlock mt = T("In-Game Menu Key", 13, Ui.B(Ui.Text));
1775 mt.VerticalAlignment = VerticalAlignment.Center;
1776 mk.Children.Add(mt);
1777 Button mkb = KeyButton("menu");
1778 Grid.SetColumn(mkb, 1);
1779 mk.Children.Add(mkb);
1780 gb.Children.Add(mk);
1781 PluginOpt(gb, "pause", "Pause the Game While the Menu Is Open", "Stops time while you pick cheats in the in-game menu.");
1782 PluginOpt(gb, "remember", "Remember My Cheats", "The cheats you had on switch back on the next time you start the game.");
1783 gb.Children.Add(T("The in-game menu has every cheat, so you can play without this app open (Steam Deck Gaming Mode too). Press both sticks (L3 + R3) on a controller to open it.", 12, Ui.B(Ui.Dim), false, true));
1784 c0.Children.Add(gs);
1785 g.Children.Add(c0);
1786
1787 StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) };
1788 Border us = Section("UPDATES", out StackPanel ub);
1789 ub.Children.Add(updStatus);
1790 WrapPanel uw = new();
1791 Button chk = Btn("Check Now", () => _ = CheckUpdate(true));
1792 chk.Margin = new Thickness(0, 0, 6, 0);
1793 uw.Children.Add(chk);
1794 updNow = Btn("Update Now", () => _ = DoUpdate(), true);
1795 updNow.IsEnabled = false;
1796 uw.Children.Add(updNow);
1797 ub.Children.Add(uw);
1798 ub.Children.Add(Switch("Check for Updates", "Looks for a new version each time you open the trainer.", Settings.On("autoupdate", true), on => Settings.Set("autoupdate", on ? "1" : "0")));
1799 ub.Children.Add(Switch("Update Without Asking", "Installs new versions by itself when the game isn't running. Otherwise it asks first.", Settings.On("silentupdate", false), on => Settings.Set("silentupdate", on ? "1" : "0")));
1800 ub.Children.Add(Switch("Show the Splash Screen", "Shows the splash art for a moment when the trainer opens. Click it to skip.", Settings.On("splash", true), on => Settings.Set("splash", on ? "1" : "0")));
1801 ub.Children.Add(T("Updates download from casualexpie's update server and are checked against the fingerprints on the official Nexus page before they're installed.", 12, Ui.B(Ui.Dim), false, true));
1802 c1.Children.Add(us);
1803 Border cs = Section("USER COUNT", out StackPanel cbody);
1804 cbody.Children.Add(usageStatus);
1805 usageSwitch = Switch("Count Me as a User", null, Settings.On("usage", true), on => UsageToggled(on));
1806 cbody.Children.Add(usageSwitch);
1807 cbody.Children.Add(T("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 computer, the trainer version and that you're on " + Program.Platform + ". No name, no account, nothing about your computer or game, and the server doesn't keep your IP address. Turn it off to stop, and the server deletes what this computer sent.", 12, Ui.B(Ui.Dim), false, true));
1808 c1.Children.Add(cs);
1809 Border ps = Section("THIS PC", out StackPanel pb);
1810 pb.Children.Add(installStatus);
1811 CheckBox sc = new() { Content = "Also put a shortcut on my desktop", IsChecked = true };
1812 pb.Children.Add(sc);
1813 WrapPanel pw = new();
1814 installBtn = Btn("Install", () => DoInstall(sc.IsChecked == true), true);
1815 installBtn.Margin = new Thickness(0, 0, 6, 0);
1816 pw.Children.Add(installBtn);
1817 pw.Children.Add(Btn("Uninstall", () => _ = DoUninstall()));
1818 pb.Children.Add(pw);
1819 pb.Children.Add(T("Install copies the trainer into your home folder (~/.local/share/ultraparadise-cutrainer) and adds it to your app menu and an 'ultraparadise' command. No password needed.", 12, Ui.B(Ui.Dim), false, true));
1820 c1.Children.Add(ps);
1821 RefreshInstall();
1822 Grid.SetColumn(c1, 1);
1823 g.Children.Add(c1);
1824
1825 StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) };
1826 Border abs = Section("ABOUT", out StackPanel ab);
1827 ab.Children.Add(T(Program.Name + " v" + Program.Version + " for " + Program.Platform + "\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 Avalonia, HarmonyX and BepInEx (MIT / LGPL licences).", 13, Ui.B(Ui.Dim), false, true));
1828 ab.Children.Add(Btn("Nexus Page", () => Game.Open(Nexus.PageUrl)));
1829 ab.Children.Add(T("To uninstall: curl -fsSL https://updates.smellypawz.com/linux | bash -s -- --uninstall", 12, Ui.B(Ui.Dim), false, true));
1830 c2.Children.Add(abs);
1831 Grid.SetColumn(c2, 2);
1832 g.Children.Add(c2);
1833 return Scroll(g);
1834 }
1835
1836 private readonly TextBlock installStatus = T("", 13, Ui.B(Ui.Text), false, true);
1837 private Button installBtn;
1838
1839 private void RefreshInstall()
1840 {
1841 installStatus.Text = Setup.Status();
1842 installBtn.Content = Setup.RunningInstalled ? "Repair Install" : Setup.Installed ? "Install This Copy" : "Install";
1843 installBtn.IsEnabled = !OperatingSystem.IsWindows() && !Mac.On;
1844 }
1845
1846 private void DoInstall(bool shortcut)
1847 {
1848 string e = Setup.Install(shortcut);
1849 if (e != null) { Message("Couldn't install it: " + e, true); RefreshInstall(); return; }
1850 if (Setup.RunningInstalled) { Message("Install repaired.", false); RefreshInstall(); return; }
1851 Message("Installed. Opening the installed copy...", false);
1852 link.RemoveLinkFile();
1853 Setup.OpenInstalled();
1854 Close();
1855 }
1856
1857 private async Task DoUninstall()
1858 {
1859 UninstallDialog d = new();
1860 await d.ShowDialog(this);
1861 if (!d.Confirmed) return;
1862 string e = Setup.Uninstall(game, d.Plugin, d.Settings_);
1863 if (e != null) { Message("Couldn't uninstall: " + e, true); RefreshInstall(); return; }
1864 link.RemoveLinkFile();
1865 Message("Uninstalled.", false);
1866 if (Setup.RunningInstalled || !File.Exists(Environment.ProcessPath ?? "")) { Close(); return; }
1867 Message("Uninstalled. This copy is still in " + Path.GetDirectoryName(Environment.ProcessPath) + "; delete that folder to remove it too.", false);
1868 RefreshInstall();
1869 }
1870
1871 private async Task CheckUpdate(bool manual)
1872 {
1873 updStatus.Text = "Checking...";
1874 try
1875 {
1876 UpdateInfo u = await Updater.Check();
1877 Updater.Ready = u;
1878 updStatus.Text = u == null ? "You have the latest version (v" + Program.Version + ")." : "Version " + u.Version + " is out." + (u.Notes.Length > 0 ? "\n" + u.Notes : "") + (Updater.Manual ? "" : "\n" + u.VtLine);
1879 updNow.IsEnabled = u != null;
1880 vtNewest.Text = u == null ? "You have the newest version, so the result above is the newest one." : "v" + u.Version + " is out. " + u.VtLine;
1881 updateFlagOk = false;
1882 if (u != null) Message("Version " + u.Version + " is out. Update it from the Settings tab.", false);
1883 }
1884 catch (Exception)
1885 {
1886 updStatus.Text = "Couldn't reach the update server.";
1887 if (manual) Message("Couldn't reach the update server.", true);
1888 }
1889 }
1890
1891 private async Task DoUpdate()
1892 {
1893 UpdateInfo u = Updater.Ready;
1894 if (u == null) return;
1895 if (Updater.Manual) { Game.Open(Updater.ManualPage); updStatus.Text = "Download v" + u.Version + " from the Nexus page that just opened, and replace the app with it."; return; }
1896 if (u.VtFlagged && !updateFlagOk)
1897 {
1898 updateFlagOk = true;
1899 updStatus.Text = u.VtLine + "\nLook at the report first (" + u.Vt.Link + "). Click Update Now again to install it anyway.";
1900 Message("VirusTotal flagged v" + u.Version + ". Click Update Now again to install it anyway.", true);
1901 return;
1902 }
1903 updNow.IsEnabled = false;
1904 string e = await Updater.Install(u, pc => Dispatcher.UIThread.Post(() => updStatus.Text = "Downloading v" + u.Version + "... " + pc + "%"));
1905 if (e == null) { Close(); return; }
1906 updStatus.Text = "Couldn't update: " + e;
1907 updNow.IsEnabled = true;
1908 }
1909 }
1910}