using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Platform.Storage; using Avalonia.Styling; using Path = System.IO.Path; namespace UltraParadise.Linux { internal static class Monitors { public static int Count(TopLevel t) { try { return t?.Screens?.All.Count ?? 1; } catch (Exception) { return 1; } } public static string Name(TopLevel t, Screen s) { int i = 0; try { i = t.Screens.All.ToList().IndexOf(s); } catch (Exception) { } return "Screen " + (i + 1) + " (" + s.Bounds.Width + "x" + s.Bounds.Height + (s.IsPrimary ? ", main" : "") + ")"; } public static Screen Spare(Window w) { IReadOnlyList all = w.Screens.All; if (all.Count < 2) return null; Screen game = all.FirstOrDefault(s => s.IsPrimary) ?? all[0]; Screen mine = w.Screens.ScreenFromWindow(w); Screen best = null; foreach (Screen s in all) { if (s.Equals(game)) continue; if (best == null || (long)s.Bounds.Width * s.Bounds.Height > (long)best.Bounds.Width * best.Bounds.Height) best = s; } if (best != null && mine != null && best.Equals(mine)) { int i = all.ToList().IndexOf(mine); Screen next = all[(i + 1) % all.Count]; if (!next.Equals(game)) best = next; } return best; } public static void MoveTo(Window w, Screen s, bool fill) { if (w == null || s == null) return; bool max = w.WindowState == WindowState.Maximized; if (w.WindowState != WindowState.Normal) w.WindowState = WindowState.Normal; PixelRect wa = s.WorkingArea; double sc = s.Scaling <= 0 ? 1 : s.Scaling; double aw = wa.Width / sc, ah = wa.Height / sc; double ww = Math.Min(double.IsNaN(w.Width) ? w.Bounds.Width : w.Width, aw), hh = Math.Min(double.IsNaN(w.Height) ? w.Bounds.Height : w.Height, ah); if (fill) { ww = Math.Min(aw, Math.Max(ww, aw * 0.8)); hh = Math.Min(ah, Math.Max(hh, ah * 0.8)); } w.Width = ww; w.Height = hh; w.Position = new PixelPoint(wa.X + (int)((wa.Width - ww * sc) / 2), wa.Y + (int)((wa.Height - hh * sc) / 2)); if (max) w.WindowState = WindowState.Maximized; } public static string Advice(TopLevel t) { int n = Count(t); if (n < 2) return "Only one screen found. A second screen is recommended, see below."; return n + " screens found. The trainer treats your main screen as the game's screen."; } } internal sealed class DLine { public string Time, Kind, Text; public bool First; } internal sealed class DebugWindow : Window { public const char NL = '\u001e', REC = '\u001d', SEP = '\u001c'; public Action Live; public Action Say; public bool Quitting; private readonly ObservableCollection shown = new(); private readonly List all = new(); private readonly ListBox log = new(); private readonly StackPanel statusPanel = new(); private readonly List statusRows = new(); private readonly TextBlock state = new() { FontSize = 13, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center, TextTrimming = TextTrimming.CharacterEllipsis }; private readonly TextBox find = new() { Width = 220, Watermark = "Find", VerticalAlignment = VerticalAlignment.Center }; private readonly Dictionary filters = new(); private Button pauseBtn, pinBtn, otherBtn; private string snap = "", sys = ""; private bool paused, linked, dirty; private DateTime lastSnap = DateTime.MinValue; private StreamWriter file; private readonly FontFamily mono = new("Cascadia Mono, DejaVu Sans Mono, Liberation Mono, Noto Sans Mono, monospace"); private readonly IBrush bText = Ui.B(Ui.Text), bDim = Ui.B(Ui.Dim), bOrange = Ui.B(Ui.Orange), bGood = Ui.B(Ui.Good), bWarn = Ui.B(Ui.Warn), bBad = Ui.B(Ui.Bad), bBright = Ui.B(Ui.Bright), bCard = Ui.B(Ui.Card), bSunk = Ui.B(Ui.Sunk), bLine = Ui.B(Ui.Line); private static readonly string[] FilterNames = { "Game log", "Warnings", "Errors", "Events", "Trainer", "Commands" }; private static readonly string[][] FilterKinds = { new[] { "GAME", "SCENE", "SYSTEM", "BEPINEX" }, new[] { "WARNING" }, new[] { "ERROR" }, new[] { "EVENT", "LIMB", "GOOD", "ALERT" }, new[] { "TRAINER" }, new[] { "COMMAND" } }; public static string LogPath => Path.Combine(Dirs.Cache, "debug.log"); public DebugWindow() { Title = "Ultra Paradise - Debug"; Width = 1100; Height = 680; MinWidth = 640; MinHeight = 380; Background = Ui.B(Ui.Back); FontFamily = Ui.Font; WindowStartupLocation = WindowStartupLocation.CenterScreen; Avalonia.Media.Imaging.Bitmap icon = Program.Image("icon.png"); if (icon != null) Icon = new WindowIcon(icon); Grid root = new() { RowDefinitions = new RowDefinitions("Auto,Auto,*") }; Grid top = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Background = Ui.B(Ui.Side), Margin = new Thickness(0) }; state.Margin = new Thickness(14, 0, 10, 0); top.Children.Add(state); StackPanel btns = new() { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 8, 10, 8) }; otherBtn = Btn("Other Screen", MoveToOther); pinBtn = Btn("Pin on Top", () => { Topmost = !Topmost; Paint(pinBtn, Topmost); }); pauseBtn = Btn("Pause", () => SetPaused(!paused)); btns.Children.Add(otherBtn); btns.Children.Add(pinBtn); btns.Children.Add(pauseBtn); btns.Children.Add(Btn("Clear", () => { all.Clear(); shown.Clear(); })); btns.Children.Add(Btn("Copy", () => _ = CopyAll())); btns.Children.Add(Btn("Save...", () => _ = SaveLog())); btns.Children.Add(Btn("Log Folder", () => Game.Open(Path.GetDirectoryName(LogPath)))); Grid.SetColumn(btns, 1); top.Children.Add(btns); root.Children.Add(top); Grid bar = new() { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Background = Ui.B(Ui.Card) }; WrapPanel fl = new() { Margin = new Thickness(12, 4, 0, 4) }; foreach (string n in FilterNames) { CheckBox c = new() { Content = n, IsChecked = true, Margin = new Thickness(0, 0, 14, 0) }; c.IsCheckedChanged += (_, _) => Refilter(); filters[n] = c; fl.Children.Add(c); } bar.Children.Add(fl); find.Margin = new Thickness(0, 4, 12, 4); find.TextChanged += (_, _) => Refilter(); Grid.SetColumn(find, 1); bar.Children.Add(find); Grid.SetRow(bar, 1); root.Children.Add(bar); Grid body = new() { ColumnDefinitions = new ColumnDefinitions("46*,6,54*") }; body.Children.Add(Pane("LIVE STATUS", new ScrollViewer { Content = statusPanel, HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, Padding = new Thickness(10, 4) })); GridSplitter sp = new() { Background = Ui.B(Ui.Line), ResizeDirection = GridResizeDirection.Columns }; Grid.SetColumn(sp, 1); body.Children.Add(sp); log.ItemsSource = shown; log.SelectionMode = SelectionMode.Multiple; log.Background = bCard; log.ItemTemplate = new FuncDataTemplate((l, _) => Row(l)); log.Styles.Add(new Style(x => x.OfType()) { Setters = { new Setter(ListBoxItem.PaddingProperty, new Thickness(8, 1)), new Setter(ListBoxItem.MinHeightProperty, 0d) }, }); ScrollViewer.SetHorizontalScrollBarVisibility(log, ScrollBarVisibility.Auto); Control lp = Pane("LIVE FEED", log); Grid.SetColumn(lp, 2); body.Children.Add(lp); Grid.SetRow(body, 2); root.Children.Add(body); Content = root; KeyDown += (_, e) => { if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.C && log.SelectedItems != null && log.SelectedItems.Count > 0) { _ = CopySelected(); e.Handled = true; } else if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.F) { find.Focus(); e.Handled = true; } else if (e.Key == Key.F5) { SetPaused(!paused); e.Handled = true; } }; Opened += (_, _) => { otherBtn.IsVisible = Monitors.Count(this) > 1; OpenFile(); }; Activated += (_, _) => otherBtn.IsVisible = Monitors.Count(this) > 1; Closing += (_, e) => { if (Quitting) return; e.Cancel = true; Hide(); }; Closed += (_, _) => { try { file?.Dispose(); } catch (Exception) { } file = null; }; PropertyChanged += (_, e) => { if (e.Property == IsVisibleProperty) { bool v = IsVisible; Live?.Invoke(v); if (v) { OpenFile(); if (dirty) { RebuildStatus(); Refilter(); } } else try { file?.Flush(); } catch (Exception) { } } }; Avalonia.Threading.DispatcherTimer t = new() { Interval = TimeSpan.FromSeconds(1) }; t.Tick += (_, _) => { try { file?.Flush(); } catch (Exception) { } UpdateState(); }; t.Start(); SetLinked(false); } private Control Pane(string title, Control content) { Grid g = new() { RowDefinitions = new RowDefinitions("Auto,*") }; StackPanel head = new() { Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(12, 10, 0, 6) }; head.Children.Add(new Border { Width = 3, Height = 13, CornerRadius = new CornerRadius(2), Background = bOrange, VerticalAlignment = VerticalAlignment.Center }); head.Children.Add(new TextBlock { Text = string.Join(" ", title.ToCharArray()), FontSize = 11, FontWeight = FontWeight.Bold, Foreground = bOrange }); g.Children.Add(head); Border b = new() { Background = bCard, Child = content }; Grid.SetRow(b, 1); g.Children.Add(b); return g; } private static Button Btn(string text, Action click) { Button b = new() { Content = text, Padding = new Thickness(12, 5), MinHeight = 30, CornerRadius = new CornerRadius(6) }; b.Click += (_, _) => click(); return b; } private static void Paint(Button b, bool on) { if (on) { b.Background = Ui.B(Ui.Orange); b.Foreground = Ui.B(Ui.OnAccent); } else { b.ClearValue(BackgroundProperty); b.ClearValue(ForegroundProperty); } } private IBrush KindBrush(string k) => k switch { "ERROR" or "ALERT" => bBad, "WARNING" or "LIMB" => bWarn, "EVENT" or "SCENE" => bOrange, "GOOD" => bGood, "TRAINER" or "COMMAND" => bBright, _ => bText, }; private Control Row(DLine l) { if (l == null) return new TextBlock(); IBrush kc = KindBrush(l.Kind); IBrush tc = l.Kind is "GAME" or "BEPINEX" or "SYSTEM" ? bText : (!l.First && l.Kind == "ERROR" ? bDim : kc); TextBlock tb = new() { FontFamily = mono, FontSize = 12, TextWrapping = TextWrapping.NoWrap }; tb.Inlines = new InlineCollection { new Run((l.First ? l.Time : new string(' ', l.Time.Length)) + " ") { Foreground = bDim }, new Run((l.First ? l.Kind : "").PadRight(8) + " ") { Foreground = kc, FontWeight = FontWeight.Bold }, new Run(l.Text) { Foreground = tc }, }; if (l.First && (l.Kind == "ERROR" || l.Kind == "ALERT")) return new Border { Background = bSunk, Child = tb }; return tb; } private void OpenFile() { if (file != null) return; try { Private.Dir(Path.GetDirectoryName(LogPath)); file = new StreamWriter(LogPath, false, new UTF8Encoding(false)); file.WriteLine("Ultra Paradise CU:Trainer v" + Program.Version + " (" + Program.Platform + ") debug log, started " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); } catch (Exception) { file = null; } } public void MoveToOther() { Screen s = Monitors.Spare(this); if (s == null) { Say?.Invoke("Only one screen is plugged in.", false); return; } Monitors.MoveTo(this, s, true); } public void SetLinked(bool on) { linked = on; if (!on) { snap = ""; RebuildStatus(); } UpdateState(); } private void SetPaused(bool p) { paused = p; pauseBtn.Content = p ? "Resume" : "Pause"; Paint(pauseBtn, p); if (!p) { Refilter(); if (dirty) RebuildStatus(); } UpdateState(); } private void UpdateState() { string t; IBrush c; if (!linked) { t = "Not attached. Start the game and let the trainer attach, then everything shows up here."; c = bDim; } else if (paused) { t = "Paused. New lines are still saved. Press Resume (F5) to catch up."; c = bWarn; } else if ((DateTime.UtcNow - lastSnap).TotalSeconds > 4) { t = "Attached. Waiting for the game (it sends nothing while it's loading)."; c = bWarn; } else { int n = Monitors.Count(this); t = "Live · " + all.Count + " lines" + (n > 1 ? " · " + n + " screens" : ""); c = bGood; } state.Text = t; state.Foreground = c; } public void OnSnapshot(string text) { snap = text; lastSnap = DateTime.UtcNow; dirty = true; if (!paused && IsVisible) RebuildStatus(); UpdateState(); } public void OnSystem(string text) { sys = text; dirty = true; if (!paused && IsVisible) RebuildStatus(); } private List StatusLines() { List lines = new(); if (snap.Length == 0) lines.Add(linked ? "DWaiting for the first update from the game..." : "DNothing yet. Attach to the game to see its live status."); else lines.AddRange(snap.Split(NL)); if (sys.Length > 0) { lines.Add("N"); lines.AddRange(sys.Split(NL)); } return lines; } private void RebuildStatus() { dirty = false; List lines = StatusLines(); while (statusRows.Count < lines.Count) { SelectableTextBlock tb = new() { FontFamily = mono, FontSize = 12, TextWrapping = TextWrapping.NoWrap }; statusRows.Add(tb); statusPanel.Children.Add(tb); } for (int i = 0; i < statusRows.Count; i++) { SelectableTextBlock tb = statusRows[i]; if (i >= lines.Count) { tb.IsVisible = false; continue; } tb.IsVisible = true; string s = lines[i]; char code = s.Length > 0 ? s[0] : 'N'; string text = s.Length > 1 ? s[1..] : ""; if (tb.Text != text) tb.Text = text; tb.Foreground = code switch { 'H' => bOrange, 'D' => bDim, 'G' => bGood, 'Y' => bWarn, 'R' => bBad, _ => bText }; tb.FontWeight = code == 'H' || code == 'R' ? FontWeight.Bold : FontWeight.Normal; tb.Margin = new Thickness(0, code == 'H' && i > 0 ? 8 : 0, 0, 0); } } public void OnLog(string batch) { string now = DateTime.Now.ToString("HH:mm:ss.fff"); List fresh = new(); foreach (string rec in batch.Split(REC)) { int s = rec.IndexOf(SEP); if (s <= 0) continue; string kind = rec[..s]; string[] parts = rec[(s + 1)..].Split(NL); for (int i = 0; i < parts.Length; i++) { if (i > 0 && i == parts.Length - 1 && parts[i].Length == 0) break; fresh.Add(new DLine { Time = now, Kind = kind, Text = parts[i], First = i == 0 }); try { file?.WriteLine((i == 0 ? now + " [" + kind + "] " : new string(' ', now.Length + kind.Length + 4)) + SysInfo.Scrub(parts[i])); } catch (Exception) { } } } if (fresh.Count == 0) return; all.AddRange(fresh); if (all.Count > 30000) all.RemoveRange(0, all.Count - 25000); if (paused || !IsVisible) { dirty = true; return; } bool follow = AtBottom(); foreach (DLine l in fresh) if (Passes(l)) shown.Add(l); if (shown.Count > 8000) { for (int i = 0; i < 1000; i++) shown.RemoveAt(0); } if (follow && shown.Count > 0 && (log.SelectedItems == null || log.SelectedItems.Count == 0)) log.ScrollIntoView(shown.Count - 1); } private bool AtBottom() { IScrollable sv = log.Scroll; if (sv == null) return true; return sv.Offset.Y + sv.Viewport.Height >= sv.Extent.Height - 30; } private bool Passes(DLine l) { bool known = false, ok = true; for (int i = 0; i < FilterNames.Length; i++) { if (Array.IndexOf(FilterKinds[i], l.Kind) < 0) continue; known = true; ok = filters[FilterNames[i]].IsChecked == true; break; } if (known && !ok) return false; string q = (find.Text ?? "").Trim(); return q.Length == 0 || l.Text.Contains(q, StringComparison.OrdinalIgnoreCase) || l.Kind.Contains(q, StringComparison.OrdinalIgnoreCase); } private void Refilter() { if (paused) return; List keep = new(); for (int i = all.Count - 1; i >= 0 && keep.Count < 7000; i--) if (Passes(all[i])) keep.Add(all[i]); keep.Reverse(); shown.Clear(); foreach (DLine l in keep) shown.Add(l); if (shown.Count > 0) log.ScrollIntoView(shown.Count - 1); } private static string Prefix(DLine l) => l.Time + " " + (l.First ? l.Kind.PadRight(8) : new string(' ', 8)) + " "; private string StatusText() { StringBuilder sb = new(); foreach (string s in StatusLines()) { if (s.Length == 0) continue; sb.Append(s[0] == 'H' ? "== " + s[1..] + " ==" : s[1..]).Append('\n'); } return sb.ToString(); } private async Task CopySelected() { StringBuilder sb = new(); foreach (object o in log.SelectedItems) if (o is DLine l) sb.Append(Prefix(l)).Append(l.Text).Append('\n'); if (Clipboard != null && sb.Length > 0) await Clipboard.SetTextAsync(SysInfo.Scrub(sb.ToString())); } private async Task CopyAll() { StringBuilder sb = new(); sb.Append("=== Ultra Paradise CU:Trainer v").Append(Program.Version).Append(" (").Append(Program.Platform).Append(") debug ===\n\n"); sb.Append(StatusText()); sb.Append("\n=== Live feed ===\n"); bool sel = log.SelectedItems != null && log.SelectedItems.Count > 0; if (sel) foreach (object o in log.SelectedItems) { if (o is DLine l) sb.Append(Prefix(l)).Append(l.Text).Append('\n'); } else for (int i = Math.Max(0, shown.Count - 500); i < shown.Count; i++) sb.Append(Prefix(shown[i])).Append(shown[i].Text).Append('\n'); if (Clipboard == null) { Say?.Invoke("Couldn't reach the clipboard. Try Save.", true); return; } await Clipboard.SetTextAsync(SysInfo.Scrub(sb.ToString())); Say?.Invoke("Copied the status and " + (sel ? "the selected lines" : "the last " + Math.Min(500, shown.Count) + " lines") + ".", false); } private async Task SaveLog() { IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions { Title = "Save the debug log", SuggestedFileName = "UltraParadise-debug-" + DateTime.Now.ToString("yyyyMMdd-HHmm") + ".txt", DefaultExtension = "txt", }); string p = f?.TryGetLocalPath(); if (p == null) return; try { StringBuilder sb = new(); sb.Append("=== Ultra Paradise CU:Trainer v").Append(Program.Version).Append(" (").Append(Program.Platform).Append(") debug, saved ").Append(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Append(" ===\n\n"); sb.Append(StatusText()); sb.Append("\n=== Live feed (").Append(all.Count).Append(" lines) ===\n"); foreach (DLine l in all) sb.Append(Prefix(l)).Append(l.Text).Append('\n'); File.WriteAllText(p, SysInfo.Scrub(sb.ToString()), new UTF8Encoding(false)); Say?.Invoke("Saved " + Path.GetFileName(p) + ".", false); } catch (Exception e) { Say?.Invoke("Couldn't save it: " + e.Message, true); } } } }