casualexpiesource

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

346 lines · 17.4 KB · plain text · download

1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Globalization;
5using System.IO;
6using System.Linq;
7using System.Runtime.InteropServices;
8using System.Text;
9using System.Threading.Tasks;
10using Avalonia;
11using Avalonia.Controls;
12using Avalonia.Controls.Primitives;
13using Avalonia.Layout;
14using Avalonia.Media;
15using Avalonia.Platform.Storage;
16using Avalonia.Threading;
17using Path = System.IO.Path;
18
19namespace UltraParadise.Linux
20{
21 internal static class SysInfo
22 {
23 private static string Read(string f)
24 {
25 try { return File.Exists(f) ? File.ReadAllText(f).Trim() : null; } catch (Exception) { return null; }
26 }
27
28 private static string Run(string exe, params string[] args)
29 {
30 try
31 {
32 ProcessStartInfo si = new(exe) { RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };
33 foreach (string a in args) si.ArgumentList.Add(a);
34 using Process p = Process.Start(si);
35 string o = p.StandardOutput.ReadToEnd();
36 if (!p.WaitForExit(4000)) { try { p.Kill(); } catch (Exception) { } return null; }
37 return o;
38 }
39 catch (Exception) { return null; }
40 }
41
42 public static List<(string label, string value)> Collect(string game)
43 {
44 List<(string, string)> o = new();
45 o.Add(("Trainer", Program.Name + " v" + Program.Version + " (" + Program.Platform + " app, " + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant() + ")"));
46 if (OperatingSystem.IsWindows())
47 {
48 o.Add(("System", RuntimeInformation.OSDescription + " (" + RuntimeInformation.OSArchitecture + ")"));
49 }
50 else if (Mac.On)
51 {
52 string name = Run("/usr/bin/sw_vers", "-productName")?.Trim(), ver = Run("/usr/bin/sw_vers", "-productVersion")?.Trim();
53 o.Add(("macOS", ((name ?? "macOS") + " " + (ver ?? "?")).Trim()));
54 o.Add(("Kernel", Run("/usr/bin/uname", "-r")?.Trim() ?? RuntimeInformation.OSDescription));
55 string model = Sysctl("hw.model");
56 if (model != null) o.Add(("Model", model));
57 }
58 else
59 {
60 string pretty = null;
61 string rel = Read("/etc/os-release");
62 if (rel != null)
63 foreach (string line in rel.Split('\n'))
64 if (line.StartsWith("PRETTY_NAME=", StringComparison.Ordinal)) pretty = line[12..].Trim('"');
65 o.Add(("Distro", pretty ?? "Unknown Linux"));
66 o.Add(("Kernel", Read("/proc/sys/kernel/osrelease") ?? RuntimeInformation.OSDescription));
67 string vendor = Read("/sys/devices/virtual/dmi/id/sys_vendor"), product = Read("/sys/devices/virtual/dmi/id/product_name"), board = Read("/sys/devices/virtual/dmi/id/board_vendor");
68 if (board == "Valve" || vendor == "Valve") o.Add(("Device", "Steam Deck (" + (product == "Galileo" ? "OLED" : product == "Jupiter" ? "LCD" : product ?? "?") + ")"));
69 else if (vendor != null || product != null) o.Add(("Device", ((vendor ?? "") + " " + (product ?? "")).Trim()));
70 string desk = Environment.GetEnvironmentVariable("XDG_CURRENT_DESKTOP"), sess = Environment.GetEnvironmentVariable("XDG_SESSION_TYPE");
71 if (desk != null || sess != null) o.Add(("Desktop", ((desk ?? "?") + " (" + (sess ?? "?") + ")")));
72 }
73 o.Add(("CPU", Cpu()));
74 o.Add(("RAM", Ram()));
75 foreach (string g in Gpus()) o.Add(("GPU", g));
76 if (game != null)
77 {
78 o.Add(("BepInEx", Game.BepInstalled(game) ? Game.BepVersion + (Game.BepRan(game) ? "" : " (hasn't run yet)") : "not installed"));
79 o.Add(("Plugin", Game.PluginState(game)));
80 o.Add((Mac.On ? "Wine setting" : "Launch option", Game.LaunchOptionState()));
81 if (Mac.On) o.Add(("Wine", Mac.WineVersion(game)));
82 string proton = Mac.On ? null : Proton(game);
83 if (proton != null) o.Add(("Proton", proton));
84 List<string> mods = Mods.All.Where(m => Mods.Installed(game, m)).Select(m => m.Name).ToList();
85 if (Game.OtherCheats(game) != null && !mods.Contains("CU Cheats - Ultra Paradise")) mods.Add("CU Cheats");
86 o.Add(("Other mods", mods.Count == 0 ? "none of casualexpie's" : string.Join(", ", mods)));
87 }
88 else o.Add(("Game", "not found"));
89 return o;
90 }
91
92 private static string Sysctl(string key)
93 {
94 string v = Run("/usr/sbin/sysctl", "-n", key)?.Trim();
95 return string.IsNullOrEmpty(v) ? null : v;
96 }
97
98 private static string Cpu()
99 {
100 if (OperatingSystem.IsWindows()) return (Environment.GetEnvironmentVariable("PROCESSOR_IDENTIFIER") ?? "?") + ", " + Environment.ProcessorCount + " threads";
101 if (Mac.On) return (Sysctl("machdep.cpu.brand_string") ?? "?") + ", " + Environment.ProcessorCount + " cores";
102 string c = Read("/proc/cpuinfo");
103 string model = c?.Split('\n').FirstOrDefault(l => l.StartsWith("model name", StringComparison.Ordinal))?.Split(':', 2)[1].Trim();
104 return (model ?? "?") + ", " + Environment.ProcessorCount + " threads";
105 }
106
107 private static string Ram()
108 {
109 long bytes = 0;
110 if (OperatingSystem.IsWindows()) bytes = GC.GetGCMemoryInfo().TotalAvailableMemoryBytes;
111 else if (Mac.On) long.TryParse(Sysctl("hw.memsize"), out bytes);
112 else
113 {
114 string m = Read("/proc/meminfo");
115 string line = m?.Split('\n').FirstOrDefault(l => l.StartsWith("MemTotal:", StringComparison.Ordinal));
116 if (line != null && long.TryParse(new string(line.Where(char.IsDigit).ToArray()), out long kb)) bytes = kb * 1024;
117 }
118 return bytes > 0 ? (bytes / 1073741824.0).ToString("0.0", CultureInfo.InvariantCulture) + " GB" : "?";
119 }
120
121 private static List<string> Gpus()
122 {
123 List<string> o = new();
124 if (OperatingSystem.IsWindows()) { o.Add("(shown on Linux)"); return o; }
125 if (Mac.On)
126 {
127 string sp = Run("/usr/sbin/system_profiler", "SPDisplaysDataType");
128 if (sp != null)
129 foreach (string line in sp.Split('\n'))
130 {
131 string t = line.Trim();
132 if (t.StartsWith("Chipset Model:", StringComparison.Ordinal)) o.Add(t[14..].Trim());
133 else if (t.StartsWith("Total Number of Cores:", StringComparison.Ordinal) && o.Count > 0) o[^1] += " (" + t[22..].Trim() + " GPU cores)";
134 }
135 if (o.Count == 0) o.Add("?");
136 return o;
137 }
138 string l = Run("lspci");
139 if (l != null)
140 foreach (string line in l.Split('\n'))
141 if (line.Contains("VGA compatible", StringComparison.Ordinal) || line.Contains("3D controller", StringComparison.Ordinal) || line.Contains("Display controller", StringComparison.Ordinal))
142 {
143 int i = line.IndexOf(": ", StringComparison.Ordinal);
144 o.Add(i > 0 ? line[(i + 2)..].Trim() : line.Trim());
145 }
146 if (o.Count == 0)
147 {
148 try
149 {
150 foreach (string card in Directory.GetDirectories("/sys/class/drm", "card?"))
151 {
152 string v = Read(Path.Combine(card, "device", "vendor")), d = Read(Path.Combine(card, "device", "device"));
153 if (v == null) continue;
154 string name = v == "0x10de" ? "NVIDIA" : v == "0x1002" ? "AMD" : v == "0x8086" ? "Intel" : v;
155 o.Add(name + " (device " + d + ")");
156 }
157 }
158 catch (Exception) { }
159 }
160 string nv = Read("/proc/driver/nvidia/version");
161 if (nv != null) o.Add("NVIDIA driver: " + nv.Split('\n')[0]);
162 if (o.Count == 0) o.Add("?");
163 return o;
164 }
165
166 private static string Proton(string game)
167 {
168 try
169 {
170 string lib = Directory.GetParent(game)?.Parent?.FullName;
171 if (lib == null) return null;
172 string cfg = Path.Combine(lib, "compatdata", Game.AppId, "config_info");
173 if (File.Exists(cfg)) return File.ReadLines(cfg).FirstOrDefault()?.Trim();
174 string ver = Path.Combine(lib, "compatdata", Game.AppId, "version");
175 if (File.Exists(ver)) return File.ReadAllText(ver).Trim();
176 }
177 catch (Exception) { }
178 return null;
179 }
180
181 public static string Scrub(string s)
182 {
183 string home = Dirs.Home;
184 if (!string.IsNullOrEmpty(home) && home.Length > 3) s = s.Replace(home, "~");
185 string user = Environment.UserName;
186 if (!string.IsNullOrEmpty(user) && user.Length > 2) s = s.Replace("/" + user + "/", "/<user>/").Replace("\\" + user + "\\", "\\<user>\\");
187 return s;
188 }
189 }
190
191 internal sealed partial class MainWindow
192 {
193 private readonly TextBox logBox = new()
194 {
195 IsReadOnly = true,
196 AcceptsReturn = true,
197 TextWrapping = TextWrapping.NoWrap,
198 FontFamily = new FontFamily("monospace"),
199 FontSize = 12,
200 Height = 420,
201 };
202 private readonly StackPanel sysRows = new() { Spacing = 4 };
203 private readonly TextBlock logState = T("", 12, Ui.B(Ui.Dim), false, true);
204 private readonly List<string> logLines = new();
205 private string logFile;
206 private long logPos;
207 private string logPartial = "";
208 private bool logErrorsOnly, logFollow = true;
209 private List<(string, string)> sys;
210 private DateTime sysAt;
211
212 private Control ReportPage()
213 {
214 Grid g = new() { ColumnDefinitions = new ColumnDefinitions("2*,*") };
215 StackPanel left = new() { Margin = new Thickness(0, 0, 7, 0) };
216 Border ls = Section("GAME LOG (LIVE)", out StackPanel lb);
217 lb.Children.Add(logState);
218 lb.Children.Add(logBox);
219 WrapPanel lw = new();
220 ToggleButton err = Switch("Only Warnings and Errors", "Hides the normal lines.", false, on => { logErrorsOnly = on; ShowLog(); });
221 err.HorizontalAlignment = HorizontalAlignment.Left;
222 err.Margin = new Thickness(0, 0, 6, 0);
223 lw.Children.Add(err);
224 ToggleButton follow = Switch("Follow", "Keeps the newest lines in view.", true, on => logFollow = on);
225 follow.HorizontalAlignment = HorizontalAlignment.Left;
226 follow.Margin = new Thickness(0, 0, 6, 0);
227 lw.Children.Add(follow);
228 lw.Children.Add(Btn("Open Log Folder", () => { if (logFile != null) Game.Open(Path.GetDirectoryName(logFile)); }));
229 lb.Children.Add(lw);
230 left.Children.Add(ls);
231 g.Children.Add(left);
232
233 StackPanel right = new() { Margin = new Thickness(7, 0, 0, 0) };
234 Border ss = Section("YOUR SYSTEM", out StackPanel sb);
235 sb.Children.Add(sysRows);
236 right.Children.Add(ss);
237 Border rs = Section("REPORT A BUG", out StackPanel rb);
238 rb.Children.Add(T("1. Copy the report (your system and the last 300 log lines).\n2. Open the Nexus Bugs page and paste it in, with what you did and what happened.\n\nYour home folder and user name are hidden in the report.", 13, Ui.B(Ui.Dim), false, true));
239 WrapPanel rw = new();
240 foreach (Button b in new[]
241 {
242 Btn("Copy Report", async () => { if (Clipboard != null) await Clipboard.SetTextAsync(BuildReport()); Message("Report copied. Paste it on the Nexus Bugs page.", false); }, true),
243 Btn("Save Report...", () => _ = SaveReport()),
244 Btn("Open Nexus Bugs Page", () => Game.Open(Nexus.PageUrl + "?tab=bugs")),
245 })
246 { b.Margin = new Thickness(0, 4, 6, 0); rw.Children.Add(b); }
247 rb.Children.Add(rw);
248 right.Children.Add(rs);
249 Grid.SetColumn(right, 1);
250 g.Children.Add(right);
251 return Scroll(g);
252 }
253
254 private void RefreshReport()
255 {
256 if (sys == null || DateTime.UtcNow - sysAt > TimeSpan.FromSeconds(30))
257 {
258 sysAt = DateTime.UtcNow;
259 string gd = game;
260 Task.Run(() => SysInfo.Collect(gd)).ContinueWith(t =>
261 {
262 if (t.IsFaulted) return;
263 Dispatcher.UIThread.Post(() =>
264 {
265 sys = t.Result;
266 sysRows.Children.Clear();
267 foreach (var (label, value) in sys)
268 {
269 Grid r = new() { ColumnDefinitions = new ColumnDefinitions("110,*") };
270 r.Children.Add(T(label, 12, Ui.B(Ui.Dim)));
271 TextBlock v = T(SysInfo.Scrub(value), 12, Ui.B(Ui.Text), false, true);
272 Grid.SetColumn(v, 1);
273 r.Children.Add(v);
274 sysRows.Children.Add(r);
275 }
276 });
277 });
278 }
279 PollLog();
280 }
281
282 private void PollLog()
283 {
284 string f = game != null ? Path.Combine(game, "BepInEx", "LogOutput.log") : null;
285 if (f != logFile) { logFile = f; logPos = 0; logPartial = ""; logLines.Clear(); ShowLog(); }
286 if (f == null) { logState.Text = "Set the game folder in Game Setup to see the log."; return; }
287 if (!File.Exists(f)) { logState.Text = "No log yet. It appears once the game has started with BepInEx."; return; }
288 try
289 {
290 using FileStream fs = new(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
291 if (fs.Length < logPos) { logPos = 0; logPartial = ""; logLines.Clear(); }
292 if (logPos == 0 && fs.Length > 2 * 1024 * 1024) logPos = fs.Length - 2 * 1024 * 1024;
293 if (fs.Length == logPos) { logState.Text = (Game.GameRunning() ? "Live. " : "The game isn't running; this is its last log. ") + logLines.Count + " lines."; return; }
294 fs.Position = logPos;
295 byte[] buf = new byte[Math.Min(fs.Length - logPos, 4 * 1024 * 1024)];
296 int n = fs.Read(buf, 0, buf.Length);
297 logPos += n;
298 string text = logPartial + Encoding.UTF8.GetString(buf, 0, n);
299 int last = text.LastIndexOf('\n');
300 if (last < 0) { logPartial = text; return; }
301 logPartial = text[(last + 1)..];
302 foreach (string line in text[..last].Split('\n')) logLines.Add(line.TrimEnd('\r'));
303 if (logLines.Count > 3000) logLines.RemoveRange(0, logLines.Count - 3000);
304 logState.Text = (Game.GameRunning() ? "Live. " : "The game isn't running; this is its last log. ") + logLines.Count + " lines.";
305 ShowLog();
306 }
307 catch (Exception e) { logState.Text = "Couldn't read the log: " + e.Message; }
308 }
309
310 private static bool IsProblem(string l) => l.StartsWith("[Warning", StringComparison.Ordinal) || l.StartsWith("[Error", StringComparison.Ordinal) || l.StartsWith("[Fatal", StringComparison.Ordinal) || l.Contains("Exception", StringComparison.Ordinal);
311
312 private void ShowLog()
313 {
314 IEnumerable<string> lines = logErrorsOnly ? logLines.Where(IsProblem) : logLines;
315 logBox.Text = SysInfo.Scrub(string.Join("\n", lines.TakeLast(1500)));
316 if (logFollow) logBox.CaretIndex = logBox.Text?.Length ?? 0;
317 }
318
319 private string BuildReport()
320 {
321 StringBuilder sb = new();
322 sb.AppendLine("=== Ultra Paradise CU:Trainer bug report ===");
323 sb.AppendLine("Made " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture) + " UTC");
324 sb.AppendLine("Attached to game: " + (link.IsConnected ? "yes" + (pluginVersion != null ? " (plugin v" + pluginVersion + ")" : "") : "no"));
325 foreach (var (label, value) in sys ?? SysInfo.Collect(game)) sb.AppendLine(label + ": " + value);
326 sb.AppendLine();
327 sb.AppendLine("=== Last log lines (BepInEx/LogOutput.log) ===");
328 foreach (string l in logLines.TakeLast(300)) sb.AppendLine(l);
329 return SysInfo.Scrub(sb.ToString());
330 }
331
332 private async Task SaveReport()
333 {
334 IStorageFile f = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
335 {
336 Title = "Save the bug report",
337 SuggestedFileName = "UltraParadise-bug-report.txt",
338 DefaultExtension = "txt",
339 });
340 string p = f?.TryGetLocalPath();
341 if (p == null) return;
342 try { File.WriteAllText(p, BuildReport()); Message("Report saved.", false); }
343 catch (Exception e) { Message("Couldn't save it: " + e.Message, true); }
344 }
345 }
346}