using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Platform.Storage; using Avalonia.Threading; using UltraParadise.Shared; using Path = System.IO.Path; using SPath = Avalonia.Controls.Shapes.Path; namespace UltraParadise.Linux { internal sealed partial class MainWindow : Window { private readonly LinkServer link = new(); private readonly List tabs = Cheats.Build(); private readonly Dictionary byId = new(); private readonly Dictionary> stateSetters = new(); private readonly Dictionary keyButtons = new(); private readonly Dictionary binds = new(); private readonly List<(TextBlock tb, COpt o)> infoRows = new(); private Dictionary info; private readonly ContentControl view = new(); private readonly StackPanel sideList = new() { Spacing = 1, Margin = new Thickness(10, 4, 10, 12) }; private readonly Panel bgLayer = new() { ClipToBounds = true, IsHitTestVisible = false }; private readonly LayoutTransformControl scaleHost = new(); private Image bannerArt; private Border bannerFade; private readonly List cards = new(); private readonly List themeRefresh = new(); private readonly Dictionary sideParts = new(); private string lastGroup; private readonly Dictionary pages = new(); private readonly Dictionary sideButtons = new(); private string page; private readonly Ellipse dot = new() { Width = 10, Height = 10 }; private readonly TextBlock statusText = new() { FontSize = 14, VerticalAlignment = VerticalAlignment.Center }; private readonly TextBlock messageText = new() { FontSize = 13, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis }; private string gameDir; private string game { get => gameDir; set { gameDir = value; Game.Current = value; } } private string bindingId; private DateTime gameSeenSince = DateTime.MinValue; private string pluginVersion; private string blocked; private bool autoPluginTried; public MainWindow() { Title = Program.Name; Width = 1200; Height = 720; MinWidth = 980; MinHeight = 620; Background = Ui.B(Ui.Back); WindowStartupLocation = WindowStartupLocation.CenterScreen; Bitmap icon = Program.Image("icon.png"); if (icon != null) Icon = new WindowIcon(icon); foreach (CTab t in tabs) foreach (CSection s in t.Sections) foreach (COpt o in s.Rows) { byId[o.Id] = o; if (o.Kind == CKind.Toggle || o.Kind == CKind.Action) binds[o.Id] = Settings.Get("bind." + o.Id, o.Key); } binds["menu"] = Settings.Get("bind.menu", Cheats.MenuKey); binds["overlay"] = Settings.Get("bind.overlay", Cheats.OverlayKey); Grid root = new() { RowDefinitions = new RowDefinitions("86,*,60"), ColumnDefinitions = new ColumnDefinitions("190,*") }; Panel banner = new(); Bitmap splashArt = Program.Image("splash.jpg"); banner.Background = Ui.B(Ui.Side); if (splashArt != null) { bannerArt = new Image { Source = splashArt, Stretch = Stretch.UniformToFill, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, IsVisible = Ui.BannerArt }; banner.Children.Add(bannerArt); } bannerFade = new Border { BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(0, 0, 0, 1), Background = BannerFade() }; banner.Children.Add(bannerFade); banner.ClipToBounds = true; StackPanel bp = new() { Orientation = Orientation.Horizontal, Margin = new Thickness(22, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, Spacing = 14 }; if (icon != null) bp.Children.Add(new Image { Source = icon, Width = 46, Height = 46 }); StackPanel titles = new() { VerticalAlignment = VerticalAlignment.Center }; titles.Children.Add(new TextBlock { Text = "ULTRA PARADISE", FontSize = 24, FontWeight = FontWeight.Bold, Foreground = Ui.B(Ui.Bright) }); 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) }); bp.Children.Add(titles); banner.Children.Add(bp); Grid.SetColumnSpan(banner, 2); root.Children.Add(banner); 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 } }; Grid.SetRow(side, 1); root.Children.Add(side); Grid.SetRow(bgLayer, 1); Grid.SetColumn(bgLayer, 1); root.Children.Add(bgLayer); view.Margin = new Thickness(0); Grid.SetRow(view, 1); Grid.SetColumn(view, 1); root.Children.Add(view); Border footer = new() { Background = Ui.B(Ui.Side), BorderBrush = Ui.B(Ui.Line), BorderThickness = new Thickness(0, 1, 0, 0) }; Grid fg = new() { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,*,Auto"), Margin = new Thickness(24, 0, 16, 0) }; dot.VerticalAlignment = VerticalAlignment.Center; dot.Margin = new Thickness(0, 0, 10, 0); fg.Children.Add(dot); Grid.SetColumn(statusText, 1); fg.Children.Add(statusText); messageText.Margin = new Thickness(24, 0, 12, 0); messageText.Foreground = Ui.B(Ui.Dim); Grid.SetColumn(messageText, 2); fg.Children.Add(messageText); Button start = Btn("Start Game", () => StartGame(), true); start.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(start, 3); fg.Children.Add(start); footer.Child = fg; Grid.SetRow(footer, 2); Grid.SetColumnSpan(footer, 2); root.Children.Add(footer); scaleHost.Child = root; scaleHost.LayoutTransform = new ScaleTransform(Ui.Scale, Ui.Scale); Content = scaleHost; FontFamily = Ui.Font; RefreshBackground(); SetupTools(); AddPage("Welcome", WelcomePage(), "START"); AddPage("Search", SearchPage(), "CHEATS"); AddPage("Favorites", FavsPage(), "CHEATS"); foreach (CTab t in tabs) { AddPage(t.Name, t.Name == "Items" ? ItemsPage(t) : CheatPage(t), "CHEATS"); if (t.Name == "Player") AddPage("Health", HealthPage(), "CHEATS"); } AddPage("Profiles", ProfilesPage(), "TOOLS"); AddPage("Tools", ToolsPage(), "TOOLS"); AddPage("Watchlist", WatchPage(), "TOOLS"); AddPage("Run Stats", StatsPage(), "TOOLS"); AddPage("Game Setup", SetupPage(), "TRAINER"); AddPage("Settings", TrainerPage(), "TRAINER"); AddPage("Appearance", AppearancePage(), "TRAINER"); if (!Mac.On) AddPage("Debug", DebugPage(), "TRAINER"); AddPage("VirusTotal", VirusTotalPage(), "TRAINER"); AddPage("My Mods", MyModsPage(), "EXTRAS"); AddPage("Music", MusicPage(), "EXTRAS"); AddPage("Install My Mods", ModsPage(), "EXTRAS"); AddPage("Report a Bug", ReportPage(), "EXTRAS"); AddPage("About Me", AboutPage(), "EXTRAS"); Ui.Changed += OnThemeChanged; Closed += (_, _) => Ui.Changed -= OnThemeChanged; if (Application.Current?.PlatformSettings is { } ps) { EventHandler h = (_, _) => Dispatcher.UIThread.Post(Ui.SystemChanged); ps.ColorValuesChanged += h; Closed += (_, _) => ps.ColorValuesChanged -= h; } AddHandler(KeyDownEvent, OnKey, RoutingStrategies.Tunnel); link.Line += l => Dispatcher.UIThread.Post(() => OnLine(l)); link.Connected += () => Dispatcher.UIThread.Post(OnConnected); link.Disconnected += () => Dispatcher.UIThread.Post(OnDisconnected); link.Start(); string saved = Settings.Get("game", ""); game = Game.IsGameDir(saved) ? saved : Game.Find(); if (game != null && !Piracy.Ok(game)) { string flagged = game; game = null; Opened += (_, _) => Dispatcher.UIThread.Post(() => _ = ShowPiracy(flagged)); } if (game != null) link.WriteLinkFile(game); if (Settings.Get("welcomed", "0") != "1") { Settings.Set("welcomed", "1"); Show("Welcome"); } else Show(SetupDone() ? "Player" : "Game Setup"); if (Settings.Get("notice.updates", "0") != "1" || Settings.Get("notice.usage", "0") != "1") Opened += (_, _) => Dispatcher.UIThread.Post(async () => { await UpdatesNotice(); await UsageNotice(); }); StartUsage(); DispatcherTimer timer = new() { Interval = TimeSpan.FromSeconds(1) }; timer.Tick += (_, _) => Tick(); timer.Start(); Tick(); if (LauncherWindow.Checked) { updStatus.Text = LauncherWindow.Result; updNow.IsEnabled = Updater.Ready != null; } else if (Settings.On("autoupdate", true)) _ = CheckUpdate(false); if (!OperatingSystem.IsWindows() && !Mac.On && !Setup.RunningInstalled && !Setup.Installed && Settings.Get("install.told", "0") != "1") { Settings.Set("install.told", "1"); Message("Tip: install the trainer to your PC (app menu entry and desktop shortcut) from the Settings tab.", false); } if (Program.Args.Contains("--updated")) Message("Updated to v" + Program.Version + ".", false); else if (Settings.On("launchwith", false) && game != null && SetupDone() && !Game.GameRunning()) StartGame(); } protected override void OnClosed(EventArgs e) { CloseDebug(); link.RemoveLinkFile(); base.OnClosed(e); } private bool SetupDone() => Game.PluginState(game) is "ok" or "old" && Game.LaunchOptionState() != "unset"; private static TextBlock T(string text, double size, IBrush fg, bool bold = false, bool wrap = false) => new() { Text = text, FontSize = size, Foreground = fg, FontWeight = bold ? FontWeight.Bold : FontWeight.Normal, TextWrapping = wrap ? TextWrapping.Wrap : TextWrapping.NoWrap }; private static Button Btn(string text, Action click, bool accent = false) { Button b = new() { Content = text, Padding = new Thickness(14, 6), MinHeight = 32 }; b.CornerRadius = new CornerRadius(6); if (accent) { b.Background = Ui.B(Ui.Orange); b.Foreground = Ui.B(Ui.OnAccent); b.FontWeight = FontWeight.SemiBold; } b.Click += (_, _) => click(); return b; } private static void AddLogo(Button b) { string label = b.Content as string; string file = label switch { "Nexus Mods" or "Nexus Page" => "logo-nexus.png", "GameBanana" => "logo-gamebanana.png", "Discord" => "logo-discord.png", _ => null }; if (file == null) return; Avalonia.Media.Imaging.Bitmap bmp = Program.Image(file); if (bmp == null) return; StackPanel sp = new() { Orientation = Orientation.Horizontal, Spacing = 7 }; Image img = new() { Source = bmp, Width = 16, Height = 16, VerticalAlignment = VerticalAlignment.Center }; if (file == "logo-gamebanana.png") RenderOptions.SetBitmapInterpolationMode(img, Avalonia.Media.Imaging.BitmapInterpolationMode.None); sp.Children.Add(img); sp.Children.Add(new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center }); b.Content = sp; } private Border Section(string title, out StackPanel body) { body = new StackPanel { Spacing = 6 }; StackPanel all = new() { Spacing = 10 }; if (!string.IsNullOrWhiteSpace(title)) { StackPanel head = new() { Orientation = Orientation.Horizontal, Spacing = 8 }; head.Children.Add(new Border { Width = 3, Height = 13, CornerRadius = new CornerRadius(2), Background = Ui.B(Ui.Orange), VerticalAlignment = VerticalAlignment.Center }); TextBlock tt = T(string.Join(" ", title.ToCharArray()), 11, Ui.B(Ui.Orange), true); tt.VerticalAlignment = VerticalAlignment.Center; head.Children.Add(tt); all.Children.Add(head); } all.Children.Add(body); 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 }; cards.Add(card); return card; } private static readonly Dictionary Icons = new() { ["Welcome"] = "M4,11 L12,4 L20,11 M6,9.5 V20 H18 V9.5", ["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", ["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", ["Movement"] = "M5,6 L11,12 L5,18 M12,6 L18,12 L12,18", ["Items"] = "M4,8 L12,4 L20,8 L20,17 L12,21 L4,17 Z M4,8 L12,12 L20,8 M12,12 L12,21", ["Combat"] = "M13,3 L5,14 H12 L11,21 L19,10 H12 Z", ["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", ["Traders"] = "M5,8 H19 L18,20 H6 Z M9,8 V6.5 A3,3 0 0,1 15,6.5 V8", ["Challenges"] = "M6,21 V4 M6,4 H17 L15,8 L17,12 H6", ["Game Setup"] = "M4,7 H20 M4,17 H20 M9,4.5 V9.5 M15,14.5 V19.5", ["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", ["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", ["Debug"] = "M3,5 H21 V16 H3 Z M7,9 L9.5,11 L7,13 M11,13 H15 M9,20 H15 M12,16 V20", ["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", ["My Mods"] = "M4,6 H20 M4,12 H20 M4,18 H20 M8,4 V8 M16,10 V14 M11,16 V20", ["Install My Mods"] = "M12,4 V15 M7,10.5 L12,15.5 L17,10.5 M5,20 H19", ["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", ["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", ["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", ["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", ["Profiles"] = "M4,5 H20 V19 H4 Z M8,9 H16 M8,13 H16 M8,17 H12", ["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", ["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", ["Run Stats"] = "M4,20 V4 M4,20 H20 M8,16 V11 M12,16 V7 M16,16 V13", }; private void AddPage(string name, Control c, string group) { pages[name] = c; if (group != lastGroup) { lastGroup = group; TextBlock gh = T(string.Join(" ", group.ToCharArray()), 10, Ui.B(Ui.Faint), true); gh.Margin = new Thickness(10, sideList.Children.Count == 0 ? 8 : 14, 0, 4); sideList.Children.Add(gh); } SPath icon = new() { Data = StreamGeometry.Parse(Icons.GetValueOrDefault(name, "M4,12 H20")), Stroke = Ui.B(Ui.Dim), StrokeThickness = 1.7, StrokeLineCap = PenLineCap.Round, StrokeJoin = PenLineJoin.Round, Width = 18, Height = 18, Stretch = Stretch.Uniform, VerticalAlignment = VerticalAlignment.Center, }; TextBlock label = T(name, 13.5, Ui.B(Ui.Soft)); label.VerticalAlignment = VerticalAlignment.Center; StackPanel content = new() { Orientation = Orientation.Horizontal, Spacing = 11 }; content.Children.Add(icon); content.Children.Add(label); Button b = new() { Content = content, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Left, Background = Brushes.Transparent, Padding = new Thickness(12, 7), CornerRadius = new CornerRadius(8), }; if (name == "VirusTotal") { icon.Data = StreamGeometry.Parse("F0 " + VtLogo); icon.Stroke = null; icon.StrokeThickness = 0; icon.Fill = new SolidColorBrush(Color.FromRgb(0x3d, 0x7b, 0xff)); icon.Width = 16; icon.Height = 16; icon.Margin = new Thickness(1, 0, 1, 0); } b.Click += (_, _) => Show(name); sideButtons[name] = b; sideParts[name] = (icon, label); sideList.Children.Add(b); } private void PaintSide() { foreach (var kv in sideButtons) { bool on = kv.Key == page; kv.Value.Background = on ? Ui.B(Ui.Select) : Brushes.Transparent; var (icon, label) = sideParts[kv.Key]; if (kv.Key == "VirusTotal") icon.Opacity = on ? 1 : 0.85; else icon.Stroke = Ui.B(on ? Ui.Orange : Ui.Dim); label.Foreground = Ui.B(on ? Ui.Text : Ui.Soft); label.FontWeight = on ? FontWeight.SemiBold : FontWeight.Normal; } } private IBrush BannerFade() => new LinearGradientBrush { StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative), EndPoint = new RelativePoint(1, 0, RelativeUnit.Relative), 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) }, }; private void RefreshBackground() { bgLayer.Children.Clear(); if (Ui.BgImage == null || Ui.BgOpacity <= 0) return; double op = Ui.BgOpacity / 100.0; if (Ui.BgFit == "tile") { Size s = Ui.BgImage.Size; 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) } }); return; } Stretch st = Ui.BgFit switch { "fit" => Stretch.Uniform, "stretch" => Stretch.Fill, "center" => Stretch.None, _ => Stretch.UniformToFill }; bgLayer.Children.Add(new Image { Source = Ui.BgImage, Stretch = st, Opacity = op, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }); } private void OnThemeChanged(Color[] before) { foreach (Border b in cards) b.Background = Ui.B(Ui.Card); if (bannerArt != null) bannerArt.IsVisible = Ui.BannerArt; if (bannerFade != null) bannerFade.Background = BannerFade(); scaleHost.LayoutTransform = new ScaleTransform(Ui.Scale, Ui.Scale); FontFamily = Ui.Font; RefreshBackground(); PaintSide(); foreach (Action a in themeRefresh) a(); if (link.IsConnected) link.Send(Ui.OverlayMessage); } private void Show(string name) { page = name; if (name == "Favorites") RebuildFavs(); else if (name == "Search") RebuildSearch(); else if (name == "Music") RebuildSongs(); view.Content = pages[name]; MusicShown(); PaintSide(); if (name == "Game Setup") RefreshSetup(); if (name == "Install My Mods") { mgrScanned = DateTime.MinValue; RefreshMods(true); _ = RefreshThunderstore(); } if (name == "Items") AskItems(); if (name == "Report a Bug") RefreshReport(); if (name == "About Me") { _ = LoadAbout(); _ = RefreshThunderstore(); } } private static ScrollViewer Scroll(Control c) => new() { Content = c, Padding = new Thickness(22, 18, 22, 8), HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }; private Control CheatPage(CTab t) { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; for (int c = 0; c < 3; c++) { StackPanel col = new() { Margin = new Thickness(c == 0 ? 0 : 7, 0, c == 2 ? 0 : 7, 0) }; foreach (CSection s in t.Sections.Where(x => x.Col == c)) col.Children.Add(BuildSection(s)); Grid.SetColumn(col, c); g.Children.Add(col); } return Scroll(g); } private Border BuildSection(CSection s) { Border b = Section(s.Title, out StackPanel body); foreach (COpt o in s.Rows) { Control row = BuildRow(o); if (row != null) body.Children.Add(row); } return b; } private Button KeyButton(string id) { 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) }; k.Content = Cheats.KeyLabel(binds.GetValueOrDefault(id, "")); ToolTip.SetTip(k, "Click, then press a key. Esc cancels, Delete clears it."); k.Click += (_, _) => StartBind(id); keyButtons[id] = k; return k; } private Control BuildRow(COpt o) { switch (o.Kind) { case CKind.Toggle: { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") }; ToggleSwitch tb = new() { OnContent = o.Name, OffContent = o.Name, HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 34, Margin = new Thickness(0, 0, 6, 0) }; if (o.Hint != null) ToolTip.SetTip(tb, o.Hint); tb.ContextMenu = CheatContext(o); tb.Click += (_, _) => { bool on = tb.IsChecked == true; if (!Linked()) { tb.IsChecked = !on; return; } link.Send("SET " + o.Id + (on ? " 1" : " 0")); if (on && Settings.On("bark", true)) Bark.Play(); }; RegisterSetter(o.Id, v => tb.IsChecked = v == "1"); g.Children.Add(tb); Button st = StarButton(o); Grid.SetColumn(st, 1); g.Children.Add(st); if (!buildingExtra) { Button k = KeyButton(o.Id); Grid.SetColumn(k, 2); g.Children.Add(k); } return g; } case CKind.Action: { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") }; 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) }; if (o.Hint != null) ToolTip.SetTip(b, o.Hint); b.Click += (_, _) => { if (Linked()) link.Send("ACT " + o.Id); }; g.Children.Add(b); Button st = StarButton(o); Grid.SetColumn(st, 1); g.Children.Add(st); if (!buildingExtra) { Button k = KeyButton(o.Id); Grid.SetColumn(k, 2); g.Children.Add(k); } return g; } case CKind.Slider: { StackPanel sp = new() { Spacing = 0 }; Grid top = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto,Auto") }; top.Children.Add(T(o.Name, 13, Ui.B(Ui.Text))); TextBlock val = T(string.Format(CultureInfo.InvariantCulture, o.Format, o.Default), 13, Ui.B(Ui.Orange), true); val.Margin = new Thickness(0, 0, 8, 0); val.VerticalAlignment = VerticalAlignment.Center; Grid.SetColumn(val, 1); top.Children.Add(val); Slider s = new() { Minimum = o.Min, Maximum = o.Max, TickFrequency = o.Step, IsSnapToTickEnabled = true, Value = o.Default }; Button reset = new() { Content = "Reset", FontSize = 11, Padding = new Thickness(8, 2), MinHeight = 22 }; Grid.SetColumn(reset, 2); top.Children.Add(reset); sp.Children.Add(top); sp.Children.Add(s); if (o.Hint != null) ToolTip.SetTip(sp, o.Hint); bool quiet = false; s.PropertyChanged += (_, e) => { if (e.Property != RangeBase.ValueProperty) return; val.Text = string.Format(CultureInfo.InvariantCulture, o.Format, s.Value); if (quiet || !link.IsConnected) return; link.Send("VAL " + o.Id + " " + s.Value.ToString("0.###", CultureInfo.InvariantCulture)); }; reset.Click += (_, _) => { if (Linked()) s.Value = o.Default; }; RegisterSetter(o.Id, v => { if (!double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d)) return; quiet = true; s.Value = Math.Clamp(d, o.Min, o.Max); quiet = false; }); return sp; } case CKind.Buttons: { WrapPanel w = new() { Orientation = Orientation.Horizontal }; TextBlock label = T(o.Name ?? "", 13, Ui.B(Ui.Text)); label.Width = 130; label.VerticalAlignment = VerticalAlignment.Center; if (o.Text != null) infoRows.Add((label, o)); w.Children.Add(label); foreach (CBtn cb in o.Buttons) { Button b = new() { Content = cb.Label, Margin = new Thickness(0, 0, 4, 4), Padding = new Thickness(10, 4), MinHeight = 30, CornerRadius = new CornerRadius(6) }; b.Click += (_, _) => { if (Linked()) link.Send("ACT " + cb.Act + (cb.Arg != null ? " " + cb.Arg : "")); }; w.Children.Add(b); } if (o.Hint != null) ToolTip.SetTip(w, o.Hint); return w; } case CKind.Info: { TextBlock tb = T("", 13, Ui.B(Ui.Text), false, true); infoRows.Add((tb, o)); return tb; } case CKind.Note: return T(o.Name, 13, Ui.B(Ui.Dim), false, true); } return null; } private bool Linked() { if (link.IsConnected) return true; Message(game == null ? "Set up the game first (Game Setup tab)." : "Start the game first. The cheats run inside the game.", true); return false; } private void RefreshInfo() { foreach (var (tb, o) in infoRows) tb.Text = o.Text(info) ?? ""; } private void StartBind(string id) { if (!Linked()) return; if (bindingId != null && keyButtons.TryGetValue(bindingId, out Button old)) old.Content = Cheats.KeyLabel(binds.GetValueOrDefault(bindingId, "")); bindingId = id; if (keyButtons.TryGetValue(id, out Button b)) b.Content = "press a key"; Message("Press the key for " + (byId.TryGetValue(id, out COpt o) ? o.Name : id) + ". Esc cancels, Delete clears it.", false); } private void OnKey(object sender, KeyEventArgs e) { if (bindingId == null) { if (e.Key == Key.F && e.KeyModifiers.HasFlag(KeyModifiers.Control)) { OpenSearch(); e.Handled = true; } return; } e.Handled = true; Key k = e.Key; if (k is Key.LeftCtrl or Key.RightCtrl or Key.LeftShift or Key.RightShift or Key.LeftAlt or Key.RightAlt or Key.LWin or Key.RWin) return; string id = bindingId; bindingId = null; string v; if (k == Key.Escape) v = null; else if (k is Key.Delete or Key.Back) v = "none"; else { string u = KeyMap.Unity(k); if (u == null) { Message("That key can't be used. Pick another.", true); v = null; } else if (id == "menu") v = u; else v = (e.KeyModifiers.HasFlag(KeyModifiers.Control) ? "Ctrl+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Shift) ? "Shift+" : "") + (e.KeyModifiers.HasFlag(KeyModifiers.Alt) ? "Alt+" : "") + u; } if (v != null) { binds[id] = v; Settings.Set("bind." + id, v); link.Send("BIND " + id + " " + v); Message("Key set: " + Cheats.KeyLabel(v), false); } if (keyButtons.TryGetValue(id, out Button b)) b.Content = Cheats.KeyLabel(binds.GetValueOrDefault(id, "")); } private void Message(string s, bool bad) { messageText.Text = s; messageText.Foreground = bad ? Ui.B(Ui.Bad) : Ui.B(Ui.Dim); } private void Status(string s, Color c) { statusText.Text = s; statusText.Foreground = Ui.B(Ui.Text); dot.Fill = Ui.B(c); } private DateTime startAsked = DateTime.MinValue; private async void StartGame() { if (Game.GameRunning()) { Message("The game is already running.", false); return; } if (game == null) { Show("Game Setup"); Message("Set the game folder first.", true); return; } Message("Asking Steam to start Casualties: Unknown...", false); string e = await Game.Start(); if (e != null) { Message("Couldn't start the game: " + e, true); return; } startAsked = DateTime.UtcNow; Message("Steam is starting Casualties: Unknown. If Steam was closed, it opens first, which can take a minute.", false); } private bool attachedThisRun; private DateTime gameGoneSince = DateTime.MinValue; private void Tick() { MusicTick(); ToolsTick(); if (game != null && !Game.IsGameDir(game)) game = null; if (game != null) link.WriteLinkFile(game); bool running = game != null && Game.GameRunning(); if (running) startAsked = DateTime.MinValue; else if (startAsked != DateTime.MinValue && (DateTime.UtcNow - startAsked).TotalSeconds > 90) { startAsked = DateTime.MinValue; Message("The game still hasn't started. Start it from your Steam library, and check Steam is logged in.", true); } if (running && gameSeenSince == DateTime.MinValue) gameSeenSince = DateTime.UtcNow; if (!running) gameSeenSince = DateTime.MinValue; if (!running && game != null && !autoPluginTried && !busy && Game.PluginState(game) is "old" or "missing") { autoPluginTried = true; _ = AutoUltraPara(); } if (link.IsConnected) attachedThisRun = true; if (running) gameGoneSince = DateTime.MinValue; else if (attachedThisRun && !link.IsConnected) { if (gameGoneSince == DateTime.MinValue) gameGoneSince = DateTime.UtcNow; else if ((DateTime.UtcNow - gameGoneSince).TotalSeconds >= 3) { attachedThisRun = false; gameGoneSince = DateTime.MinValue; if (Settings.On("closewithgame", true)) { Close(); return; } } } if (link.IsConnected) { if (blocked != null) Status("Cheats are off: " + blocked, Ui.Bad); 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); else Status("Attached · " + Cheats.Get(info, "where", "loading"), Ui.Good); } else if (game == null) Status("Couldn't find Casualties: Unknown. Set the game folder in Game Setup.", Ui.Bad); 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); else if (running && (DateTime.UtcNow - gameSeenSince).TotalSeconds > 40) Status(LinkProblem(), Ui.Warn); else if (running) Status("Waiting for the game to load...", Ui.Warn); else Status("Ready. Start the game and the trainer attaches by itself.", Ui.Dim); if (page == "Game Setup") RefreshSetup(); if (page == "Install My Mods") RefreshMods(false); if (page == "Items") AskItems(); if (page == "Report a Bug") RefreshReport(); DebugTick(); } private DateTime barkAfter = DateTime.MinValue; private void OnConnected() { barkAfter = DateTime.UtcNow.AddSeconds(4); blocked = null; pluginVersion = null; items.Clear(); itemsLoading = false; link.Send("HEALTH 1"); link.Send(Ui.OverlayMessage); DebugConnected(); myModsLoaded = false; RebuildMyMods(); MyModsConnected(); MusicConnected(); lastOvExtra = ""; SendXBinds(); Message("Attached to the game.", false); } private void OnDisconnected() { vitals = null; UpdateHealth(); SetMoodles(""); blocked = null; debugWin?.SetLinked(false); MyModsDisconnected(); MusicDisconnected(); Message("The game closed or unlinked.", false); } private void OnLine(string s) { int sp = s.IndexOf(' '); string cmd = sp < 0 ? s : s[..sp]; string rest = sp < 0 ? "" : s[(sp + 1)..]; switch (cmd) { case "INFO": info = ParseDict(rest); RefreshInfo(); break; case "VITALS": vitals = rest == "none" ? null : ParseDict(rest); UpdateHealth(); break; case "MOODLES": SetMoodles(rest); break; case "MICON": OnIcon(rest); break; case "BARKSET": foreach (string n in Bark.OnSet(rest)) link.Send("GETSFX " + n); break; case "SFX": Bark.OnSfx(rest); break; case "MSG": Message(rest, false); ToolsLine(cmd, rest); break; case "HOTKEY": ToolsLine(cmd, rest); break; case "READY": if (int.TryParse(rest, out int n2)) { if (n2 == -1) Message("The trainer's patch library didn't load, so many cheats won't work. Try restarting the game.", true); else if (n2 > 0) Message(n2 + " cheat hook" + (n2 == 1 ? "" : "s") + " couldn't load. A game update may have changed something.", true); } break; case "BLOCKED": blocked = rest; Message(Program.Name + " doesn't run alongside multiplayer mods.", true); break; case "STATE": { int p = rest.IndexOf(' '); if (p > 0 && rest[(p + 1)..] == "1" && DateTime.UtcNow > barkAfter && lastState.TryGetValue(rest[..p], out string wasV) && wasV == "0" && byId.TryGetValue(rest[..p], out COpt bo) && bo.Kind == CKind.Toggle && Settings.On("bark", true)) Bark.Play(); if (p > 0 && stateSetters.TryGetValue(rest[..p], out Action set)) set(rest[(p + 1)..]); if (p > 0) NoteState(rest[..p], rest[(p + 1)..]); break; } case "BIND": { int p = rest.IndexOf(' '); if (p <= 0) break; string id = rest[..p], v = rest[(p + 1)..]; binds[id] = v; if (Settings.Get("bind." + id, "") != v) Settings.Set("bind." + id, v); if (bindingId != id && keyButtons.TryGetValue(id, out Button b)) b.Content = Cheats.KeyLabel(v); break; } case "OPTS": { Dictionary d = ParseDict(rest); foreach (var kv in d) if (optSetters.TryGetValue(kv.Key, out Action set)) set(kv.Value == "1"); break; } case "PLUGIN": pluginVersion = rest; break; case "LOADER": loaderVersion = rest == "none" ? null : rest; break; case "DLOG": debugWin?.OnLog(rest); break; case "DSNAP": debugWin?.OnSnapshot(rest); break; case "DSYS": debugWin?.OnSystem(rest); break; case "MODS": MyModsParse(rest); break; case "MODSTAT": MyModsStats(rest); break; case "MUSIC": OnMusicLine(rest); break; case "MUSICLIST": OnMusicList(rest); break; case "MODERR": { int sp2 = rest.IndexOf(' '); Message(sp2 > 0 ? rest[(sp2 + 1)..] : rest, true); } break; case "ITEM": { int tab = rest.IndexOf('\t'); if (tab > 0) items.Add((rest[..tab], rest[(tab + 1)..])); break; } case "ITEMSEND": itemsLoading = false; items.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase)); FilterItems(); spawnStatus.Text = items.Count > 0 ? items.Count + " items. Pick one and click Spawn." : "Start a run to load the item list."; break; } } private static Dictionary ParseDict(string rest) { Dictionary d = new(); foreach (string part in rest.Split('|')) { int eq = part.IndexOf('='); if (eq > 0) d[part[..eq]] = part[(eq + 1)..]; } return d; } private Dictionary vitals; private readonly List vitalUpdaters = new(); private readonly WrapPanel moodlePanel = new() { Orientation = Orientation.Horizontal }; private readonly StackPanel issuePanel = new() { Spacing = 8 }; private readonly TextBlock healthNote = T("", 13, Ui.B(Ui.Dim), false, true); private readonly Dictionary icons = new(); private string moodlesRaw = "", issuesKey = ""; private Control HealthPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*") }; StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) }; Border vs = Section("VITALS", out StackPanel vb); vb.Children.Add(healthNote); Vital(vb, "Heart rate", "hr", 0, 200, v => v.ToString("0", CultureInfo.InvariantCulture) + " bpm", false); Vital(vb, "Blood", "blood", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false); Vital(vb, "Bleeding", "bleed", 0, 1, v => v.ToString("0.00", CultureInfo.InvariantCulture) + " L/min", true); Vital(vb, "Oxygen", "oxy", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false); Vital(vb, "Brain", "brain", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false); Vital(vb, "Consciousness", "consc", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false); Vital(vb, "Pain", "pain", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", true); Vital(vb, "Temperature", "temp", 25, 45, v => v.ToString("0.0", CultureInfo.InvariantCulture) + " °C", false); Vital(vb, "Hunger", "hunger", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false); Vital(vb, "Thirst", "thirst", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false); Vital(vb, "Energy", "energy", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", false); Vital(vb, "Sickness", "sick", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture) + "%", true); Vital(vb, "Infection", "infect", 0, 100, v => v.ToString("0", CultureInfo.InvariantCulture), true); Vital(vb, "Radiation", "rad", 0, 10, v => v.ToString("0.0", CultureInfo.InvariantCulture) + " gy", true); Vital(vb, "Mood", "mood", -100, 100, v => v.ToString("0", CultureInfo.InvariantCulture), false); left.Children.Add(vs); g.Children.Add(left); StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) }; Border ms = Section("MOODLES", out StackPanel mb); mb.Children.Add(moodlePanel); right.Children.Add(ms); Border ws = Section("WHAT TO DO", out StackPanel wb); wb.Children.Add(issuePanel); right.Children.Add(ws); Grid.SetColumn(right, 1); g.Children.Add(right); UpdateHealth(); return Scroll(g); } private void Vital(StackPanel host, string label, string key, double min, double max, Func fmt, bool badHigh) { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("120,*,90") }; g.Children.Add(T(label, 13, Ui.B(Ui.Text))); ProgressBar bar = new() { Minimum = min, Maximum = max, Height = 8, MinHeight = 8, MinWidth = 0, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(6, 0) }; Grid.SetColumn(bar, 1); g.Children.Add(bar); TextBlock val = T("-", 13, Ui.B(Ui.Dim)); val.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(val, 2); g.Children.Add(val); host.Children.Add(g); vitalUpdaters.Add(() => { if (vitals == null || !vitals.ContainsKey(key)) { bar.Value = min; val.Text = "-"; return; } double v = Advisor.F(vitals, key, 0); bar.Value = Math.Clamp(v, min, max); double frac = (v - min) / (max - min); bool bad = badHigh ? frac > 0.5 : frac < 0.3; bar.Foreground = Ui.B(bad ? Ui.Bad : Ui.Orange); val.Text = fmt(v); }); } private void UpdateHealth() { foreach (Action a in vitalUpdaters) a(); 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." : ""; healthNote.IsVisible = healthNote.Text.Length > 0; List issues = Advisor.Check(vitals, byId); string key = string.Join("|", issues.Select(i => i.Title + i.Detail)); if (key == issuesKey) return; issuesKey = key; issuePanel.Children.Clear(); if (issues.Count == 0) { issuePanel.Children.Add(T(vitals == null ? "Nothing to show yet." : "All good. Nothing needs fixing right now.", 13, Ui.B(Ui.Dim), false, true)); return; } foreach (Issue i in issues) { StackPanel sp = new() { Spacing = 4 }; sp.Children.Add(T(i.Title, 14, Ui.B(i.Danger ? Ui.Bad : Ui.Text), true)); sp.Children.Add(T(i.Detail, 12, Ui.B(Ui.Dim), false, true)); WrapPanel fixes = new(); foreach (Fix f in i.Fixes) { Fix fx = f; Button b = new() { Content = fx.Label, FontSize = 12, Padding = new Thickness(10, 3), Margin = new Thickness(0, 2, 6, 0), MinHeight = 26 }; b.Click += (_, _) => { if (!Linked()) return; if (fx.Act != null) link.Send("ACT " + fx.Act); else if (fx.Opt.Kind == CKind.Toggle) { link.Send("SET " + fx.Opt.Id + " 1"); if (Settings.On("bark", true)) Bark.Play(); } else link.Send("ACT " + fx.Opt.Id); }; fixes.Children.Add(b); } if (fixes.Children.Count > 0) sp.Children.Add(fixes); 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 }); } } private void OnIcon(string rest) { int sp = rest.IndexOf(' '); if (sp <= 0) return; string id = rest[..sp]; if (!int.TryParse(id, out _)) return; try { byte[] b = Convert.FromBase64String(rest[(sp + 1)..]); if (b.Length > 512 * 1024) return; using MemoryStream ms = new(b); icons[id] = new Bitmap(ms); SetMoodles(moodlesRaw, true); } catch (Exception) { } } private void SetMoodles(string raw, bool force = false) { if (raw == moodlesRaw && !force) return; moodlesRaw = raw; moodlePanel.Children.Clear(); if (raw.Length == 0) { moodlePanel.Children.Add(T(link.IsConnected ? "No moodles right now." : "Start the game to see moodles.", 13, Ui.B(Ui.Dim))); return; } foreach (string row in raw.Split('\u001e')) { string[] f = row.Split('\u001f'); if (f.Length < 6) continue; Panel stack = new() { Width = 46, Height = 46 }; foreach (string id in new[] { f[0], f[1] }) { if (id.Length == 0 || !icons.TryGetValue(id, out Bitmap bmp)) continue; Image img = new() { Source = bmp, Width = 46, Height = 46, Stretch = Stretch.Uniform }; RenderOptions.SetBitmapInterpolationMode(img, BitmapInterpolationMode.None); stack.Children.Add(img); } 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) }; ToolTip.SetTip(b, f[4] + (f[5].Length > 0 ? "\n" + f[5] : "")); moodlePanel.Children.Add(b); } } private readonly List<(string key, string name)> items = new(); private List<(string key, string name)> shown = new(); private bool itemsLoading; private DateTime nextItemsAsk; private readonly TextBox itemSearch = new() { Watermark = "Search items" }; private readonly ListBox itemList = new() { Height = 380 }; private readonly NumericUpDown itemCount = new() { Minimum = 1, Maximum = 50, Increment = 1, Value = 1, FormatString = "0", Width = 130 }; private readonly TextBlock spawnStatus = T("Start a run to load the item list.", 12, Ui.B(Ui.Dim), false, true); private Control ItemsPage(CTab t) { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,2*") }; StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) }; foreach (CSection s in t.Sections) left.Children.Add(BuildSection(s)); g.Children.Add(left); Border sb = Section("ITEM SPAWNER", out StackPanel body); body.Children.Add(itemSearch); itemSearch.TextChanged += (_, _) => FilterItems(); body.Children.Add(itemList); itemList.SelectionMode = SelectionMode.Multiple; itemList.DoubleTapped += (_, _) => Spawn(); StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 8 }; row.Children.Add(T("How many", 13, Ui.B(Ui.Text))); ((TextBlock)row.Children[0]).VerticalAlignment = VerticalAlignment.Center; row.Children.Add(itemCount); row.Children.Add(Btn("Spawn", Spawn, true)); row.Children.Add(Btn("Favorite", ToggleItemFav)); row.Children.Add(Btn("Reload List", () => { items.Clear(); FilterItems(); nextItemsAsk = DateTime.MinValue; AskItems(); })); body.Children.Add(row); body.Children.Add(spawnStatus); 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)); StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) }; right.Children.Add(sb); Grid.SetColumn(right, 1); g.Children.Add(right); return Scroll(g); } private void AskItems() { if (!link.IsConnected || items.Count > 0 || itemsLoading || DateTime.UtcNow < nextItemsAsk) return; nextItemsAsk = DateTime.UtcNow.AddSeconds(5); itemsLoading = true; spawnStatus.Text = "Loading the item list..."; link.Send("ITEMS"); } private void FilterItems() { string q = (itemSearch.Text ?? "").Trim(); 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(); List<(string key, string name)> favs = match.Where(i => itemFavs.Contains(i.key)).ToList(); 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(); shown = favs.Concat(recent).Concat(match.Where(i => !itemFavs.Contains(i.key) && !recent.Any(r => r.key == i.key))).ToList(); itemList.ItemsSource = shown.Select(i => (itemFavs.Contains(i.key) ? "\u2605 " : recent.Any(r => r.key == i.key) ? "\u21BA " : "") + i.name).ToList(); } private void Spawn() { if (!Linked()) return; List picked = itemList.Selection.SelectedIndexes.Where(i => i >= 0 && i < shown.Count).ToList(); if (picked.Count == 0) { spawnStatus.Text = "Pick an item first."; return; } int n = (int)(itemCount.Value ?? 1); List keys = picked.Select(i => shown[i].key).ToList(); foreach (string k in keys) { link.Send("SPAWN " + k + " " + Math.Clamp(n, 1, 50)); itemRecent.Remove(k); itemRecent.Insert(0, k); } if (itemRecent.Count > 12) itemRecent.RemoveRange(12, itemRecent.Count - 12); Settings.Set("items.recent", string.Join(",", itemRecent)); } private readonly HashSet itemFavs = new(Settings.Get("items.fav", "").Split(',', StringSplitOptions.RemoveEmptyEntries)); private readonly List itemRecent = Settings.Get("items.recent", "").Split(',', StringSplitOptions.RemoveEmptyEntries).Take(12).ToList(); private void ToggleItemFav() { List picked = itemList.Selection.SelectedIndexes.Where(i => i >= 0 && i < shown.Count).ToList(); if (picked.Count == 0) { spawnStatus.Text = "Pick an item first."; return; } foreach (int i in picked) if (!itemFavs.Remove(shown[i].key)) itemFavs.Add(shown[i].key); Settings.Set("items.fav", string.Join(",", itemFavs)); FilterItems(); } private readonly TextBlock gamePath = T("", 13, Ui.B(Ui.Text), false, true); private readonly TextBlock bepStatus = T("", 13, Ui.B(Ui.Text), false, true); private readonly TextBlock pluginStatus = T("", 13, Ui.B(Ui.Text), false, true); private readonly TextBlock launchStatus = T("", 13, Ui.B(Ui.Text), false, true); private readonly TextBlock setupWarn = T("", 13, Ui.B(Ui.Warn), false, true); private Button bepBtn, pluginBtn; private bool busy; private Control SetupPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*") }; StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) }; Border all = Section("QUICK SETUP", out StackPanel ab); 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)); ab.Children.Add(Btn("Set Everything Up", () => _ = SetupAll(), true)); left.Children.Add(all); Border gs = Section("GAME", out StackPanel gb); gb.Children.Add(gamePath); WrapPanel gbtn = new(); foreach (Button b in new[] { Btn("Find Again", () => { game = Game.Find(); if (game != null && !Piracy.Ok(game)) { string fl = game; game = null; RefreshSetup(); _ = ShowPiracy(fl); return; } if (game != null) Settings.Set("game", game); RefreshSetup(); 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); }), Btn("Pick Game .exe", () => _ = PickGame(false)), Btn("Open Folder", () => { if (game != null) Game.Open(game); }), Btn("Start Game", () => StartGame()), }) { b.Margin = new Thickness(0, 4, 6, 0); gbtn.Children.Add(b); } gb.Children.Add(gbtn); left.Children.Add(gs); Border ps = Section("1 ULTRAPARA.DLL (REQUIRED)", out StackPanel pb); 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)); pb.Children.Add(pluginStatus); WrapPanel pbtn = new(); pluginBtn = Btn("Install UltraPara.dll", () => _ = InstallUltraPara(true)); pluginBtn.Margin = new Thickness(0, 4, 6, 0); pbtn.Children.Add(pluginBtn); 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(); }); rm.Margin = new Thickness(0, 4, 6, 0); pbtn.Children.Add(rm); pb.Children.Add(pbtn); left.Children.Add(ps); Border bs = Section("BEPINEX " + Game.BepVersion + " (OPTIONAL, FOR MY OTHER MODS)", out StackPanel bb); 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)); bb.Children.Add(bepStatus); bepBtn = Btn("Install BepInEx", () => _ = InstallBep()); bb.Children.Add(bepBtn); left.Children.Add(bs); g.Children.Add(left); StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) }; Border ls = Section(Mac.On ? "2 WINE SETTING" : "2 STEAM LAUNCH OPTION", out StackPanel lb); WrapPanel lbtn = new(); if (Mac.On) { 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)); lb.Children.Add(new TextBox { Text = "winhttp (native, builtin)", IsReadOnly = true, FontFamily = new FontFamily("monospace") }); 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(); })); } else { 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)); lb.Children.Add(new TextBox { Text = Game.LaunchOption, IsReadOnly = true, FontFamily = new FontFamily("monospace") }); 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); }); copy.Margin = new Thickness(0, 0, 6, 0); lbtn.Children.Add(copy); 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(); })); } lb.Children.Add(lbtn); lb.Children.Add(launchStatus); right.Children.Add(ls); Border ws = Section("NOTES", out StackPanel wb); wb.Children.Add(setupWarn); 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)); 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)); 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)); right.Children.Add(ws); Border lk = Section("LINKS", out StackPanel lkb); 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)); WrapPanel lkw = new(); foreach (Button b in new[] { Btn("Nexus Mods", () => Game.Open("https://www.nexusmods.com/scavprototype/mods/1203")), Btn("GameBanana", () => Game.Open("https://gamebanana.com/mods/749667")), Btn("Discord", () => Message("The Discord server isn't open yet. It's coming later.", false)), }) { b.Margin = new Thickness(0, 4, 6, 0); AddLogo(b); lkw.Children.Add(b); } lkb.Children.Add(lkw); right.Children.Add(lk); Grid.SetColumn(right, 1); g.Children.Add(right); return Scroll(g); } private async Task UpdatesNotice() { if (Settings.Get("notice.updates", "0") == "1") return; Settings.Set("notice.updates", "1"); Window w = new() { Title = Program.Name + " - About updates", Width = 460, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = Ui.B(Ui.Back), }; StackPanel sp = new() { Margin = new Thickness(20), Spacing = 12 }; 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 }); 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) }); 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) }); 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) }); Button ok = new() { Content = "Got it", Padding = new Thickness(20, 6), HorizontalAlignment = HorizontalAlignment.Right, Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent) }; ok.Click += (_, _) => w.Close(); sp.Children.Add(ok); w.Content = sp; await w.ShowDialog(this); } private async Task ShowPiracy(string dir) { PiracyDialog d = new(); await d.ShowDialog(this); 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; } await PickGame(true); } private async Task PickGame(bool proceeded) { IReadOnlyList r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Pick the Casualties: Unknown game .exe (CasualtiesUnknown.exe)", AllowMultiple = false, FileTypeFilter = new[] { new FilePickerFileType("Game (.exe)") { Patterns = new[] { "*.exe", "*.EXE" } } }, }); string f = r.Count > 0 ? r[0].TryGetLocalPath() : null; if (f == null) return; string p = Path.GetDirectoryName(f); if (!Game.IsGameDir(p)) { Message("That isn't CasualtiesUnknown.exe. Pick the game's own .exe.", true); return; } if (Piracy.Flagged(p)) { if (!proceeded && !Piracy.Ok(p)) { PiracyDialog d = new(); await d.ShowDialog(this); if (!d.Proceed) return; } Settings.Set("piracy.ok", p); } game = p; Settings.Set("game", p); link.WriteLinkFile(p); RefreshSetup(); Message("Game folder set.", false); } private async Task InstallBep() { if (busy || game == null) return false; busy = true; bepBtn.IsEnabled = false; string e = await Game.InstallBepInEx(game, pc => Dispatcher.UIThread.Post(() => bepStatus.Text = "Downloading BepInEx... " + pc + "%")); busy = false; bepBtn.IsEnabled = true; Message(e == null ? "BepInEx is installed." : "Couldn't install BepInEx: " + e, e != null); RefreshSetup(); return e == null; } private string upProgress, loaderVersion; private async Task InstallUltraPara(bool tell) { if (busy || game == null) return false; busy = true; upProgress = "Downloading UltraPara.dll..."; RefreshSetup(); string e = await Game.InstallPlugin(game, pc => Dispatcher.UIThread.Post(() => { upProgress = "Downloading UltraPara.dll... " + pc + "%"; RefreshSetup(); })); busy = false; upProgress = null; if (e != null || tell) Message(e == null ? "UltraPara.dll v" + UltraParaInfo.Version + " is installed." : "Couldn't install UltraPara.dll: " + e, e != null); RefreshSetup(); return e == null; } private async Task AutoUltraPara() { string before = Game.PluginState(game); 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); } private string LinkProblem() { string log = game != null ? Game.LoaderLog(game) : null; 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."; if (log.Contains("FAILED")) return "UltraPara.dll couldn't start the trainer: " + log.Substring(log.IndexOf("FAILED", StringComparison.Ordinal)); return "UltraPara.dll is loaded but the trainer code hasn't connected yet."; } private async Task SetupAll() { if (game == null) { Message("Find or pick the game folder first.", true); return; } if (Game.GameRunning()) { Message("Close the game first.", true); return; } if (!await InstallUltraPara(false)) return; if (Game.LaunchOptionState() != "set") { string e = Game.SetLaunchOption(); if (e != null) { Message("UltraPara.dll is in. Last step: " + e, true); RefreshSetup(); return; } } RefreshSetup(); Message(Mac.On ? "All set. Start the game through Steam in CrossOver/Whisky." : "All set. Start the game through Steam.", false); } private void RefreshSetup() { gamePath.Text = game ?? "Not found. Use Find Again, or Pick Game .exe."; gamePath.Foreground = Ui.B(game == null ? Ui.Bad : Ui.Text); bool running = Game.GameRunning(); if (!busy) { bool bep = Game.BepInstalled(game); 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."; bepStatus.Foreground = Ui.B(bep ? Ui.Good : Ui.Warn); bepBtn.Content = bep ? "Reinstall BepInEx" : "Install BepInEx"; bepBtn.IsEnabled = game != null && !running; } string ps = Game.PluginState(game); string loaderLog = game != null ? Game.LoaderLog(game) : null; string st = ps switch { "ok" => "✓ Installed (v" + UltraParaInfo.Version + ").", "old" => running ? "An update is ready. It installs when the game is closed." : "An older version is installed. Update it.", "missing" => "✗ Not installed.", "foreign" => "✗ Blocked: the game folder has a version.dll from another program. Move it out first.", _ => "Waiting for the game folder.", }; if (link.IsConnected && loaderVersion != null) st += "\n✓ DLL loaded in the game (UltraPara " + loaderVersion + ")."; else if (running && loaderLog != null && loaderLog.Contains("LOADED")) st += "\n✓ DLL loaded in the game."; else if (running) st += "\nIn the game: not loaded yet. If it stays like this, restart the game and check the launch option."; if (loaderLog != null && loaderLog.Contains("FAILED")) st += "\nLast start: " + loaderLog; if (upProgress != null) st += "\n" + upProgress; pluginStatus.Text = st; pluginStatus.Foreground = Ui.B(ps == "ok" ? Ui.Good : Ui.Warn); pluginBtn.Content = ps == "old" ? "Update UltraPara.dll" : ps == "ok" ? "Reinstall UltraPara.dll" : "Install UltraPara.dll"; pluginBtn.IsEnabled = game != null && !running && !busy; string ls = Game.LaunchOptionState(); 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."); launchStatus.Foreground = Ui.B(ls == "set" ? Ui.Good : Ui.Warn); List warn = new(); string other = game != null ? Game.OtherCheats(game) : null; 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)."); if (running) warn.Add("The game is running. Close it to install or update anything."); setupWarn.Text = string.Join("\n\n", warn); setupWarn.IsVisible = warn.Count > 0; } private readonly StackPanel modRows = new() { Spacing = 8 }; private readonly TextBlock modsNote = T("", 13, Ui.B(Ui.Dim), false, true); private readonly Dictionary pendingZips = new(); private readonly Dictionary zipCache = new(); private readonly HashSet announced = new(); private DateTime nextModScan; private string modsKey = ""; private Dictionary tsMods; private List managers; private string mgrHandler; private DateTime tsFetched = DateTime.MinValue, mgrScanned = DateTime.MinValue; private bool tsBusy; private readonly StackPanel mgrRows = new() { Spacing = 4 }; private readonly TextBlock tsStatus = T("", 12, Ui.B(Ui.Dim), false, true); private static void OpenTs(string url) { if (Thunderstore.SafeUrl(url)) Game.Open(url); } private async Task RefreshThunderstore() { if (tsBusy || (DateTime.UtcNow - tsFetched).TotalMinutes < 10) return; tsBusy = true; Dictionary d = null; try { d = await Thunderstore.Fetch(); } catch (Exception) { } tsBusy = false; if (d != null && d.Count > 0) { tsFetched = DateTime.UtcNow; tsMods = d; tsStatus.Text = "Thunderstore: " + d.Count + " of my mods, updated " + DateTime.Now.ToString("HH:mm", CultureInfo.InvariantCulture) + "."; } else { tsFetched = DateTime.UtcNow.AddMinutes(-8); tsStatus.Text = tsMods != null ? "Couldn't reach Thunderstore, showing the saved list." : "Couldn't reach Thunderstore."; } RefreshMods(true); ShowTsAbout(); } private void ScanManagers(bool force) { if (!force && (DateTime.UtcNow - mgrScanned).TotalSeconds < 15) return; mgrScanned = DateTime.UtcNow; try { managers = ModManagers.Scan(); } catch (Exception) { managers = new(); } mgrHandler = ModManagers.Handler(); mgrRows.Children.Clear(); if (managers.Count == 0) 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)); else { foreach (ModManager m in managers) 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))); 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)); } } private Control ModsPage() { StackPanel sp = new(); Border hs = Section("INSTALL MY MODS", out StackPanel hb); 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)); WrapPanel w = new(); Button pick = Btn("Install From Zip...", () => _ = PickZip()); pick.Margin = new Thickness(0, 0, 6, 0); w.Children.Add(pick); w.Children.Add(Btn("Open Downloads", () => { string d = Mods.Downloads; if (d != null) Game.Open(d); })); hb.Children.Add(w); hb.Children.Add(modsNote); sp.Children.Add(hs); Border mg = Section("MOD MANAGERS", out StackPanel mgb); mgb.Children.Add(mgrRows); Button tsb = Btn("My Thunderstore page", () => OpenTs(Thunderstore.TeamUrl)); tsb.Margin = new Thickness(0, 6, 0, 0); tsb.HorizontalAlignment = HorizontalAlignment.Left; mgb.Children.Add(tsb); mgb.Children.Add(tsStatus); sp.Children.Add(mg); tsMods = Thunderstore.Load(out DateTime tsAt); if (tsMods != null) tsStatus.Text = "Thunderstore: saved list from " + tsAt.ToLocalTime().ToString("d MMM, HH:mm", CultureInfo.InvariantCulture) + "."; Border ms = Section("MODS", out StackPanel mb); mb.Children.Add(modRows); sp.Children.Add(ms); return Scroll(sp); } private async Task PickZip() { IReadOnlyList r = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions { Title = "Pick a mod zip from Nexus", AllowMultiple = false, FileTypeFilter = new[] { new FilePickerFileType("Zip files") { Patterns = new[] { "*.zip" } } }, }); string p = r.Count > 0 ? r[0].TryGetLocalPath() : null; if (p != null) InstallZip(p); } private void InstallZip(string zip) { string e = Mods.Install(zip, game, out KnownMod m); if (e == null) { Message(m.Name + " is installed.", false); if (m != null) pendingZips.Remove(m.Id); } else Message("Couldn't install it: " + e, true); RefreshMods(true); } private void ScanDownloads() { string d = Mods.Downloads; if (d == null || game == null) return; List zips; try { zips = new DirectoryInfo(d).EnumerateFiles("*.zip").OrderByDescending(f => f.LastWriteTimeUtc).Take(150).ToList(); } catch (Exception) { return; } Dictionary best = new(); foreach (FileInfo f in zips) { if (!zipCache.TryGetValue(f.FullName, out var c) || c.size != f.Length || c.time != f.LastWriteTimeUtc) { c = (f.Length, f.LastWriteTimeUtc, Mods.Identify(f.FullName)); zipCache[f.FullName] = c; } if (c.mod == null) continue; if (!best.TryGetValue(c.mod.Id, out var b) || f.LastWriteTimeUtc > b.time) best[c.mod.Id] = (f.FullName, f.LastWriteTimeUtc); } pendingZips.Clear(); foreach (var kv in best) { KnownMod m = Mods.All.First(x => x.Id == kv.Key); if (Mods.SameAsInstalled(game, kv.Value.path, m)) continue; pendingZips[kv.Key] = kv.Value.path; if (announced.Add(kv.Value.path + kv.Value.time.Ticks)) Message("You downloaded " + m.Name + ". Install it from the Install My Mods tab.", false); } } private void RefreshMods(bool force) { if (DateTime.UtcNow >= nextModScan || force) { nextModScan = DateTime.UtcNow.AddSeconds(3); ScanDownloads(); } bool running = Game.GameRunning(); bool bep = Game.BepInstalled(game); 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." : ""; modsNote.IsVisible = modsNote.Text.Length > 0; ScanManagers(false); 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)))); 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; if (key == modsKey && !force) return; modsKey = key; modRows.Children.Clear(); IEnumerable recIds = Mods.Recommended.Select(r => r.id); if (Mods.SteamDeck) recIds = new[] { 1190 }.Concat(recIds.Where(i => i != 1190)); List 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(); foreach (KnownMod m in rec.Concat(Mods.All.Where(x => !rec.Contains(x)))) { bool inst = Mods.Installed(game, m); pendingZips.TryGetValue(m.Id, out string zip); string why = rec.Contains(m) ? Mods.Why(m.Id) : null; TsPackage tp = null; if (tsMods != null && m.Ts != null) tsMods.TryGetValue(m.Ts, out tp); MgrProfile mp = ModManagers.Find(managers, m); string mv = null; if (mp != null && m.Ts != null) mp.Versions.TryGetValue(m.Ts, out mv); bool mgrOld = mp != null && tp != null && mv != null && Thunderstore.Compare(mv, tp.Version) < 0; bool any = inst || mp != null; 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"; IBrush sc = Ui.B(zip != null ? Ui.Orange : inst ? Ui.Good : why != null ? Ui.Warn : Ui.Dim); if (zip == null && mp != null) { string where = mp.Manager + " (" + mp.Name + ")"; if (mgrOld) { status = "Update on Thunderstore: v" + mv + " \u2192 v" + tp.Version + " in " + where; sc = Ui.B(Ui.Orange); } else if (inst) status += ", and in " + where; else { status = "Installed in " + where + (mv != null ? ", v" + mv : ""); sc = Ui.B(Ui.Good); } } else if (zip == null && !any && why == null && tp != null) status = "Not installed \u00b7 v" + tp.Version + " on Thunderstore"; Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; StackPanel info = new() { VerticalAlignment = VerticalAlignment.Center }; info.Children.Add(T(m.Name, 14, Ui.B(Ui.Text), true)); info.Children.Add(T(status, 12, sc, false, true)); g.Children.Add(info); StackPanel btns = new() { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center }; if (zip != null) { Button ib = Btn(inst ? "Update" : "Install", () => InstallZip(zip), true); ib.IsEnabled = bep && !running; btns.Children.Add(ib); } string link = tp != null ? Thunderstore.InstallLink(tp) : null, page = tp?.Url; if (mgrOld && zip == null) btns.Children.Add(Btn("Update", () => OpenTs(mgrHandler != null ? link : page), true)); btns.Children.Add(Btn(any || zip != null ? "Nexus" : "Get on Nexus", () => Game.Open(m.Page + "?tab=files"))); if (tp != null) { if (!any && zip == null && mgrHandler != null) btns.Children.Add(Btn("Get with " + mgrHandler, () => OpenTs(link))); else btns.Children.Add(Btn("Thunderstore", () => OpenTs(page))); } if (inst) { 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); }); rb.IsEnabled = !running; btns.Children.Add(rb); } Grid.SetColumn(btns, 1); g.Children.Add(btns); modRows.Children.Add(new Border { Background = Ui.B(Ui.Sunk), CornerRadius = new CornerRadius(6), Padding = new Thickness(12, 8), Child = g }); } } private readonly Dictionary> optSetters = new(); private readonly TextBlock updStatus = T("Not checked yet.", 13, Ui.B(Ui.Text), false, true); private Button updNow; private readonly TextBlock vtStatus = T("Not checked yet.", 13, Ui.B(Ui.Text), false, true); private readonly TextBlock usageStatus = T("Not counted yet.", 13, Ui.B(Ui.Text), false, true); private ToggleButton usageSwitch; private bool usageBusy, vtBusy, updateFlagOk; private readonly TextBlock vtDetail = T("Engine breakdown: not checked yet.", 13, Ui.B(Ui.Dim), false, true); private readonly TextBlock vtNewest = T("Checking for updates...", 13, Ui.B(Ui.Text), false, true); 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"; private Control VirusTotalPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) }; Border vs = Section("THIS VERSION", out StackPanel vb); vb.Children.Add(vtStatus); vb.Children.Add(vtDetail); WrapPanel vw = new(); 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); vo.Margin = new Thickness(0, 4, 6, 0); vw.Children.Add(vo); Button va = Btn("Check Again", () => _ = CheckVirusTotal(true)); va.Margin = new Thickness(0, 4, 0, 0); vw.Children.Add(va); vb.Children.Add(vw); 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)); c0.Children.Add(vs); Border ns = Section("NEWEST VERSION", out StackPanel nb); nb.Children.Add(vtNewest); 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)); c0.Children.Add(ns); g.Children.Add(c0); StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) }; Border ws = Section("WHAT IT IS", out StackPanel wb); 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)); c1.Children.Add(ws); Border ms = Section("WHAT THE NUMBERS MEAN", out StackPanel mb); 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)); c1.Children.Add(ms); Grid.SetColumn(c1, 1); g.Children.Add(c1); StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) }; Border ys = Section("WHY TRAINERS GET FLAGGED", out StackPanel yb); 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)); c2.Children.Add(ys); Border os = Section("ON NEXUS", out StackPanel ob); 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)); ob.Children.Add(Btn("Nexus Page", () => Game.Open(Nexus.PageUrl))); c2.Children.Add(os); Grid.SetColumn(c2, 2); g.Children.Add(c2); return Scroll(g); } private async Task CheckVirusTotal(bool manual) { if (vtBusy) return; vtBusy = true; vtStatus.Text = "Checking VirusTotal..."; try { VtResult v = await VirusTotal.ForThisVersion(); VirusTotal.Self = v; vtStatus.Text = "v" + Program.Version + ". " + v.Line; vtDetail.Text = v.Detail; if (v.Status == "queued") DispatcherTimer.RunOnce(() => _ = CheckVirusTotal(false), TimeSpan.FromSeconds(90)); if (manual) Message(v.Line, v.Status == "done" && v.Flagged > 0); } catch (Exception) { vtStatus.Text = "VirusTotal: couldn't reach the update server. Try Check Again later."; if (manual) Message("Couldn't reach the update server.", true); } vtBusy = false; } private async Task UsageNotice() { if (Settings.Get("notice.usage", "0") == "1") return; bool yes = false; Window w = new() { Title = Program.Name + " - User count", Width = 460, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner, Background = Ui.B(Ui.Back), }; StackPanel sp = new() { Margin = new Thickness(20), Spacing = 12 }; 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 }); 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) }); 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) }); 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) }); StackPanel row = new() { Orientation = Orientation.Horizontal, Spacing = 8, HorizontalAlignment = HorizontalAlignment.Right }; Button no = new() { Content = "No thanks", Padding = new Thickness(16, 6) }; no.Click += (_, _) => w.Close(); Button ok = new() { Content = "Yes, count me", Padding = new Thickness(20, 6), Background = Ui.B(Ui.Orange), Foreground = Ui.B(Ui.OnAccent) }; ok.Click += (_, _) => { yes = true; w.Close(); }; row.Children.Add(no); row.Children.Add(ok); sp.Children.Add(row); w.Content = sp; await w.ShowDialog(this); Settings.Set("notice.usage", "1"); Settings.Set("usage", yes ? "1" : "0"); if (usageSwitch != null) usageSwitch.IsChecked = yes; await UsageTick(); } private void StartUsage() { _ = CheckVirusTotal(false); if (Settings.Get("notice.usage", "0") == "1") _ = UsageTick(); DispatcherTimer t = new() { Interval = TimeSpan.FromHours(1) }; t.Tick += (_, _) => _ = UsageTick(); t.Start(); } private readonly TextBlock usageBoard = T("Loading...", 13, Ui.B(Ui.Text), false, true); private bool boardBusy; private async Task RefreshBoard() { if (boardBusy) return; boardBusy = true; string s = null; try { s = await Usage.Stats(); } catch (Exception) { } boardBusy = false; if (s != null) usageBoard.Text = s; else if (usageBoard.Text == "Loading...") usageBoard.Text = "Couldn't reach the update server. Tries again in an hour."; } private async Task UsageTick() { if (usageBusy || Settings.Get("notice.usage", "0") != "1") { await RefreshBoard(); return; } if (!Settings.On("usage", true)) { 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."; await RefreshBoard(); return; } usageBusy = true; string id = Settings.Get("usage.id", ""); if (!Usage.ValidId(id)) { id = Usage.NewId(); Settings.Set("usage.id", id); } string day = Usage.Day.ToString(CultureInfo.InvariantCulture); try { if (Settings.Get("usage.day", "") != day && await Usage.Ping(id)) Settings.Set("usage.day", day); } catch (Exception) { } string count = null; try { count = await Usage.Count(); } catch (Exception) { } usageBusy = false; await RefreshBoard(); if (!Settings.On("usage", true)) return; usageStatus.Text = count != null ? count + " You're counted." : "Couldn't reach the server. You're counted once it's back."; } private void UsageToggled(bool on) { Settings.Set("usage", on ? "1" : "0"); Settings.Set("notice.usage", "1"); if (on) { Message("Thanks! You're counted as a user.", false); _ = UsageTick(); return; } Message("You're no longer counted.", false); string id = Settings.Get("usage.id", ""); Settings.Set("usage.id", null); Settings.Set("usage.day", null); usageStatus.Text = "You're not counted. Asking the server to delete what this computer sent..."; _ = Task.Run(async () => { bool ok = false; try { ok = await Usage.Forget(id); } catch (Exception) { } 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."); }); } private ToggleButton Switch(string name, string hint, bool on, Action changed) { ToggleSwitch tb = new() { OnContent = name, OffContent = name, IsChecked = on, HorizontalAlignment = HorizontalAlignment.Stretch, MinHeight = 34 }; if (hint != null) ToolTip.SetTip(tb, hint); tb.Click += (_, _) => changed(tb.IsChecked == true); return tb; } private void PluginOpt(StackPanel host, string key, string name, string hint) { ToggleButton tb = null; tb = Switch(name, hint, true, on => { if (!Linked()) { tb.IsChecked = !on; return; } link.Send("OPT " + key + (on ? " 1" : " 0")); }); optSetters[key] = v => tb.IsChecked = v; host.Children.Add(tb); } private Control TrainerPage() { Grid g = new() { ColumnDefinitions = new ColumnDefinitions("*,*,*") }; StackPanel c0 = new() { Margin = new Thickness(0, 0, 7, 0) }; Border ts = Section("SETTINGS", out StackPanel tb); 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"))); Button testBark = Btn("Test Bark", () => { string why = Bark.Play(true); Message(why ?? "Woof.", why != null); }); testBark.Margin = new Thickness(0, 4, 0, 6); testBark.HorizontalAlignment = HorizontalAlignment.Left; tb.Children.Add(testBark); 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"))); 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"))); tb.Children.Add(Btn("Start Game", () => StartGame())); tb.Children.Add(Btn("Switch Everything Off", () => { if (Linked()) link.Send("ACT alloff"); })); tb.Children.Add(Btn("Reset All Keys", () => { if (!Linked()) return; foreach (CTab t in tabs) foreach (CSection s in t.Sections) foreach (COpt o in s.Rows) if (o.Kind == CKind.Toggle || o.Kind == CKind.Action) link.Send("BIND " + o.Id + " " + (o.Key.Length > 0 ? o.Key : "none")); link.Send("BIND menu " + Cheats.MenuKey); link.Send("BIND overlay " + Cheats.OverlayKey); Message("Keys reset.", false); })); c0.Children.Add(ts); Border gs = Section("IN GAME", out StackPanel gb); Grid ov = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; StackPanel ovs = new(); PluginOpt(ovs, "overlay", "In-Game Overlay", "Shows what's on in the top-left corner of the game."); ovs.Margin = new Thickness(0, 0, 6, 0); ov.Children.Add(ovs); Button ok = KeyButton("overlay"); Grid.SetColumn(ok, 1); ov.Children.Add(ok); gb.Children.Add(ov); Grid mk = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto") }; TextBlock mt = T("In-Game Menu Key", 13, Ui.B(Ui.Text)); mt.VerticalAlignment = VerticalAlignment.Center; mk.Children.Add(mt); Button mkb = KeyButton("menu"); Grid.SetColumn(mkb, 1); mk.Children.Add(mkb); gb.Children.Add(mk); PluginOpt(gb, "pause", "Pause the Game While the Menu Is Open", "Stops time while you pick cheats in the in-game menu."); PluginOpt(gb, "remember", "Remember My Cheats", "The cheats you had on switch back on the next time you start the game."); 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)); c0.Children.Add(gs); g.Children.Add(c0); StackPanel c1 = new() { Margin = new Thickness(7, 0, 7, 0) }; Border us = Section("UPDATES", out StackPanel ub); ub.Children.Add(updStatus); WrapPanel uw = new(); Button chk = Btn("Check Now", () => _ = CheckUpdate(true)); chk.Margin = new Thickness(0, 0, 6, 0); uw.Children.Add(chk); updNow = Btn("Update Now", () => _ = DoUpdate(), true); updNow.IsEnabled = false; uw.Children.Add(updNow); ub.Children.Add(uw); 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"))); 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"))); 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"))); 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)); c1.Children.Add(us); Border cs = Section("USER COUNT", out StackPanel cbody); cbody.Children.Add(usageStatus); usageSwitch = Switch("Count Me as a User", null, Settings.On("usage", true), on => UsageToggled(on)); cbody.Children.Add(usageSwitch); 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)); c1.Children.Add(cs); Border ps = Section("THIS PC", out StackPanel pb); pb.Children.Add(installStatus); CheckBox sc = new() { Content = "Also put a shortcut on my desktop", IsChecked = true }; pb.Children.Add(sc); WrapPanel pw = new(); installBtn = Btn("Install", () => DoInstall(sc.IsChecked == true), true); installBtn.Margin = new Thickness(0, 0, 6, 0); pw.Children.Add(installBtn); pw.Children.Add(Btn("Uninstall", () => _ = DoUninstall())); pb.Children.Add(pw); 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)); c1.Children.Add(ps); RefreshInstall(); Grid.SetColumn(c1, 1); g.Children.Add(c1); StackPanel c2 = new() { Margin = new Thickness(7, 0, 0, 0) }; Border abs = Section("ABOUT", out StackPanel ab); 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)); ab.Children.Add(Btn("Nexus Page", () => Game.Open(Nexus.PageUrl))); ab.Children.Add(T("To uninstall: curl -fsSL https://updates.smellypawz.com/linux | bash -s -- --uninstall", 12, Ui.B(Ui.Dim), false, true)); c2.Children.Add(abs); Grid.SetColumn(c2, 2); g.Children.Add(c2); return Scroll(g); } private readonly TextBlock installStatus = T("", 13, Ui.B(Ui.Text), false, true); private Button installBtn; private void RefreshInstall() { installStatus.Text = Setup.Status(); installBtn.Content = Setup.RunningInstalled ? "Repair Install" : Setup.Installed ? "Install This Copy" : "Install"; installBtn.IsEnabled = !OperatingSystem.IsWindows() && !Mac.On; } private void DoInstall(bool shortcut) { string e = Setup.Install(shortcut); if (e != null) { Message("Couldn't install it: " + e, true); RefreshInstall(); return; } if (Setup.RunningInstalled) { Message("Install repaired.", false); RefreshInstall(); return; } Message("Installed. Opening the installed copy...", false); link.RemoveLinkFile(); Setup.OpenInstalled(); Close(); } private async Task DoUninstall() { UninstallDialog d = new(); await d.ShowDialog(this); if (!d.Confirmed) return; string e = Setup.Uninstall(game, d.Plugin, d.Settings_); if (e != null) { Message("Couldn't uninstall: " + e, true); RefreshInstall(); return; } link.RemoveLinkFile(); Message("Uninstalled.", false); if (Setup.RunningInstalled || !File.Exists(Environment.ProcessPath ?? "")) { Close(); return; } Message("Uninstalled. This copy is still in " + Path.GetDirectoryName(Environment.ProcessPath) + "; delete that folder to remove it too.", false); RefreshInstall(); } private async Task CheckUpdate(bool manual) { updStatus.Text = "Checking..."; try { UpdateInfo u = await Updater.Check(); Updater.Ready = u; 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); updNow.IsEnabled = u != null; vtNewest.Text = u == null ? "You have the newest version, so the result above is the newest one." : "v" + u.Version + " is out. " + u.VtLine; updateFlagOk = false; if (u != null) Message("Version " + u.Version + " is out. Update it from the Settings tab.", false); } catch (Exception) { updStatus.Text = "Couldn't reach the update server."; if (manual) Message("Couldn't reach the update server.", true); } } private async Task DoUpdate() { UpdateInfo u = Updater.Ready; if (u == null) return; 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; } if (u.VtFlagged && !updateFlagOk) { updateFlagOk = true; updStatus.Text = u.VtLine + "\nLook at the report first (" + u.Vt.Link + "). Click Update Now again to install it anyway."; Message("VirusTotal flagged v" + u.Version + ". Click Update Now again to install it anyway.", true); return; } updNow.IsEnabled = false; string e = await Updater.Install(u, pc => Dispatcher.UIThread.Post(() => updStatus.Text = "Downloading v" + u.Version + "... " + pc + "%")); if (e == null) { Close(); return; } updStatus.Text = "Couldn't update: " + e; updNow.IsEnabled = true; } } }