diff --git a/docs/launcher.md b/docs/launcher.md index c4803f8e8..3b194fafb 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -57,6 +57,15 @@ needs its line in every file, which `tests/test_leonida_launcher.py` checks (sam of #3192). The rail shows the same update state at its bottom, with the time of the last check. + + **Copy info for a bug report** (the Output card and the Tools page; `tools/bug_report_info.py`) puts at most 25 + short lines of plain text on the clipboard, to paste in Discord or in a GitHub issue: the commit and date, Windows' + version, the card the newest `%LOCALAPPDATA%\Leonida\logs\play-*.log` names (the runtime logs no driver version, + and the video memory only with `LEONIDA_ADAPTER`: those read "not in the log"), the profile, resolution, upscaler, + frame generation, switches and `LEONIDA_*` values PLAY runs with, and up to 10 error lines of that log. Each log + line is scrubbed: home folders become `%USERPROFILE%`, hex runs of 8 digits or more, `0x` values, hex-like names + after a shader stage word and the values of `program=`, `shader=`, `pipeline=`, `pso=` and `hash=` are removed, + and lines are cut at 200 characters. It holds no game data and no paths; read it before pasting anyway. - **Settings**: the page of the launcher mockup OreoFR chose: cards in two columns with switches, segmented choices and lists, a short line under some options and the longer text when the pointer rests on one; saved with **Save** (PLAY saves too): diff --git a/tests/test_bug_report_info.py b/tests/test_bug_report_info.py new file mode 100644 index 000000000..d04849614 --- /dev/null +++ b/tests/test_bug_report_info.py @@ -0,0 +1,233 @@ +"""tools/bug_report_info.py: the bug report block, its log parsing and its scrub (synthetic text only, no game data). + + python -I tests/test_bug_report_info.py -v +""" +import os +from pathlib import Path +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tools")) +import bug_report_info as info # noqa: E402 +import leonida_launcher as launcher # noqa: E402 + +CARD_LOG = ('2026-12-03T10:00:00.123456Z INFO leonida_gpu::indirect: the card was asked whether it runs an indirect ' + 'dispatch card="NVIDIA GeForce RTX 4070", runs=true, ms=1.5\n') +ADAPTER_LOG = ("2026-12-03T10:00:00.1Z WARN leonida_gpu::host: host device on the card LEONIDA_ADAPTER names " + "adapter=AMD Radeon RX 7800 XT index=1 memory_mb=16368\n") + + +def build(head=None, tail=None, **changes): + arguments = dict(version="abc1234 2026-12-03", system="Windows 11 (10.0.26300)", console="series-x", + args=["-Dlss", "quality", "-FrameGen", "3"], variables={"LEONIDA_FG_LIMIT_FPS": "60"}, + log_head=head, log_tail=tail) + arguments.update(changes) + return info.build_report(**arguments) + + +class ScrubTests(unittest.TestCase): + def test_home_folder(self): + for path in (r"C:\Users\Jean Dupont\AppData\x", "c:/users/bob/x", r"\\?\D:\Users\bob\x", "/home/bob/x", + "/Users/bob/x"): + with self.subTest(path=path): + out = info.scrub_line(f"open {path} failed") + self.assertIn("%USERPROFILE%", out) + self.assertNotIn("bob", out) + self.assertNotIn("Dupont", out) + self.assertEqual(info.scrub_line(r"C:\Users\bob started"), "%USERPROFILE% started") + self.assertEqual(info.scrub_line("a home/ folder"), "a home/ folder") + + def test_hex_runs(self): + out = info.scrub_line("fault at 00007FF6A1B2C3D4 and deadbeef and 1234567") + self.assertNotIn("7FF6", out) + self.assertNotIn("deadbeef", out) + self.assertIn("1234567", out) # 7 digits stay + self.assertEqual(info.scrub_line("t=10:00:00.123456789Z ok"), "t=10:00:00.123456789Z ok") + + def test_hex_values(self): + out = info.scrub_line("status 0xC0000409 and 0x1f") + self.assertNotIn("0x", out) + self.assertNotIn("C0000409", out) + + def test_stage_names(self): + for text in ("ps_1a2b3c", "vs 8F3A9C", "cs=beef", "GS:cafe", "ms-abcd12_main", "ds_deadbeef", "hs_0123", "as_f00d"): + with self.subTest(text=text): + out = info.scrub_line(f"compile {text} failed") + self.assertEqual(out.split()[1][:3].lower().rstrip("_:=-"), text[:2].lower()) + self.assertIn("", out) + for kept in ("as added", "ps_5_0", "cs of the box", "vs bad"): + with self.subTest(kept=kept): + self.assertEqual(info.scrub_line(f"x {kept} y"), f"x {kept} y") + + def test_named_values(self): + for key in ("program", "shader", "pipeline", "pso", "hash", "shader_hash", "PSO"): + for value in ("secret_name", '"two words"', "'q v'", "12"): + with self.subTest(key=key, value=value): + out = info.scrub_line(f"error {key}={value}, next=1") + self.assertNotIn("secret", out) + self.assertNotIn("two", out) + self.assertNotIn("q v", out) + self.assertIn(f"{key}=", out) + self.assertIn("next=1", out) + self.assertIn("hash = ", info.scrub_line("hash = abc")) + + def test_cut_comes_after_the_scrub(self): + out = info.scrub_line("error " + "x" * 190 + " shader=" + "y" * 50) + self.assertLessEqual(len(out), info.MAX_LINE) + self.assertNotIn("y" * 5, out) + self.assertEqual(len(info.scrub_line("g" * 500)), info.MAX_LINE) + + def test_ansi_and_control(self): + self.assertEqual(info.scrub_line("\x1b[31mERROR\x1b[0m boom\x07\r\n"), "ERROR boom") + + +class LogTests(unittest.TestCase): + def test_error_lines_match_and_cap(self): + text = "\n".join(["INFO fine", "ERROR a", "WARN device lost", "INFO device removed here", "panicked at x", + "an exception", "exit 0xC0000005", "INFO 0 errors", "INFO ok"]) + self.assertEqual(info.error_lines(text), ["ERROR a", "WARN device lost", "INFO device removed here", + "panicked at x", "an exception", ""[:0] or "exit "]) + + def test_ten_line_cap_keeps_the_newest(self): + text = "\n".join(f"ERROR number {i}" for i in range(30)) + lines = info.error_lines(text) + self.assertEqual(len(lines), 10) + self.assertEqual(lines[0], "ERROR number 20") + self.assertEqual(lines[-1], "ERROR number 29") + + def test_repeated_lines_once(self): + text = "ERROR a\n" + "ERROR device removed\n" * 50 + "ERROR b\n" + self.assertEqual(info.error_lines(text), ["ERROR a", "ERROR device removed", "ERROR b"]) + + def test_lines_are_scrubbed(self): + out = info.error_lines(r"ERROR C:\Users\bob\x shader=abc ps_1a2b3c 0xDEAD deadbeef01") + self.assertEqual(len(out), 1) + for leaked in ("bob", "abc", "1a2b3c", "DEAD", "deadbeef"): + self.assertNotIn(leaked, out[0].replace("shader=", "")) + + def test_card(self): + self.assertEqual(info.gpu_from_log("noise\n" + CARD_LOG)["name"], "NVIDIA GeForce RTX 4070") + self.assertIsNone(info.gpu_from_log(CARD_LOG)["memory_mb"]) + self.assertEqual(info.gpu_from_log("\x1b[2m" + CARD_LOG)["name"], "NVIDIA GeForce RTX 4070") + + def test_adapter_line_has_memory(self): + gpu = info.gpu_from_log(CARD_LOG + ADAPTER_LOG) + self.assertEqual((gpu["name"], gpu["memory_mb"]), ("AMD Radeon RX 7800 XT", 16368)) + quoted = info.gpu_from_log('LEONIDA_ADAPTER adapter="X Y" index=0 memory_mb=8000') + self.assertEqual((quoted["name"], quoted["memory_mb"]), ("X Y", 8000)) + + def test_software_adapter(self): + self.assertEqual(info.gpu_from_log("host device on the software adapter (WARP)")["name"], + "software adapter (WARP)") + + def test_no_card(self): + self.assertEqual(info.gpu_from_log("INFO nothing"), {"name": None, "memory_mb": None, "driver": None}) + + def test_newest_log_and_ends(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertIsNone(info.newest_play_log(tmp)) + self.assertIsNone(info.newest_play_log(os.path.join(tmp, "missing"))) + for name, stamp in (("play-1.log", 100), ("play-2.log", 300), ("other.log", 900), ("play-3.log", 200)): + path = os.path.join(tmp, name) + Path(path).write_text("x", encoding="utf-8", newline="\n") + os.utime(path, (stamp, stamp)) + self.assertEqual(os.path.basename(info.newest_play_log(tmp)), "play-2.log") + big = os.path.join(tmp, "play-9.log") + Path(big).write_bytes(b"HEAD" + b"." * 100 + b"TAIL") + os.utime(big, (999, 999)) + head, tail = info.read_log_ends(big, head=4, tail=4) + self.assertEqual((head, tail), ("HEAD", "TAIL")) + self.assertEqual(info.read_log_ends(os.path.join(tmp, "none.log")), ("", "")) + + +class ReportTests(unittest.TestCase): + def test_full_block(self): + text = build(CARD_LOG + ADAPTER_LOG, "ERROR device removed 0x887A0006\nERROR second") + lines = text.splitlines() + self.assertEqual(lines[0], "Leonida bug report info") + for expected in ("Version: abc1234 2026-12-03", "Windows: Windows 11 (10.0.26300)", + "GPU: AMD Radeon RX 7800 XT", "Driver: not in the log", "Video memory: 16368 MB", + "Console profile: series-x", "Resolution: default", "Upscaler: DLSS quality", + "Frame generation: DLSS 3x", "Options: -Dlss quality -FrameGen 3", + "Variables: LEONIDA_FG_LIMIT_FPS=60"): + self.assertIn(expected, lines) + self.assertEqual(lines[-3:], ["Last errors of the newest play log:", "ERROR device removed ", + "ERROR second"]) + self.assertTrue(text.endswith("\n") and "\r" not in text) + + def test_missing_fields_say_so(self): + lines = build("INFO nothing", "INFO nothing").splitlines() + self.assertIn("GPU: not in the log", lines) + self.assertIn("Driver: not in the log", lines) + self.assertIn("Video memory: not in the log", lines) + self.assertEqual(lines[-1], "Last errors of the newest play log: none") + + def test_missing_log(self): + text = build(None, None, args=["-NoDlss", "-NoFrameGen", "-Resolution", "1440"], variables={}) + lines = text.splitlines() + self.assertIn("GPU: not in the log", lines) + self.assertIn("Resolution: 1440", lines) + self.assertIn("Upscaler: off", lines) + self.assertIn("Frame generation: off", lines) + self.assertIn("Variables: (none)", lines) + self.assertTrue(lines[-1].startswith("Last errors: no play log found")) + + def test_line_cap(self): + text = build("", "\n".join(f"ERROR line {i}" for i in range(40))) + lines = text.splitlines() + self.assertLessEqual(len(lines), info.MAX_LINES) + self.assertEqual(sum(1 for line in lines if line.startswith("ERROR")), 10) + many = build("", "\n".join(f"ERROR e{i}" for i in range(40)), variables={f"LEONIDA_V{i}": "1" for i in range(90)}) + self.assertLessEqual(len(many.splitlines()), info.MAX_LINES) + self.assertTrue(all(len(line) <= info.MAX_LINE + 40 for line in many.splitlines())) + + def test_paths_in_variables_are_not_shown(self): + text = build(variables={"LEONIDA_CACHE_DIR": r"C:\Users\bob\cache", "LEONIDA_X": "/home/bob/x", "LEONIDA_Y": "2"}) + self.assertNotIn("bob", text) + self.assertIn("LEONIDA_CACHE_DIR=", text) + self.assertIn("LEONIDA_Y=2", text) + + def test_commit_hash_stays(self): + self.assertIn("Version: bfd03e7f3 2026-12-03", build(version="bfd03e7f3 2026-12-03")) + + def test_fsr_frame_generation(self): + self.assertEqual(info.describe_options(["-FsrFrameGen"])["frame_gen"], "FSR 3") + self.assertEqual(info.describe_options([])["upscaler"], "DLSS (auto)") + + def test_no_user_name_anywhere(self): + text = build(CARD_LOG, r"ERROR C:\Users\bob\x failed", version=r"abc C:\Users\bob", system=r"Win /home/bob") + self.assertNotIn("bob", text) + + +class LauncherTests(unittest.TestCase): + def test_bug_report_text_reads_the_newest_log(self): + settings = dict(launcher.DEFAULTS, game_dir="D:/Games/GTA", resolution="1080", series_s=True, fg_limit="60") + with tempfile.TemporaryDirectory() as tmp: + repo = os.path.join(tmp, "repo") + os.makedirs(repo) + logs = os.path.join(tmp, "logs") + os.makedirs(logs) + Path(logs, "play-a.log").write_text(CARD_LOG + "ERROR boom shader=zzz\n", encoding="utf-8", newline="\n") + text = launcher.bug_report_text(settings, repo=repo, logs=logs, windows=True, system="Windows 11 (x)") + self.assertNotIn(tmp, text) + lines = text.splitlines() + self.assertIn("Version: zip copy", lines) + self.assertIn("GPU: NVIDIA GeForce RTX 4070", lines) + self.assertIn("Console profile: series-s", lines) + self.assertIn("Resolution: 1080", lines) + self.assertIn("Variables: LEONIDA_FG_LIMIT_FPS=60", lines) + self.assertEqual(lines[-1], "ERROR boom shader=") + self.assertNotIn("Games", text) + + def test_bug_report_text_without_a_log(self): + with tempfile.TemporaryDirectory() as tmp: + text = launcher.bug_report_text(dict(launcher.DEFAULTS), repo=tmp, logs=os.path.join(tmp, "none"), + windows=True, system="Windows 11 (x)") + self.assertIn("no play log found", text) + self.assertIn("GPU: not in the log", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/bug_report_info.py b/tools/bug_report_info.py new file mode 100644 index 000000000..c5a73c133 --- /dev/null +++ b/tools/bug_report_info.py @@ -0,0 +1,236 @@ +"""The text of the launcher's "Copy info for a bug report" button: pure functions, no game data. + + import bug_report_info # after sys.path.insert(0, ), as -I needs + +The block holds the Leonida version, Windows, the card the runtime's newest play log names, the play settings in +effect and the last error lines of that log, scrubbed so that nothing of the game and no user name is in it: no +shader, pipeline or program name or hash, no address, no home folder. It is at most MAX_LINES lines of at most +MAX_LINE characters. The launcher gathers the inputs (tools/leonida_launcher.py `bug_report_text`); this module +only parses and formats them, so a test feeds it synthetic text. + +What the runtime logs of the card (d3d12/crates/leonida-gpu/src), through `tracing` to stderr, which +`play-nvidia.ps1 -Log` redirects to %LOCALAPPDATA%\\Leonida\\logs\\play-.log: + +* `indirect.rs` (runs_wide), at the run's first indirect execution: a field `card=""`; +* `host.rs` (chosen_adapter), only with LEONIDA_ADAPTER set: `adapter= index= memory_mb=`; +* `host.rs`, only with LEONIDA_D3D12_WARP: "host device on the software adapter (WARP)". + +The driver version is not logged at all, and the video memory only in the LEONIDA_ADAPTER case. +""" +from __future__ import annotations + +import os +import re + +MAX_LINES = 25 +MAX_LINE = 200 +MAX_ERROR_LINES = 10 +HOME = "%USERPROFILE%" +NOT_IN_LOG = "not in the log" +PLAY_LOG = re.compile(r"^play-.*\.log$", re.IGNORECASE) + +# ---------------------------------------------------------------- scrubbing + +ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]") +CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f]") +# C:\Users\, \\?\C:\Users\, C:/Users/, /Users/, /home/: the name is what is removed. +HOME_FOLDER = re.compile( + r"(?:[A-Za-z]:[\\/]+Users[\\/]+|[\\/]+(?:home|Users)[\\/]+)" + r"(?:[^\\/\s\"'<>|:*?]+(?:[ ][^\\/\s\"'<>|:*?]+)*(?=[\\/])|[^\\/\s\"'<>|:*?]+)", re.IGNORECASE) +NAMED_VALUE = re.compile( + r"(?P\b\w*(?:program|shader|pipeline|pso|hash)\w*)(?P\s*=\s*)" + r"(?:\"[^\"]*\"|'[^']*'|[^\s,;)\]}]+)", re.IGNORECASE) +HEX_VALUE = re.compile(r"0x[0-9A-Fa-f]+", re.IGNORECASE) +STAGE_NAME = re.compile(r"\b(?:cs|ps|vs|gs|hs|ds|ms|as)(?P[_:=\-\s]+)(?P\w+)", re.IGNORECASE) +HEX_RUN = re.compile(r"[0-9A-Fa-f]{8,}") +LEADING_HEX = re.compile(r"[0-9A-Fa-f]{4,}") + + +def _stage_name(match: re.Match) -> str: + """A name after a stage word is dropped when it starts with a run of 4 or more hex digits that holds a digit, or + follows a separator other than a space (`ps_beef`, `vs=cafe`); "as added" is left alone.""" + lead = LEADING_HEX.match(match.group("name")) + if not lead: + return match.group(0) + if any(c.isdigit() for c in lead.group()) or match.group("sep").strip(): + return match.group(0)[:match.start("name") - match.start()] + "" + return match.group(0) + + +def scrub_line(line: str) -> str: + """One log line with nothing of the game or of the user left in it, cut at MAX_LINE characters: + + 1. a home folder (`C:\\Users\\`, `/home/`) becomes %USERPROFILE%; + 2. the value of a `program=`, `shader=`, `pipeline=`, `pso=` or `hash=` (also `shader_hash=`) is removed; + 3. a `0x...` value is removed; + 4. the name after a stage word (cs, ps, vs, gs, hs, ds, ms, as) that is hex-like is removed; + 5. a run of 8 or more hex digits is removed. + + The cut comes last, so it cannot leave half of a value that was meant to go.""" + line = CONTROL.sub("", ANSI.sub("", line.rstrip("\r\n"))) + line = HOME_FOLDER.sub(HOME, line) + line = NAMED_VALUE.sub(lambda m: m.group("key") + m.group("eq") + "", line) + line = HEX_VALUE.sub("", line) + line = STAGE_NAME.sub(_stage_name, line) + # A run of digits after a dot is a timestamp's fraction (".123456789Z"): kept. + line = HEX_RUN.sub(lambda m: m.group(0) if m.group(0).isdigit() and line[m.start() - 1:m.start()] == "." + else "", line) + return line[:MAX_LINE] + + +def scrub_home(text: str) -> str: + """`text` with a home folder replaced and control characters dropped, cut at MAX_LINE: for what the launcher itself + knows (the commit, Windows, the card, its own settings), where a short commit hash must stay.""" + text = CONTROL.sub("", ANSI.sub("", str(text).strip())) + return HOME_FOLDER.sub(lambda m: HOME, text)[:MAX_LINE] + + +# ---------------------------------------------------------------- the log + +ERROR_LINE = re.compile( + r"\berror\b|\bERROR\b|\bpanick?ed\b|\bpanic\b|device[ _-]?(?:lost|removed|hung)|\bremoved\b|\bexception\b" + r"|0xC0000[0-9A-Fa-f]{3}", re.IGNORECASE) +NO_ERROR = re.compile(r"\b(?:no|0|zero) errors?\b|\berrors?=0\b|\bwithout errors?\b", re.IGNORECASE) + + +def error_lines(text: str, limit: int = MAX_ERROR_LINES) -> list[str]: + """The last `limit` distinct scrubbed lines of `text` that name an error, panic, lost or removed device, exception + or a 0xC0000... status, oldest first. A line repeated (a device-removed flood) is kept once, at its newest place.""" + found: list[str] = [] + seen: set[str] = set() + for raw in reversed(text.splitlines()): + plain = ANSI.sub("", raw) + if not ERROR_LINE.search(plain) or NO_ERROR.search(plain): + continue + line = scrub_line(plain).strip() + if not line or line in seen: + continue + seen.add(line) + found.append(line) + if len(found) >= limit: + break + found.reverse() + return found + + +CARD_FIELD = re.compile(r'\bcard="((?:[^"\\]|\\.)*)"') +ADAPTER_FIELD = re.compile(r"\badapter=(?:\"((?:[^\"\\]|\\.)*)\"|(.+?)(?=\s+index=\d))") +MEMORY_FIELD = re.compile(r"\bmemory_mb=(\d+)") + + +def gpu_from_log(text: str) -> dict: + """The card the log names: {"name": ..., "memory_mb": int or None, "driver": None}. The driver is never in the + runtime's log. The first line that names a card wins; the memory is the one on a LEONIDA_ADAPTER line.""" + info: dict = {"name": None, "memory_mb": None, "driver": None} + for raw in text.splitlines(): + line = ANSI.sub("", raw) + if "software adapter (WARP)" in line and info["name"] is None: + info["name"] = "software adapter (WARP)" + card = ADAPTER_FIELD.search(line) if "LEONIDA_ADAPTER" in line else None + if card: + info["name"] = (card.group(1) or card.group(2) or "").strip() or info["name"] + memory = MEMORY_FIELD.search(line) + if memory: + info["memory_mb"] = int(memory.group(1)) + break + card = CARD_FIELD.search(line) + if card and info["name"] in (None, "software adapter (WARP)"): + info["name"] = card.group(1).strip() or info["name"] + if info["name"]: + info["name"] = scrub_home(info["name"]) + return info + + +def newest_play_log(folder: str) -> str | None: + """The newest play-*.log of `folder` (by modification time), or None.""" + try: + names = [n for n in os.listdir(folder) if PLAY_LOG.match(n)] + except OSError: + return None + best, best_time = None, -1.0 + for name in names: + path = os.path.join(folder, name) + try: + if not os.path.isfile(path): + continue + stamp = os.path.getmtime(path) + except OSError: + continue + if stamp > best_time: + best, best_time = path, stamp + return best + + +def read_log_ends(path: str, head: int = 256 * 1024, tail: int = 2 * 1024 * 1024) -> tuple[str, str]: + """The first `head` and the last `tail` bytes of a log as text (the card is named near the start, the errors + are near the end); ("", "") when it cannot be read. A short file comes back whole as both.""" + try: + with open(path, "rb") as f: + first = f.read(head) + size = f.seek(0, os.SEEK_END) + f.seek(max(0, size - tail)) + last = f.read() + except OSError: + return "", "" + return first.decode("utf-8", errors="replace"), last.decode("utf-8", errors="replace") + + +# ---------------------------------------------------------------- the settings + +def _shown_value(value: str) -> str: + """A value of a setting as it goes in the block: a path is not shown (it can name the user).""" + value = str(value).strip() + if re.match(r"^[A-Za-z]:[\\/]", value) or value.startswith(("\\\\", "/")) or "\\" in value: + return "" + return scrub_home(value) + + +def describe_options(args: list[str]) -> dict: + """What the switches PLAY passes say, for the block: resolution, upscaler, frame generation.""" + def after(flag): + return args[args.index(flag) + 1] if flag in args and args.index(flag) + 1 < len(args) else None + + upscaler = "off" if "-NoDlss" in args else (f"DLSS {after('-Dlss')}" if "-Dlss" in args else "DLSS (auto)") + if "-NoFrameGen" in args: + frame = "off" + elif "-FsrFrameGen" in args: + frame = "FSR 3" + elif "-FrameGen" in args: + frame = f"DLSS {after('-FrameGen')}x" + else: + frame = "auto" + return {"resolution": after("-Resolution") or "default", "upscaler": upscaler, "frame_gen": frame} + + +# ---------------------------------------------------------------- the block + +def build_report(version: str, system: str, console: str, args: list[str], variables: dict, log_head: str | None, + log_tail: str | None, driver: str | None = None) -> str: + """The block, at most MAX_LINES lines. `version`: leonida_version(); `system`: Windows' name and build; `console`: + the profile the next PLAY runs; `args`: the switches PLAY passes; `variables`: the LEONIDA_* values in effect; + `log_head` and `log_tail`: the ends of the newest play log, None when there is none. `driver` is only for a caller + that has it from elsewhere (the runtime does not log it).""" + gpu = gpu_from_log((log_head or "") + "\n" + (log_tail or "")) + options = describe_options(args) + shown = [f"{name}={_shown_value(value)}" for name, value in sorted(variables.items())] + head = [ + "Leonida bug report info", + f"Version: {scrub_home(version)}", + f"Windows: {scrub_home(system)}", + f"GPU: {gpu['name'] or NOT_IN_LOG}", + f"Driver: {scrub_home(driver) if driver else NOT_IN_LOG}", + f"Video memory: {str(gpu['memory_mb']) + ' MB' if gpu['memory_mb'] else NOT_IN_LOG}", + f"Console profile: {scrub_home(console)}", + f"Resolution: {options['resolution']}", + f"Upscaler: {options['upscaler']}", + f"Frame generation: {options['frame_gen']}", + "Options: " + scrub_home(" ".join(_shown_value(a) for a in args) or "(defaults)"), + "Variables: " + (scrub_home("; ".join(shown)) if shown else "(none)"), + ] + if log_head is None and log_tail is None: + tail = ["Last errors: no play log found (turn on Log in Settings or use Run in diagnostic mode)"] + else: + errors = error_lines(log_tail or log_head or "", min(MAX_ERROR_LINES, MAX_LINES - len(head) - 1)) + tail = ["Last errors of the newest play log:" if errors else "Last errors of the newest play log: none"] + tail += errors + return "\n".join((head + tail)[:MAX_LINES]) + "\n" diff --git a/tools/launcher_i18n/de.json b/tools/launcher_i18n/de.json index e574e6ae0..d3df8c7c4 100644 --- a/tools/launcher_i18n/de.json +++ b/tools/launcher_i18n/de.json @@ -399,5 +399,9 @@ "AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "AMDs FSR-3-Dateien sind noch nicht da: PLAY lädt sie zuerst (etwa 29 MB).", "AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "AMDs FSR-3-Dateien sind nicht da, also bleibt FSR 3 aus: Werkzeuge > AMD-FidelityFX-Dateien holen.", "{path} is a drive's root.": "{path} ist das Stammverzeichnis eines Laufwerks.", - "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} enthält {folder} oder liegt darin: es wird nicht gelöscht. Leere es von Hand, wenn du sicher bist." + "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} enthält {folder} oder liegt darin: es wird nicht gelöscht. Leere es von Hand, wenn du sicher bist.", + "Copy info for a bug report": "Infos für einen Fehlerbericht kopieren", + "Copied: paste it in Discord or in a GitHub issue": "Kopiert: füge es in Discord oder in ein GitHub-Issue ein", + "Reading the newest log ...": "Das neueste Log wird gelesen ...", + "Version, card, settings and the last errors of the newest log, to paste in a report": "Version, Karte, Einstellungen und letzte Fehler des neuesten Logs, zum Einfügen in einen Bericht" } diff --git a/tools/launcher_i18n/es.json b/tools/launcher_i18n/es.json index 109e05fda..039c3180b 100644 --- a/tools/launcher_i18n/es.json +++ b/tools/launcher_i18n/es.json @@ -399,5 +399,9 @@ "AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Los archivos FSR 3 de AMD aún no están: PLAY los descarga primero (unos 29 MB).", "AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Los archivos FSR 3 de AMD no están, así que FSR 3 sigue desactivado: Herramientas > Obtener los archivos AMD FidelityFX.", "{path} is a drive's root.": "{path} es la raíz de una unidad.", - "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contiene {folder} o está dentro: no se borra. Vacíalo a mano si estás seguro." + "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contiene {folder} o está dentro: no se borra. Vacíalo a mano si estás seguro.", + "Copy info for a bug report": "Copiar info para un informe de error", + "Copied: paste it in Discord or in a GitHub issue": "Copiado: pégalo en Discord o en una issue de GitHub", + "Reading the newest log ...": "Leyendo el último registro ...", + "Version, card, settings and the last errors of the newest log, to paste in a report": "Versión, tarjeta, ajustes y últimos errores del último registro, para pegar en un informe" } diff --git a/tools/launcher_i18n/fr.json b/tools/launcher_i18n/fr.json index 5d5baf7b0..3b0c956e6 100644 --- a/tools/launcher_i18n/fr.json +++ b/tools/launcher_i18n/fr.json @@ -399,5 +399,9 @@ "AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Les fichiers FSR 3 d'AMD ne sont pas encore là : PLAY les télécharge d'abord (environ 29 Mo).", "AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Les fichiers FSR 3 d'AMD ne sont pas là, donc FSR 3 reste désactivé : Outils > Récupérer les fichiers AMD FidelityFX.", "{path} is a drive's root.": "{path} est la racine d'un disque.", - "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contient {folder} ou se trouve dedans : il n'est pas supprimé. Videz-le à la main si vous êtes sûr." + "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contient {folder} ou se trouve dedans : il n'est pas supprimé. Videz-le à la main si vous êtes sûr.", + "Copy info for a bug report": "Copier les infos pour un rapport de bug", + "Copied: paste it in Discord or in a GitHub issue": "Copié : collez-le sur Discord ou dans une issue GitHub", + "Reading the newest log ...": "Lecture du dernier log ...", + "Version, card, settings and the last errors of the newest log, to paste in a report": "Version, carte, réglages et dernières erreurs du dernier log, à coller dans un rapport" } diff --git a/tools/launcher_i18n/pt.json b/tools/launcher_i18n/pt.json index b872715ed..8ef301d2d 100644 --- a/tools/launcher_i18n/pt.json +++ b/tools/launcher_i18n/pt.json @@ -399,5 +399,9 @@ "AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Os arquivos FSR 3 da AMD ainda não estão aqui: o PLAY os baixa primeiro (cerca de 29 MB).", "AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Os arquivos FSR 3 da AMD não estão aqui, então o FSR 3 fica desligado: Ferramentas > Obter os arquivos AMD FidelityFX.", "{path} is a drive's root.": "{path} é a raiz de uma unidade.", - "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contém {folder} ou está dentro dele: não é apagado. Limpe-o à mão se tiver certeza." + "{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contém {folder} ou está dentro dele: não é apagado. Limpe-o à mão se tiver certeza.", + "Copy info for a bug report": "Copiar infos para um relatório de bug", + "Copied: paste it in Discord or in a GitHub issue": "Copiado: cole no Discord ou numa issue do GitHub", + "Reading the newest log ...": "Lendo o log mais recente ...", + "Version, card, settings and the last errors of the newest log, to paste in a report": "Versão, placa, configurações e últimos erros do log mais recente, para colar num relatório" } diff --git a/tools/leonida_launcher.py b/tools/leonida_launcher.py index 8c187d43d..229b71f4a 100644 --- a/tools/leonida_launcher.py +++ b/tools/leonida_launcher.py @@ -20,6 +20,7 @@ from __future__ import annotations import importlib.util import json import os +import platform import queue import re import shutil @@ -1720,6 +1721,37 @@ def info_text(settings: dict, version: str, cards: list[tuple[str, str]], python return "\n".join(lines) + "\n" +def _bug_report_module(): + """tools/bug_report_info.py, loaded by path (`python -I` leaves this folder off sys.path).""" + path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bug_report_info.py") + spec = importlib.util.spec_from_file_location("bug_report_info", path) + module = importlib.util.module_from_spec(spec) + sys.modules.setdefault("bug_report_info", module) + spec.loader.exec_module(module) + return module + + +def bug_report_text(settings: dict, repo: str = REPO, logs: str | None = None, windows: bool = WINDOWS, + git=_git, system: str | None = None) -> str: + """What "Copy info for a bug report" puts on the clipboard (tools/bug_report_info.py): the commit (leonida_version), + Windows, the card the runtime's newest play log in the logs folder names, the play settings in effect (the profile + the next PLAY runs, the switches it passes, the LEONIDA_* values it sets) and that log's last error lines, scrubbed. + No game data, no folder names. Reads a log and runs git: not on the window's thread.""" + info = _bug_report_module() + menu = read_menu_settings(repo) if windows else {} + values = launch_values(settings, menu, windows) + variables = {k: v for k, v in values.items() if k not in ("console", "from")} + variables.update(extra_variables(settings)) + path = info.newest_play_log(logs if logs is not None else logs_dir()) + head, tail = info.read_log_ends(path) if path else (None, None) + if path and head == "" and tail == "": + head = tail = None + return info.build_report( + leonida_version(repo, git), + system or f"{platform.system()} {platform.release()} ({platform.version()})", + values["console"], switch_args(settings), variables, head, tail) + + def enable_dpi_awareness(windows: bool = WINDOWS) -> None: """Tells Windows the window draws at the screen's own scale, so its text is not a blurred, stretched bitmap. System-wide awareness: Tk does not follow a window moved to a monitor of another scale.""" @@ -3098,6 +3130,8 @@ def run_gui() -> int: buttons.grid(row=0, column=1, sticky="e", padx=px(16), pady=(px(12), 0)) ttk.Button(buttons, text=t("Run in diagnostic mode"), command=self.play_diagnostic).pack(side="left") ttk.Button(buttons, text=t("Copy my info"), command=self.copy_info).pack(side="left", padx=(px(8), 0)) + ttk.Button(buttons, text=t("Copy info for a bug report"), command=self.copy_report).pack( + side="left", padx=(px(8), 0)) box = tk.Frame(out, bg=PANEL) box.grid(row=out.next_row, column=0, columnspan=2, sticky="nsew", padx=px(16), pady=(px(8), px(16))) out.rowconfigure(out.next_row, weight=1) @@ -3603,6 +3637,9 @@ def run_gui() -> int: if kind == "info": self.show_info(value) continue + if kind == "report": + self.show_report(value) + continue if kind == "rail": self.rail_seen = value self.rail_info.set(value) @@ -3670,6 +3707,26 @@ def run_gui() -> int: self.set_status_note(t("Reading the graphics card ...")) threading.Thread(target=work, daemon=True).start() + def copy_report(self): + self.collect_settings() + settings = dict(self.settings) + + def work(): + try: + text = bug_report_text(settings) + except Exception as exc: # a broken git or an unreadable log must not take the launcher down + text = "Leonida bug report info\n(could not be read: " + str(exc) + ")\n" + self.lines.put(("report", None, text)) + self.set_status_note(t("Reading the newest log ...")) + threading.Thread(target=work, daemon=True).start() + + def show_report(self, text): + self.root.clipboard_clear() + self.root.clipboard_append(text) + self.status_var.set(t("Copied: paste it in Discord or in a GitHub issue")) + messagebox.showinfo(t("Copy info for a bug report"), + t("Copied: paste it in Discord or in a GitHub issue") + "\n\n" + text) + def set_status_note(self, text): self.status_var.set(text) @@ -4925,6 +4982,9 @@ def run_gui() -> int: self.play_diagnostic), (t("Copy my info"), t("Your card, driver, Mandy version and options, to paste in a report"), self.copy_info), + (t("Copy info for a bug report"), + t("Version, card, settings and the last errors of the newest log, to paste in a report"), + self.copy_report), (t("Clear shader cache"), t("Deletes the shaders and pipelines made so far; your saves stay"), self.clear_cache), (t("Open the logs folder"), t("The files -Log and the diagnostic mode write"),