Files
mandy/tools/leonida_launcher.py
OreoFR f1e9718e95 launcher, play scripts: review fixes of #3272 (card mask kept out of the F1 file, -Adapter for auto FG, Linux cache and binds, clear-cache race, unreadable binds kept)
merzleckeier's reviews at 02:35, 02:47 and 02:58 and DeadlyChirp's 02:46 note:
1. The AMD/Intel card filter named NoDlss, NoFrameGen and SmoothMotion in
   -Chosen, so a real PLAY rewrote leonida-settings.txt without the F1
   menu's DLSS, DLSS frame generation and Smooth Motion. The launcher now
   passes -CardMask (card_mask) instead; play-d3d12.ps1 hands it over and
   play-nvidia.ps1 leaves those settings out of this start only, keeping
   them in the menu file (and says so); the menu's FSR stays.
2. play-nvidia.ps1's automatic DLSS frame generation looked at every card:
   with -Adapter it now judges the cards whose name holds it (all when none
   does), so an AMD card chosen beside an RTX 4070 gets none; the card
   mask's NoFrameGen also keeps it off.
3. Clear shader cache on Linux looked under the Windows data folder: it now
   uses play-linux.sh's LEONIDA_CACHE_DIR or ${XDG_DATA_HOME:-~/.local/share}
   /leonida/cache.
4. After the confirmation, clear_cache asks game_running() again, not only
   its own process.
5. Linux PLAY passes the extra variables (the Controls page's binds, the
   advanced options, Advanced winning) in play-linux.sh's environment
   (`env NAME=value sh play-linux.sh ...`); none were passed before.
6. The Controls page keeps entries it cannot read beside its rows
   (split_kbm_binds) and writes them back after them: adding a row no longer
   drops a saved list with an unknown entry. Its note called t() with a
   `text=` value, which crashed the page as soon as it showed one: the
   placeholder is {entries} now, in de/es/fr/pt too.

Tests: test_card_mask_leaves_the_menus_nvidia_values_out_and_in_the_file
(dry runs, a real start with Start-Process stubbed keeping the menu file,
AMD + RTX 4070 with -Adapter each way and with the mask); card_mask and
-CardMask in play_command; LinuxPlayTests; SplitBindsTests with a guard
that no t() call passes text=. Launcher suite OK (1 skip), win launchers
12 OK, docs links, line endings, check_no_game_data. Counter-tests: the
mask ignored, the adapter filter off, the Linux env/cache, split and
card_mask reverted each fail their tests; the guard regex matches the old
source. Real window (isolated APPDATA): the game started during the
confirmation leaves the cache and says close the game first; adding H to
`both:G=Square;vehicle:N=FutureAction` saves G, H and the unknown entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 04:15:54 +01:00

4850 lines
257 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Mandy Launcher (formerly Leonida): a desktop window to start the port, set its options and look after it.
Pages: Play (the PLAY button, the launcher's output and the state), Settings (game and data folders, the switches of
scripts/play-d3d12.ps1), Mods (the enabled switches of mods/*/mod.json), Tools (fetch NVIDIA's DLSS files, rebuild the
runtime, open folders) and About. Settings are kept in a JSON file under the user's config folder
(%APPDATA%\\Leonida\\launcher.json, ~/.config/leonida/launcher.json).
Standard library only (Tkinter for the window). Its look is the launcher mockup's: indigo, violet and pink, drawn by the
window itself. No picture files, no artwork of the game, no company logos.
python -I tools/leonida_launcher.py (Windows: Launcher.bat)
python3 tools/leonida_launcher.py (Linux)
The pure parts (settings, the command line, the mod list) have no Tkinter in them and are tested without a display
(tests/test_leonida_launcher.py).
"""
from __future__ import annotations
import importlib.util
import json
import os
import queue
import re
import shutil
import signal
import stat
import subprocess
import sys
import threading
import time
EXPECTED_EXE = "game_scarlett_master.exe"
# Shown beside "Precompile every pipeline" and when it is ticked: players kept compiling in the game after the full
# precompile because NVIDIA's shader cache was at its default size, which throws part of it away.
NVIDIA_CACHE_NOTE = ("Set NVIDIA's shader cache to Unlimited first: NVIDIA Control Panel > Manage 3D settings > "
"Global Settings > Shader Cache Size > Unlimited > Apply (a global setting, not per program). "
"With the default size the driver throws part of the precompiled pipelines away and the game "
"compiles them again while it runs.")
WINDOWS = os.name == "nt"
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Switches of scripts/play-d3d12.ps1 that the Settings page offers, with the value they have by default.
RESOLUTIONS = ("", "2160", "1440", "1080", "720", "540", "480")
DLSS_MODES = ("", "quality", "balanced", "performance", "ultra")
FRAME_GEN = (0, 2, 3, 4, 5, 6)
PRESENT_SCALES = ("", "fit", "stretch")
ASPECT = re.compile(r"^(auto|\d+(\.\d+)?([:x/]\d+(\.\d+)?)?)$") # the script's own pattern for -Aspect
ADAPTER = re.compile(r"^[\w #.()+-]{0,64}$") # part of a card's name, or #<index>
# The window shapes Settings offers (-Aspect); "" is the script's default, 16:9. A shape saved otherwise (W:H, a
# decimal) is kept and shown as it is.
ASPECTS = ("", "auto", "21:9", "32:9", "16:10")
DEFAULTS: dict = {
"game_dir": "",
"data_dir": "",
"mods_dir": "",
"dlss": True, # off = -NoDlss
"ray_tracing": False, # -RayTracing
"hardware_rt": False, # -HardwareRT (a trial, in place of -RayTracing)
"smooth_motion": False, # -SmoothMotion
"precompile": True, # off = -NoPrecompile
"precompile_all": True, # off = -PrecompileUsed
"series_x": False, # -SeriesX
"quality": False, # -Quality
"resolution": "", # -Resolution <height>, empty = the default path
"capture": False, # -Capture
"log": False, # -Log
"series_s": False, # -SeriesS (the script's default is Series X)
"dlss_mode": "", # -Dlss <mode>, empty = the profile's own path
"frame_gen": 0, # -FrameGen <n>, 0 = the script's own choice (2x on RTX 40 and 50 with NVIDIA's files)
"no_frame_gen": False, # -NoFrameGen: none at all (with frame_gen 0)
"fsr_frame_gen": False, # -FsrFrameGen: AMD's FSR 3 frame generation instead of DLSS's
"fg_limit": "", # LEONIDA_FG_LIMIT_FPS: "" = auto (the runtime's default), "0" = none, or shown frames a second
"aspect": "", # -Aspect <shape>, empty = 16:9
"present_scale": "", # -PresentScale, with -Aspect; empty = the script's default (fit)
"adapter": "", # -Adapter <part of the card's name, or #index>
"last_switches": "", # switch_args at the last PLAY, as JSON: only the ones changed since are -Chosen
"background": "", # the picture behind PLAY in launcher/; "" = background.* in config_dir()
"check_updates": True, # kept for older files; the check runs at every start whatever it says
"language": "", # the window's language, "" = the system's (system_language)
"dred": False, # crash tracing: LEONIDA_D3D12_DRED=1 (names what the card was doing when it stopped)
"advanced": "", # LEONIDA_* variables for -More, "NAME=value" separated by ; or new lines
"kbm_binds": "", # the Controls page's binds: LEONIDA_KBM_BINDS, "scope:key=action;..." (kbm.rs syntax)
}
# The frame limits Settings offers (LEONIDA_FG_LIMIT_FPS); "" leaves the runtime's own, which follows the PC.
FG_LIMITS = ("", "30", "40", "60", "0")
# The languages the window is translated into (tools/launcher_i18n/<code>.json); "" follows the system.
LANGUAGES = ("", "en", "fr", "es", "pt", "de")
# The options with a fixed set of values, and the others whose text has to match a pattern.
CHOICES: dict = {"resolution": RESOLUTIONS, "dlss_mode": DLSS_MODES, "frame_gen": FRAME_GEN,
"present_scale": PRESENT_SCALES, "language": LANGUAGES, "fg_limit": FG_LIMITS}
PATTERNS: dict = {"aspect": ASPECT, "adapter": ADAPTER}
# ---------------------------------------------------------------- settings
def config_dir() -> str:
if WINDOWS:
base = os.environ.get("APPDATA") or os.path.join(os.path.expanduser("~"), "AppData", "Roaming")
else:
base = os.environ.get("XDG_CONFIG_HOME") or os.path.join(os.path.expanduser("~"), ".config")
return os.path.join(base, "Leonida")
def config_path() -> str:
return os.path.join(config_dir(), "launcher.json")
def normalise(data: object) -> dict:
"""The defaults with every valid value of `data` laid over them; anything of the wrong type is dropped."""
settings = dict(DEFAULTS)
if not isinstance(data, dict):
return settings
for key, default in DEFAULTS.items():
value = data.get(key, default)
if key in CHOICES: # the type is checked too: False == 0 would pass for frame_gen
settings[key] = value if type(value) is type(default) and value in CHOICES[key] else default
elif isinstance(default, bool):
settings[key] = value if isinstance(value, bool) else default
elif key in PATTERNS:
settings[key] = value.strip() if isinstance(value, str) and PATTERNS[key].match(value.strip()) else default
else:
settings[key] = value if isinstance(value, str) else default
if settings["series_s"]:
settings["series_x"] = False
if not settings["precompile"]:
settings["precompile_all"] = False
return settings
def load_settings(path: str | None = None) -> dict:
try:
with open(path or config_path(), encoding="utf-8") as f:
return normalise(json.load(f))
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
return normalise(None)
def save_settings(settings: dict, path: str | None = None) -> None:
path = path or config_path()
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(normalise(settings), f, indent=2, ensure_ascii=False)
f.write("\n")
def game_exe_present(folder: str) -> bool:
return bool(folder) and os.path.isfile(os.path.join(folder, EXPECTED_EXE))
def mods_dir_of(settings: dict) -> str:
return settings.get("mods_dir") or os.path.join(REPO, "mods")
# ---------------------------------------------------------------- the command line
def switch_args(settings: dict) -> list[str]:
"""The PowerShell switches the options stand for (scripts/play-d3d12.ps1)."""
args: list[str] = []
if settings["series_s"]:
args.append("-SeriesS")
if not settings["dlss"]:
args.append("-NoDlss")
elif settings["dlss_mode"]:
args += ["-Dlss", settings["dlss_mode"]]
if settings.get("no_frame_gen"):
args.append("-NoFrameGen")
elif settings.get("fsr_frame_gen"):
args.append("-FsrFrameGen")
elif settings["frame_gen"]:
args += ["-FrameGen", str(settings["frame_gen"])]
if settings.get("hardware_rt"):
args.append("-HardwareRT")
elif settings["ray_tracing"]:
args.append("-RayTracing")
if settings["smooth_motion"]:
args.append("-SmoothMotion")
if not settings["precompile"]:
args.append("-NoPrecompile")
elif not settings["precompile_all"]:
args.append("-PrecompileUsed")
if settings["series_x"] and not settings["series_s"]:
args.append("-SeriesX")
if settings["quality"]:
args.append("-Quality")
if settings["resolution"] and not (settings["dlss"] and settings["dlss_mode"]):
args += ["-Resolution", settings["resolution"]] # the script wants it left out with a DLSS mode
if settings["aspect"]:
args += ["-Aspect", settings["aspect"]]
if settings["present_scale"]:
args += ["-PresentScale", settings["present_scale"]]
if settings["adapter"]:
args += ["-Adapter", settings["adapter"]]
if settings["capture"]:
args.append("-Capture")
if settings["log"]:
args.append("-Log")
return args
def for_card(settings: dict, card: dict) -> dict:
"""The settings PLAY passes on `card` (card_facts): without an NVIDIA card (one was read and none is NVIDIA), DLSS,
its mode, DLSS frame generation's multiplier and Smooth Motion are off, as settings_rules greys them (-NoDlss: an
AMD or Intel card does not get DLSS asked of it); FSR frame generation stays. The saved settings keep their values,
so choosing an NVIDIA card again brings them back."""
if card.get("nvidia", True):
return settings
hidden = settings.get("dlss") and settings.get("dlss_mode") # a DLSS mode left the resolution out (switch_args)
settings = dict(settings, dlss=False, dlss_mode="", smooth_motion=False)
if not settings.get("no_frame_gen") and not settings.get("fsr_frame_gen"):
settings["frame_gen"] = 0
# That resolution comes back without DLSS: one above what the Series S outputs (1080 lines) would stop the
# script, so it stays out (review of #3272).
if hidden and settings.get("series_s") and settings.get("resolution", "").isdigit() and int(settings["resolution"]) > SERIES_S_OUTPUT_LINES:
settings["resolution"] = ""
return settings
SERIES_S_OUTPUT_LINES = 1080 # play-nvidia.ps1: $outHeight on the Series S profile
# The switches whose settings the F1 menu's file also holds and that an AMD or Intel card cannot run (for_card),
# passed as play-d3d12.ps1's -CardMask: play-nvidia.ps1 leaves the menu's values for them out of this start only and
# keeps them in the menu file, for a later start on an NVIDIA card ($switchSettings: NoDlss, NoFrameGen,
# NoSmoothMotion). The menu's FSR frame generation stays. They are not named in -Chosen: a switch named there removes
# the menu's value from its file (review of #3272: the saved choices were lost after one start on the AMD card).
CARD_MASK = ("NoDlss", "NoFrameGen", "SmoothMotion")
def card_mask(card: dict) -> list[str]:
"""The -CardMask of a start on `card`: CARD_MASK without an NVIDIA card, nothing otherwise."""
return [] if card.get("nvidia", True) else list(CARD_MASK)
def switch_values(args: list[str]) -> dict:
"""The switches of `args` (switch_args) by name, each with its value or True."""
values: dict = {}
for i, arg in enumerate(args):
if arg.startswith("-") and arg[1:].isalpha():
nxt = args[i + 1] if i + 1 < len(args) else None
values[arg[1:]] = nxt if nxt is not None and not (nxt.startswith("-") and nxt[1:].isalpha()) else True
return values
def chosen_switches(args: list[str], last: str) -> list[str]:
"""The switches whose value changed since the last PLAY (`last`: its switch_args as JSON), sorted: those were
chosen now and win over the F1 menu's saved values (scripts/play-d3d12.ps1 -Chosen); the others the launcher
passes at every start leave the menu's standing. None at the first PLAY, which has nothing to compare with."""
try:
before = json.loads(last) if last else None
except json.JSONDecodeError:
before = None
if not isinstance(before, list):
return []
now, then = switch_values(args), switch_values([a for a in before if isinstance(a, str)])
return sorted(k for k in now.keys() | then.keys() if now.get(k) != then.get(k))
ADVANCED_NAME = re.compile(r"^LEONIDA_[A-Z0-9_]{1,64}$")
def parse_advanced(text: str) -> tuple[dict, list[str]]:
"""The advanced options of the Settings page: `NAME=value` pairs separated by `;` or new lines, each NAME a
LEONIDA_* variable. Returns them in order, and the parts that are not such a pair (to show, not to pass)."""
values: dict = {}
wrong: list[str] = []
for part in re.split(r"[;\r\n]+", text or ""):
part = part.strip()
if not part:
continue
name, sep, value = part.partition("=")
name, value = name.strip(), value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
# A double quote would end the -Command argument Windows hands PowerShell: such a value is not passed.
if not sep or not ADVANCED_NAME.match(name) or any(c in value for c in "\"\x00"):
wrong.append(part)
continue
values[name] = value
return values, wrong
def extra_variables(settings: dict, extra: dict | None = None) -> dict:
"""What PLAY passes to -More: the frame limit when one is chosen, the Controls page's binds, the advanced options
over them (a LEONIDA_KBM_BINDS typed there wins), crash tracing when it is on, then `extra` (the diagnostic start's)
over them."""
values = {}
if settings.get("fg_limit"):
values["LEONIDA_FG_LIMIT_FPS"] = settings["fg_limit"]
if settings.get("kbm_binds", "").strip():
values["LEONIDA_KBM_BINDS"] = settings["kbm_binds"].strip()
values.update(parse_advanced(settings.get("advanced", ""))[0])
if settings.get("dred"):
values["LEONIDA_D3D12_DRED"] = "1"
values.update(extra or {})
return values
# ---------------------------------------------------------------- the Controls page (LEONIDA_KBM_BINDS)
# The runtime's own words for LEONIDA_KBM_BINDS (d3d12/crates/leonida-hle/src/modules/gameinput/kbm.rs: key_named,
# action_named, RESERVED; docs/gameinput.md "Your own binds"), as the page writes them. A test checks each against
# kbm.rs. The scopes, in the page's order.
KBM_SCOPES = ("both", "foot", "vehicle")
# Key names other than a letter, a digit, F1 to F12 and Numpad0 to Numpad9.
KBM_NAMED_KEYS = ("Space", "Enter", "Tab", "Esc", "Backspace", "LShift", "RShift", "LCtrl", "RCtrl", "Up", "Down",
"Left", "Right", "Insert", "Delete", "Home", "End", "PageUp", "PageDown", "MouseLeft", "MouseRight")
# The runtime's own keys: kbm.rs skips an entry naming one (F1 settings menu, F3 numbers panel, F4 trainer, F8 ped
# dump, F9 capture, Alt for Windows' shortcuts, Caps Lock the switch to the driving keys).
KBM_RESERVED = ("F1", "F3", "F4", "F8", "F9", "LAlt", "RAlt", "CapsLock")
# The pad's inputs, (the runtime's name, the page's label), in the list's order; "none" unbinds.
KBM_ACTIONS = (("Cross", "Cross (A)"), ("Circle", "Circle (B)"), ("Square", "Square (X)"),
("Triangle", "Triangle (Y)"), ("LB", "LB (L1)"), ("RB", "RB (R1)"), ("LT", "LT (L2)"),
("RT", "RT (R2)"), ("LS", "Left stick click (L3)"), ("RS", "Right stick click (R3)"),
("View", "View (map)"), ("Menu", "Menu (pause)"), ("DpadUp", "D-pad up"),
("DpadDown", "D-pad down"), ("DpadLeft", "D-pad left"), ("DpadRight", "D-pad right"),
("LeftY+", "Left stick up"), ("LeftY-", "Left stick down"), ("LeftX-", "Left stick left"),
("LeftX+", "Left stick right"), ("RightY+", "Right stick up"), ("RightY-", "Right stick down"),
("RightX-", "Right stick left"), ("RightX+", "Right stick right"), ("none", "Nothing"))
# Other names kbm.rs reads for the same inputs, read back as the page's.
KBM_ACTION_ALIASES = {"a": "Cross", "b": "Circle", "x": "Square", "y": "Triangle"}
# Tk's keysyms whose runtime name is not the keysym itself (letters, digits and F keys are).
KBM_KEYSYMS = {"space": "Space", "Return": "Enter", "KP_Enter": "Enter", "Tab": "Tab", "Escape": "Esc",
"BackSpace": "Backspace", "Shift_L": "LShift", "Shift_R": "RShift", "Control_L": "LCtrl",
"Control_R": "RCtrl", "Alt_L": "LAlt", "Alt_R": "RAlt", "Caps_Lock": "CapsLock", "Up": "Up",
"Down": "Down", "Left": "Left", "Right": "Right", "Insert": "Insert", "Delete": "Delete",
"Home": "Home", "End": "End", "Prior": "PageUp", "Next": "PageDown",
# The keypad with Num Lock off is the arrows and the block above them, as Windows reports it.
"KP_Up": "Up", "KP_Down": "Down", "KP_Left": "Left", "KP_Right": "Right", "KP_Home": "Home",
"KP_End": "End", "KP_Prior": "PageUp", "KP_Next": "PageDown", "KP_Insert": "Insert",
"KP_Delete": "Delete"}
def kbm_key_name(name: str) -> str | None:
"""A key's name as kbm.rs reads it, in the page's spelling: a letter or digit upper case, F1 to F12, Numpad0 to
Numpad9 (Num0 too), the KBM_NAMED_KEYS and the reserved ones (any case); None when kbm.rs knows no such key."""
low = name.strip().lower()
if len(low) == 1 and low.isascii() and low.isalnum():
return low.upper()
for prefix in ("numpad", "num"):
rest = low[len(prefix):]
if low.startswith(prefix) and rest.isdigit() and int(rest) <= 9 and rest.isascii():
return f"Numpad{int(rest)}"
if low.startswith("f") and low[1:].isdigit() and low[1:].isascii() and 1 <= int(low[1:]) <= 12:
return f"F{int(low[1:])}"
aliases = {"return": "Enter", "escape": "Esc"}
if low in aliases:
return aliases[low]
return next((k for k in KBM_NAMED_KEYS + KBM_RESERVED if k.lower() == low), None)
def kbm_key_of_event(keysym: str, button: int = 0) -> str | None:
"""The runtime's name of the key Tk reports (`keysym`) or of a mouse button (1 left, 3 right); None for one the
runtime cannot bind (the wheel, a media key...)."""
if button:
return {1: "MouseLeft", 3: "MouseRight"}.get(button)
if keysym in KBM_KEYSYMS:
return KBM_KEYSYMS[keysym]
if keysym.startswith("KP_") and keysym[3:].isdigit():
return kbm_key_name("Numpad" + keysym[3:])
return kbm_key_name(keysym) if keysym.isascii() and (len(keysym) == 1 or keysym[:1] in "Ff") else None
def kbm_action_name(name: str) -> str | None:
"""An action's name in the page's spelling (KBM_ACTIONS), any case and kbm.rs's other names; None if unknown."""
low = name.strip().lower()
if low in KBM_ACTION_ALIASES:
return KBM_ACTION_ALIASES[low]
return next((n for n, _label in KBM_ACTIONS if n.lower() == low), None)
def parse_kbm_binds(text: str) -> list[tuple[str, str, str]] | None:
"""The rows of a LEONIDA_KBM_BINDS value, (scope, key, action) in the page's spelling; None when an entry does not
read or names a reserved key (the page then keeps the text as it is rather than lose it)."""
rows = []
for part in (text or "").split(";"):
part = part.strip()
if not part:
continue
scope, sep, rest = part.partition(":")
key, sep2, action = rest.partition("=")
scope, key, action = scope.strip().lower(), kbm_key_name(key), kbm_action_name(action)
if not sep or not sep2 or scope not in KBM_SCOPES or key is None or key in KBM_RESERVED or action is None:
return None
rows.append((scope, key, action))
return rows
def split_kbm_binds(text: str) -> tuple[list[tuple[str, str, str]], list[str]]:
"""The entries of a LEONIDA_KBM_BINDS value the page reads, as rows (parse_kbm_binds's), and the others as they
are (an unknown key or action, a reserved key, a newer launcher's): the page edits the rows and writes the others
back unchanged after them, so adding a row never loses one (review of #3272)."""
rows, kept = [], []
for part in (text or "").split(";"):
part = part.strip()
if not part:
continue
read = parse_kbm_binds(part)
if read:
rows.extend(read)
else:
kept.append(part)
return rows, kept
def kbm_binds_text(rows) -> str:
"""The LEONIDA_KBM_BINDS value of the rows: `scope:key=action` joined by `;`; rows without a key are left out."""
return ";".join(f"{scope}:{key}={action}" for scope, key, action in rows if key and action)
# ---------------------------------------------------------------- the runtime's variables (Advanced mode)
# The list the Advanced mode window shows: every LEONIDA_* name the D3D12 runtime reads, made by
# tools/d3d12_switches.py. Read from the repository when the window opens, never copied into this file.
SWITCHES_DOC = ("d3d12", "docs", "switches.md")
FINDINGS_DOC = ("d3d12", "docs", "findings.md")
# The kinds of switches.md whose value is on or off (a toggle in the window); the others take a text.
KIND_OFF_UNLESS_SET = "off unless set and not 0"
KIND_ON_UNLESS_ZERO = "on, 0 turns it off"
SWITCH_CELL = re.compile(r"(?<!\\)\|")
def switches_file(repo: str = REPO) -> str:
return os.path.join(repo, *SWITCHES_DOC)
def switch_cell(text: str) -> str:
"""A cell of switches.md as plain text: the backticks dropped, `\\|`, `&lt;`, `&gt;` and `&amp;` undone (the
escapes tools/d3d12_switches.py writes)."""
text = text.strip().replace("`", "").replace("\\|", "|")
return text.replace("&lt;", "<").replace("&gt;", ">").replace("&amp;", "&")
def parse_switches(text: str) -> list[dict]:
"""The rows of switches.md's tables, in the file's order, as {section, name, kind, ab, launcher, findings, text}:
`section` is the `## ` heading above the table, `ab`, `launcher` (the L column) and `findings` (F) are booleans,
`text` is "In the code's words". A row whose name is not a LEONIDA_* name the advanced options take is skipped."""
rows: list[dict] = []
section = ""
for line in (text or "").splitlines():
if line.startswith("## "):
section = line[3:].strip()
continue
if not line.startswith("| `LEONIDA_"):
continue
cells = [switch_cell(c) for c in SWITCH_CELL.split(line.strip())[1:-1]]
if len(cells) < 7 or not ADVANCED_NAME.match(cells[0]):
continue
rows.append({"section": section, "name": cells[0], "kind": cells[1], "ab": cells[2] == "yes",
"launcher": cells[3] == "yes", "findings": cells[4] == "yes", "text": cells[6]})
return rows
def read_switches(repo: str = REPO) -> list[dict] | None:
"""parse_switches of the repository's d3d12/docs/switches.md; None when the file is missing or does not read."""
try:
with open(switches_file(repo), encoding="utf-8") as f:
return parse_switches(f.read())
except (OSError, UnicodeDecodeError):
return None
HINT_LIMIT = 40 # the longest placeholder a value field shows, "…" included
def value_hint(name: str, description: str) -> str:
"""The placeholder of `name`'s value field: the format the description gives after `NAME=` (`<seconds>,<switch>`,
`<folder>`, `<n>`), up to the first space or the colon that ends it, without the punctuation of the sentence
around it; at most HINT_LIMIT characters, cut with "…". "" when the description names no value."""
match = re.search(r"(?<![A-Za-z0-9_])" + re.escape(name) + r"=((?:<[^<>\n]{1,40}>|\S)+)", description or "")
if not match:
return ""
hint = match.group(1)
if len(hint) > 1 and hint[0] == hint[-1] and hint[0] in "\"'":
hint = hint[1:-1]
hint = re.sub(r"\.{4,}$", "", hint) # "1...." : the end of the sentence after an ellipsis
while hint:
last = hint[-1]
if last in ":;,":
hint = hint[:-1]
elif last == "." and not hint.endswith(".."):
hint = hint[:-1]
elif last == ")" and hint.count(")") > hint.count("("):
hint = hint[:-1]
else:
break
hint = hint.strip("*`")
# A bare number is an example ("LEONIDA_FPS_LINE=0: not"), not a format: shown grey it would read as a value set.
if re.fullmatch(r"-?\d+(\.\d+)?", hint):
return ""
if len(hint) > HINT_LIMIT:
hint = hint[:HINT_LIMIT - 1].rstrip() + "…"
return hint
def plain_description(text: str) -> str:
"""A description as the window shows it: the markdown switches.md kept in a cell (`**shown**`, a stray backtick)
dropped. The stored text keeps it."""
return (text or "").replace("**", "").replace("`", "")
def advanced_value_problem(value: str) -> str:
"""Why `value` cannot go into the advanced options ("" when it can): a double quote would end the -Command
argument (parse_advanced refuses it too), and `;` or a new line would split the pair in two."""
if any(c in value for c in "\"\x00"):
return '"'
if any(c in value for c in ";\r\n"):
return ";"
return ""
def merge_advanced(text: str, edits: dict) -> str:
"""The advanced options `text` with `edits` (NAME -> value; "" or None removes the pair) laid over it. A pair for an
edited name is replaced where it stands (later pairs of the same name are dropped) or removed; new names go at the
end; every other part, an unknown pair or one parse_advanced reports, is kept as it was written. Raises
ValueError for a value advanced_value_problem refuses. `text` comes back unchanged when `edits` is empty."""
for name, value in edits.items():
if not ADVANCED_NAME.match(name):
raise ValueError(f"not a LEONIDA_ name: {name}")
if value and advanced_value_problem(value):
raise ValueError(f"{name}: a value with \" or ; cannot be passed")
if not edits:
return text
parts: list[str] = []
done: set = set()
for part in re.split(r"[;\r\n]+", text or ""):
part = part.strip()
if not part:
continue
name = part.partition("=")[0].strip()
if "=" in part and name in edits:
if name not in done:
done.add(name)
value = (edits[name] or "").strip()
if value:
parts.append(f"{name}={value}")
continue
parts.append(part)
for name, value in edits.items():
value = (value or "").strip()
if name not in done and value:
parts.append(f"{name}={value}")
return "; ".join(parts)
# ---------------------------------------------------------------- what the F1 menu saved
MENU_FILE = "leonida-settings.txt"
# A line d3d12/scripts/play-nvidia.ps1 takes (Read-SettingsFile; PowerShell's -match ignores case): NAME=value, the
# value trimmed. Anything else (the # header, blank lines) is skipped.
MENU_LINE = re.compile(r"^\s*(LEONIDA_[A-Z0-9_]+)\s*=(.*)$", re.IGNORECASE)
# The names the F1 menu gives its settings (ITEMS in d3d12/crates/leonida-gpu/src/host/menu.rs), as the launcher
# writes them; a variable not listed here is shown by its own name.
MENU_LABELS = {
"LEONIDA_UPSCALE": "Upscaler",
"LEONIDA_RENDER_SCALE": "Render scale (DLSS mode)",
"LEONIDA_RENDER_SCALE_MIN": "Lowest scale (dynamic resolution)",
"LEONIDA_FRAME_GEN": "Frame generation",
"LEONIDA_FSR_FRAMEGEN": "FSR 3 frame generation",
"LEONIDA_ASPECT": "Window shape",
"LEONIDA_PRESENT_SCALE": "Picture in another shape",
"LEONIDA_FULLSCREEN": "Fullscreen (no border)",
"LEONIDA_FPS_LINE": "FPS at the top",
"LEONIDA_FPS_CAP": "Frame rate cap",
"LEONIDA_BVH_BUILDER": "Ray tracing (real lighting)",
"LEONIDA_HW_RT": "Hardware ray tracing (trial)",
"LEONIDA_DLSS_PRESET": "DLSS model",
"LEONIDA_DLSS_SHARPNESS": "DLSS sharpness",
"LEONIDA_MENU_SMOOTH_MOTION": "Smooth Motion",
"LEONIDA_MENU_CONSOLE": "Console",
"LEONIDA_ADAPTER": "Graphics card",
"LEONIDA_PANEL": "Stats panel (F3)",
"LEONIDA_D3D12_DRED": "Crash breadcrumbs",
}
# The menu's settings whose 1 and 0 are on and off.
MENU_ON_OFF = {"LEONIDA_FSR_FRAMEGEN", "LEONIDA_FULLSCREEN", "LEONIDA_FPS_LINE", "LEONIDA_BVH_BUILDER",
"LEONIDA_HW_RT", "LEONIDA_MENU_SMOOTH_MOTION", "LEONIDA_PANEL"}
MENU_NAMED_VALUES = {"dlss": "DLSS", "series-s": "Series S", "series-x": "Series X"}
# The Settings controls whose choice a variable of the menu file also makes (play-nvidia.ps1's $switchSettings).
MENU_FOR_OPTION = {"fg_mode": ("LEONIDA_FRAME_GEN", "LEONIDA_FSR_FRAMEGEN"), "dlss": ("LEONIDA_UPSCALE",),
"rt": ("LEONIDA_BVH_BUILDER", "LEONIDA_HW_RT"), "profile": ("LEONIDA_MENU_CONSOLE",),
"smooth_motion": ("LEONIDA_MENU_SMOOTH_MOTION",)}
def menu_file(repo: str = REPO) -> str:
"""The file the in-game F1 menu saves its choices to: d3d12/leonida-settings.txt of the repository."""
return os.path.join(repo, "d3d12", MENU_FILE)
def read_menu_settings(repo: str = REPO) -> dict:
"""What the F1 menu saved, as play-nvidia.ps1 reads it: NAME -> value in the file's order, the last line of a name
winning, "" for a value left empty (unset: the script removes that setting). {} without a file that reads."""
values: dict = {}
try:
with open(menu_file(repo), encoding="utf-8-sig", errors="replace") as f:
for line in f:
match = MENU_LINE.match(line.rstrip("\r\n"))
if match:
values[match.group(1).upper()] = match.group(2).strip()
except OSError:
return {}
return values
def clear_menu_settings(repo: str = REPO) -> bool:
"""Deletes the F1 menu's file, and only that file, when it is a regular file (not a link or a folder). True when
it was deleted."""
path = menu_file(repo)
if os.path.islink(path) or not os.path.isfile(path):
return False
os.remove(path)
return True
def menu_label(name: str) -> str:
return t(MENU_LABELS[name]) if name in MENU_LABELS else name
def menu_value(name: str, value: str) -> str:
"""A saved value as the launcher shows it: unset, On/Off, 2x, DLSS ...; otherwise the value itself."""
if value == "":
return t("unset")
if name in MENU_ON_OFF and value in ("0", "1"):
return t("On") if value == "1" else t("Off")
if name == "LEONIDA_FRAME_GEN" and value.isdigit():
return value + "x"
if name == "LEONIDA_FPS_CAP" and value == "0":
return t("No limit")
return MENU_NAMED_VALUES.get(value, value)
def menu_lines(values: dict) -> list[str]:
"""Each saved setting as "label: value"."""
return [t("{name}: {value}", name=menu_label(k), value=menu_value(k, v)) for k, v in values.items()]
def menu_note(option: str, values: dict) -> str:
"""The note beside a Settings control when the F1 menu file holds a value for the same setting; "" otherwise."""
names = [n for n in MENU_FOR_OPTION.get(option, ()) if n in values]
if not names:
return ""
if len(MENU_FOR_OPTION[option]) == 1:
shown = menu_value(names[0], values[names[0]])
else:
shown = ", ".join(t("{name}: {value}", name=menu_label(n), value=menu_value(n, values[n])) for n in names)
return t("F1 menu: {value}", value=shown)
CONSOLE_SWITCHES = {"SeriesS", "SeriesX"}
def effective_console(settings: dict, menu: dict, windows: bool = WINDOWS) -> str:
"""The profile the next PLAY runs, "series-x" or "series-s", with the start scripts' precedence: the launcher's
profile when its switch is among those changed since the last PLAY (chosen_switches: play-d3d12.ps1 -Chosen),
otherwise the F1 menu's LEONIDA_MENU_CONSOLE when the menu file (`menu`: read_menu_settings) holds one, otherwise
the launcher's. At the first PLAY nothing counts as changed (`-Chosen none`), so the menu's wins there too, as in
play-nvidia.ps1 ("What the F1 menu saved"). Linux: play-linux.sh reads no menu file, the launcher's profile."""
if not windows:
return "series-x" if settings["series_x"] else "series-s"
own = "series-s" if settings["series_s"] else "series-x" # Series X unless -SeriesS (the script's default)
if CONSOLE_SWITCHES & set(chosen_switches(switch_args(settings), settings.get("last_switches", ""))):
return own
saved = str(menu.get("LEONIDA_MENU_CONSOLE", "")).strip().lower()
# An empty value leaves the command line's console (play-nvidia.ps1: `if ($v) { $console = $v }`).
return saved if saved in ("series-x", "series-s") else own
def ps_quote(text: str) -> str:
"""`text` as a single-quoted PowerShell string. Every quote inside is doubled: PowerShell takes the typographic
single quotes (U+2018 to U+201B) for ' too, so a folder named with one would end the string."""
return "'" + re.sub("['‘’‚‛]", lambda m: m.group() * 2, text) + "'"
def play_command(settings: dict, repo: str = REPO, windows: bool = WINDOWS, chosen: list[str] | None = None,
extra: dict | None = None, mask: list[str] | None = None) -> list[str]:
"""The command PLAY runs. Raises ValueError when the game folder is not set. With `chosen`, only those switches
count as typed for the F1 menu (-Chosen; `none` for none); `mask` (card_mask) is -CardMask. With variables to pass
(extra_variables), the script is started with -Command, since -More takes a hashtable that -File cannot hand
over. On Linux the variables go into play-linux.sh's environment (`env NAME=value ...`), which the runtime
inherits: the Controls page's binds and the advanced options, as on Windows (review of #3272)."""
game = settings["game_dir"].strip()
if not game:
raise ValueError("Choose the game folder in Settings first.")
if windows:
script = os.path.join(repo, "scripts", "play-d3d12.ps1")
args = ["-Game", game]
if settings["data_dir"].strip():
args += ["-Data", settings["data_dir"].strip()]
if chosen is not None:
args += ["-Chosen", ",".join(chosen) or "none"]
if mask:
args += ["-CardMask", ",".join(mask)]
args += switch_args(settings)
more = extra_variables(settings, extra)
if not more:
return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script] + args
words = [a if re.fullmatch(r"-[A-Za-z]+", a) else ps_quote(a) for a in args]
table = "@{" + "; ".join(f"{k}={ps_quote(v)}" for k, v in more.items()) + "}"
return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command",
"& " + ps_quote(script) + " " + " ".join(words) + " -More " + table + "; exit $LASTEXITCODE"]
# scripts/play-linux.sh takes the executable and --series-x; the other options are Windows launcher switches.
command = ["sh", os.path.join(repo, "scripts", "play-linux.sh"), os.path.join(game, EXPECTED_EXE)]
if settings["series_x"]:
command.append("--series-x")
more = extra_variables(settings, extra)
if more:
command = ["env"] + [f"{k}={v}" for k, v in more.items()] + command
return command
def tool_command(name: str, repo: str = REPO, windows: bool = WINDOWS) -> list[str]:
"""The command of a Tools button: `get_dlss` or `build`. Both are Windows scripts."""
if not windows:
raise ValueError("This tool is a Windows script; on Linux see docs/linux.md.")
runtime = os.path.join(repo, "d3d12")
if name == "get_dlss":
return ["cmd", "/c", os.path.join(runtime, "Get-NVIDIA-DLSS.cmd")]
if name == "build":
return ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File",
os.path.join(runtime, "scripts", "build-nvidia.ps1")]
raise ValueError(f"unknown tool {name}")
def state_for_line(state: str, line: str) -> str:
"""The state shown after a line of output (a heuristic over the scripts' own messages)."""
text = line.strip()
if "Building the layer" in text or text.startswith("Compiling "):
return "Building the runtime"
if "Precompiling" in text:
return "Preparing shaders"
if state == "Preparing shaders" and text and not line.startswith(" "):
return "Running"
if text.startswith("Series ") and "F1 in the game" in text:
return "Running" if state != "Starting" else state
return state
# ---------------------------------------------------------------- updates
REPO_URL = "https://github.com/ProjectLeonida/mandy.git" # what a zip copy becomes a clone of (README's)
REPO_BRANCH = "main"
GIT_WINGET = ["install", "--id", "Git.Git", "-e", "--source", "winget", "--silent", "--accept-package-agreements",
"--accept-source-agreements"]
def find_git(windows: bool = WINDOWS, which=shutil.which, isfile=os.path.isfile, env=None) -> str | None:
"""git's program: the one on PATH, else (Windows) where Git for Windows installs it, for the machine or for this
user. A launcher started before Git was installed (by Update, below) still has the PATH it started with."""
found = which("git")
if found:
return found
if not windows:
return None
env = os.environ if env is None else env
for base in (env.get("ProgramFiles"), env.get("ProgramW6432"), env.get("ProgramFiles(x86)"),
os.path.join(env["LOCALAPPDATA"], "Programs") if env.get("LOCALAPPDATA") else None):
if base:
path = os.path.join(base, "Git", "cmd", "git.exe")
if isfile(path):
return path
return None
def find_winget(which=shutil.which, isfile=os.path.isfile, env=None) -> str | None:
found = which("winget")
if found:
return found
env = os.environ if env is None else env
if not env.get("LOCALAPPDATA"):
return None
path = os.path.join(env["LOCALAPPDATA"], "Microsoft", "WindowsApps", "winget.exe")
return path if isfile(path) else None
def _git(repo: str, *args: str, timeout: float = 60) -> subprocess.CompletedProcess:
kwargs: dict = {}
if WINDOWS:
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
return subprocess.run([find_git() or "git", "-C", repo, *args], capture_output=True, text=True, timeout=timeout,
stdin=subprocess.DEVNULL, check=False, **kwargs)
def update_status(repo: str = REPO, git=_git, fetch: bool = True) -> dict:
"""Whether this copy can be updated, how far behind it is and what the new commits are.
`kind` is "zip" (no .git: downloaded as an archive), "nogit" (git is not installed), "noupstream" (the branch
follows nothing), "error" (the fetch failed, `detail` says why), "behind" (`behind` new commits upstream) or
"current". A "behind" status also has `changes` (parse_changes: what the new first-parent commits are, newest
first; empty when git log failed). `git` runs `git -C repo <args>` and returns a CompletedProcess (replaced in the
tests).
"""
if not os.path.exists(os.path.join(repo, ".git")):
return {"kind": "zip", "behind": 0}
try:
if git(repo, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}").returncode != 0:
return {"kind": "noupstream", "behind": 0}
if fetch:
done = git(repo, "fetch", "--quiet")
if done.returncode != 0:
return {"kind": "error", "behind": 0, "detail": (done.stderr or done.stdout).strip()[:300]}
# First-parent only: one per pull request merged (or commit pushed) on the followed branch, the same as the
# lines of "what is new", not every commit inside each pull request.
count = git(repo, "rev-list", "--first-parent", "--count", "HEAD..@{u}")
if count.returncode == 0 and count.stdout.strip().isdigit() and int(count.stdout.strip()):
log = git(repo, "log", "--first-parent", "-n", str(CHANGES_READ), "--format=%h%x1f%s%x1f%b%x1e",
"HEAD..@{u}")
changes = parse_changes(log.stdout) if log.returncode == 0 else []
else:
changes = []
except FileNotFoundError:
return {"kind": "nogit", "behind": 0}
except subprocess.TimeoutExpired:
return {"kind": "error", "behind": 0, "detail": "git took too long"}
if count.returncode != 0 or not count.stdout.strip().isdigit():
return {"kind": "error", "behind": 0, "detail": (count.stderr or count.stdout).strip()[:300]}
behind = int(count.stdout.strip())
if behind:
return {"kind": "behind", "behind": behind, "changes": changes}
return {"kind": "current", "behind": 0}
CHANGES_READ = 50 # first-parent commits read for "what is new"
MERGE_SUBJECT = re.compile(r"^Merge pull request #(\d+) from \S+")
def parse_changes(text: str) -> list[dict]:
"""The new commits from `git log --first-parent --format=%h%x1f%s%x1f%b%x1e`, newest first, as {title, pr, hash}.
A merge of a pull request ("Merge pull request #N from owner/branch") is named by the first line of its body, the
pull request's title, with pr = N; any other commit by its subject, pr = None."""
changes = []
for record in text.split("\x1e"):
record = record.strip("\r\n")
if not record.strip():
continue
parts = record.split("\x1f")
if len(parts) < 2:
continue
commit, subject = parts[0].strip(), parts[1].strip()
body = parts[2] if len(parts) > 2 else ""
title, pr = subject, None
merge = MERGE_SUBJECT.match(subject)
if merge:
pr = int(merge.group(1))
lines = [line.strip() for line in body.splitlines() if line.strip()]
if lines:
title = lines[0]
changes.append({"title": title, "pr": pr, "hash": commit})
return changes
def change_line(change: dict, limit: int = 70) -> str:
"""One line of "what is new": "#3097 Compare on the sender thread", cut with an ellipsis past `limit`."""
text = (f"#{change['pr']} " if change.get("pr") else "") + change.get("title", "")
return text if len(text) <= limit else text[:limit - 1].rstrip() + "\u2026"
def update_note(status: dict) -> str:
"""The line the launcher shows for an update status ("" when there is nothing to say)."""
kind = status.get("kind")
if kind == "behind":
return t("Update available: {n} new commit(s): the Update button, or Tools > Update Mandy.",
n=status["behind"])
if kind == "zip":
return t("This copy was downloaded as a zip: Update Mandy turns it into a git copy that updates itself.")
if kind == "nogit":
return t("Git is not installed: the launcher cannot check for updates.")
if kind == "error":
return t("Could not check for updates: {detail}", detail=status.get("detail") or "git failed")
return ""
def update_command(repo: str = REPO, install_git: bool = False) -> list[str]:
"""The Update button's command: this file's own --update (git pull --ff-only, then a rebuild if d3d12/ moved),
so its output streams into the launcher like the other tools. `install_git`: the window asked already."""
command = [sys.executable, "-I", os.path.abspath(__file__), "--update", repo]
return command + ["--install-git"] if install_git else command
def install_git(windows: bool = WINDOWS, run=None, find=find_git, winget=find_winget) -> str | None:
"""Installs Git for Windows with winget (Windows may ask for permission) and returns git's program, or prints how
to install it and returns None (no winget, Linux, macOS, or the install failed)."""
found = find()
if found:
return found
if not windows:
print("Git is not installed: install it with your package manager (for example: sudo apt install git), "
"then update again.", flush=True)
return None
program = winget()
if program is None:
print("Git is not installed and winget is not available: install Git from https://git-scm.com/download/win, "
"then update again.", flush=True)
return None
print("Installing Git with winget (Windows may ask for permission) ...", flush=True)
code = (run or subprocess.call)([program, *GIT_WINGET])
found = find()
if found is None:
print(f"Git could not be installed (winget ended with code {code}): install it from "
"https://git-scm.com/download/win, then update again.", flush=True)
return None
print(f"Git is installed: {found}", flush=True)
return found
def zip_backup_dir(now: float | None = None) -> str:
"""Where a zip copy's files that differ from the repository are kept before they are replaced."""
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
return os.path.join(local_data_dir(), "Leonida", f"zip-copy-backup-{stamp}")
def _remove_tree(path: str) -> None:
def writable(func, target, _exc): # git's packs and objects are read-only on Windows
os.chmod(target, stat.S_IWRITE)
func(target)
shutil.rmtree(path, onexc=writable)
def zip_collisions(repo: str, paths: list[str]) -> list[str]:
"""The local files and folders that would be lost writing the repository's `paths` over a zip copy: a folder where
a tracked file goes, or a file (or link) where a tracked file's folder goes. git's checkout replaces those without a
word, and the backup copies files only, so zip_to_clone stops before it when there is one (review of #3272)."""
found: set[str] = set()
for path in paths:
parts = path.split("/")
local = os.path.join(repo, *parts)
if os.path.isdir(local) and not os.path.islink(local):
found.add(path)
continue
for i in range(1, len(parts)):
parent = os.path.join(repo, *parts[:i])
if os.path.lexists(parent) and (os.path.islink(parent) or not os.path.isdir(parent)):
found.add("/".join(parts[:i]))
break
return sorted(found)
def zip_to_clone(repo: str, git=_git, backup: str | None = None, url: str = REPO_URL,
branch: str = REPO_BRANCH) -> tuple[int, bool]:
"""Turns a copy downloaded as a zip into a clone of `url`'s `branch`, in place, and returns (exit code, whether a
file under d3d12/ was replaced or added).
git init, an origin remote, a fetch of the branch, a local branch following it, the index set to it with the files
left as they are; then every tracked file that differs (the zip's older version or the player's own edit: they
cannot be told apart) is copied to `backup`, and the branch's version is checked out over the tracked files. Files
the repository does not track (builds, caches, settings) are not touched. A local folder where the branch has a
file, or a file where it has a folder (zip_collisions), stops it before anything is written. Any failure removes the new .git, so the
next start finds a zip copy again (one whose replaced files already match, if it got that far), never half a
clone."""
git_dir = os.path.join(repo, ".git")
backup = backup or zip_backup_dir()
def give_up(what: str, done: subprocess.CompletedProcess | None = None) -> tuple[int, bool]:
detail = (done.stderr or done.stdout or "").strip()[:300] if done is not None else ""
print(f"The update stopped: {what}" + (f" ({detail})" if detail else "") + ".", flush=True)
try:
if os.path.isdir(git_dir):
_remove_tree(git_dir)
print("This copy is a zip copy again: press Update Mandy to try again.", flush=True)
except OSError as exc:
print(f"The new .git folder could not be removed ({exc}): delete {git_dir} before trying again.",
flush=True)
return ((done.returncode or 1) if done is not None else 1), False
print("This copy was downloaded as a zip: making it a git copy of the repository, so it can update itself.",
flush=True)
replaced: list[str] = []
try:
for args, what in ((("init", "-q"), "git init failed"),
(("symbolic-ref", "HEAD", f"refs/heads/{branch}"), "git could not name the branch"),
(("remote", "add", "origin", url), "git could not add the repository")):
done = git(repo, *args)
if done.returncode != 0:
return give_up(what, done)
print(f"Downloading {url} ({branch}): a few minutes the first time ...", flush=True)
done = git(repo, "fetch", "--quiet", "origin", branch, timeout=3600)
if done.returncode != 0:
return give_up("the download failed", done)
for args, what in ((("update-ref", f"refs/heads/{branch}", f"refs/remotes/origin/{branch}"),
"git could not make the branch"),
(("branch", "-q", f"--set-upstream-to=origin/{branch}", branch),
"git could not make the branch follow the repository's"),
(("reset", "-q"), "git could not read the files")):
done = git(repo, *args, timeout=600)
if done.returncode != 0:
return give_up(what, done)
# Tracked files that differ from the branch: changed (kept first) or missing (new in the repository).
changed = git(repo, "diff", "--name-only", "-z", "--no-renames", "--diff-filter=MT", timeout=600)
every = git(repo, "diff", "--name-only", "-z", "--no-renames", timeout=600)
if changed.returncode != 0 or every.returncode != 0:
return give_up("git could not compare the files", changed if changed.returncode else every)
kept = [p for p in changed.stdout.split("\0") if p]
replaced = [p for p in every.stdout.split("\0") if p]
# A folder where the repository puts a file, or a file where it puts a folder: the checkout would replace it
# and the backup (files only) would not have it. Stop first: nothing is changed, the copy stays a zip copy.
blocked = zip_collisions(repo, replaced)
if blocked:
shown = ", ".join(blocked[:5]) + (f" and {len(blocked) - 5} more" if len(blocked) > 5 else "")
return give_up(f"these are in the way of the repository's files: {shown}. Move or rename them, then "
"press Update Mandy again")
for path in kept:
source = os.path.join(repo, *path.split("/"))
target = os.path.join(backup, *path.split("/"))
try:
os.makedirs(os.path.dirname(target), exist_ok=True)
shutil.copy2(source, target)
except OSError as exc:
return give_up(f"{path} could not be kept in {backup}: {exc}")
if kept:
print(f"{len(kept)} file(s) differ from the repository: a copy of each is in {backup}", flush=True)
if replaced:
done = git(repo, "checkout", "-q", "HEAD", "--", ".", timeout=600)
if done.returncode != 0:
if kept:
print(f"Your copies of the files are still in {backup}.", flush=True)
return give_up("git could not write the new files", done)
left = git(repo, "status", "--porcelain", "--untracked-files=no")
if left.returncode == 0 and left.stdout.strip():
print("Still different after the update (line endings?):\n" + left.stdout.rstrip(), flush=True)
except FileNotFoundError:
return give_up("git is not installed")
except subprocess.TimeoutExpired:
return give_up("git took too long")
head = git(repo, "rev-parse", "--short", "HEAD").stdout.strip()
print(f"This copy is now a git copy of {branch} ({head}): {len(replaced)} file(s) updated. "
"Next time, Update Mandy is a git pull.", flush=True)
return 0, any(p.startswith("d3d12/") for p in replaced)
def rebuild_if_changed(changed: bool, repo: str, build=None, windows: bool = WINDOWS) -> int:
"""The end of an update: rebuild the runtime when d3d12/ changed (Windows; on Linux only say so)."""
if not changed:
print("Updated. The runtime did not change: no rebuild needed.", flush=True)
return 0
if not windows:
print("Updated. d3d12/ changed: rebuild the runtime (docs/linux.md).", flush=True)
return 0
print("Updated. d3d12/ changed: rebuilding the runtime (a few minutes) ...", flush=True)
if build is None:
build = lambda: subprocess.call(tool_command("build", repo))
return build()
def run_update(repo: str, git=_git, build=None, windows: bool = WINDOWS, install: bool = False, ask=None,
find=find_git, get_git=None, backup: str | None = None) -> int:
"""`--update`: fast-forward the clone to its upstream, then rebuild the runtime when d3d12/ changed. Prints what
it does; returns the exit code. `build` runs the build (the tests replace it).
A zip copy is made a clone first (zip_to_clone). Without Git, Git is installed first (install_git; `get_git` in
the tests) when `install` is set (the launcher's window asked already) or `ask()` says yes (a console)."""
status = update_status(repo, git)
if status["kind"] == "zip":
if find() is None:
if not (install or (ask is not None and ask())):
print("A zip copy needs Git to update, and Git is not installed: use the launcher's Update Mandy, "
"or install Git (https://git-scm.com/download/win) and update again.", flush=True)
return 1
if (get_git or (lambda: install_git(windows)))() is None:
return 1
code, changed = zip_to_clone(repo, git, backup)
if code:
return code
return rebuild_if_changed(changed, repo, build, windows)
if status["kind"] not in ("behind", "current"):
print(update_note(status) or f"Cannot update ({status['kind']}).", flush=True)
return 1
before = git(repo, "rev-parse", "HEAD").stdout.strip()
if status["kind"] == "current":
print("Already up to date.", flush=True)
return 0
print(f"Updating: {status['behind']} new commit(s) ...", flush=True)
pulled = git(repo, "pull", "--ff-only", timeout=600)
print((pulled.stdout + pulled.stderr).strip(), flush=True)
if pulled.returncode != 0:
print("The update stopped: git could not fast-forward (local changes or another branch?). "
"Nothing was changed.", flush=True)
return pulled.returncode
after = git(repo, "rev-parse", "HEAD").stdout.strip()
changed = git(repo, "diff", "--quiet", before, after, "--", "d3d12").returncode != 0
return rebuild_if_changed(changed, repo, build, windows)
# ---------------------------------------------------------------- folders
def local_data_dir() -> str:
if WINDOWS:
return os.environ.get("LOCALAPPDATA") or os.path.join(os.path.expanduser("~"), "AppData", "Local")
return os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share")
def logs_dir() -> str:
return os.path.join(local_data_dir(), "Leonida", "logs")
def captures_dir() -> str:
return os.path.join(local_data_dir(), "Leonida", "captures")
def screenshot_dirs(repo: str = REPO) -> list[str]:
"""Where the runtime saves pictures: the F4 menu's screenshots (next to the exe) and F9 captures."""
return [os.path.join(repo, "d3d12", "target", "diag", "screenshots"), captures_dir()]
# ---------------------------------------------------------------- languages
I18N_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "launcher_i18n")
# The names the language menu shows, each in its own language; English is the text in this file.
LANGUAGE_NAMES = {"en": "English", "fr": "Français", "es": "Español", "pt": "Português", "de": "Deutsch"}
# Windows' primary language identifiers (the low 10 bits of a LANGID) of the languages above.
WINDOWS_LANGUAGES = {0x09: "en", 0x0C: "fr", 0x0A: "es", 0x16: "pt", 0x07: "de"}
STRINGS: dict = {} # English text -> the chosen language's (load_strings); empty = English
def t(text: str, **values) -> str:
"""`text` in the window's language (STRINGS), English when it has no translation, with {names} filled in."""
text = STRINGS.get(text) or text
return text.format(**values) if values else text
def system_language(windows: bool = WINDOWS) -> str:
"""The user's language as a two-letter code: Windows' display language, else the locale variables; "" when
neither says."""
if windows:
try:
import ctypes
primary = ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF
if primary in WINDOWS_LANGUAGES:
return WINDOWS_LANGUAGES[primary]
except (OSError, AttributeError, ImportError):
pass
for name in ("LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"):
value = os.environ.get(name, "")
if value and value not in ("C", "POSIX"):
return value.split(":")[0][:2].lower()
try:
import locale
code = locale.getlocale()[0] or ""
except (ValueError, TypeError):
code = ""
return code[:2].lower()
def pick_language(setting: str, system: str) -> str:
"""The language to show: the setting when it names one, else the system's when it is translated, else English."""
if setting in LANGUAGE_NAMES:
return setting
return system if system in LANGUAGE_NAMES else "en"
def load_strings(language: str, folder: str = I18N_DIR) -> dict:
"""tools/launcher_i18n/<language>.json: English text -> translation. {} for English or a file that does not read;
a value that is not text is left out (that text stays English)."""
if language == "en":
return {}
try:
with open(os.path.join(folder, language + ".json"), encoding="utf-8") as f:
data = json.load(f)
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
return {}
if not isinstance(data, dict):
return {}
return {k: v for k, v in data.items() if isinstance(k, str) and isinstance(v, str) and v}
# ---------------------------------------------------------------- what to send when asking for help
def nvidia_driver(version: str) -> str:
"""NVIDIA's own driver number (621.47) from the Windows one (32.0.16.2147): the last five digits of its last two
fields. "" when `version` is not of that form."""
parts = version.strip().split(".")
if len(parts) != 4 or not all(p.isdigit() for p in parts):
return ""
digits = (parts[2] + parts[3])[-5:]
if len(digits) < 5:
return ""
return f"{int(digits[:3])}.{digits[3:]}"
def graphics_cards(windows: bool = WINDOWS) -> list[tuple[str, str]]:
"""Each graphics card's name and Windows driver version (WMI). Slow (about a second): not on the window's thread."""
if not windows:
return []
command = ["powershell", "-NoProfile", "-Command",
"Get-CimInstance Win32_VideoController | ForEach-Object { $_.Name + '|' + $_.DriverVersion }"]
try:
out = subprocess.run(command, capture_output=True, text=True, timeout=20, stdin=subprocess.DEVNULL,
creationflags=subprocess.CREATE_NO_WINDOW, check=False).stdout
except (OSError, subprocess.TimeoutExpired):
return []
cards = []
for line in out.splitlines():
name, _sep, version = line.strip().partition("|")
if name:
cards.append((name.strip(), version.strip()))
return cards
# Windows' display adapter class: one numbered subkey (0000, 0001 ...) per graphics driver installed, its card's name in
# DriverDesc and its own memory in HardwareInformation.qwMemorySize (64-bit; play-nvidia.ps1 reads the same value).
# Read from the registry (winreg): about 10 ms the first time, under 1 ms after, so on the window's thread.
DISPLAY_CLASS = r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}"
CARD_MEMORY = "HardwareInformation.qwMemorySize"
def read_display_class(windows: bool = WINDOWS) -> list[dict]:
"""Each numbered subkey of the display adapter class as {"DriverDesc": ..., "MatchingDeviceId": ...,
CARD_MEMORY: ...} (the values it has); [] off Windows or when the key does not read."""
if not windows:
return []
try:
import winreg
except ImportError:
return []
entries = []
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, DISPLAY_CLASS) as root:
for index in range(1000):
try:
name = winreg.EnumKey(root, index)
except OSError:
break
if not name.isdigit(): # Configuration, Properties
continue
entry = {}
try:
with winreg.OpenKey(root, name) as key:
for value in ("DriverDesc", "MatchingDeviceId", CARD_MEMORY):
try:
entry[value] = winreg.QueryValueEx(key, value)[0]
except OSError:
pass
except OSError:
continue
entries.append(entry)
except OSError:
return []
return entries
def read_entries(read=None) -> list:
"""read_display_class's entries (or `read`'s); [] when reading raises."""
try:
entries = (read or read_display_class)()
except Exception:
return []
return entries if isinstance(entries, list) else []
def card_entries(entries: list) -> list[dict]:
"""The real cards among the display class `entries`, as {"name", "memory"} in the registry's order: each name once
(any case), without Windows' software adapters (Microsoft Basic Render Driver, Basic Display Adapter, Remote
Display Adapter, Hyper-V Video) or drivers that are not on the PCI bus (virtual displays)."""
cards, seen = [], set()
for entry in entries:
if not isinstance(entry, dict):
continue
name = entry.get("DriverDesc")
device = entry.get("MatchingDeviceId")
if not isinstance(name, str) or not name.strip():
continue
name = name.strip()
if name.lower().startswith("microsoft "):
continue
if isinstance(device, str) and device and not device.lower().startswith("pci\\"):
continue
if name.lower() not in seen:
seen.add(name.lower())
cards.append({"name": name, "memory": card_memory(entry.get(CARD_MEMORY))})
return cards
def display_adapters(read=None) -> list[str]:
"""The names of this PC's graphics cards for the Graphics card list (card_entries), from read_display_class or
`read`. [] when nothing reads."""
return [card["name"] for card in card_entries(read_entries(read))]
def card_memory(value) -> int:
"""A qwMemorySize value in bytes: the QWORD's number, or its 8 bytes when a driver wrote it as binary; 0 when
there is none or it is of another kind, a shorter or longer byte array included (unknown, as in play-nvidia.ps1,
which reads exactly the same values)."""
if isinstance(value, bool):
return 0
if isinstance(value, int):
return max(value, 0)
if isinstance(value, (bytes, bytearray)) and len(value) == 8:
return int.from_bytes(bytes(value), "little")
return 0
def card_vendor(name: str) -> str:
""""nvidia", "amd" or "intel" from a card's name (DriverDesc); "" for another maker."""
low = name.lower()
if "nvidia" in low:
return "nvidia"
if "amd" in low or "radeon" in low:
return "amd"
if "intel" in low:
return "intel"
return ""
def card_facts(entries: list, adapter: str = "") -> dict:
"""What Settings' rules know of the card the game runs on, from the display class `entries` (read_entries):
{"known": a card was read, "nvidia": an NVIDIA card is among those judged, "vendor": their maker (card_vendor;
"nvidia" when one is), "vram": play-nvidia.ps1's $vram, in bytes, 0 when unknown}. With `adapter` (the Graphics
card list's value) the cards whose name contains it (any case, as the runtime looks for it) are judged; without
one, or when no card's name has it (#1, a card taken out), every card. That choice is about what the chosen card
can do (DLSS, Smooth Motion, its maker) and leaves "vram" alone. Nothing read (off Windows): known False, NVIDIA
assumed, nothing greyed."""
# play-nvidia.ps1's $vram: the largest qwMemorySize of every subkey of the display class, whatever -Adapter says
# (the script does not look at -Adapter for it). Its 20 GB rule of frame generation with ray tracing reads it, so
# Settings does too: an 8 GB card chosen beside a 24 GB one runs that rule with 24 GB.
vram = max([card_memory(e.get(CARD_MEMORY)) for e in entries if isinstance(e, dict)] + [0])
cards = card_entries(entries)
if not cards:
return {"known": False, "nvidia": True, "vendor": "", "vram": vram}
wanted = adapter.strip().lower()
judged = [c for c in cards if wanted and wanted in c["name"].lower()] or cards
vendors = [card_vendor(c["name"]) for c in judged]
vendor = "nvidia" if "nvidia" in vendors else next((v for v in vendors if v), "")
return {"known": True, "nvidia": "nvidia" in vendors, "vendor": vendor, "vram": vram}
# The settings play-nvidia.ps1 decides frame generation with ray tracing from (after the menu merge and -More).
LAUNCH_KEYS = ("LEONIDA_HW_RT", "LEONIDA_BVH_BUILDER", "LEONIDA_FG_WITH_RT", "LEONIDA_FRAME_GEN",
"LEONIDA_FSR_FRAMEGEN")
# play-nvidia.ps1's $switchSettings for those keys and the console: a switch named in -Chosen (changed since the last
# PLAY) takes them from the F1 menu's file. A switch not listed takes none: -HardwareRT is not in the script's table,
# so the menu file's LEONIDA_HW_RT wins over the Ray tracing control even when it was changed since the last PLAY.
# play-d3d12.ps1 passes -SeriesS on as SeriesX. A test reads the script's table to keep this one equal to it.
LAUNCH_SWITCH_SETTINGS = {
"SeriesX": ("LEONIDA_MENU_CONSOLE",),
"SeriesS": ("LEONIDA_MENU_CONSOLE",),
"FrameGen": ("LEONIDA_FRAME_GEN", "LEONIDA_FSR_FRAMEGEN"),
"NoFrameGen": ("LEONIDA_FRAME_GEN",),
"FsrFrameGen": ("LEONIDA_FSR_FRAMEGEN", "LEONIDA_FRAME_GEN"),
"RayTracing": ("LEONIDA_BVH_BUILDER", "LEONIDA_AMBIENT"),
}
def launch_values(settings: dict, menu: dict, windows: bool = WINDOWS) -> dict:
"""What play-nvidia.ps1 will hold for LAUNCH_KEYS and the console when PLAY starts it with `settings` (the
launcher's, as the controls are now) and the F1 menu's file `menu` (read_menu_settings), in the script's order:
the launcher's switches (switch_args) first; then the menu file's value of each key that no switch changed since
the last PLAY takes (LAUNCH_SWITCH_SETTINGS; an empty value unsets it); then -More (extra_variables: the Advanced
field, the frame limit), which always wins. Returns {"console": effective_console's, KEY: value for each key set,
"from": {KEY: "launcher", "menu" or "advanced", the last step that set or unset it}}. Linux: play-linux.sh reads
neither the menu file nor -More, the launcher's switches only."""
passed = switch_values(switch_args(settings))
values: dict = {}
sources: dict = {}
def put(name, value, source):
if value:
values[name] = value
else:
values.pop(name, None)
sources[name] = source
if "HardwareRT" in passed: # the script's -HardwareRT, else -RayTracing
put("LEONIDA_HW_RT", "1", "launcher")
elif "RayTracing" in passed:
put("LEONIDA_BVH_BUILDER", "1", "launcher")
if passed.get("FrameGen") not in (None, True):
put("LEONIDA_FRAME_GEN", str(passed["FrameGen"]), "launcher")
if "FsrFrameGen" in passed:
put("LEONIDA_FSR_FRAMEGEN", "1", "launcher")
if not windows:
return {"console": effective_console(settings, menu, windows), **values, "from": sources}
more = extra_variables(settings)
chosen = {k for name in chosen_switches(switch_args(settings), settings.get("last_switches", ""))
for k in LAUNCH_SWITCH_SETTINGS.get(name, ())}
for name, value in menu.items():
if name in LAUNCH_KEYS and name not in chosen and name not in more:
put(name, str(value).strip(), "menu")
for name, value in more.items():
if name in LAUNCH_KEYS:
put(name, str(value), "advanced")
# A -More name counts as chosen now in the script too: the menu's value of it is dropped (the console's as well).
kept = {k: v for k, v in menu.items() if k not in more}
return {"console": effective_console(settings, kept, windows), **values, "from": sources}
# Frame generation with ray tracing (play-nvidia.ps1, LEONIDA_FG_WITH_RT): left off on the Series X profile with under
# 20 GB of video memory, where it ran out of it after a few minutes (16 GB cards); 0 (unknown) holds nothing back.
FG_RT_MEMORY = 20 * 1024 ** 3
def fg_with_rt(ray_tracing: bool, console: str, vram: int, unlock: str | None) -> str:
"""What play-nvidia.ps1 does with frame generation under ray tracing (software or hardware): "" without ray
tracing; "off" with LEONIDA_FG_WITH_RT=0 (left off everywhere); "memory" on the Series X profile with `vram` (the
script's $vram: card_facts) under FG_RT_MEMORY (left off); "unlocked" there with LEONIDA_FG_WITH_RT=1; "asked"
otherwise (it runs when asked for: never the automatic 2x)."""
if not ray_tracing:
return ""
unlock = (unlock or "").strip()
if unlock == "0":
return "off"
if console == "series-x" and 0 < vram < FG_RT_MEMORY:
return "unlocked" if unlock == "1" else "memory"
return "asked"
def settings_rules(values: dict, card: dict, launch: dict) -> tuple[dict, dict]:
"""Settings' greying and notes from the controls' values, the card (card_facts) and what the next PLAY's script
will hold (launch_values: the console, ray tracing, frame generation and LEONIDA_FG_WITH_RT after the F1 menu's
file and Advanced), so that the greying, the notes and the launch agree. `values`: rt ("off"/"hw"), dlss (bool),
dlss_mode ("" = Auto), fg_mode ("dlss"/"fsr"/"off"), aspect, precompile_all. Returns ({control: enabled}, notes):
"fg_dlss" is the DLSS button of the frame generation mode, and the notes are {"fg": (text, warning) or None,
"nvidia": text or None, "rt": text or None}. Nothing here changes a value: a greyed control keeps its own."""
nvidia = bool(card.get("nvidia", True)) or not card.get("known")
dlss_on = bool(values.get("dlss"))
fg_mode = values.get("fg_mode", "dlss")
sources = launch.get("from", {})
hardware = launch.get("LEONIDA_HW_RT") == "1"
software = launch.get("LEONIDA_BVH_BUILDER") == "1"
state = fg_with_rt(hardware or software, launch.get("console", ""), card.get("vram", 0),
launch.get("LEONIDA_FG_WITH_RT"))
blocked = state in ("off", "memory")
enabled = {
"dlss": nvidia,
"dlss_mode": nvidia and dlss_on,
"resolution": not (nvidia and dlss_on and values.get("dlss_mode", "")),
"smooth_motion": nvidia,
"fg_mode": not blocked,
"fg_dlss": nvidia,
"fg_limit": not blocked and fg_mode != "off",
"frame_gen": not blocked and fg_mode == "dlss" and nvidia,
"present_scale": values.get("aspect", "") != "",
"precompile": not values.get("precompile_all"),
}
in_file = sources.get("LEONIDA_FG_WITH_RT") == "menu"
lines, warning = [], False
if state == "off":
lines.append(t("Frame generation is off with ray tracing: LEONIDA_FG_WITH_RT=0 in the F1 menu's file")
if in_file else t("Frame generation is off with ray tracing: LEONIDA_FG_WITH_RT=0 in Advanced"))
warning = True
elif state == "memory":
lines.append(t("Series X with ray tracing needs 20 GB of video memory for frame generation"))
warning = True
elif state == "unlocked":
lines.append(t("Frame generation with ray tracing: unlocked in the F1 menu's file (LEONIDA_FG_WITH_RT=1)")
if in_file else t("Frame generation with ray tracing: unlocked in Advanced (LEONIDA_FG_WITH_RT=1)"))
asked = launch.get("LEONIDA_FRAME_GEN") or launch.get("LEONIDA_FSR_FRAMEGEN") == "1"
if state in ("asked", "unlocked") and fg_mode == "dlss" and nvidia and not asked:
lines.append(t("With ray tracing, frame generation runs only when asked: choose 2x"))
# Muted notes under the Ray tracing control when the F1 menu's file or Advanced decides it, not the control.
rt_lines = []
where = sources.get("LEONIDA_HW_RT")
if where == "menu" and hardware:
rt_lines.append(t("Hardware ray tracing is on from the F1 menu"))
elif where == "advanced" and hardware:
rt_lines.append(t("Hardware ray tracing is on from Advanced"))
elif where == "menu" and values.get("rt") == "hw":
rt_lines.append(t("Hardware ray tracing is off from the F1 menu"))
elif where == "advanced" and values.get("rt") == "hw":
rt_lines.append(t("Hardware ray tracing is off from Advanced"))
where = sources.get("LEONIDA_BVH_BUILDER")
if software and where in ("menu", "advanced"):
rt_lines.append(t("Ray tracing is on from the F1 menu") if where == "menu"
else t("Ray tracing is on from Advanced"))
if card.get("known") and card.get("vendor") in ("amd", "intel"):
rt_lines.append(t("Not tested on AMD/Intel cards yet"))
notes = {"fg": ("\n".join(lines), warning) if lines else None,
"nvidia": None if nvidia else t("DLSS and Smooth Motion need an NVIDIA RTX card"),
"rt": "\n".join(rt_lines) or None}
return enabled, notes
def adapter_value(name: str) -> str:
"""What -Adapter gets for the card `name`: the name itself, which play-nvidia.ps1 hands the runtime as
LEONIDA_ADAPTER and the runtime looks for in each card's name (any case, host.rs chosen_adapter). A name ADAPTER
does not take (longer than 64, or other characters such as ®) gives its longest part ADAPTER takes, which the
name still contains. "" when nothing of it fits."""
name = name.strip()
if ADAPTER.match(name):
return name
parts = sorted((p.strip() for p in re.findall(r"[\w #.()+-]+", name)), key=len, reverse=True)
best = parts[0][:64].strip() if parts else ""
return best if ADAPTER.match(best) else ""
def frame_gen_options() -> list[tuple[str, str]]:
"""The frame generation multiplier list as (value, label): Auto (0, nothing passed: the script's own choice), then
2x to 6x (-FrameGen n). 3x and up are marked RTX 50: the runtime makes no more than the card does (fg.rs asks
Streamline for its most), which is 2x on an RTX 40."""
return [("0", t("Auto"))] + [(str(n), f"{n}x" if n == 2 else f"{n}x (RTX 50)") for n in FRAME_GEN if n]
def aspect_options(saved: str) -> list[tuple[str, str]]:
"""The window shape list as (value, label): Default (nothing passed, 16:9), the screen's (auto) and the usual
shapes, then the saved shape when it is another one (W:H, a decimal: ASPECT takes them), kept as it is."""
options = [("", t("Default (16:9)")), ("auto", t("Your screen's"))] + [(a, a) for a in ASPECTS if a and a != "auto"]
if saved and saved not in ASPECTS:
options.append((saved, saved))
return options
def adapter_options(names: list[str], saved: str) -> list[tuple[str, str]]:
"""The Graphics card list as (value, label): Default first (empty: the script's own choice, Windows' default card),
then each card by its name, then the saved value when no card gives it (an older choice, #1, a card taken out)."""
options = [("", t("Default"))]
for name in names:
value = adapter_value(name)
if value and value not in dict(options):
options.append((value, name))
if saved and saved not in dict(options):
options.append((saved, saved))
return options
def leonida_version(repo: str = REPO, git=_git) -> str:
"""The commit this copy is at, with its date ("zip copy" without .git)."""
if not os.path.exists(os.path.join(repo, ".git")):
return "zip copy"
try:
done = git(repo, "log", "-1", "--format=%h %cs")
except (OSError, subprocess.TimeoutExpired):
return "unknown (git did not run)"
return done.stdout.strip() if done.returncode == 0 and done.stdout.strip() else "unknown"
def rail_version(repo: str = REPO, git=_git) -> str:
"""The branch and commit for the rail ("main 4910c5c2e"); "zip copy" without .git, "" when git does not run."""
if not os.path.exists(os.path.join(repo, ".git")):
return "zip copy"
try:
branch = git(repo, "rev-parse", "--abbrev-ref", "HEAD")
commit = git(repo, "rev-parse", "--short", "HEAD")
except (OSError, subprocess.TimeoutExpired):
return ""
if commit.returncode != 0:
return ""
name = branch.stdout.strip() if branch.returncode == 0 else ""
return f"{name} {commit.stdout.strip()}".strip()
# ---------------------------------------------------------------- Windows' commit limit (RAM + page file)
GIB = 1 << 30
# The Series X profile commits about 59 GB in all: 58.8 GB measured in an open-world run on a 48 GB PC, where a
# 52.8 GB commit limit (automatic page file) fell short and a fixed 32 GB page file (79.8 GB limit) left 0 seconds
# under pressure (d3d12/docs/windows-memory.md, "Fixed page file sizing for the Series X profile"). 64 GiB leaves
# room for Windows and the applications left open. Below it, long frames are likely, and every frame over 100 ms
# resets DLSS frame generation. Series S has no such total measured (that page only has one cutscene's peak, with
# gameplay unverified), so it gets no note.
SERIES_X_COMMIT_BYTES = 64 * GIB
COMMIT_TARGET_GB = 80 # what the note suggests reaching: the measured 79.8 GB limit
def _memory_status(windows: bool = WINDOWS):
"""GlobalMemoryStatusEx's answer, or None off Windows or when the call fails."""
if not windows:
return None
try:
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
status = MEMORYSTATUSEX()
status.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
return None
return status
except (OSError, AttributeError, ImportError):
return None
def commit_limit_bytes(windows: bool = WINDOWS) -> int | None:
"""Windows' current commit limit in bytes (GlobalMemoryStatusEx's ullTotalPageFile: RAM plus the page file, the
second figure of Task Manager's "Committed"); None off Windows or when it cannot be read."""
status = _memory_status(windows)
if status is None or not status.ullTotalPageFile:
return None
return int(status.ullTotalPageFile)
def physical_memory_bytes(windows: bool = WINDOWS) -> int | None:
"""The PC's usable RAM in bytes (ullTotalPhys, read by the same call); None off Windows or when it cannot be
read."""
status = _memory_status(windows)
if status is None or not status.ullTotalPhys:
return None
return int(status.ullTotalPhys)
def gb(n: int | None, digits: int = 0) -> str:
"""Bytes as Windows' GB (GiB, as Task Manager counts them); "?" when unknown."""
return "?" if n is None else f"{n / GIB:.{digits}f}"
def memory_note(series_x: bool, commit_limit: int | None, total_phys: int | None, short: bool = False) -> str | None:
"""The warning for a commit limit too low for the Series X profile: the long one under Settings' Profile, the
`short` one on the Play card. None with Series S, a limit of SERIES_X_COMMIT_BYTES or more, or an unknown limit.
Only a warning: PLAY and its command stay the same."""
if not series_x or commit_limit is None or commit_limit >= SERIES_X_COMMIT_BYTES:
return None
if short:
return t("Series X needs about 59 GB of memory (RAM + page file), this PC has {limit} GB: expect stutters",
limit=gb(commit_limit, 1))
return t("This PC: {ram} GB of RAM, {limit} GB of memory with the page file. The Series X profile alone needs "
"about 59 GB, whatever the DLSS and ray tracing settings, plus room for Windows and your apps (64 GB in "
"all): expect stutters and frame generation cutting in and out. Use Series S, or a fixed page file that "
"brings it to about {target} GB.",
ram=gb(total_phys), limit=gb(commit_limit, 1),
target=COMMIT_TARGET_GB)
def page_file_steps(total_phys: int | None) -> str:
"""How to set a fixed page file, for the note's tooltip, with the size that brings RAM + page file to about
COMMIT_TARGET_GB (rounded up to a whole GB) when the RAM is known."""
steps = t("Fixed page file: Win+R, sysdm.cpl > Advanced > Performance Settings > Advanced > Virtual memory > "
"Change. Untick the automatic size, choose Custom size, then Set, OK and restart Windows.")
if total_phys:
mb = max(1024, -(-(COMMIT_TARGET_GB * GIB - total_phys) // GIB) * 1024)
steps += "\n" + t("Here: {mb} MB as initial and maximum size (RAM + page file: about {target} GB).",
mb=mb, target=COMMIT_TARGET_GB)
return steps + "\n" + t("More in d3d12/docs/windows-memory.md.")
def info_text(settings: dict, version: str, cards: list[tuple[str, str]], python: str, tk_version: str,
system: str, memory: tuple = (None, None)) -> str:
"""What "Copy my info" puts on the clipboard, to paste when asking for help: the Mandy commit, the cards and
drivers, Windows, the RAM and commit limit (`memory`: commit_limit_bytes, physical_memory_bytes), Python and the
options PLAY passes. No folder names: they can carry the user's name."""
lines = ["Mandy launcher info", f"Mandy: {version}"]
for name, driver in cards or [("unknown", "")]:
shown = driver
if "nvidia" in name.lower() and nvidia_driver(driver):
shown = f"{nvidia_driver(driver)} ({driver})"
lines.append(f"GPU: {name}" + (f", driver {shown}" if shown else ""))
lines.append(f"System: {system}")
limit, phys = memory
lines.append(f"Memory: {gb(phys, 1)} GB RAM, commit limit (RAM + page file) {gb(limit, 1)} GB")
lines.append(f"Python: {python}, Tk {tk_version}")
lines.append("Options: " + (" ".join(switch_args(settings)) or "(defaults)"))
extra = extra_variables(settings)
if extra:
lines.append("Variables: " + "; ".join(f"{k}={v}" for k, v in extra.items()))
lines.append("Game folder found: " + ("yes" if game_exe_present(settings.get("game_dir", "")) else "no"))
return "\n".join(lines) + "\n"
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."""
if not windows:
return
try:
import ctypes
try:
ctypes.windll.shcore.SetProcessDpiAwareness(1)
except (OSError, AttributeError):
ctypes.windll.user32.SetProcessDPIAware()
except (OSError, AttributeError, ImportError):
pass
# ---------------------------------------------------------------- mods
def _mods_module():
"""tools/leonida_mods.py, loaded by path (`python -I` leaves this folder off sys.path)."""
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "leonida_mods.py")
spec = importlib.util.spec_from_file_location("leonida_mods", path)
module = importlib.util.module_from_spec(spec)
sys.modules.setdefault("leonida_mods", module)
spec.loader.exec_module(module)
return module
def list_mods(mods_dir: str) -> tuple[list[dict], list[str]]:
"""Every mods/*/mod.json as {folder, name, enabled, swaps, path}, and the errors of the ones that did not parse."""
mods_module = _mods_module()
mods, errors = mods_module.load_mods(mods_dir)
rows = [{"folder": m.folder, "name": m.name, "enabled": m.enabled, "swaps": len(m.swaps),
"path": os.path.join(mods_dir, m.folder, mods_module.MANIFEST)} for m in mods]
return rows, errors
def set_mod_enabled(manifest_path: str, enabled: bool) -> None:
"""Writes `enabled` into the manifest the way the mod manager does (mods.ModsError on failure)."""
_mods_module().set_enabled_in_manifest(manifest_path, enabled)
# ---------------------------------------------------------------- saves
def _saves_module():
"""tools/leonida_saves.py, loaded by path like the mod manager."""
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "leonida_saves.py")
spec = importlib.util.spec_from_file_location("leonida_saves", path)
module = importlib.util.module_from_spec(spec)
sys.modules.setdefault("leonida_saves", module)
spec.loader.exec_module(module)
return module
def data_root(settings: dict) -> str:
"""The data folder in use: the setting, else the default of scripts/play-d3d12.ps1 (<local>/Leonida/d3d12)."""
return settings.get("data_dir", "").strip() or os.path.join(local_data_dir(), "Leonida", "d3d12")
SHADER_CACHE = "cache-2" # scripts/play-d3d12.ps1: LEONIDA_CACHE_DIR = <data>\cache-2 (made again at each start)
def shader_cache_dir(settings: dict, windows: bool = WINDOWS, environ=None) -> str:
"""The runtime's cache for PLAY's starts: translated shaders, pipelines, the title's prepared images. Windows:
play-d3d12.ps1's <data>\\cache-2. Linux: play-linux.sh's LEONIDA_CACHE_DIR, by default
${XDG_DATA_HOME:-~/.local/share}/leonida/cache (the launcher passes no data folder there; review of #3272)."""
if windows:
return os.path.join(data_root(settings), SHADER_CACHE)
env = os.environ if environ is None else environ
if env.get("LEONIDA_CACHE_DIR"):
return env["LEONIDA_CACHE_DIR"]
data = env.get("XDG_DATA_HOME") or os.path.join(env.get("HOME") or os.path.expanduser("~"), ".local", "share")
return os.path.join(data, "leonida", "cache")
def folder_size(path: str) -> int:
"""The bytes of the files under `path` (links not followed); 0 when it is not there."""
total = 0
for root, _dirs, files in os.walk(path):
for name in files:
try:
total += os.lstat(os.path.join(root, name)).st_size
except OSError:
pass
return total
def size_text(n: int) -> str:
"""`n` bytes in the largest unit that keeps it at 1 or more: B, KB, MB or GB."""
for unit, scale in (("GB", 1 << 30), ("MB", 1 << 20), ("KB", 1 << 10)):
if n >= scale:
return f"{n / scale:.1f} {unit}"
return f"{n} B"
def clear_shader_cache(settings: dict, running=None) -> tuple[bool, str]:
"""Tools > Clear shader cache: deletes the data folder's cache-2 (shader_cache_dir), nothing else, the saves in
<data>/data included; the next start makes it again. Refused while the game runs. (done, message)."""
if (running or game_running)():
return False, t("Close the game first: its cache is in use.")
path = shader_cache_dir(settings)
if not os.path.isdir(path):
return True, t("The shader cache is already empty.")
try:
_remove_tree(path)
except OSError as exc:
return False, t("The shader cache could not be deleted: {error}", error=exc)
return True, t("Shader cache deleted. The next start makes it again, which takes a while.")
def game_running(windows: bool = WINDOWS) -> bool:
"""Whether a runtime process (leonida.exe or its Smooth Motion copy) is running, started here or not."""
try:
if windows:
out = subprocess.run(["tasklist", "/FO", "CSV", "/NH"], capture_output=True, text=True,
creationflags=subprocess.CREATE_NO_WINDOW, check=False).stdout.lower()
return '"leonida.exe"' in out or '"leonida_sm.exe"' in out
return subprocess.run(["pgrep", "-f", "leonida(_sm)?[.]exe"], capture_output=True, check=False).returncode == 0
except OSError:
return False
# ---------------------------------------------------------------- processes
def stop_tree(process: subprocess.Popen) -> None:
"""Ends the process and everything it started."""
if process.poll() is not None:
return
if WINDOWS:
subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], capture_output=True, check=False)
else:
try:
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
except OSError:
process.terminate()
def spawn(command: list[str], cwd: str) -> subprocess.Popen:
kwargs: dict = {}
if WINDOWS:
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
else:
kwargs["start_new_session"] = True
return subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, **kwargs)
# The window's output pump (Launcher.pump) takes at most OUTPUT_BATCH items of the reader threads' queue a turn, so a
# run that writes faster than the output box draws (the runtime's stderr with -Log off) cannot hold Tk's thread: clicks
# and redraws get their turn between two. A turn that leaves more queued comes back after OUTPUT_RESUME_MS, not 100 ms.
OUTPUT_BATCH = 2000
OUTPUT_RESUME_MS = 10
def take_output(lines: queue.Queue, limit: int = OUTPUT_BATCH) -> list[tuple]:
"""Up to `limit` items of `lines` ((kind, process, value) from the reader threads), in order and without waiting,
with each run of "line" items of one process joined into one ("lines", process, [text, ...]) item: the output box
then takes one insert per run rather than one per line, which is what kept the window from its own events."""
taken: list[tuple] = []
for _ in range(limit):
try:
kind, process, value = lines.get_nowait()
except queue.Empty:
break
if kind != "line":
taken.append((kind, process, value))
elif taken and taken[-1][0] == "lines" and taken[-1][1] is process:
taken[-1][2].append(value)
else:
taken.append(("lines", process, [value]))
return taken
def open_folder(path: str) -> None:
os.makedirs(path, exist_ok=True)
if WINDOWS:
os.startfile(path) # noqa: S606 (a folder the user asked to see)
elif sys.platform == "darwin":
subprocess.Popen(["open", path])
else:
subprocess.Popen(["xdg-open", path])
# ---------------------------------------------------------------- the window
# The mockup's palette (leonida-notes/launcher_mockup.html) taken toward neutral: a city at night, its surfaces a
# grey with a little blue in it. Violet and pink are kept for what matters: the PLAY pill (their only gradient), the
# rail's mark on the page shown and a switch that is on. Three text roles: TEXT, MUTED (secondary, 4.5:1 or more on
# PANEL) and FAINT (what can be missed).
BG = "#14121f"
PANEL = "#1b1829"
PANEL2 = "#221f33"
RAISED = "#2c2940"
NAV = "#100e19"
LINE = "#2a2738"
EDGE = "#46425a"
ROW_LINE = "#242131"
TEXT = "#ecebf3"
MUTED = "#a9a6bd"
FAINT = "#7d7a93"
DISABLED = "#5c596f"
VIOLET = "#8b5cf6"
VIOLET_DEEP = "#7c3aed" # a chosen segment: white text on it at 5.7:1 (VIOLET gives 4.2)
PINK = "#ec4899"
ON_ACCENT = "#ffffff"
OK = "#4cc38a"
WARN = "#d9a441"
DANGER = "#ec5a5f"
TIP_BG = PANEL2
TIP_LINE = LINE
TIP_TEXT = MUTED
FIELD = "#110f1a"
def blend(a: str, b: str, f: float) -> str:
"""The colour a fraction `f` of the way from `a` to `b` (#rrggbb)."""
x = [int(a[i:i + 2], 16) for i in (1, 3, 5)]
y = [int(b[i:i + 2], 16) for i in (1, 3, 5)]
return "#%02x%02x%02x" % tuple(int(p + (q - p) * f) for p, q in zip(x, y))
ABOUT = """Mandy (formerly Leonida) is a compatibility runtime that runs your own copy of the Xbox Series build of GTA VI on a PC: a \
loader that maps the game's executable and a Direct3D 12 layer that draws its frames on your graphics card. It is an \
unofficial, independent project. It is not made, endorsed or supported by the game's publisher, and it contains none of \
the game: you build it from a copy you own, and nothing goes online."""
CREDITS = """Built on the work of others (full credits in d3d12/README.md):
- VIctory by Marvisak and its contributors: the loader, the runtime services, the Direct3D 12 back end, the shader \
recompiler
- avatarmanz/VIctory-7900XTX, the fork this one started from
- fxceless/victory-fork, DexNom/VIctory, Belobug/VIctory-Belobug-AMD, FQY55kai/ZJOU-VICTORY, myokex/victory-amd, \
and the people named in d3d12/README.md
- NVIDIA's DLSS and Streamline, which you fetch yourself under NVIDIA's own licences
Licence: GPL-3.0-or-later (the LICENSE file in the repository). The launcher is part of it."""
# The states the bar under PLAY shows (state_for_line and the buttons), translated when shown.
STATE_TEXTS = ("Ready", "Starting", "Running", "Preparing shaders", "Building the runtime", "Updating",
"Fetching the DLSS files", "Rebuilding the runtime", "Could not start")
def run_gui() -> int:
try:
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
except ImportError:
print("Tkinter is not installed; on Windows install Python from python.org with Tcl/Tk, "
"on Linux the python3-tk package.", file=sys.stderr)
return 1
import platform
import traceback
class Toggle(tk.Canvas):
"""An on/off switch bound to a BooleanVar: a click or the space bar turns it over. On, it is the mockup's
violet-to-pink track with a white knob."""
def __init__(self, parent, var, k, bg=PANEL):
self.w, self.h = int(38 * k), int(21 * k)
super().__init__(parent, width=self.w, height=self.h, bg=bg, highlightthickness=0, cursor="hand2",
takefocus=1)
self.var = var
self.focused = False
self.active = True
self.shown_off = False # greyed because the card cannot run it: drawn off (PLAY passes it off: for_card)
self.bind("<Button-1>", lambda _e: self.flip())
self.bind("<space>", lambda _e: self.flip())
self.bind("<FocusIn>", lambda _e: self.set_focus(True))
self.bind("<FocusOut>", lambda _e: self.set_focus(False))
var.trace_add("write", lambda *_: self.draw())
self.draw()
def set_focus(self, inside):
self.focused = inside
self.draw()
def flip(self):
if not self.active:
return
self.focus_set()
self.var.set(not self.var.get())
def enabled(self, flag):
"""Greyed and deaf to clicks and the space bar when off; the value stays as it is."""
flag = bool(flag)
if flag != self.active:
self.active = flag
self.configure(cursor="hand2" if flag else "arrow", takefocus=1 if flag else 0)
self.draw()
def show_off(self, flag):
"""Drawn off while greyed (the card cannot run it and PLAY passes it off); the value stays as it is."""
flag = bool(flag)
if flag != self.shown_off:
self.shown_off = flag
self.draw()
def draw(self):
self.delete("all")
on = bool(self.var.get()) and not (self.shown_off and not self.active)
w, h = self.w, self.h
r = h // 2
if not self.active:
track = blend(VIOLET, PANEL, 0.55) if on else "#262333"
self.create_oval(0, 0, h - 1, h - 1, fill=track, outline="")
self.create_oval(w - h, 0, w - 1, h - 1, fill=track, outline="")
self.create_rectangle(r, 0, w - r, h - 1, fill=track, outline="")
pad = max(3, h // 7)
x = w - h + pad if on else pad
self.create_oval(x, pad, x + h - 2 * pad, h - pad, fill=DISABLED, outline="")
return
track = VIOLET if on else "#34314a"
self.create_oval(0, 0, h - 1, h - 1, fill=track, outline="")
self.create_oval(w - h, 0, w - 1, h - 1, fill=track, outline="")
self.create_rectangle(r, 0, w - r, h - 1, fill=track, outline="")
if self.focused:
self.create_rectangle(0, 0, w - 1, h - 1, outline=TEXT, dash=(1, 2))
pad = max(3, h // 7)
x = w - h + pad if on else pad
self.create_oval(x, pad, x + h - 2 * pad, h - pad, fill="#ffffff" if on else "#c9c7d6", outline="")
class Segmented(tk.Frame):
"""One choice among a few, as a row of buttons bound to a StringVar; `options` are (value, label)."""
def __init__(self, parent, var, options, k):
super().__init__(parent, bg=LINE)
self.var = var
self.active = True
self.off: set = set() # buttons greyed on their own (option_enabled), the others still live
self.labels: dict = {}
for index, (value, text) in enumerate(options):
label = tk.Label(self, text=text, bg=PANEL, fg=MUTED, font=("Segoe UI", 9), padx=int(12 * k),
pady=int(4 * k), cursor="hand2", highlightthickness=1)
label.pack(side="left", padx=(1 if index == 0 else 0, 1), pady=1)
label.bind("<Button-1>", lambda _e, v=value: self.live(v) and var.set(v))
# Hover: an unchosen button's text brightens while the pointer is on it (a recolour, nothing drawn).
label.bind("<Enter>", lambda _e, v=value: self.hover(v, True), add="+")
label.bind("<Leave>", lambda _e, v=value: self.hover(v, False), add="+")
self.labels[value] = label
var.trace_add("write", lambda *_: self.draw())
self.draw()
def enabled(self, flag):
"""Greyed and deaf to clicks when off; the choice stays as it is."""
flag = bool(flag)
if flag != self.active:
self.active = flag
self.draw()
def option_enabled(self, value, flag):
"""Greys one button and makes it deaf to clicks, the others staying live; when it is the choice, the
choice stays as it is (shown greyed) until another button is clicked."""
if value in self.labels and bool(flag) == (value in self.off):
if flag:
self.off.discard(value)
else:
self.off.add(value)
self.draw()
def live(self, value):
return self.active and value not in self.off
def hover(self, value, inside):
if self.live(value) and value != self.var.get():
self.labels[value].configure(fg=TEXT if inside else MUTED)
def draw(self):
current = self.var.get()
for value, label in self.labels.items():
chosen = value == current
live = self.live(value)
label.configure(cursor="hand2" if live else "arrow")
# The choice in the switches' violet with white text, as an "on" switch: a raised grey was too close
# to the others to read on a screenshot (players could not tell FSR was chosen). Greyed, the same violet
# dimmed, as a greyed "on" switch.
if chosen:
bg = VIOLET_DEEP if live else blend(VIOLET_DEEP, PANEL, 0.55)
fg = ON_ACCENT if live else TEXT
else:
bg = PANEL
fg = MUTED if live else DISABLED
label.configure(bg=bg, fg=fg, highlightbackground=bg, highlightcolor=bg)
class Tip:
"""The longer text of an option, shown when the pointer rests on it ("Hover any option for what it does")."""
def __init__(self, widgets, text, k):
self.text, self.k, self.window, self.job = text, k, None, None
for widget in widgets:
widget.bind("<Enter>", self.later, add="+")
widget.bind("<Leave>", self.hide, add="+")
widget.bind("<ButtonPress>", self.hide, add="+")
self.widget = widgets[0]
def later(self, _event=None):
self.hide()
self.job = self.widget.after(450, self.show)
def show(self):
self.job = None
if not self.widget.winfo_exists():
return
x, y = self.widget.winfo_pointerx() + int(14 * self.k), self.widget.winfo_pointery() + int(16 * self.k)
self.window = tk.Toplevel(self.widget)
self.window.wm_overrideredirect(True)
self.window.configure(bg=LINE)
tk.Label(self.window, text=self.text, bg=PANEL2, fg=TEXT, justify="left", font=("Segoe UI", 9),
wraplength=int(320 * self.k), padx=int(10 * self.k), pady=int(7 * self.k)).pack(padx=1, pady=1)
self.window.wm_geometry(f"+{x}+{y}")
def hide(self, _event=None):
if self.job is not None:
self.widget.after_cancel(self.job)
self.job = None
if self.window is not None:
self.window.destroy()
self.window = None
class PrimaryButton(tk.Canvas):
"""The page's main button (Save, Update Mandy): off-white with dark text, no gradient (that is PLAY's)."""
def __init__(self, parent, text, command, k, bg=BG):
import tkinter.font as tkfont
font = tkfont.Font(family="Segoe UI", size=10)
w, h = font.measure(text) + int(32 * k), int(36 * k)
super().__init__(parent, width=w, height=h, bg=bg, highlightthickness=0, cursor="hand2")
self.command = command
self.face = self.create_rectangle(0, 0, w, h, fill=TEXT, outline="")
self.create_text(w // 2, h // 2, text=text, fill=BG, font=font)
self.bind("<Button-1>", lambda _e: self.command())
self.bind("<Enter>", lambda _e: self.itemconfigure(self.face, fill="#ffffff"))
self.bind("<Leave>", lambda _e: self.itemconfigure(self.face, fill=TEXT))
class AdvancedWindow:
"""Advanced mode: every LEONIDA_* variable of d3d12/docs/switches.md in a second window, edited into the same
advanced options as the Settings field (settings["advanced"], NAME=value pairs that PLAY passes to -More).
Apply or Close writes the edits into that field, so its own checks and rules run as if they were typed.
The list is virtual: a pool of rows as tall as the window shows, filled again from the filtered list when it
scrolls, so the 682 names cost no more than the dozen rows on screen. Hovering only recolours widgets."""
ROW_H = 64 # one row, before px() scaling
CONTROL_W = 230 # the value's column
def __init__(self, app):
started = time.perf_counter()
self.app, self.k = app, app.k
px = app.px
self.switches = read_switches(REPO) or []
self.missing = not self.switches
self.by_name = {r["name"]: r for r in self.switches}
self.names = set(self.by_name)
self.hay = [(r["name"] + " " + plain_description(r["text"])).lower() for r in self.switches]
self.hints = {r["name"]: value_hint(r["name"], r["text"]) for r in self.switches}
self.values: dict = {} # name -> the value shown ("" = not set)
self.edited: set = set() # names changed here since the last Apply
self.seen_text = None # the field's text the values were read from
self.shown: list[int] = list(range(len(self.switches)))
self.first = 0
self.pool: list = []
self.filling = False
self.visible = 0
self.desc_width = px(400)
self.tip_window = self.tip_job = None
self.filter_ms = 0.0
import tkinter.font as tkfont
self.desc_font = tkfont.Font(family="Segoe UI", size=8)
self.hint_font = tkfont.Font(family="Consolas", size=9)
win = self.win = tk.Toplevel(app.root)
win.title(t("Advanced mode") + " · Mandy")
win.configure(bg=BG)
width = min(px(1000), int(win.winfo_screenwidth() * 0.9))
height = min(px(740), int(win.winfo_screenheight() * 0.85))
win.geometry(f"{width}x{height}")
win.minsize(min(px(720), width), min(px(480), height))
win.protocol("WM_DELETE_WINDOW", self.close)
win.columnconfigure(0, weight=1)
win.rowconfigure(4, weight=1)
head = tk.Frame(win, bg=BG)
head.grid(row=0, column=0, sticky="ew", padx=px(24), pady=(px(20), px(12)))
tk.Label(head, text=t("Advanced mode"), bg=BG, fg=TEXT, font=("Segoe UI Semibold", 16), anchor="w",
padx=0).pack(fill="x")
tk.Label(head, text=t("Every variable the runtime reads, written into the Advanced field of Settings"),
bg=BG, fg=MUTED, font=("Segoe UI", 9), anchor="w", padx=0).pack(fill="x")
# The warning switches.md opens with: it is not a list of settings to try.
warn = tk.Frame(win, bg=TIP_BG, highlightthickness=1, highlightbackground=TIP_LINE)
warn.grid(row=1, column=0, sticky="ew", padx=px(24), pady=(0, px(12)))
warn.columnconfigure(0, weight=1)
tk.Label(warn, text=t("Not a list of recommended settings."), bg=TIP_BG, fg=WARN,
font=("Segoe UI Semibold", 9), anchor="w", padx=0).grid(row=0, column=0, sticky="w",
padx=px(12), pady=(px(10), 0))
body = tk.Label(warn, text=t("It says which names exist and what the code's comments say of them, nothing "
"of what a switch gains: read d3d12/docs/findings.md first, and set one only "
"when someone asks you to. The names and descriptions come from the code and "
"stay in English."),
bg=TIP_BG, fg=TIP_TEXT, font=("Segoe UI", 9), anchor="w", justify="left", padx=0,
wraplength=px(700))
body.grid(row=1, column=0, sticky="ew", padx=px(12), pady=(px(2), px(10)))
body.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(200), e.width - 4)))
link_fg = blend(VIOLET, "#ffffff", 0.35)
link = tk.Label(warn, text=t("Open findings.md"), bg=TIP_BG, fg=link_fg, cursor="hand2",
font=("Segoe UI", 9, "underline"), padx=0)
link.grid(row=0, column=1, rowspan=2, sticky="ne", padx=px(12), pady=px(10))
link.bind("<Button-1>", lambda _e: self.open_findings())
link.bind("<Enter>", lambda _e: link.configure(fg=TEXT))
link.bind("<Leave>", lambda _e: link.configure(fg=link_fg))
bar = tk.Frame(win, bg=BG)
bar.grid(row=2, column=0, sticky="ew", padx=px(24), pady=(0, px(6)))
self.search = tk.StringVar()
tk.Label(bar, text=t("Search"), bg=BG, fg=MUTED, font=("Segoe UI", 9), padx=0).pack(side="left")
self.search_entry = tk.Entry(bar, textvariable=self.search, bg=FIELD, fg=TEXT, insertbackground=TEXT,
relief="flat", font=("Segoe UI", 10), width=26, highlightthickness=1,
highlightbackground=LINE, highlightcolor=EDGE)
self.search_entry.pack(side="left", padx=(px(8), px(16)), ipady=px(4))
self.all_sections = t("All sections")
sections = list(dict.fromkeys(r["section"] for r in self.switches))
self.section = tk.StringVar(value=self.all_sections)
self.section_box = ttk.Combobox(bar, textvariable=self.section, state="readonly", width=18,
values=[self.all_sections] + sections)
self.section_box.pack(side="left", padx=(0, px(16)))
self.only_set = tk.BooleanVar(value=False)
self.only_launcher = tk.BooleanVar(value=False)
for var, text, tip in ((self.only_set, t("Only what I set"),
t("Only the variables you set here, that is the ones in the Advanced field and "
"passed to the game.")),
(self.only_launcher, t("Only those the play script sets"),
t("Variables the play script (play-nvidia.ps1) already sets by itself, sometimes "
"only with some option (the L column of switches.md). A value typed here "
"replaces the script's."))):
toggle = Toggle(bar, var, self.k, bg=BG)
toggle.pack(side="left")
label = tk.Label(bar, text=text, bg=BG, fg=TEXT, font=("Segoe UI", 9), padx=0, cursor="hand2")
label.pack(side="left", padx=(px(6), px(16)))
label.bind("<Button-1>", lambda _e, w=toggle: w.flip())
if tip:
Tip([toggle, label], tip, self.k)
self.shown_var = tk.StringVar()
tk.Label(bar, textvariable=self.shown_var, bg=BG, fg=FAINT, font=("Segoe UI", 8)).pack(side="right")
# What a value field takes: the value alone, an empty one leaves the name out.
tk.Label(win, text=t("Type only the value: the name is already on the row. Empty = not set (the "
"runtime's default)."), bg=BG, fg=MUTED, font=("Segoe UI", 8), anchor="w",
padx=0).grid(row=3, column=0, sticky="ew", padx=px(24), pady=(0, px(6)))
box = tk.Frame(win, bg=PANEL, highlightthickness=1, highlightbackground=LINE)
box.grid(row=4, column=0, sticky="nsew", padx=px(24))
box.columnconfigure(0, weight=1)
box.rowconfigure(0, weight=1)
self.area = tk.Frame(box, bg=PANEL)
self.area.grid(row=0, column=0, sticky="nsew")
self.scroll = ttk.Scrollbar(box, orient="vertical", command=self.yview)
self.scroll.grid(row=0, column=1, sticky="ns")
self.empty = tk.Label(self.area, text="", bg=PANEL, fg=MUTED, font=("Segoe UI", 9), justify="left",
wraplength=px(600))
foot = tk.Frame(win, bg=BG)
foot.grid(row=5, column=0, sticky="ew", padx=px(24), pady=(px(10), px(18)))
foot.columnconfigure(0, weight=1)
self.count_var = tk.StringVar()
self.count_label = tk.Label(foot, textvariable=self.count_var, bg=BG, fg=TEXT, font=("Segoe UI", 10),
anchor="w", padx=0)
self.count_label.grid(row=0, column=0, sticky="w")
tk.Label(foot, text=t("Passed through -More, which wins over the F1 menu's file at a normal start."),
bg=BG, fg=MUTED, font=("Segoe UI", 8), anchor="w", padx=0).grid(row=1, column=0, sticky="w",
pady=(px(2), 0))
self.problem_var = tk.StringVar()
tk.Label(foot, textvariable=self.problem_var, bg=BG, fg=DANGER, font=("Segoe UI", 8), anchor="w",
padx=0).grid(row=2, column=0, sticky="w")
buttons = self.buttons = tk.Frame(foot, bg=BG)
buttons.grid(row=0, column=1, rowspan=3, sticky="e")
ttk.Button(buttons, text=t("Reset all"), command=self.reset_all).pack(side="left", padx=(0, px(8)))
ttk.Button(buttons, text=t("Close"), command=self.close).pack(side="left", padx=(0, px(8)))
PrimaryButton(buttons, t("Apply"), self.apply, self.k).pack(side="left")
# The wheel scrolls the list wherever the pointer is in this window; "break" keeps the Settings page's
# handler (bound for the whole application) from scrolling it too.
for name in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
win.bind(name, self.wheel)
win.bind("<Control-f>", lambda _e: self.search_entry.focus_set())
self.area.bind("<Configure>", self.resized)
self.search.trace_add("write", lambda *_: self.refilter())
for var in (self.section, self.only_set, self.only_launcher):
var.trace_add("write", lambda *_: self.refilter())
# Typed in Settings while this window is open: shown here at once (the names not edited here).
self.field_trace = app.vars["advanced"].trace_add("write", lambda *_: self.sync())
if self.missing:
self.empty.configure(text=t("d3d12/docs/switches.md is not in this copy, so there is no list to show. "
"The Advanced field in Settings still takes NAME=value pairs."))
self.empty.place(x=px(16), y=px(16))
for widget in (self.search_entry, self.section_box):
widget.configure(state="disabled")
self.sync(force=True)
self.search_entry.focus_set()
win.update_idletasks()
self.open_ms = (time.perf_counter() - started) * 1000
# ---- the values
def sync(self, force=False):
"""Reads the Settings field again: every name not edited here takes the field's value."""
try:
text = self.app.vars["advanced"].get()
except (KeyError, tk.TclError):
return
if not force and text == self.seen_text:
return
self.seen_text = text
parsed = parse_advanced(text)[0]
for name in self.names - self.edited:
if parsed.get(name):
self.values[name] = parsed[name]
else:
self.values.pop(name, None)
self.render()
self.count()
def set_value(self, name, value):
if value:
self.values[name] = value
else:
self.values.pop(name, None)
self.edited.add(name)
self.count()
def problems(self):
return sorted(n for n, v in self.values.items() if advanced_value_problem(v))
def count(self):
n = sum(1 for v in self.values.values() if v.strip())
text = t("{n} set", n=n)
values, wrong = parse_advanced(self.seen_text or "")
other = len([k for k in values if k not in self.names]) + len(wrong)
if other:
text += " · " + t("{n} other entries of the field kept as typed", n=other)
self.count_var.set(text)
bad = self.problems()
self.problem_var.set(t("Cannot be passed (a double quote or ;): {names}", names=", ".join(bad))
if bad else "")
def edits(self):
"""What Apply writes: the names edited here whose value differs from the field's."""
now = parse_advanced(self.app.vars["advanced"].get())[0]
return {n: self.values.get(n, "").strip() for n in sorted(self.edited)
if self.values.get(n, "").strip() != now.get(n, "")}
def apply(self):
"""Writes the edits into the Settings field (its checks and rules then run). False, with a message, when a
value cannot be passed."""
bad = self.problems()
if bad:
messagebox.showwarning(t("Advanced mode"), t(
"These values cannot be passed: a double quote or ; would break the command line. Change them "
"first: {names}", names=", ".join(bad)), parent=self.win)
return False
var = self.app.vars["advanced"]
current = var.get()
merged = merge_advanced(current, self.edits())
self.edited.clear()
if merged != current:
var.set(merged)
self.sync(force=True)
return True
def close(self):
if not self.apply():
return
self.hide_tip()
try:
self.app.vars["advanced"].trace_remove("write", self.field_trace)
except (KeyError, tk.TclError, ValueError):
pass
self.app.advanced_window = None
self.win.destroy()
def reset_all(self):
if not any(v for v in self.values.values()):
return
if not messagebox.askyesno(t("Reset all"), t(
"Clear every variable of this list? The other entries of the Advanced field are kept, and nothing "
"changes until Apply or Close."), parent=self.win):
return
for name in list(self.values):
self.set_value(name, "")
self.render()
def open_findings(self):
path = os.path.join(REPO, *FINDINGS_DOC)
try:
if WINDOWS:
os.startfile(path if os.path.isfile(path) else os.path.dirname(path)) # noqa: S606
else:
subprocess.Popen(["xdg-open", path])
except OSError:
messagebox.showinfo(t("Advanced mode"), path, parent=self.win)
# ---- the list
def refilter(self):
started = time.perf_counter()
words = self.search.get().lower().split()
section = self.section.get()
section = "" if section == self.all_sections else section
only_set, only_launcher = self.only_set.get(), self.only_launcher.get()
self.shown = [i for i, r in enumerate(self.switches)
if (not section or r["section"] == section)
and (not only_set or self.values.get(r["name"], "").strip())
and (not only_launcher or r["launcher"])
and all(w in self.hay[i] for w in words)]
self.first = 0
self.render()
self.win.update_idletasks()
self.filter_ms = (time.perf_counter() - started) * 1000
def full_rows(self):
return max(1, self.area.winfo_height() // self.app.px(self.ROW_H))
def resized(self, event):
px = self.app.px
row_h = px(self.ROW_H)
self.visible = event.height // row_h + 1
while len(self.pool) < self.visible:
self.pool.append(self.make_row())
self.desc_width = max(px(200), event.width - px(3) - px(16) - px(self.CONTROL_W) - px(32))
for row in self.pool:
row.desc.configure(wraplength=self.desc_width)
row.key = None # filled again at the new width
self.render()
def make_row(self):
px = self.app.px
row = tk.Frame(self.area, bg=PANEL, height=px(self.ROW_H))
row.columnconfigure(1, weight=1)
row.rowconfigure(0, weight=1)
row.mark = tk.Frame(row, bg=PANEL, width=px(3))
row.mark.grid(row=0, column=0, sticky="ns")
body = tk.Frame(row, bg=PANEL)
body.grid(row=0, column=1, sticky="nsew", padx=(px(13), px(16)), pady=(px(8), 0))
line = tk.Frame(body, bg=PANEL)
line.pack(fill="x")
row.title = tk.Label(line, text="", bg=PANEL, fg=TEXT, font=("Consolas", 10), anchor="w", padx=0)
row.title.pack(side="left")
row.meta = tk.Label(line, text="", bg=PANEL, fg=MUTED, font=("Segoe UI", 8), anchor="w", padx=0)
row.meta.pack(side="left", padx=(px(10), 0))
row.desc = tk.Label(body, text="", bg=PANEL, fg=MUTED, font=self.desc_font, anchor="nw", justify="left",
padx=0, wraplength=self.desc_width)
row.desc.pack(fill="x", pady=(px(2), 0))
control = tk.Frame(row, bg=PANEL, width=px(self.CONTROL_W))
control.grid(row=0, column=2, sticky="nse", padx=(0, px(16)))
control.pack_propagate(False)
row.text_var = tk.StringVar()
row.entry = tk.Entry(control, textvariable=row.text_var, bg=FIELD, fg=TEXT, insertbackground=TEXT,
relief="flat", font=("Consolas", 9), highlightthickness=1, highlightbackground=LINE,
highlightcolor=EDGE)
# The placeholder: a label laid over the empty entry, never its text, so it cannot become a value.
row.hint = tk.Label(row.entry, text="", bg=FIELD, fg=FAINT, font=self.hint_font, padx=0, pady=0,
cursor="xterm")
row.hint_text = ""
row.focused = False
row.hint.bind("<Button-1>", lambda _e: (row.entry.focus_set(), row.entry.icursor("end")))
row.entry.bind("<FocusIn>", lambda _e: self.entry_focus(row, True), add="+")
row.entry.bind("<FocusOut>", lambda _e: self.entry_focus(row, False), add="+")
row.bool_var = tk.BooleanVar()
row.switch = tk.Frame(control, bg=PANEL)
row.toggle = Toggle(row.switch, row.bool_var, self.k)
row.toggle.pack(side="left")
row.state = tk.Label(row.switch, text="", bg=PANEL, fg=MUTED, font=("Segoe UI", 8), padx=0)
row.state.pack(side="left", padx=(px(8), 0))
tk.Frame(row, bg=ROW_LINE, height=1).grid(row=1, column=0, columnspan=3, sticky="ew")
row.paint = [row, body, line, row.title, row.meta, row.desc, control, row.switch, row.toggle, row.state]
row.name = row.key = row.mode = None
row.cut = False
row.placed = False
row.text_var.trace_add("write", lambda *_: self.typed(row))
row.bool_var.trace_add("write", lambda *_: self.flipped(row))
for widget in row.paint + [row.entry, row.hint, row.mark]:
widget.bind("<Enter>", lambda _e: self.hover(row, True), add="+")
widget.bind("<Leave>", lambda _e: self.left(row), add="+")
for widget in (row.title, row.desc):
widget.bind("<Enter>", lambda _e: self.tip_later(row), add="+")
widget.bind("<Leave>", lambda _e: self.hide_tip(), add="+")
return row
def fit(self, text):
"""At most about two lines of the description column, cut with an ellipsis (the rest in a tooltip)."""
room = self.desc_width * 1.8
if self.desc_font.measure(text) <= room:
return text, False
low, high = 0, len(text)
while low < high:
mid = (low + high + 1) // 2
if self.desc_font.measure(text[:mid] + "…") <= room:
low = mid
else:
high = mid - 1
return text[:low].rstrip() + "…", True
def fit_hint(self, hint):
"""The placeholder cut with "…" to the value field's width (a long one would be clipped silently)."""
room = self.app.px(self.CONTROL_W) - self.app.px(12)
if self.hint_font.measure(hint) <= room:
return hint
hint = hint.rstrip("…")
while hint and self.hint_font.measure(hint + "…") > room:
hint = hint[:-1]
return hint.rstrip() + "…"
def render(self):
"""Fills the pool's rows from the filtered list, from self.first on."""
if not self.pool:
self.update_bar()
return
px = self.app.px
row_h = px(self.ROW_H)
limit = max(0, len(self.shown) - self.full_rows())
self.first = max(0, min(self.first, limit))
self.filling = True
try:
for i, row in enumerate(self.pool):
index = self.first + i
if i >= self.visible or index >= len(self.shown):
if row.placed:
row.place_forget()
row.placed = False
row.name = None
continue
if not row.placed:
row.place(x=0, y=i * row_h, relwidth=1, height=row_h)
row.placed = True
self.fill(row, self.switches[self.shown[index]])
finally:
self.filling = False
if self.missing:
return
if self.shown:
self.empty.place_forget()
else:
self.empty.configure(text=t("Nothing matches."))
self.empty.place(x=px(16), y=px(16))
self.update_bar()
def fill(self, row, switch):
name = switch["name"]
value = self.values.get(name, "")
if row.key != name:
row.key = name
row.name = name
row.title.configure(text=name)
meta = [switch["section"], switch["kind"]]
if switch["ab"]:
meta.append("A/B")
if switch["launcher"]:
meta.append(t("set by the launcher script"))
if switch["findings"]:
meta.append(t("in findings.md"))
row.meta.configure(text=" · ".join(meta))
text, row.cut = self.fit(plain_description(switch["text"]) or t("No comment in the code."))
row.desc.configure(text=text)
mode = "switch" if switch["kind"] in (KIND_OFF_UNLESS_SET, KIND_ON_UNLESS_ZERO) else "entry"
if mode != row.mode:
if row.mode is not None:
(row.entry if row.mode == "entry" else row.switch).pack_forget()
if mode == "entry":
row.entry.pack(fill="x", expand=True, ipady=self.app.px(4))
else:
row.switch.pack(side="right")
row.mode = mode
if row.mode == "entry":
if row.text_var.get() != value:
row.text_var.set(value)
hint = self.hints.get(name) or t("value")
if hint != row.hint_text:
row.hint_text = hint
row.hint.configure(text=self.fit_hint(hint))
self.show_hint(row)
else:
on = value != "0" if switch["kind"] == KIND_ON_UNLESS_ZERO else bool(value) and value != "0"
if row.bool_var.get() != on:
row.bool_var.set(on)
self.paint_state(row, switch, value)
def paint_state(self, row, switch, value):
row.mark.configure(bg=PINK if value else row.cget("bg"))
bad = bool(advanced_value_problem(value))
edge = DANGER if bad else LINE
row.entry.configure(highlightbackground=edge, highlightcolor=DANGER if bad else EDGE)
if row.mode == "switch":
on = row.bool_var.get()
state = t("On") if on else t("Off")
if not value:
state += " · " + t("default")
row.state.configure(text=state, fg=TEXT if value else MUTED)
def show_hint(self, row):
"""The placeholder shows while the entry is empty and does not have the focus."""
show = row.mode == "entry" and not row.text_var.get() and not row.focused
if show and not row.hint.winfo_manager():
# Where the entry starts its text: inside its border and focus ring.
inset = int(row.entry.cget("borderwidth")) + int(row.entry.cget("highlightthickness"))
row.hint.place(x=inset, rely=0.5, anchor="w")
elif not show and row.hint.winfo_manager():
row.hint.place_forget()
def entry_focus(self, row, inside):
row.focused = inside
self.show_hint(row)
def typed(self, row):
self.show_hint(row)
if self.filling or row.name is None:
return
value = row.text_var.get()
self.set_value(row.name, value.strip())
self.paint_state(row, self.switches_by(row.name), value.strip())
def flipped(self, row):
if self.filling or row.name is None:
return
switch = self.switches_by(row.name)
on = row.bool_var.get()
if switch["kind"] == KIND_ON_UNLESS_ZERO:
value = "" if on else "0"
else:
value = "1" if on else ""
self.set_value(row.name, value)
self.paint_state(row, switch, value)
def switches_by(self, name):
return self.by_name[name]
def update_bar(self):
total = len(self.shown)
if self.missing:
self.shown_var.set("")
self.scroll.set(0, 1)
return
self.shown_var.set(t("{shown} of {total} shown", shown=total, total=len(self.switches)))
if not total:
self.scroll.set(0, 1)
return
full = self.full_rows()
self.scroll.set(self.first / total, min(1.0, (self.first + full) / total))
def scroll_to(self, first):
limit = max(0, len(self.shown) - self.full_rows())
first = max(0, min(int(first), limit))
if first == self.first:
return
self.first = first
self.hide_tip()
# An entry keeps the focus while its row shows another name: the focus goes back to the list.
focus = self.win.focus_get()
if isinstance(focus, tk.Entry) and focus is not self.search_entry:
self.area.focus_set()
self.render()
def yview(self, *args):
if not args:
return
if args[0] == "moveto":
self.scroll_to(round(float(args[1]) * len(self.shown)))
elif args[0] == "scroll":
step = self.full_rows() if args[2] == "pages" else 1
self.scroll_to(self.first + int(args[1]) * step)
def wheel(self, event):
if getattr(event, "num", 0) in (4, 5):
rows = -3 if event.num == 4 else 3
elif event.delta:
rows = -3 * (int(event.delta / 120) or (1 if event.delta > 0 else -1))
else:
return "break"
self.scroll_to(self.first + rows)
return "break"
# ---- hover: colours only, nothing is drawn again under the pointer
def hover(self, row, inside):
colour = PANEL2 if inside else PANEL
if row.cget("bg") == colour:
return
for widget in row.paint:
widget.configure(bg=colour)
if not (row.name and self.values.get(row.name)):
row.mark.configure(bg=colour)
def left(self, row):
def check():
try:
under = self.win.winfo_containing(*self.win.winfo_pointerxy())
except (tk.TclError, KeyError):
under = None
inside = under is not None and str(under).startswith(str(row))
self.hover(row, inside)
self.win.after(15, check)
def tip_later(self, row):
self.hide_tip()
if row.cut and row.name:
self.tip_job = self.win.after(450, lambda: self.show_tip(row))
def show_tip(self, row):
self.tip_job = None
if not row.name or not self.win.winfo_exists():
return
x, y = self.win.winfo_pointerx() + self.app.px(14), self.win.winfo_pointery() + self.app.px(16)
self.tip_window = tk.Toplevel(self.win)
self.tip_window.wm_overrideredirect(True)
self.tip_window.configure(bg=LINE)
tip = plain_description(self.switches_by(row.name)["text"])
tk.Label(self.tip_window, text=tip, bg=PANEL2, fg=TEXT, justify="left",
font=("Segoe UI", 9), wraplength=self.app.px(420), padx=self.app.px(10),
pady=self.app.px(7)).pack(padx=1, pady=1)
self.tip_window.wm_geometry(f"+{x}+{y}")
def hide_tip(self):
if self.tip_job is not None:
self.win.after_cancel(self.tip_job)
self.tip_job = None
if self.tip_window is not None:
self.tip_window.destroy()
self.tip_window = None
class Launcher:
PAGES = ("Play", "Settings", "Controls", "Mods", "Saves", "Tools", "About")
def __init__(self, root, settings):
self.root = root
self.settings = settings
self.process: subprocess.Popen | None = None
self.kind = "" # what runs: "game", "update" or "tool"
self.what = "" # the same, as the dialogs name it (translated)
self.diagnostic = False
self.lines: queue.Queue = queue.Queue()
self.state = "Ready"
self.update_seen: dict | None = None
self.checking = False # an update check is running
self.last_check: float | None = None
self.rail_seen = ""
# Tk sizes fonts in points, which follow the screen's scale; sizes in pixels go through px().
self.k = max(1.0, root.winfo_fpixels("1i") / 96.0)
root.title("Mandy Launcher")
root.configure(bg=BG)
width, height = self.px(1120), self.px(740)
width = min(width, int(root.winfo_screenwidth() * 0.94))
height = min(height, int(root.winfo_screenheight() * 0.88))
root.geometry(f"{width}x{height}")
root.minsize(min(self.px(900), width), min(self.px(600), height))
root.protocol("WM_DELETE_WINDOW", self.close)
root.report_callback_exception = self.callback_failed
root.columnconfigure(1, weight=1)
root.rowconfigure(0, weight=1)
self.build_all("Play")
# The F1 menu saves while the game runs: what the Play card shows of it is read again when the window
# comes back to the front (and when a run ends, in finished()).
root.bind("<FocusIn>", lambda _e: self.render_menu_settings(), add="+")
self.read_rail()
self.pump()
# At every start, whatever an older launcher saved: players with the old "Check for updates at start"
# unticked never saw an update. The check runs off the window's thread; without git or network the
# Updates card says so.
self.check_updates()
self.tick_updates()
def px(self, n):
return int(n * self.k)
def callback_failed(self, kind, value, tb):
"""An error in a button's code is shown in the output, not lost in a console nobody sees."""
text = "".join(traceback.format_exception(kind, value, tb))
print(text, file=sys.stderr)
try:
self.append("\n" + t("The launcher hit an error (please report it):") + "\n" + text)
except tk.TclError:
pass
def build_all(self, page):
"""Builds every page (again after a language change: the texts are read when a page is built)."""
for child in self.root.winfo_children():
child.destroy()
self.language_shown = self.settings["language"]
self.advanced_window = None # destroyed above with the other windows of the launcher
self.vars: dict = {}
self.choices: dict = {} # a drop-down's shown text -> its value, by setting
self.controls: dict = {} # the Settings control of a setting, for apply_rules
self.menu_notes: dict = {} # the "F1 menu: <value>" label under a control, by setting
# Windows' commit limit and RAM (commit_limit_bytes, physical_memory_bytes: one quick call each), read
# again at every build; refresh_memory warns from them.
self.memory = (commit_limit_bytes(), physical_memory_bytes())
self.memory_line = self.profile_memory = None
self.nav_buttons: dict = {}
self.current = ""
self.style()
self.build_nav()
self.content = tk.Frame(self.root, bg=BG)
self.content.grid(row=0, column=1, sticky="nsew")
self.content.columnconfigure(0, weight=1)
self.content.rowconfigure(0, weight=1)
self.pages = {name: tk.Frame(self.content, bg=BG) for name in self.PAGES}
for frame in self.pages.values():
frame.grid(row=0, column=0, sticky="nsew")
self.build_play()
self.build_settings()
self.build_controls()
self.build_mods()
self.build_saves()
self.build_tools()
self.build_about()
self.render_updates()
self.show(page)
# ---- look
def style(self):
s = ttk.Style(self.root)
try:
s.theme_use("clam")
except tk.TclError:
pass
px = self.px
s.configure(".", background=BG, foreground=TEXT, fieldbackground=NAV, bordercolor=LINE,
lightcolor=PANEL, darkcolor=PANEL, troughcolor=PANEL, font=("Segoe UI", 10))
s.configure("TFrame", background=BG)
s.configure("TLabel", background=BG, foreground=TEXT)
s.configure("Muted.TLabel", foreground=MUTED)
s.configure("TButton", background=PANEL2, foreground=TEXT, padding=(px(14), px(6)), borderwidth=1,
bordercolor=LINE, font=("Segoe UI", 10), width=0)
s.map("TButton", background=[("active", RAISED), ("disabled", NAV)], bordercolor=[("active", EDGE)],
foreground=[("disabled", FAINT)])
s.configure("TEntry", insertcolor=TEXT, padding=px(5))
s.configure("TCombobox", arrowcolor=TEXT, padding=px(4), fieldbackground=PANEL2, background=PANEL2)
s.map("TCombobox", fieldbackground=[("disabled", PANEL), ("readonly", PANEL2)],
foreground=[("disabled", DISABLED), ("readonly", TEXT)], arrowcolor=[("disabled", DISABLED)],
selectbackground=[("readonly", PANEL2)], selectforeground=[("readonly", TEXT)],
background=[("readonly", PANEL2)])
self.root.option_add("*TCombobox*Listbox.background", PANEL2)
self.root.option_add("*TCombobox*Listbox.foreground", TEXT)
self.root.option_add("*TCombobox*Listbox.selectBackground", RAISED)
self.root.option_add("*TCombobox*Listbox.selectForeground", TEXT)
s.configure("Treeview", background=PANEL, fieldbackground=PANEL, foreground=TEXT, rowheight=px(32),
borderwidth=0)
s.configure("Treeview.Heading", background=NAV, foreground=MUTED, relief="flat", font=("Segoe UI", 9),
padding=(px(8), px(6)))
s.map("Treeview.Heading", background=[("active", NAV)], foreground=[("active", TEXT)])
s.configure("Treeview.Item", padding=(px(8), 0))
s.configure("Treeview.Cell", padding=(px(8), 0))
s.map("Treeview", background=[("selected", RAISED)], foreground=[("selected", TEXT)])
s.configure("Vertical.TScrollbar", background=PANEL, troughcolor=NAV, arrowcolor=MUTED, bordercolor=NAV,
lightcolor=PANEL, darkcolor=PANEL)
s.map("Vertical.TScrollbar", background=[("active", LINE)])
def build_nav(self):
px = self.px
nav = tk.Frame(self.root, bg=NAV, width=px(170))
nav.grid(row=0, column=0, sticky="ns")
nav.grid_propagate(False)
nav.pack_propagate(False)
tk.Label(nav, text="Mandy", bg=NAV, fg=TEXT, font=("Segoe UI Semibold", 15), anchor="w",
padx=0, pady=0).pack(fill="x", padx=px(16), pady=(px(16), 0))
tk.Label(nav, text=t("Launcher"), bg=NAV, fg=MUTED, font=("Segoe UI", 9),
anchor="w").pack(fill="x", padx=px(16), pady=(0, px(16)))
names = {"Play": t("Play"), "Settings": t("Settings"), "Controls": t("Controls"), "Mods": t("Mods"),
"Saves": t("Saves"), "Tools": t("Tools"), "About": t("About")}
for name in self.PAGES:
row = tk.Frame(nav, bg=NAV, cursor="hand2")
row.pack(fill="x", pady=(0, px(2)))
mark = tk.Frame(row, bg=NAV, width=px(3))
mark.pack(side="left", fill="y")
label = tk.Label(row, text=names[name], bg=NAV, fg=MUTED, font=("Segoe UI", 10), anchor="w",
padx=px(13), pady=px(6), cursor="hand2")
label.pack(side="left", fill="x", expand=True)
for widget in (row, label):
widget.bind("<Button-1>", lambda _e, n=name: self.show(n))
widget.bind("<Enter>", lambda _e, n=name: self.nav_hover(n, True))
widget.bind("<Leave>", lambda _e, n=name: self.nav_hover(n, False))
self.nav_buttons[name] = (row, mark, label)
# At the bottom of the rail, as in the mockup: up to date or not, the commit, the card and its driver.
foot = tk.Frame(nav, bg=NAV)
foot.pack(side="bottom", fill="x", padx=px(16), pady=(0, px(16)))
state = tk.Frame(foot, bg=NAV)
state.pack(fill="x")
self.rail_dot = self.status_dot(state, NAV)
self.rail_dot.pack(side="left", anchor="n")
self.rail_state = tk.StringVar(value="")
tk.Label(state, textvariable=self.rail_state, bg=NAV, fg=TEXT, font=("Segoe UI", 8), anchor="w",
justify="left", wraplength=px(120)).pack(side="left", padx=(px(4), 0))
self.rail_checked = tk.StringVar(value="")
tk.Label(foot, textvariable=self.rail_checked, bg=NAV, fg=MUTED, font=("Segoe UI", 8),
anchor="w").pack(fill="x", pady=(0, px(4)))
self.rail_info = tk.StringVar(value=self.rail_seen)
tk.Label(foot, textvariable=self.rail_info, bg=NAV, fg=FAINT, font=("Segoe UI", 8), anchor="w",
justify="left", wraplength=px(136)).pack(fill="x")
tk.Label(foot, text=t("Unofficial \u00b7 Runs your own copy"), bg=NAV, fg=FAINT, font=("Segoe UI", 8),
anchor="w", wraplength=px(136), justify="left").pack(fill="x", pady=(px(8), 0))
def read_rail(self):
"""The commit and the card for the rail, read off the window's thread (the card takes a second)."""
def work():
try:
version = rail_version()
cards = graphics_cards()
except Exception:
version, cards = "", []
lines = [version]
for name, driver in cards[:1]:
short = name.replace("NVIDIA GeForce ", "").replace("Laptop GPU", "Laptop")
number = nvidia_driver(driver) if "nvidia" in name.lower() else ""
lines.append(short + (f" \u00b7 {number}" if number else ""))
self.lines.put(("rail", None, "\n".join(x for x in lines if x)))
threading.Thread(target=work, daemon=True).start()
def nav_hover(self, name, inside):
if name != self.current:
row, mark, label = self.nav_buttons[name]
for widget in (row, label):
widget.configure(bg=PANEL if inside else NAV)
def show(self, name):
self.current = name
self.pages[name].tkraise()
for key, (row, mark, label) in self.nav_buttons.items():
chosen = key == name
row.configure(bg=PANEL if chosen else NAV)
label.configure(bg=PANEL if chosen else NAV, fg=TEXT if chosen else MUTED)
mark.configure(bg=PINK if chosen else NAV)
if name == "Mods":
self.refresh_mods()
if name == "Saves":
self.refresh_saves()
if name == "Controls":
self.refresh_controls_note()
def title(self, parent, text, row=0, note=None):
ttk.Label(parent, text=text, font=("Segoe UI Semibold", 20)).grid(row=row, column=0, columnspan=3,
sticky="w")
if note:
ttk.Label(parent, text=note, style="Muted.TLabel", wraplength=self.px(760), justify="left").grid(
row=row + 1, column=0, columnspan=3, sticky="w", pady=(self.px(2), 0))
# ---- Play
def build_play(self):
"""The Play page as cards: PLAY with the state and the game folder, the updates (state, last check, what
is new) beside it, and the output under both."""
px = self.px
page = self.pages["Play"]
page.columnconfigure(0, weight=1, uniform="play")
page.columnconfigure(1, weight=1, uniform="play")
page.rowconfigure(2, weight=1)
tk.Frame(page, bg=BG, height=px(24)).grid(row=0, column=0, columnspan=2)
play = self.card(page, 1, 0, t("Play"), t("Runs your own copy of GTA VI \u00b7 Unofficial"))
self.play_canvas = tk.Canvas(play, bg=PANEL, highlightthickness=0, width=px(260), height=px(64))
self.play_canvas.grid(row=play.next_row, column=0, columnspan=2, sticky="w", padx=px(16),
pady=(px(8), px(10)))
play.next_row += 1
# PLAY (Stop while something runs): a rounded pill in the violet-to-pink gradient, lighter under the
# pointer.
self.button_hover = False
self.play_canvas.tag_bind("button", "<Button-1>", lambda _e: self.stop() if self.process else self.play())
# The widget's own Enter/Leave, not its items': the pill's items are made again when PLAY turns into
# Stop, and items made under the pointer send Leave/Enter again; hovering only recolours them in place.
self.play_canvas.bind("<Enter>", lambda _e: self.hover_button(True))
self.play_canvas.bind("<Leave>", lambda _e: self.hover_button(False))
self.status_var = tk.StringVar(value=t(self.state))
tk.Label(play, textvariable=self.status_var, bg=PANEL, fg=TEXT, font=("Segoe UI", 10),
anchor="w", justify="left", wraplength=px(420)).grid(row=play.next_row, column=0, columnspan=2,
sticky="ew", padx=px(16))
play.next_row += 1
self.hint_var = tk.StringVar()
tk.Label(play, textvariable=self.hint_var, bg=PANEL, fg=MUTED, font=("Segoe UI", 8), anchor="w",
justify="left", wraplength=px(420)).grid(row=play.next_row, column=0, columnspan=2, sticky="ew",
padx=px(16), pady=(px(4), 0))
play.next_row += 1
# While no game folder with the executable is set: a box that says so where PLAY is, with the button that
# picks it (refresh_hint shows or hides it; the same field as Settings' Game folder).
self.folder_box = tk.Frame(play, bg=PANEL2, highlightthickness=1, highlightbackground=WARN)
self.folder_box.grid(row=play.next_row, column=0, columnspan=2, sticky="ew", padx=px(16),
pady=(px(12), px(4)))
self.folder_box.columnconfigure(0, weight=1)
tk.Label(self.folder_box, text=t("Where is your game?"), bg=PANEL2, fg=TEXT, font=("Segoe UI", 10),
anchor="w").grid(row=0, column=0, sticky="ew", padx=px(12), pady=(px(10), 0))
tk.Label(self.folder_box, text=t("Choose the folder of your own copy, the one with {exe}.",
exe=EXPECTED_EXE),
bg=PANEL2, fg=MUTED, font=("Segoe UI", 8), anchor="w", justify="left",
wraplength=px(380)).grid(row=1, column=0, sticky="ew", padx=px(12), pady=(px(2), 0))
self.folder_error = tk.StringVar()
self.folder_error_label = tk.Label(self.folder_box, textvariable=self.folder_error, bg=PANEL2, fg=DANGER,
font=("Segoe UI", 8), anchor="w", justify="left", wraplength=px(380))
self.folder_error_label.grid(row=2, column=0, sticky="ew", padx=px(12), pady=(px(2), 0))
self.folder_error_label.grid_remove()
PrimaryButton(self.folder_box, t("Choose game folder"), self.choose_game_folder, self.k,
bg=PANEL2).grid(row=3, column=0, sticky="w", padx=px(12), pady=(px(10), px(12)))
self.folder_box.grid_remove()
play.next_row += 1
# One line while the saved profile is Series X and Windows' commit limit is under what it needs
# (memory_note); refresh_hint shows or hides it. A warning only: PLAY stays as it is.
self.memory_line = tk.Label(play, text="", bg=PANEL, fg=WARN, font=("Segoe UI", 8), anchor="w",
justify="left", wraplength=px(420))
self.memory_line.grid(row=play.next_row, column=0, columnspan=2, sticky="ew", padx=px(16),
pady=(px(4), 0))
self.memory_line.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
Tip([self.memory_line], page_file_steps(self.memory[1]), self.k)
play.next_row += 1
# What PLAY passes, so a player sees the options before starting (Settings changes them).
self.options_var = tk.StringVar()
options = tk.Label(play, textvariable=self.options_var, bg=PANEL, fg=MUTED, font=("Consolas", 8),
anchor="w", justify="left", wraplength=px(420))
options.grid(row=play.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(8), px(12)))
options.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
play.next_row += 1
# What the in-game F1 menu saved (d3d12/leonida-settings.txt), which the script applies at every start
# over the options above unless one of them was changed since the last PLAY.
self.menu_box = tk.Frame(play, bg=PANEL)
self.menu_box.grid(row=play.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(0, px(16)))
self.menu_box.columnconfigure(0, weight=1)
play.next_row += 1
self.menu_shown = None
self.render_menu_settings()
self.draw_button()
news = self.card(page, 1, 1, t("Updates"))
self.update_body = tk.Frame(news, bg=PANEL)
self.update_body.grid(row=news.next_row, column=0, columnspan=2, sticky="nsew", padx=px(16),
pady=(px(8), px(16)))
self.update_body.columnconfigure(0, weight=1)
news.next_row += 1
out = self.card(page, 2, 0, t("Output"), wide=True)
out.grid_configure(pady=(0, px(24)))
buttons = tk.Frame(out, bg=PANEL)
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))
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)
box.columnconfigure(0, weight=1)
box.rowconfigure(0, weight=1)
self.log = tk.Text(box, bg=FIELD, fg=TEXT, insertbackground=TEXT, relief="flat", wrap="word",
font=("Consolas" if WINDOWS else "monospace", 9), state="disabled", height=6,
highlightthickness=1, highlightbackground=LINE, padx=px(8), pady=px(6))
scroll = ttk.Scrollbar(box, orient="vertical", command=self.log.yview)
self.log.configure(yscrollcommand=scroll.set)
self.log.grid(row=0, column=0, sticky="nsew")
scroll.grid(row=0, column=1, sticky="ns")
self.refresh_hint()
def render_menu_settings(self, force=False):
"""The Play card's "Saved in the F1 menu" section and the F1 notes of Settings, from the menu file as it
is now. Built again only when what the file says changed (the window's focus calls this often)."""
values = read_menu_settings(REPO)
if values == self.menu_shown and not force:
return
self.menu_shown = values
self.render_menu_notes(values)
# The F1 menu's console can be the one the next PLAY runs: Play's commit-limit line follows it, and so
# does frame generation with ray tracing on Settings (apply_rules), as the menu's ray tracing and frame
# generation do (launch_values).
self.refresh_memory()
self.apply_rules()
px = self.px
box = getattr(self, "menu_box", None)
if box is None:
return
for child in box.winfo_children():
child.destroy()
tk.Frame(box, bg=ROW_LINE, height=1).grid(row=0, column=0, columnspan=2, sticky="ew", pady=(0, px(10)))
tk.Label(box, text=t("Saved in the F1 menu"), bg=PANEL, fg=TEXT, font=("Segoe UI Semibold", 9),
anchor="w", padx=0).grid(row=1, column=0, sticky="w")
if not values:
tk.Label(box, text=t("Nothing saved in the F1 menu"), bg=PANEL, fg=MUTED, font=("Segoe UI", 8),
anchor="w", padx=0).grid(row=2, column=0, columnspan=2, sticky="w", pady=(px(2), 0))
return
self.quiet_button(box, t("Clear F1 settings"), self.clear_menu).grid(row=1, column=1, sticky="e")
lines = menu_lines(values)
shown = 5 if len(lines) > 6 else 6
row = 2
for text in lines[:shown]:
tk.Label(box, text=text, bg=PANEL, fg=TEXT, font=("Segoe UI", 9), anchor="w", padx=0).grid(
row=row, column=0, columnspan=2, sticky="w", pady=(px(4) if row == 2 else 0, 0))
row += 1
if len(lines) > shown:
more = tk.Label(box, text=t("+ {n} more", n=len(lines) - shown), bg=PANEL, fg=FAINT,
font=("Segoe UI", 8), anchor="w", padx=0)
more.grid(row=row, column=0, columnspan=2, sticky="w")
Tip([more], "\n".join(lines), self.k)
row += 1
note = tk.Label(box, text=t("These apply at every start unless you change the same option here before "
"PLAY"), bg=PANEL, fg=MUTED, font=("Segoe UI", 8), anchor="w",
justify="left", wraplength=px(400), padx=0)
note.grid(row=row, column=0, columnspan=2, sticky="ew", pady=(px(6), 0))
note.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
def quiet_button(self, parent, text, command):
"""A secondary action that stays out of the way: muted text in a thin frame, brighter under the pointer
(the widget's own Enter/Leave, recolouring only)."""
px = self.px
label = tk.Label(parent, text=text, bg=PANEL, fg=MUTED, font=("Segoe UI", 8), padx=px(10), pady=px(3),
cursor="hand2", highlightthickness=1, highlightbackground=LINE, highlightcolor=EDGE,
takefocus=1)
label.bind("<Button-1>", lambda _e: command())
label.bind("<Return>", lambda _e: command())
label.bind("<space>", lambda _e: command())
label.bind("<Enter>", lambda _e: label.configure(fg=TEXT, highlightbackground=EDGE))
label.bind("<Leave>", lambda _e: label.configure(fg=MUTED, highlightbackground=LINE))
return label
def clear_menu(self):
if self.process is not None and self.kind == "game":
messagebox.showinfo(t("Clear F1 settings"), t("Close the game first: it writes this file."))
return
if not messagebox.askyesno(t("Clear F1 settings"), t(
"Delete what the F1 menu saved ({file})? The next start uses the launcher's options and the "
"game's defaults.", file=os.path.join("d3d12", MENU_FILE))):
return
try:
clear_menu_settings(REPO)
except OSError as exc:
messagebox.showwarning(t("Clear F1 settings"), t("Could not delete it: {error}", error=exc))
self.render_menu_settings()
def render_menu_notes(self, values):
"""The muted "F1 menu: <value>" under a Settings control whose setting the menu file also holds."""
for key, label in getattr(self, "menu_notes", {}).items():
text = menu_note(key, values)
label.configure(text=text)
if text:
label.pack(fill="x")
else:
label.pack_forget()
def render_updates(self):
"""The Updates card and the rail's state, from update_seen, checking and last_check (they outlive a
rebuild of the window)."""
px = self.px
body = self.update_body
for child in body.winfo_children():
child.destroy()
status = self.update_seen or {}
kind = status.get("kind")
if kind == "behind":
head = t("{n} update(s) available", n=status["behind"])
elif kind == "current":
head = t("Up to date")
elif kind == "noupstream":
head = t("No branch to follow")
elif kind:
head = update_note(status) or t("Could not check for updates")
else:
head = t("Not checked yet")
top = tk.Frame(body, bg=PANEL)
top.grid(row=0, column=0, sticky="ew")
self.status_dot(top, PANEL).pack(side="left", anchor="n")
tk.Label(top, text=head, bg=PANEL, fg=TEXT, font=("Segoe UI", 10), anchor="w", justify="left",
wraplength=px(300)).pack(side="left", padx=(px(4), 0), fill="x")
line = tk.Frame(body, bg=PANEL)
line.grid(row=1, column=0, sticky="ew", pady=(px(4), px(8)))
self.last_check_var = tk.StringVar(value=self.last_check_text())
tk.Label(line, textvariable=self.last_check_var, bg=PANEL, fg=MUTED, font=("Segoe UI", 8),
anchor="w").pack(side="left")
check = ttk.Button(line, text=t("Check now"), command=lambda: self.check_updates(fetch=True))
check.pack(side="right")
if self.checking:
check.state(["disabled"])
changes = status.get("changes") or [] if kind == "behind" else []
row = 2
if changes:
tk.Label(body, text=t("What is new:"), bg=PANEL, fg=MUTED, font=("Segoe UI", 8), anchor="w").grid(
row=row, column=0, sticky="ew", pady=(px(4), px(4)))
row += 1
# A log: the pull request's number in mono in a column of its own (blank for a direct commit),
# the title in the interface font, cut to the card's width.
lines = []
for change in changes[:6]:
entry = tk.Frame(body, bg=PANEL)
entry.grid(row=row, column=0, sticky="ew")
number = f"#{change['pr']}" if change.get("pr") else ""
tk.Label(entry, text=number, bg=PANEL, fg=MUTED, font=("Consolas", 9), width=6, anchor="w",
padx=0).pack(side="left")
label = tk.Label(entry, text="", bg=PANEL, fg=TEXT, font=("Segoe UI", 9), anchor="w", padx=0)
label.pack(side="left", fill="x", expand=True, padx=(px(4), 0))
title = change_line(dict(change, pr=None), limit=200)
lines.append((label, title))
row += 1
self.fit_lines(body, lines, indent=lines[0][0].master.winfo_children()[0])
more = status["behind"] - min(6, len(changes))
if more > 0:
tk.Label(body, text=t("+ {n} more", n=more), bg=PANEL, fg=FAINT, font=("Segoe UI", 8),
anchor="w").grid(row=row, column=0, sticky="ew", pady=(px(4), 0))
row += 1
if kind in ("behind", "zip"):
holder = tk.Frame(body, bg=PANEL)
holder.grid(row=row, column=0, sticky="w", pady=(px(12), 0))
PrimaryButton(holder, t("Update Mandy"), self.update, self.k, bg=PANEL).pack(side="left")
self.render_rail()
def dot_colour(self):
"""The status dot's colour, the same in the Updates card and the rail: green up to date, amber with
updates, red when the check failed, grey otherwise and while a check runs."""
kind = (self.update_seen or {}).get("kind")
if self.checking:
return FAINT
return {"current": OK, "behind": WARN, "zip": WARN, "error": DANGER}.get(kind, FAINT)
def status_dot(self, parent, bg):
return tk.Label(parent, text="\u25cf", bg=bg, fg=self.dot_colour(), font=("Segoe UI", 9), padx=0, pady=0)
def render_rail(self):
"""The update state at the bottom of the rail, in step with the Updates card, and when it was checked."""
status = self.update_seen or {}
kind = status.get("kind")
if self.checking:
text = t("Checking ...")
elif kind == "behind":
text = t("{n} update(s) available", n=status["behind"])
elif kind == "current":
text = t("Up to date")
elif kind == "zip":
text = t("Zip copy: press Update Mandy")
elif kind == "nogit":
text = t("Git not installed")
elif kind == "noupstream":
text = t("No branch to follow")
elif kind == "error":
text = t("Update check failed")
else:
text = t("Not checked yet")
self.rail_state.set(text)
self.rail_dot.configure(fg=self.dot_colour())
self.rail_checked.set(t("Checked {time}", time=time.strftime("%H:%M", time.localtime(self.last_check)))
if self.last_check is not None and not self.checking else "")
def fit_lines(self, body, lines, indent=None):
"""Each line cut with an ellipsis to the width the card gives it (less the `indent` widget before each
line), again when the window is resized."""
import tkinter.font as tkfont
font = tkfont.Font(family="Segoe UI", size=9)
def fit(_event=None):
room = body.winfo_width() - self.px(8) - (indent.winfo_reqwidth() if indent is not None else 0)
if room <= 1:
return
for label, text in lines:
shown = text
if font.measure(shown) > room:
while shown and font.measure(shown + "\u2026") > room:
shown = shown[:-1]
shown = shown.rstrip() + "\u2026"
label.configure(text=shown)
for label, text in lines:
label.configure(text=text)
body.bind("<Configure>", fit)
body.after_idle(fit)
def last_check_text(self):
if self.checking:
return t("Checking ...")
if self.last_check is None:
return ""
ago = time.time() - self.last_check
when = time.strftime("%H:%M", time.localtime(self.last_check))
if ago < 60:
since = t("just now")
elif ago < 3600:
since = t("{n} min ago", n=int(ago // 60))
else:
since = t("{n} h ago", n=int(ago // 3600))
return t("Last check: {time} ({since})", time=when, since=since)
def tick_updates(self):
"""Keeps "Last check: ... (n min ago)" current."""
try:
self.last_check_var.set(self.last_check_text())
except (AttributeError, tk.TclError):
pass
self.root.after(30000, self.tick_updates)
def hover_button(self, inside):
if inside == self.button_hover:
return
self.button_hover = inside
self.play_canvas.configure(cursor="hand2" if inside else "")
self.colour_button()
def colour_button(self):
"""The pill's colours for the state and the pointer, set on the lines draw_button made."""
running = self.process is not None
left, right = (DANGER, "#dc2626") if running else (VIOLET, PINK)
if self.button_hover:
left, right = blend(left, "#ffffff", 0.15), blend(right, "#ffffff", 0.15)
lines = getattr(self, "button_lines", [])
last = max(1, len(lines) - 1)
for i, item in enumerate(lines):
self.play_canvas.itemconfigure(item, fill=blend(left, right, i / last))
def draw_button(self):
"""The pill: one vertical line a pixel wide per column, cut to the rounded ends, so the gradient keeps
round corners. No shadow: a stippled one shows as dots."""
canvas, px = self.play_canvas, self.px
canvas.delete("button")
running = self.process is not None
text = ("\u25a0 " + t("Stop")) if running else ("\u25b6 " + t("PLAY"))
w, h = px(250), px(60)
x0, y0 = 0, px(2)
r = h / 2
lines = []
for i in range(w):
cx = i + 0.5
if cx < r:
dy = r - (r * r - (r - cx) ** 2) ** 0.5
elif cx > w - r:
dy = r - (r * r - (cx - (w - r)) ** 2) ** 0.5
else:
dy = 0
lines.append(canvas.create_line(x0 + i, y0 + dy, x0 + i, y0 + h - dy, tags="button"))
self.button_lines = lines
canvas.create_text(x0 + w // 2, y0 + h // 2, text=text, fill=ON_ACCENT,
font=("Segoe UI", 16, "bold"), tags="button")
self.colour_button()
def refresh_options(self):
try:
args = (switch_args(for_card(self.settings, self.card_now()))
+ [f"{k}={v}" for k, v in extra_variables(self.settings).items()])
self.options_var.set(t("Options: {switches}", switches=" ".join(args) or t("the defaults")))
except (AttributeError, tk.TclError):
pass
def refresh_memory(self):
"""The commit-limit warnings: Play's line from the profile the next PLAY runs (effective_console: the saved
one, or the F1 menu's when the launcher's has not changed since the last PLAY), Settings' note from the
Profile control as it is now (so it follows a switch between S and X before Save; the control's own
"F1 menu: Series X" note says when the menu holds another)."""
limit, phys = self.memory
menu = self.menu_shown if getattr(self, "menu_shown", None) is not None else read_menu_settings(REPO)
runs_x = effective_console(self.settings, menu) == "series-x"
line = getattr(self, "memory_line", None)
if line is not None:
text = memory_note(runs_x, limit, phys, short=True)
line.configure(text=text or "")
if text:
line.grid()
else:
line.grid_remove()
note = getattr(self, "profile_memory", None)
if note is not None and "profile" in self.vars:
text = memory_note(self.vars["profile"].get() == "x", limit, phys)
note.configure(text=text or "")
if text:
note.grid()
else:
note.grid_remove()
def refresh_hint(self):
self.refresh_options()
self.refresh_memory()
if self.process is not None:
self.hint_var.set("")
elif not game_exe_present(self.settings["game_dir"]):
self.hint_var.set("")
else:
self.hint_var.set(self.settings["game_dir"])
box = getattr(self, "folder_box", None)
if box is not None:
if self.process is None and not game_exe_present(self.settings["game_dir"]):
box.grid()
else:
box.grid_remove()
self.folder_error.set("")
self.folder_error_label.grid_remove()
def choose_game_folder(self):
"""The Play page's Choose game folder (and PLAY without one): the folder picker; a folder with the
executable is saved at once, as Settings' Game folder; another one says so in the box and changes nothing.
True when a folder with the executable is set."""
start = self.settings.get("game_dir") or os.path.expanduser("~")
chosen = filedialog.askdirectory(title=t("Where is your game?"), initialdir=start, mustexist=True)
if not chosen:
return False
folder = os.path.normpath(chosen)
if not game_exe_present(folder):
self.folder_error.set(t("{exe} is not in this folder", exe=EXPECTED_EXE) + ": " + folder)
self.folder_error_label.grid()
return False
if "game_dir" in self.vars:
self.vars["game_dir"].set(folder)
self.settings["game_dir"] = folder
try:
save_settings(self.settings)
except OSError as exc:
self.folder_error.set(t("Could not save: {error}", error=exc))
self.folder_error_label.grid()
return False
self.refresh_hint()
return True
def append(self, text):
self.log.configure(state="normal")
self.log.insert("end", text)
self.log.see("end")
self.log.configure(state="disabled")
def set_state(self, state):
self.state = state
self.status_var.set(t(state))
def play_diagnostic(self):
if self.process is not None:
return
if messagebox.askokcancel(t("Run in diagnostic mode"), t(
"This starts the game with a log file and crash tracing (DRED), a little slower. When the game "
"closes or stops, the logs folder opens: send the newest file with your report.")):
self.play(diagnostic=True)
def play(self, diagnostic=False):
if self.process is not None:
return
self.collect_settings()
if not game_exe_present(self.settings["game_dir"]) and not self.choose_game_folder():
return
card = self.card_now()
settings, extra = for_card(dict(self.settings), card), None
if diagnostic:
settings["log"] = True
extra = {"LEONIDA_D3D12_DRED": "1"}
args = switch_args(settings)
try:
command = play_command(settings, extra=extra, mask=card_mask(card),
chosen=chosen_switches(args, self.settings["last_switches"]))
except ValueError as exc:
messagebox.showwarning(t("Play"), str(exc))
return
self.run(command, "game", t("the game"), "Starting")
# The options this start passed, for the next one to tell a changed option from one passed again; only
# once it started, so a start that failed leaves a change to count as one the next time.
if self.process is not None:
self.diagnostic = diagnostic
# The options of a normal PLAY: a diagnostic start's -Log must not count as chosen at the next one.
self.settings["last_switches"] = json.dumps(switch_args(for_card(self.settings, card)))
try:
save_settings(self.settings)
except OSError:
pass
# Nothing counts as changed now: the F1 menu's values stand again for the next PLAY (launch_values).
self.apply_rules()
def run(self, command, kind, what, state):
if self.process is not None:
messagebox.showinfo("Mandy", t("Something is already running. Stop it first."))
return
self.log.configure(state="normal")
self.log.delete("1.0", "end")
self.log.configure(state="disabled")
self.append("> " + " ".join(f'"{c}"' if " " in c else c for c in command) + "\n")
try:
self.process = spawn(command, REPO)
except OSError as exc:
self.append(t("Could not start: {error}", error=exc) + "\n")
self.set_state("Could not start")
return
self.kind, self.what = kind, what
self.started = time.monotonic()
self.diagnostic = False
self.set_state(state)
self.button_hover = False
self.draw_button()
self.hint_var.set("")
process = self.process
threading.Thread(target=self.read_output, args=(process,), daemon=True).start()
def read_output(self, process):
for raw in iter(process.stdout.readline, b""):
self.lines.put(("line", process, raw.decode("utf-8", errors="replace")))
code = process.wait()
self.lines.put(("exit", process, code))
def pump(self):
# At most OUTPUT_BATCH items a turn, each run of lines in one insert (take_output, whose design and names
# are those of #3192 by 1mshy, the same fix on main's launcher): a run that floods the pipe (the runtime's
# stderr with -Log off, issue #3175) no longer holds the window. take_output keeps info and rail items in
# their place like exit and update.
for kind, process, value in take_output(self.lines):
if kind == "update":
self.show_update(value)
continue
if kind == "info":
self.show_info(value)
continue
if kind == "rail":
self.rail_seen = value
self.rail_info.set(value)
continue
if process is not self.process:
continue
if kind == "lines":
self.append("".join(value))
if self.kind == "game":
state = self.state
for line in value:
state = state_for_line(state, line)
if state != self.state:
self.set_state(state)
else:
self.finished(value)
self.root.after(100 if self.lines.empty() else OUTPUT_RESUME_MS, self.pump)
def finished(self, code):
quick = time.monotonic() - self.started < 30
if code == 0 and self.kind == "game" and quick:
text = t("The game closed right after starting. Run in diagnostic mode, then send the newest log "
"and Copy my info with your report.")
elif code == 0:
text = t("The game closed.") if self.kind == "game" else t("Done.")
else:
text = t("Stopped with an error (code {code}).", code=code)
self.append("\n" + text + "\n")
self.state = "Ready"
self.status_var.set(text)
if self.kind == "update":
self.check_updates(fetch=False)
if self.diagnostic:
self.append(t("Diagnostic run over: the logs folder is {folder}", folder=logs_dir()) + "\n")
self.open(logs_dir())
self.process = None
self.diagnostic = False
self.button_hover = False
self.draw_button()
self.refresh_hint()
self.render_menu_settings()
# ---- what to send when asking for help
def copy_info(self):
self.collect_settings()
settings = dict(self.settings)
tk_version = str(tk.TkVersion)
def work():
try:
text = info_text(settings, leonida_version(), graphics_cards(),
f"{platform.python_version()} ({platform.architecture()[0]})", tk_version,
f"{platform.system()} {platform.release()} ({platform.version()})",
(commit_limit_bytes(), physical_memory_bytes()))
except Exception as exc:
text = f"Mandy launcher info\n(could not be read: {exc})\n"
self.lines.put(("info", None, text))
self.set_status_note(t("Reading the graphics card ..."))
threading.Thread(target=work, daemon=True).start()
def set_status_note(self, text):
self.status_var.set(text)
def show_info(self, text):
self.root.clipboard_clear()
self.root.clipboard_append(text)
self.status_var.set(t(self.state))
messagebox.showinfo(t("Copy my info"), t("Copied. Paste it with your report:") + "\n\n" + text)
# ---- updates
def check_updates(self, fetch=True):
if self.checking:
return
self.checking = True
self.render_updates()
def work():
try:
status = update_status(REPO, fetch=fetch)
except Exception as exc: # a broken git must not take the launcher down
status = {"kind": "error", "behind": 0, "detail": str(exc)[:300]}
self.lines.put(("update", None, status))
threading.Thread(target=work, daemon=True).start()
def show_update(self, status):
self.update_seen = status
self.checking = False
self.last_check = time.time()
self.render_updates()
def update(self):
if not os.path.exists(os.path.join(REPO, ".git")):
self.update_zip()
return
if not messagebox.askokcancel(t("Update Mandy"), t(
"This runs git pull in the launcher's folder, then rebuilds the runtime if it changed (a few "
"minutes).\n\nContinue?")):
return
self.show("Play")
self.run(update_command(), "update", t("the update"), "Updating")
def update_zip(self):
"""Update on a zip copy: one question (Git's install included when it is missing), then --update makes
the folder a clone (zip_to_clone)."""
missing = find_git() is None
if missing and not WINDOWS:
messagebox.showinfo(t("Update Mandy"), t("Git is not installed: install it with your package manager, "
"then press Update Mandy again."))
return
text = t("This copy was downloaded as a zip, so it cannot update itself. Update Mandy makes this folder a "
"git copy of the repository: it downloads the repository, keeps a copy of every file that "
"differs in {folder}, puts the current version in their place, then rebuilds the runtime (a few "
"minutes). Your settings, saves and builds are not touched.",
folder=os.path.dirname(zip_backup_dir()))
if missing:
text += "\n\n" + t("Git is not installed: it is installed first, with winget (Windows may ask for "
"permission).")
if not messagebox.askokcancel(t("Update Mandy"), text + "\n\n" + t("Continue?")):
return
self.show("Play")
self.run(update_command(install_git=missing), "update", t("the update"), "Updating")
def stop(self):
if self.process is None:
return
if messagebox.askyesno(t("Stop"), t("Stop {what}? Everything it started is ended.", what=self.what)):
stop_tree(self.process)
self.append("\n" + t("Stopping ...") + "\n")
def close(self):
if self.process is not None:
if not messagebox.askyesno("Mandy", t("{what} is still running. Stop it and close the launcher?",
what=self.what)):
return
stop_tree(self.process)
self.collect_settings()
self.root.destroy()
# ---- Settings
def scrolled(self, page):
"""A frame in `page` that scrolls with the wheel when it is taller than the window."""
canvas = tk.Canvas(page, bg=BG, highlightthickness=0)
bar = ttk.Scrollbar(page, orient="vertical", command=canvas.yview)
canvas.configure(yscrollcommand=bar.set)
canvas.grid(row=0, column=0, sticky="nsew")
bar.grid(row=0, column=1, sticky="ns")
inner = tk.Frame(canvas, bg=BG)
item = canvas.create_window(0, 0, window=inner, anchor="nw")
inner.bind("<Configure>", lambda _e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(item, width=e.width))
# The wheel scrolls the page wherever the pointer is on it (over a card too): bound for the whole
# window, it acts only while this page is shown.
def wheel(event):
if self.current != "Settings" or canvas.yview() == (0.0, 1.0):
return
if isinstance(event.widget, tk.Misc) and event.widget.winfo_toplevel() is not self.root:
return # another window's (Advanced mode scrolls its own list)
if getattr(event, "num", 0) in (4, 5):
canvas.yview_scroll(-1 if event.num == 4 else 1, "units")
elif event.delta:
canvas.yview_scroll(int(-event.delta / 120) or (-1 if event.delta > 0 else 1), "units")
for name in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
self.root.bind_all(name, wheel)
# Tk's own Combobox binding steps a read-only list's value on the wheel: a player scrolling the page
# over Frame limit would change it without seeing. Replaced, so the wheel only scrolls.
self.root.bind_class("TCombobox", name, lambda _e: None)
return inner
def card(self, parent, row, column, title, note=None, wide=False):
"""A section of a page, as in the mockup: a panel with a title and a short line, its options in rows
(the name on the left, the control on the right)."""
px = self.px
frame = tk.Frame(parent, bg=PANEL, highlightthickness=1, highlightbackground=LINE)
left = px(24) if column == 0 else px(8)
right = px(24) if wide or column == 1 else px(8)
frame.grid(row=row, column=column, columnspan=2 if wide else 1, sticky="nsew", padx=(left, right),
pady=(0, px(16)))
frame.columnconfigure(0, weight=1)
head = tk.Frame(frame, bg=PANEL)
head.grid(row=0, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(16), 0))
tk.Label(head, text=title, bg=PANEL, fg=TEXT, font=("Segoe UI Semibold", 10), anchor="w",
padx=0).pack(side="left")
if note:
small = tk.Label(frame, text=note, bg=PANEL, fg=MUTED, anchor="w", justify="left",
font=("Segoe UI", 9), wraplength=px(300), padx=0)
small.grid(row=1, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(4), px(8)))
small.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
frame.next_row = 2
frame.rows = 0
return frame
def card_end(self, card):
tk.Frame(card, bg=PANEL, height=self.px(8)).grid(row=card.next_row, column=0)
card.next_row += 1
def option(self, card, label, small, make, tip=None):
"""A row of a card: its name (and a short line under it) on the left, the control `make(card)` builds on
the right, a thin line above every row but the first, and `tip` shown when the pointer rests on it."""
px = self.px
if card.rows:
tk.Frame(card, bg=ROW_LINE, height=1).grid(row=card.next_row, column=0, columnspan=2, sticky="ew",
padx=px(16))
card.next_row += 1
card.rows += 1
row = card.next_row
card.next_row += 1
text = tk.Frame(card, bg=PANEL)
text.grid(row=row, column=0, sticky="ew", padx=(px(16), px(12)), pady=px(6))
name = tk.Label(text, text=label, bg=PANEL, fg=TEXT, font=("Segoe UI", 10), anchor="w", padx=0)
name.pack(fill="x")
widgets = [text, name]
if small:
note = tk.Label(text, text=small, bg=PANEL, fg=MUTED, anchor="w", justify="left",
font=("Segoe UI", 8), wraplength=px(200), padx=0)
note.pack(fill="x")
note.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(120), e.width - 4)))
widgets.append(note)
control = make(card)
control.grid(row=row, column=1, sticky="e", padx=(0, px(16)), pady=px(6))
control.text_frame = text
if tip:
Tip(widgets + [control], tip, self.k)
return control
def toggle(self, card, key, label, small=None, tip=None):
var = tk.BooleanVar(value=self.settings[key])
self.vars[key] = var
self.controls[key] = self.option(card, label, small, lambda parent: Toggle(parent, var, self.k), tip)
self.menu_note_for(key)
return self.controls[key]
def segmented(self, card, key, value, label, options, small=None, tip=None):
var = tk.StringVar(value=value)
self.vars[key] = var
self.controls[key] = self.option(card, label, small, lambda parent: Segmented(parent, var, options,
self.k), tip)
self.menu_note_for(key)
return self.controls[key]
def select(self, card, key, value, label, options, small=None, tip=None, width=12, buttons=False):
"""A drop-down list; `options` are (value, label) and collect_settings reads the value back. With
`buttons`, the same choice as a row of buttons (Segmented), for a short list whose every label fits
beside the option's name in every language, at the window's default and minimum width. Either way the
variable holds the shown label and `choices` maps it back, so the rules and the settings read it alike."""
names = dict(options)
var = tk.StringVar(value=names.get(value, options[0][1]))
self.vars[key] = var
self.choices[key] = {text: v for v, text in options}
texts = [text for _v, text in options]
if buttons:
def make(parent):
return Segmented(parent, var, [(text, text) for text in texts], self.k)
else:
def make(parent):
return ttk.Combobox(parent, textvariable=var, state="readonly", width=width, values=texts)
self.controls[key] = self.option(card, label, small, make, tip)
self.menu_note_for(key)
return self.controls[key]
def menu_note_for(self, key):
"""Room under the control's name for render_menu_notes, when the F1 menu has the same setting."""
if key in MENU_FOR_OPTION:
self.menu_notes[key] = tk.Label(self.controls[key].text_frame, text="", bg=PANEL, fg=MUTED,
font=("Segoe UI", 8), anchor="w", justify="left", padx=0)
def folder(self, card, key, label, tip):
var = tk.StringVar(value=self.settings[key])
self.vars[key] = var
def make(parent):
box = tk.Frame(parent, bg=PANEL)
ttk.Entry(box, textvariable=var, width=40).pack(side="left")
ttk.Button(box, text=t("Browse ..."), command=lambda: self.browse(var)).pack(side="left",
padx=(self.px(8), 0))
return box
self.option(card, label, None, make, tip)
return var
def build_settings(self):
px = self.px
page = self.pages["Settings"]
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight=1)
inner = self.scrolled(page)
inner.columnconfigure(0, weight=1, uniform="cards")
inner.columnconfigure(1, weight=1, uniform="cards")
head = tk.Frame(inner, bg=BG)
head.grid(row=0, column=0, columnspan=2, sticky="ew", padx=px(24), pady=(px(24), px(16)))
tk.Label(head, text=t("Settings"), bg=BG, fg=TEXT, font=("Segoe UI Semibold", 16), anchor="w",
padx=0).pack(fill="x")
tk.Label(head, text=t("Changes apply at the next PLAY; hover any option for what it does"), bg=BG,
fg=MUTED, font=("Segoe UI", 9), anchor="w", padx=0).pack(fill="x")
s = self.settings
picture = self.card(inner, 1, 0, t("Picture"), t("How the game is drawn and scaled"))
# Windows: Series X is the script's default and -SeriesS the choice; Linux: play-linux.sh is Series S
# unless --series-x.
profile = ("s" if s["series_s"] else "x") if WINDOWS else ("x" if s["series_x"] else "s")
self.segmented(picture, "profile", profile, t("Profile"),
[("s", "Series S"), ("x", "Series X")],
tip=t("Series X: 1080 to 1440 lines, the default. Series S: lighter, 720 lines taken to "
"1080 by DLSS."))
# Under the profile, while Series X is chosen and Windows' commit limit is under what it needs
# (memory_note): a warning, nothing is blocked. The pointer on it shows how to set a fixed page file.
self.profile_memory = tk.Label(picture, text="", bg=PANEL, fg=WARN, anchor="w", justify="left",
font=("Segoe UI", 8), wraplength=px(300), padx=0)
self.profile_memory.grid(row=picture.next_row, column=0, columnspan=2, sticky="ew", padx=px(16),
pady=(0, px(6)))
self.profile_memory.bind("<Configure>",
lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
Tip([self.profile_memory], page_file_steps(self.memory[1]), self.k)
picture.next_row += 1
self.vars["profile"].trace_add("write", lambda *_: self.refresh_memory())
self.refresh_memory()
self.toggle(picture, "dlss", "DLSS", t("When off, the picture is stretched"),
t("NVIDIA's upscaler (its files come from Tools). Off: the picture is stretched instead."))
# Without an NVIDIA card (the one chosen in Graphics card, or none on this PC): DLSS and its mode greyed.
self.nvidia_note = self.rule_note(picture)
# The DLSS mode (-Dlss): on the Series X profile DLSS makes the picture only with one; Auto passes none.
self.select(picture, "dlss_mode", s["dlss_mode"], t("DLSS mode"),
[("", t("Auto")), ("quality", t("Quality")), ("balanced", t("Balanced")),
("performance", t("Performance")), ("ultra", t("Ultra performance"))],
small=t("Series X: pick one for DLSS"), width=16,
tip=t("Auto: Series S uses DLSS by itself, Series X uses the game's own upscaler. A mode makes "
"DLSS draw the picture from that share of the lines, on Series X too (-Dlss)."))
self.select(picture, "resolution", s["resolution"], t("Resolution"),
[("", t("Default"))] + [(r, r) for r in RESOLUTIONS if r],
tip=t("Lines the game renders. Left out with a DLSS mode."))
# -Aspect and -PresentScale (play-nvidia.ps1: the window's shape; the game still draws 16:9).
self.select(picture, "aspect", s["aspect"], t("Window shape"), aspect_options(s["aspect"]), width=16,
tip=t("The shape of the game's window (-Aspect): your screen's, or 21:9 and 32:9 for "
"ultrawide monitors. The game still draws 16:9 inside it."))
# Fit is the script's own with -Aspect: nothing is passed for it, unless "fit" was saved as such.
fit = "fit" if s["present_scale"] == "fit" else ""
self.select(picture, "present_scale", s["present_scale"], t("Picture in the window"),
[(fit, t("Fit")), ("stretch", t("Stretch"))], small=t("With a window shape"), buttons=True,
tip=t("Fit: the 16:9 picture centred, black bars beside it. Stretch: it fills the window "
"(-PresentScale). Only with a window shape."))
self.toggle(picture, "quality", t("Steady bodies"), t("Fewer stretched bodies, slower"),
t("Fewer stretched or jumping bodies (the relay's first stage, no steps on the card); slower. "
"Not a picture-quality setting."))
self.card_end(picture)
frames = self.card(inner, 1, 1, t("Frame generation"), t("More frames shown per frame rendered"))
mode = "off" if s["no_frame_gen"] else ("fsr" if s["fsr_frame_gen"] else "dlss")
self.segmented(frames, "fg_mode", mode, t("Mode"), [("dlss", "DLSS"), ("fsr", "FSR"), ("off", t("Off"))],
tip=t("DLSS: NVIDIA's frame generation, on by itself on RTX 40 and 50 with NVIDIA's files. "
"FSR: AMD's, for other cards. Off: only the frames the game renders."))
# -FrameGen n (play-nvidia.ps1 takes 2 to 6). The runtime asks the card for its most and makes no more
# (fg.rs): an RTX 40 makes 2x whatever is asked, 3x and up are RTX 50's.
self.select(frames, "frame_gen", str(s["frame_gen"]), t("Multiplier"), frame_gen_options(),
small=t("3x and more: RTX 50"), width=12,
tip=t("Frames shown per frame rendered, with DLSS (-FrameGen). Auto: the script's own "
"choice, 2x on RTX 40 and 50 with NVIDIA's files. 3x to 6x need an RTX 50: an RTX 40 "
"makes 2x. On Series X a number also brings DLSS in (Quality unless a DLSS mode is "
"chosen)."))
self.select(frames, "fg_limit", s["fg_limit"], t("Frame limit"),
[("", t("Auto")), ("30", "30"), ("40", "40"), ("60", "60"), ("0", t("No limit"))],
small=t("Auto follows your PC"), width=10,
tip=t("Auto: the limit follows what your PC holds, so frames come evenly. A number holds the "
"frames shown to it; No limit leaves them free."))
self.toggle(frames, "smooth_motion", "Smooth Motion", "RTX 40 / 50",
t("NVIDIA's driver doubles the frames shown (RTX 40 and 50). A trial."))
# Without an NVIDIA card: DLSS's frame generation and Smooth Motion greyed, the same note as Picture's.
self.nvidia_fg_note = self.rule_note(frames)
# With ray tracing (the control's, the F1 menu's or Advanced's), what play-nvidia.ps1 does with frame
# generation (settings_rules): off on the Series X profile under 20 GB of video memory (unless
# LEONIDA_FG_WITH_RT=1) or with LEONIDA_FG_WITH_RT=0, otherwise only when a multiplier is asked for.
self.fg_note = self.rule_note(frames)
self.card_end(frames)
rays = self.card(inner, 2, 0, t("Ray tracing"), t("Off by default"))
self.segmented(rays, "rt", "hw" if s["hardware_rt"] else "off", t("Ray tracing"),
[("off", t("Off")), ("hw", t("Hardware"))],
tip=t("On the card's ray-tracing cores (-HardwareRT). Needs a card that has them."))
self.rt_note = self.rule_note(rays)
self.card_end(rays)
shaders = self.card(inner, 2, 1, t("Shaders"), t("Compile before the game instead of while playing"))
self.toggle(shaders, "precompile", t("Prepare shaders before starting"),
tip=t("Compiles what the game needs first, so it stutters less. Off: -NoPrecompile."))
self.toggle(shaders, "precompile_all", t("Precompile every pipeline"), t("40-60 min the first time"),
t("Every pipeline, once: very long the first time. Needs Prepare shaders, which it turns on."))
tip = tk.Frame(shaders, bg=TIP_BG, highlightthickness=1, highlightbackground=TIP_LINE)
tip.grid(row=shaders.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(8), px(16)))
shaders.next_row += 1
tip_text = tk.Text(tip, bg=TIP_BG, fg=TIP_TEXT, relief="flat", wrap="word", height=3,
font=("Segoe UI", 8), highlightthickness=0, padx=px(8), pady=px(8), cursor="arrow")
tip_text.tag_configure("b", foreground=WARN, font=("Segoe UI Semibold", 8))
tip_text.insert("end", "NVIDIA: ", "b")
tip_text.insert("end", t("set Shader Cache Size to Unlimited (Control Panel \u203a Manage 3D settings "
"\u203a Global), or part of it is compiled again in game."))
tip_text.configure(state="disabled")
tip_text.pack(fill="x")
Tip([tip_text], t(NVIDIA_CACHE_NOTE), self.k)
# -PrecompileAll is only passed with the shader preparation on (switch_args): turning it on turns that
# on too, and turning the preparation off turns it off, so the two never say what does not run.
def precompile_all_changed(*_):
if self.vars["precompile_all"].get():
self.vars["precompile"].set(True)
messagebox.showinfo(t("Precompile every pipeline"), t(NVIDIA_CACHE_NOTE))
self.vars["precompile_all"].trace_add("write", precompile_all_changed)
self.vars["precompile"].trace_add(
"write", lambda *_: self.vars["precompile"].get() or self.vars["precompile_all"].set(False))
for key in ("rt", "dlss", "dlss_mode", "fg_mode", "frame_gen", "precompile_all", "precompile", "aspect",
"profile"):
self.vars[key].trace_add("write", lambda *_: self.apply_rules())
diag = self.card(inner, 3, 0, t("General, diagnostics & advanced"),
t("For bug reports; nothing here changes how the game looks"), wide=True)
detected = LANGUAGE_NAMES[pick_language("", system_language())]
self.select(diag, "language", s["language"], t("Language"),
[("", t("Auto ({language})", language=detected))] + list(LANGUAGE_NAMES.items()),
tip=t("The launcher's language. Automatic follows Windows."), buttons=True)
# -Adapter (play-nvidia.ps1, LEONIDA_ADAPTER): the cards Windows has drivers for, by name.
self.select(diag, "adapter", s["adapter"], t("Graphics card"),
adapter_options(display_adapters(), s["adapter"]), small=t("On a PC with more than one"),
width=30, tip=t("The card the game runs on (-Adapter). Default: Windows' own choice."))
# The card chosen there is the one DLSS, Smooth Motion and the card notes are judged by; frame generation
# with ray tracing is not: the script's 20 GB rule reads the largest card of the registry (card_facts).
self.vars["adapter"].trace_add("write", lambda *_: self.apply_rules())
self.toggle(diag, "log", t("Log to a file"), tip=t("Writes the game's output to the logs folder (-Log)."))
self.toggle(diag, "dred", t("Crash tracing (DRED)"), t("Names what the GPU was doing when it stopped"),
t("When the graphics card stops the game, the log says what it was doing."))
self.toggle(diag, "capture", t("Capture"), t("F9 saves a frame (-Capture)"))
line = tk.Frame(diag, bg=PANEL)
line.grid(row=diag.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(12), 0))
diag.next_row += 1
tk.Label(line, text=t("Advanced options"), bg=PANEL, fg=TEXT, font=("Segoe UI", 10),
padx=0).pack(side="left")
tk.Label(line, text=t("(what -More passes, no PowerShell needed)"), bg=PANEL, fg=MUTED,
font=("Segoe UI", 8)).pack(side="left", padx=(px(4), 0))
# Every variable of d3d12/docs/switches.md in a second window, written into the same field.
self.advanced_button = ttk.Button(line, text=t("Advanced mode…"), command=self.open_advanced)
self.advanced_button.pack(side="right")
self.vars["advanced"] = tk.StringVar(value=s["advanced"])
field = tk.Entry(diag, textvariable=self.vars["advanced"], bg=FIELD, fg=MUTED, insertbackground=TEXT,
relief="flat", font=("Consolas", 9), highlightthickness=1, highlightbackground=LINE,
highlightcolor=EDGE)
field.grid(row=diag.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(8), px(4)),
ipady=px(6))
diag.next_row += 1
Tip([field, line], t("LEONIDA_* variables for the runtime, as NAME=value separated by ;. Only when "
"someone asks you to."), self.k)
self.advanced_check = tk.StringVar()
tk.Label(diag, textvariable=self.advanced_check, bg=PANEL, fg=DANGER, anchor="w", justify="left",
wraplength=px(700), padx=0).grid(row=diag.next_row, column=0, columnspan=2, sticky="w",
padx=px(16), pady=(0, px(12)))
diag.next_row += 1
self.vars["advanced"].trace_add("write", lambda *_: self.check_advanced())
# LEONIDA_FG_WITH_RT=1 there lifts the greying of frame generation under ray tracing, =0 brings it, as typed.
self.vars["advanced"].trace_add("write", lambda *_: self.apply_rules())
# Not in the mockup, but the launcher needs them: where the game, its data and the mods are.
game = self.card(inner, 4, 0, t("Game folders"), wide=True)
self.folder(game, "game_dir", t("Game folder"),
t("The folder of your own copy, the one with {exe}.", exe=EXPECTED_EXE))
self.game_check = tk.StringVar()
self.game_check_label = tk.Label(game, textvariable=self.game_check, bg=PANEL, fg=OK, anchor="w",
font=("Segoe UI", 8), padx=0)
self.game_check_label.grid(row=game.next_row, column=0, columnspan=2, sticky="w", padx=px(16))
game.next_row += 1
self.vars["game_dir"].trace_add("write", lambda *_: self.check_game())
self.folder(game, "data_dir", t("Data folder"),
t("Shader caches and saves. Empty: the default (%LOCALAPPDATA%\\Leonida\\d3d12)."))
self.folder(game, "mods_dir", t("Mods folder"), t("Empty: the mods folder of this repository."))
self.card_end(game)
if not WINDOWS:
ttk.Label(inner, text=t("On Linux the launcher starts scripts/play-linux.sh, which takes the game "
"folder and the Series X profile; the other options are for Windows."),
style="Muted.TLabel", wraplength=px(720)).grid(row=5, column=0, columnspan=2, sticky="w",
padx=px(24))
actions = tk.Frame(inner, bg=BG)
actions.grid(row=6, column=0, columnspan=2, sticky="ew", padx=px(24), pady=(px(4), 0))
PrimaryButton(actions, t("Save"), self.save, self.k).pack(side="left")
ttk.Button(actions, text=t("Copy my info"), command=self.copy_info).pack(side="left", padx=(px(8), 0))
ttk.Button(actions, text=t("Run in diagnostic mode"), command=self.play_diagnostic).pack(
side="left", padx=(px(8), 0))
self.saved_var = tk.StringVar()
tk.Label(actions, textvariable=self.saved_var, bg=BG, fg=MUTED, font=("Segoe UI", 8)).pack(side="right")
legend = tk.Label(inner, text=t("Copy my info copies the Mandy commit, GPU, driver and options for a bug "
"report. Run in diagnostic mode starts with the log and crash tracing "
"on, then opens the logs folder."),
bg=BG, fg=MUTED, font=("Segoe UI", 8), anchor="w", justify="left", wraplength=px(700),
padx=0)
legend.grid(row=7, column=0, columnspan=2, sticky="ew", padx=px(24), pady=(px(12), px(24)))
legend.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(200), e.width - 4)))
self.check_game()
self.check_advanced()
self.apply_rules()
self.render_menu_notes(self.menu_shown or {})
def set_enabled(self, key, flag):
control = self.controls.get(key)
if control is None:
return
if isinstance(control, ttk.Combobox):
control.state(["!disabled"] if flag else ["disabled"])
else:
control.enabled(flag)
def rule_note(self, card):
"""A short line under a card's last option for settings_rules' notes, hidden until apply_rules fills it."""
px = self.px
note = tk.Label(card, text="", bg=PANEL, fg=MUTED, anchor="w", justify="left", font=("Segoe UI", 8),
wraplength=px(300), padx=0)
note.grid(row=card.next_row, column=0, columnspan=2, sticky="ew", padx=px(16))
note.bind("<Configure>", lambda e: e.widget.configure(wraplength=max(px(160), e.width - 4)))
note.grid_remove()
card.next_row += 1
return note
def card_now(self):
"""card_facts of the card chosen in the Graphics card list (Default: this PC's cards; "vram" is always the
largest of the registry, as play-nvidia.ps1 reads it), from the registry read once per window
(read_entries)."""
if getattr(self, "card_read", None) is None:
self.card_read = read_entries()
adapter = ""
if "adapter" in self.vars:
adapter = self.choices.get("adapter", {}).get(self.vars["adapter"].get(), "")
return card_facts(self.card_read, adapter)
def apply_rules(self):
"""Greys what the other choices or the card make pointless (settings_rules), from the controls' values:
only the controls change, never a value, so turning the other choice back brings the earlier one back.
- ray tracing as the next PLAY's script will have it (launch_values: the control, then the F1 menu's file
for what was not changed since the last PLAY, then Advanced; a note says when it is not the control's):
frame generation's mode, multiplier and limit on the Series X profile (the one the next PLAY runs) with
under 20 GB of video memory (the largest card's, as the script reads it), unless LEONIDA_FG_WITH_RT=1,
and everywhere with LEONIDA_FG_WITH_RT=0 (play-nvidia.ps1 leaves it off there); otherwise live, with a
note when no multiplier is asked for (the script's automatic 2x never comes with ray tracing);
- no NVIDIA card (the chosen one, or none read on this PC): DLSS, its mode, DLSS frame generation (the
mode's button and the multiplier) and Smooth Motion; FSR stays;
- DLSS off: the DLSS mode; DLSS with a mode: the resolution (switch_args leaves it out);
- frame generation off: its limit; frame generation off or FSR: the multiplier (switch_args passes
-FrameGen with DLSS's only);
- the default window shape: how the picture fills the window (-PresentScale goes with -Aspect only);
- every pipeline precompiled: shader preparation stays on (it needs it)."""
v = getattr(self, "vars", {})
if "rt" not in v or "precompile_all" not in v:
return
values = {"rt": v["rt"].get(), "dlss": bool(v["dlss"].get()),
"dlss_mode": self.choices.get("dlss_mode", {}).get(v["dlss_mode"].get(), ""),
"fg_mode": v["fg_mode"].get(),
"aspect": self.choices.get("aspect", {}).get(v["aspect"].get(), "") if "aspect" in v else "",
"precompile_all": bool(v["precompile_all"].get())}
menu = self.menu_shown if getattr(self, "menu_shown", None) is not None else read_menu_settings(REPO)
card = self.card_now()
enabled, notes = settings_rules(values, card, launch_values(self.settings_now(), menu))
for key, flag in enabled.items():
if key == "fg_dlss":
control = self.controls.get("fg_mode")
if control is not None:
control.option_enabled("dlss", flag)
elif key != "present_scale" or "aspect" in v:
self.set_enabled(key, flag)
# Without an NVIDIA card PLAY passes DLSS and Smooth Motion off (for_card): their switches show it.
for key in ("dlss", "smooth_motion"):
control = self.controls.get(key)
if control is not None and hasattr(control, "show_off"):
control.show_off(not card.get("nvidia", True))
self.refresh_options()
fg = notes["fg"]
shown = [(getattr(self, "fg_note", None), fg[0] if fg else None, WARN if fg and fg[1] else MUTED),
(getattr(self, "nvidia_note", None), notes["nvidia"], MUTED),
(getattr(self, "nvidia_fg_note", None), notes["nvidia"], MUTED),
(getattr(self, "rt_note", None), notes["rt"], MUTED)]
for label, text, colour in shown:
if label is None:
continue
if text:
label.configure(text=text, fg=colour)
label.grid()
else:
label.grid_remove()
def browse(self, var):
chosen = filedialog.askdirectory(initialdir=var.get() or os.path.expanduser("~"))
if chosen:
var.set(os.path.normpath(chosen))
def check_game(self):
folder = self.vars["game_dir"].get().strip()
if not folder:
self.game_check.set("")
elif game_exe_present(folder):
self.game_check.set(t("Found {exe}", exe=EXPECTED_EXE))
self.game_check_label.configure(fg=OK)
else:
self.game_check.set(t("{exe} is not in this folder", exe=EXPECTED_EXE))
self.game_check_label.configure(fg=DANGER)
def open_advanced(self):
"""The Advanced mode window; a second click brings the open one to the front instead of a second."""
window = getattr(self, "advanced_window", None)
if window is not None:
try:
if window.win.winfo_exists():
window.win.deiconify()
window.win.lift()
window.win.focus_force()
return window
except tk.TclError:
pass
self.advanced_window = AdvancedWindow(self)
return self.advanced_window
def check_advanced(self):
wrong = parse_advanced(self.vars["advanced"].get())[1]
self.advanced_check.set(t("Not passed (not NAME=value with a LEONIDA_ name): {parts}",
parts="; ".join(wrong)) if wrong else "")
def settings_now(self):
"""The launcher's settings with the controls' values as they are now (what Save keeps), self.settings left
as it is: what the rules judge the next PLAY by."""
settings = dict(self.settings)
for key, var in self.vars.items():
value = var.get()
if key in self.choices:
value = self.choices[key].get(value, "")
if key == "profile":
settings["series_s"] = value == "s"
if value == "s":
settings["series_x"] = False
if not WINDOWS:
settings["series_x"] = value == "x"
elif key == "fg_mode":
settings["no_frame_gen"] = value == "off"
settings["fsr_frame_gen"] = value == "fsr"
elif key == "frame_gen":
settings["frame_gen"] = int(value) if value.isdigit() else 0
elif key == "rt":
# Software ray tracing is no longer offered: a choice saved by an older launcher is dropped.
settings["hardware_rt"] = value == "hw"
settings["ray_tracing"] = False
else:
settings[key] = value.strip() if isinstance(value, str) else value
return normalise(settings)
def collect_settings(self):
self.settings = self.settings_now()
def save(self):
self.collect_settings()
try:
save_settings(self.settings)
self.saved_var.set(t("Saved to {path}", path="%APPDATA%\\Leonida\\launcher.json" if WINDOWS
else config_path()))
except OSError as exc:
self.saved_var.set(t("Could not save: {error}", error=exc))
self.refresh_hint()
if self.settings["language"] != self.language_shown:
if self.process is None:
STRINGS.clear()
STRINGS.update(load_strings(pick_language(self.settings["language"], system_language())))
self.build_all("Settings")
else:
messagebox.showinfo(t("Language"), t("The new language shows at the next start of the launcher."))
# ---- Mods
def build_mods(self):
px = self.px
page = self.pages["Mods"]
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight=1)
inner = ttk.Frame(page, padding=(px(28), px(22)))
inner.grid(row=0, column=0, sticky="nsew")
inner.columnconfigure(0, weight=1)
inner.rowconfigure(2, weight=1)
ttk.Label(inner, text=t("Mods"), font=("Segoe UI Semibold", 20)).grid(row=0, column=0, sticky="w")
self.mods_note = tk.StringVar()
ttk.Label(inner, textvariable=self.mods_note, style="Muted.TLabel").grid(row=1, column=0, sticky="w",
pady=(px(4), px(16)))
self.tree = ttk.Treeview(inner, columns=("on", "folder", "name", "swaps"), show="headings",
selectmode="browse")
for column, title, width in (("on", t("Enabled"), 88), ("folder", t("Folder"), 200),
("name", t("Name"), 300), ("swaps", t("Swaps"), 120)):
self.tree.heading(column, text=title, anchor="w")
self.tree.column(column, width=px(width), anchor="w")
self.tree.grid(row=2, column=0, sticky="nsew")
self.tree.bind("<Double-1>", lambda _e: self.toggle_mod())
row = ttk.Frame(inner)
row.grid(row=3, column=0, sticky="w", pady=(px(16), 0))
for text, command in ((t("Enable / disable"), self.toggle_mod), (t("Refresh"), self.refresh_mods),
(t("Open the mod manager"), self.open_mod_manager)):
ttk.Button(row, text=text, command=command).pack(side="left", padx=(0, px(8)))
self.mod_paths: dict = {}
def refresh_mods(self):
mods_dir = mods_dir_of(self.settings)
self.tree.delete(*self.tree.get_children())
self.mod_paths.clear()
try:
rows, errors = list_mods(mods_dir)
except Exception as exc: # a broken folder is shown, not raised
rows, errors = [], [str(exc)]
for index, mod in enumerate(rows):
self.tree.insert("", "end", iid=str(index), values=(t("yes") if mod["enabled"] else t("no"),
mod["folder"], mod["name"], mod["swaps"]))
self.mod_paths[str(index)] = (mod["path"], mod["enabled"])
note = t("{n} mod(s) in {folder}", n=len(rows), folder=mods_dir)
if errors:
note += "; " + t("{n} could not be read: {error}", n=len(errors), error=errors[0])
self.mods_note.set(note)
def toggle_mod(self):
selected = self.tree.selection()
if not selected:
return
path, enabled = self.mod_paths[selected[0]]
try:
set_mod_enabled(path, not enabled)
except Exception as exc:
messagebox.showerror(t("Mods"), str(exc))
self.refresh_mods()
def open_mod_manager(self):
command = [sys.executable, "-I", os.path.join(REPO, "tools", "leonida_mods.py"),
"--dir", mods_dir_of(self.settings), "gui"]
try:
subprocess.Popen(command, cwd=REPO)
except OSError as exc:
messagebox.showerror(t("Mods"), t("Could not open the mod manager: {error}", error=exc))
# ---- Saves
def build_saves(self):
px = self.px
self.saves = _saves_module()
page = self.pages["Saves"]
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight=1)
inner = ttk.Frame(page, padding=(px(28), px(22)))
inner.grid(row=0, column=0, sticky="nsew")
inner.columnconfigure(0, weight=1)
inner.rowconfigure(3, weight=1)
ttk.Label(inner, text=t("Saves"), font=("Segoe UI Semibold", 20)).grid(row=0, column=0, sticky="w")
self.saves_note = tk.StringVar()
ttk.Label(inner, textvariable=self.saves_note, style="Muted.TLabel", wraplength=px(800)).grid(
row=1, column=0, sticky="w", pady=(px(4), px(12)))
bar = ttk.Frame(inner)
bar.grid(row=2, column=0, sticky="ew", pady=(0, px(14)))
PrimaryButton(bar, t("Import saves ..."), self.save_import_saves, self.k).pack(side="left")
ttk.Label(bar, text=t("Saves from another PC or an older install: Import saves ..., or on the other PC "
"Back up all and import the ZIP here."), style="Muted.TLabel",
wraplength=px(600), justify="left").pack(side="left", padx=(px(14), 0))
self.stree = ttk.Treeview(inner, columns=("size", "modified", "version"), selectmode="browse")
self.stree.heading("#0", text=t("Container / blob"), anchor="w")
self.stree.column("#0", width=px(330))
for column, title, width in (("size", t("Size"), 90), ("modified", t("Modified"), 160),
("version", t("Version"), 70)):
self.stree.heading(column, text=title, anchor="w")
self.stree.column(column, width=px(width), anchor="w")
self.stree.grid(row=3, column=0, sticky="nsew")
self.stree.bind("<<TreeviewSelect>>", lambda _e: self.describe_selection())
self.save_info = tk.StringVar()
ttk.Label(inner, textvariable=self.save_info, style="Muted.TLabel", wraplength=px(800)).grid(
row=4, column=0, sticky="w", pady=(px(12), 0))
rows = (((t("Back up all"), self.save_backup_all), (t("Back up selected"), self.save_backup_one),
(t("Restore a backup ..."), self.save_restore), (t("Duplicate ..."), self.save_duplicate),
(t("Delete"), self.save_delete)),
((t("Export blob ..."), self.save_export), (t("Import blob ..."), self.save_import),
(t("View bytes"), self.save_view), (t("Backups folder"), self.save_open_backups),
(t("Refresh"), self.refresh_saves)))
for number, buttons in enumerate(rows):
row = ttk.Frame(inner)
row.grid(row=5 + number, column=0, sticky="w", pady=(px(12) if number == 0 else px(8), 0))
for text, command in buttons:
ttk.Button(row, text=text, command=command).pack(side="left", padx=(0, px(8)))
self.save_items: dict = {}
self.import_dialog = None
def saves_paths(self):
data = data_root(self.settings)
return data, self.saves.saves_root(data), self.saves.backups_dir(data)
def refresh_saves(self):
_data, root, _backups = self.saves_paths()
self.stree.delete(*self.stree.get_children())
self.save_items.clear()
containers = self.saves.scan(root)
for index, c in enumerate(containers):
iid = f"c{index}"
self.save_items[iid] = (c, None)
self.stree.insert("", "end", iid=iid, open=True, text=c.name or c.folder,
values=(self.fmt_size(c.size), self.fmt_time(c.modified),
f"v{c.version}" if c.version else c.problem))
for blob in c.blobs:
bid = f"{iid}b{blob.index}"
self.save_items[bid] = (c, blob)
self.stree.insert(iid, "end", iid=bid, text=blob.name,
values=(self.fmt_size(blob.size), self.fmt_time(blob.modified),
f"v{c.version}"))
self.saves_note.set(t("{n} container(s) in {folder}", n=len(containers), folder=root) if containers
else t("No saves found in {folder}. They appear after the game has saved once.",
folder=root))
self.save_info.set("")
@staticmethod
def fmt_size(n):
return f"{n / 1024:.1f} KB" if n >= 1024 else f"{n} B"
@staticmethod
def fmt_time(stamp):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp)) if stamp else ""
def selected(self, want_blob=False):
chosen = self.stree.selection()
if not chosen:
messagebox.showinfo(t("Saves"), t("Select a container or a blob first."))
return None
container, blob = self.save_items[chosen[0]]
if want_blob and blob is None:
messagebox.showinfo(t("Saves"), t("Select a blob (a row under a container)."))
return None
return container, blob
def describe_selection(self):
chosen = self.stree.selection()
if not chosen or chosen[0] not in self.save_items:
return
container, blob = self.save_items[chosen[0]]
if blob is None:
self.save_info.set(t("{name}: {n} blob(s), newest version v{version}, folder {folder}",
name=container.name, n=len(container.blobs), version=container.version,
folder=container.folder))
return
try:
with open(blob.path, "rb") as f:
self.save_info.set(self.saves.explain(self.saves.describe(f.read())))
except OSError as exc:
self.save_info.set(str(exc))
def guarded(self, action):
"""Runs a save action unless the game (or anything started here) is running."""
if self.process is not None or game_running():
messagebox.showwarning(t("Saves"), t("The game is running. Close it before changing saves."))
return
try:
action()
except (self.saves.SaveError, OSError) as exc:
messagebox.showerror(t("Saves"), str(exc))
self.refresh_saves()
def save_backup_all(self):
def go():
_d, root, backups = self.saves_paths()
messagebox.showinfo(t("Saves"), t("Backed up to {path}", path=self.saves.backup(root, backups)))
self.guarded(go)
def save_backup_one(self):
def go():
got = self.selected()
if got:
_d, root, backups = self.saves_paths()
messagebox.showinfo(t("Saves"), t("Backed up to {path}",
path=self.saves.backup(root, backups, [got[0]])))
self.guarded(go)
def save_restore(self):
def go():
_d, root, backups = self.saves_paths()
zip_path = filedialog.askopenfilename(title=t("Restore from a backup"),
initialdir=backups if os.path.isdir(backups) else None,
filetypes=[(t("Save backups"), "*.zip")])
if not zip_path:
return
names = sorted(self.saves.zip_containers(zip_path))
if not messagebox.askyesno(t("Restore"), t(
"Restore {n} container(s) from\n{path}?\n\nThe same containers now in your saves are "
"replaced. The current saves are backed up first.", n=len(names), path=zip_path)):
return
before = self.saves.restore(root, backups, zip_path)
messagebox.showinfo(t("Saves"), t("Restored.") + ("\n" + t("Previous state: {path}", path=before)
if before else ""))
self.guarded(go)
def save_dialog(self, title):
"""A small modal window over the launcher, in its colours."""
win = self.import_dialog = tk.Toplevel(self.root)
win.title(title)
win.configure(bg=BG)
win.transient(self.root)
win.resizable(False, False)
return win
def save_dialog_wait(self, win):
win.update_idletasks()
x = self.root.winfo_rootx() + max(0, (self.root.winfo_width() - win.winfo_reqwidth()) // 2)
y = self.root.winfo_rooty() + max(0, (self.root.winfo_height() - win.winfo_reqheight()) // 3)
win.geometry(f"+{x}+{y}")
win.grab_set()
win.bind("<Escape>", lambda _e: win.destroy())
self.root.wait_window(win)
self.import_dialog = None
def ask_import_source(self):
"""A ZIP or a folder: Windows' pickers choose one kind or the other, so the dialog asks which first."""
px, chosen = self.px, {}
win = self.save_dialog(t("Import saves"))
body = ttk.Frame(win, padding=(px(22), px(18)))
body.pack(fill="both", expand=True)
ttk.Label(body, text=t("Import saves from"), font=("Segoe UI Semibold", 13)).pack(anchor="w")
ttk.Label(body, text=t("A ZIP made by Back up all, a ZIP or a copy of a saves folder, or a whole old data "
"folder (the one that holds data\\7952987A\\saves). Only saves this runtime wrote."),
style="Muted.TLabel", wraplength=px(460), justify="left").pack(anchor="w", pady=(px(6), px(16)))
buttons = ttk.Frame(body)
buttons.pack(anchor="w")
def pick(kind):
win.grab_release()
if kind == "zip":
path = filedialog.askopenfilename(parent=win, title=t("Import saves from a ZIP"),
filetypes=[(t("ZIP files"), "*.zip"), (t("All files"), "*")])
else:
path = filedialog.askdirectory(parent=win, title=t("Import saves from a folder"), mustexist=True)
if path:
chosen["path"] = os.path.normpath(path)
win.destroy()
elif win.winfo_exists():
win.grab_set()
ttk.Button(buttons, text=t("A folder ..."), command=lambda: pick("folder")).pack(side="left")
ttk.Button(buttons, text=t("A ZIP file ..."), command=lambda: pick("zip")).pack(side="left",
padx=(px(8), 0))
ttk.Button(buttons, text=t("Cancel"), command=win.destroy).pack(side="left", padx=(px(8), 0))
self.save_dialog_wait(win)
return chosen.get("path", "")
def confirm_import(self, plan):
"""The containers found, what each does here, Import or Cancel."""
px, answer = self.px, {}
items = plan.items
win = self.save_dialog(t("Import saves"))
body = ttk.Frame(win, padding=(px(22), px(18)))
body.pack(fill="both", expand=True)
ttk.Label(body, text=t("Import {n} save(s)?", n=len(items)), font=("Segoe UI Semibold", 13)).pack(
anchor="w")
lines = [t("From {source}", source=plan.source),
t("Into {folder}", folder="; ".join(sorted({os.path.dirname(i.target) for i in items})))]
if plan.skipped:
lines.append(t("{n} other folder(s) skipped: no readable version, already in place, or an older "
"copy.", n=len(plan.skipped)))
if not all(i.from_source for i in items):
lines.append(t("The source does not name a configuration folder: they go to the one this PC has."))
ttk.Label(body, text="\n".join(lines), style="Muted.TLabel", wraplength=px(620), justify="left").pack(
anchor="w", pady=(px(6), px(12)))
tree = ttk.Treeview(body, columns=("version", "modified", "here"), selectmode="none",
height=min(max(len(items), 3), 10))
for column, title, width in (("#0", t("Save"), 250), ("version", t("Version"), 70),
("modified", t("Modified"), 160), ("here", t("On this PC"), 160)):
tree.heading(column, text=title, anchor="w")
tree.column(column, width=px(width), anchor="w")
for item in items:
c = item.container
tree.insert("", "end", text=c.display or c.name, values=(
f"v{c.version}", self.fmt_time(c.modified), t("replaced") if item.replaces else t("new")))
tree.pack(fill="both", expand=True)
replaced = sum(1 for i in items if i.replaces)
if replaced:
ttk.Label(body, text=t("{n} save(s) with the same folder are already on this PC and will be replaced. "
"All your current saves are backed up first.", n=replaced),
wraplength=px(620), justify="left").pack(anchor="w", pady=(px(12), 0))
buttons = ttk.Frame(body)
buttons.pack(anchor="w", pady=(px(16), 0))
def ok():
answer["ok"] = True
win.destroy()
PrimaryButton(buttons, t("Import"), ok, self.k).pack(side="left")
ttk.Button(buttons, text=t("Cancel"), command=win.destroy).pack(side="left", padx=(px(8), 0))
self.save_dialog_wait(win)
return bool(answer)
def save_import_saves(self):
def go():
source = self.ask_import_source()
if not source:
return
_d, root, backups = self.saves_paths()
try:
plan = self.saves.plan_import(root, source)
except self.saves.NeedsConfiguration as exc:
messagebox.showwarning(t("Import saves"), t(
"These saves do not say which configuration folder they belong to, and this PC has several. "
"Import the whole saves folder or the old data folder instead.") if exc.several else t(
"These saves do not say which configuration folder they belong to, and this PC has none yet. "
"Start the game once and let it save, then import again."))
return
try:
if not self.confirm_import(plan):
return
before = self.saves.apply_import(root, backups, plan)
finally:
self.saves.discard_import(plan)
messagebox.showinfo(t("Saves"), t("Imported {n} save(s).", n=len(plan.items))
+ ("\n" + t("Previous state: {path}", path=before) if before else ""))
self.guarded(go)
def save_duplicate(self):
def go():
got = self.selected()
if not got:
return
from tkinter import simpledialog
name = simpledialog.askstring(t("Duplicate"), t("Name of the copy (letters, digits, _ . -):"),
initialvalue=got[0].name + "_copy")
if name:
self.saves.duplicate(self.saves_paths()[1], got[0], name.strip())
self.guarded(go)
def save_delete(self):
def go():
got = self.selected()
if got and messagebox.askyesno(t("Delete"), t(
"Delete {name}?\n\nIt is moved to the backups folder (save-backups, deleted), not erased.",
name=got[0].name)):
messagebox.showinfo(t("Saves"), t("Moved to {path}",
path=self.saves.delete(got[0], self.saves_paths()[2])))
self.guarded(go)
def save_export(self):
def go():
got = self.selected(want_blob=True)
if got:
target = filedialog.asksaveasfilename(
initialfile=f"{got[0].name}-{got[1].name}.bin".replace(" ", "_"))
if target:
self.saves.export_blob(got[1], target)
self.guarded(go)
def save_import(self):
def go():
got = self.selected(want_blob=True)
if not got:
return
source = filedialog.askopenfilename(title=t("Blob file to import"))
if source and messagebox.askyesno(t("Import"), t(
"Replace '{blob}' of {name} with this file?\n\nThe container is backed up first and the "
"change is written as a new version. The header blob is not changed: a size that no longer "
"matches it can make the title reject the save.", blob=got[1].name, name=got[0].name)):
_d, root, backups = self.saves_paths()
number, _saved = self.saves.import_blob(root, backups, got[0], got[1], source)
messagebox.showinfo(t("Saves"), t("Written as v{n}.", n=number))
self.guarded(go)
def save_view(self):
got = self.selected(want_blob=True)
if not got:
return
try:
with open(got[1].path, "rb") as f:
data = f.read()
except OSError as exc:
messagebox.showerror(t("Saves"), str(exc))
return
window = tk.Toplevel(self.root)
window.title(t("{name} / {blob} (read only)", name=got[0].name, blob=got[1].name))
window.configure(bg=BG)
window.geometry(f"{self.px(820)}x{self.px(560)}")
ttk.Label(window, text=self.saves.explain(self.saves.describe(data)), wraplength=self.px(780),
style="Muted.TLabel", justify="left").pack(anchor="w", padx=self.px(16),
pady=(self.px(16), self.px(12)))
box = tk.Text(window, bg=FIELD, fg=TEXT, relief="flat", highlightthickness=1, highlightbackground=LINE,
highlightcolor=LINE, padx=self.px(12), pady=self.px(8), selectbackground=RAISED,
inactiveselectbackground=RAISED, font=("Consolas" if WINDOWS else "monospace", 9))
box.pack(fill="both", expand=True, padx=self.px(16), pady=(0, self.px(16)))
box.insert("end", self.saves.hexdump(data) + "\n\nStrings:\n" + "\n".join(self.saves.strings(data)))
box.configure(state="disabled")
def save_open_backups(self):
self.open(self.saves_paths()[2])
# ---- Controls
KBM_DEFAULTS = (("W A S D", "Move (left stick); in a vehicle W and S are RT and LT"),
("Mouse, left / right button", "Camera; shoot (RT) / aim (LT)"),
("Space / Left Ctrl / R / F", "Cross (jump) / Circle (crouch) / Square (reload, melee) / "
"Triangle (enter and leave a vehicle)"),
("E", "Triangle (interact); horn in a vehicle"),
("Q / Tab", "RB (cover) / LB (loadout wheel)"),
("Left Shift / C", "Run (L3) / look behind (R3)"),
("M / Esc", "Map (View) / pause (Menu)"),
("Arrows, Enter, Backspace", "Phone and menus (d-pad, Cross, Circle)"))
def build_controls(self):
"""The Controls page: the default keys in short, then the player's own binds as rows (scope, the key, the
pad input), written to settings["kbm_binds"] as LEONIDA_KBM_BINDS at every change and saved at once."""
px = self.px
page = self.pages["Controls"]
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight=1)
inner = self.scrolled(page)
inner.columnconfigure(0, weight=1)
head = tk.Frame(inner, bg=BG)
head.grid(row=0, column=0, sticky="ew", padx=px(24), pady=(px(24), px(16)))
tk.Label(head, text=t("Controls"), bg=BG, fg=TEXT, font=("Segoe UI Semibold", 16), anchor="w",
padx=0).pack(fill="x")
tk.Label(head, text=t("Your own keyboard and mouse binds, on top of the default keys; they apply at the "
"next PLAY"), bg=BG, fg=MUTED, font=("Segoe UI", 9), anchor="w",
padx=0).pack(fill="x")
defaults = self.card(inner, 1, 0, t("Default keys"),
t("The main ones; the full list is in docs/gameinput.md"), wide=True)
for keys, does in self.KBM_DEFAULTS:
row = tk.Frame(defaults, bg=PANEL)
row.grid(row=defaults.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(0, px(4)))
defaults.next_row += 1
tk.Label(row, text=keys, bg=PANEL, fg=TEXT, font=("Segoe UI", 9), width=26, anchor="w",
padx=0).pack(side="left")
tk.Label(row, text=t(does), bg=PANEL, fg=MUTED, font=("Segoe UI", 9), anchor="w",
padx=0).pack(side="left", fill="x", expand=True)
self.card_end(defaults)
mine = self.card(inner, 2, 0, t("Your binds"),
t("A bind replaces every default of its key there: R set to Nothing frees R. "
"F1, F3, F4, F8, F9, Alt and Caps Lock are the runtime's own."), wide=True)
self.kbm_note = tk.Label(mine, text="", bg=PANEL, fg=MUTED, anchor="w", justify="left",
font=("Segoe UI", 8), padx=0)
self.kbm_note.grid(row=mine.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(0, px(6)))
mine.next_row += 1
self.kbm_rows_frame = tk.Frame(mine, bg=PANEL)
self.kbm_rows_frame.grid(row=mine.next_row, column=0, columnspan=2, sticky="ew", padx=px(16))
self.kbm_rows_frame.columnconfigure(3, weight=1)
mine.next_row += 1
self.kbm_error = tk.Label(mine, text="", bg=PANEL, fg=DANGER, anchor="w", font=("Segoe UI", 8), padx=0)
self.kbm_error.grid(row=mine.next_row, column=0, columnspan=2, sticky="ew", padx=px(16), pady=(px(4), 0))
mine.next_row += 1
buttons = tk.Frame(mine, bg=PANEL)
buttons.grid(row=mine.next_row, column=0, columnspan=2, sticky="w", padx=px(16), pady=(px(10), 0))
mine.next_row += 1
PrimaryButton(buttons, t("Add bind"), self.kbm_add, self.k, bg=PANEL).pack(side="left")
ttk.Button(buttons, text=t("Reset to defaults"), command=self.kbm_reset).pack(side="left",
padx=(px(8), 0))
self.card_end(mine)
if "kbm_binds" not in self.vars:
self.vars["kbm_binds"] = tk.StringVar(value=self.settings.get("kbm_binds", ""))
rows, kept = split_kbm_binds(self.vars["kbm_binds"].get())
# Entries the page cannot read (typed by hand, or by a newer launcher) are kept as they are and shown;
# the rows around them stay editable, and saving writes them back after the rows.
self.kbm_raw = ";".join(kept) or None
self.kbm_rows = [list(r) for r in rows]
self.kbm_capturing = None
self.render_kbm()
def render_kbm(self):
px = self.px
frame = self.kbm_rows_frame
for child in frame.winfo_children():
child.destroy()
if self.kbm_raw is not None:
tk.Label(frame, text=t("Kept as saved (the page cannot read it): {entries}", entries=self.kbm_raw),
bg=PANEL, fg=WARN, font=("Segoe UI", 9), anchor="w", justify="left",
wraplength=px(560), padx=0).grid(row=0, column=0, columnspan=5, sticky="ew")
if self.kbm_raw is None and not self.kbm_rows:
tk.Label(frame, text=t("No binds of your own: the default keys."), bg=PANEL, fg=FAINT,
font=("Segoe UI", 9), anchor="w", padx=0).grid(row=0, column=0, columnspan=5, sticky="ew")
labels = [t(label) for _name, label in KBM_ACTIONS]
scopes = [("both", t("Both")), ("foot", t("On foot")), ("vehicle", t("In a vehicle"))]
for index, row in enumerate(self.kbm_rows):
scope = tk.StringVar(value=row[0])
scope.trace_add("write", lambda *_a, i=index, v=scope: self.kbm_set(i, 0, v.get()))
Segmented(frame, scope, scopes, self.k).grid(row=index + 1, column=0, sticky="w", pady=px(4))
key = ttk.Button(frame, text=row[1] or t("Choose a key"), width=14,
command=lambda i=index: self.kbm_capture(i))
key.grid(row=index + 1, column=1, sticky="w", padx=(px(12), 0), pady=px(4))
action = ttk.Combobox(frame, values=labels, state="readonly", width=24)
names = [n for n, _label in KBM_ACTIONS]
action.current(names.index(row[2]) if row[2] in names else 0)
action.bind("<<ComboboxSelected>>",
lambda _e, i=index, c=action: self.kbm_set(i, 2, KBM_ACTIONS[c.current()][0]))
action.grid(row=index + 1, column=2, sticky="w", padx=(px(12), 0), pady=px(4))
remove = tk.Label(frame, text="\u2715", bg=PANEL, fg=MUTED, font=("Segoe UI", 10), cursor="hand2",
padx=px(6))
remove.bind("<Button-1>", lambda _e, i=index: self.kbm_remove(i))
remove.bind("<Enter>", lambda e: e.widget.configure(fg=DANGER))
remove.bind("<Leave>", lambda e: e.widget.configure(fg=MUTED))
remove.grid(row=index + 1, column=3, sticky="w", padx=(px(8), 0))
Tip([remove], t("Remove this bind"), self.k)
row.append(key) # the key's button, for the capture
self.refresh_controls_note()
def kbm_store(self):
"""Writes the rows to kbm_binds and saves the settings (the page has no Save button)."""
self.vars["kbm_binds"].set(";".join(p for p in (kbm_binds_text(r[:3] for r in self.kbm_rows),
self.kbm_raw or "") if p))
self.collect_settings()
try:
save_settings(self.settings)
except OSError as exc:
self.kbm_error.configure(text=t("Could not save: {error}", error=exc))
self.refresh_hint()
self.refresh_controls_note()
def kbm_set(self, index, field, value):
self.kbm_rows[index][field] = value
self.kbm_store()
def kbm_add(self):
self.kbm_rows = [r[:3] for r in self.kbm_rows] + [["both", "", "Square"]]
self.render_kbm()
self.kbm_capture(len(self.kbm_rows) - 1)
def kbm_remove(self, index):
del self.kbm_rows[index]
self.kbm_rows = [r[:3] for r in self.kbm_rows]
self.render_kbm()
self.kbm_store()
def kbm_reset(self):
if (self.kbm_rows or self.kbm_raw) and not messagebox.askokcancel(
t("Reset to defaults"), t("Remove all your binds? The default keys stay.")):
return
self.kbm_raw, self.kbm_rows = None, []
self.render_kbm()
self.kbm_store()
def kbm_capture(self, index):
"""The key's button reads "Press a key…" and the next key or mouse button (left, right) pressed in the
window becomes the row's key; Esc cancels, a key of the runtime's own or one it cannot bind is refused."""
self.kbm_stop_capture()
button = self.kbm_rows[index][3] if len(self.kbm_rows[index]) > 3 else None
if button is None:
return
button.configure(text=t("Press a key\u2026"))
self.kbm_error.configure(text="")
self.kbm_capturing = index
# After this click's own release, so the click that started it is not taken as the left button.
self.root.after(150, lambda: self.kbm_listen(index))
def kbm_listen(self, index):
if self.kbm_capturing != index:
return
self.root.bind_all("<KeyPress>", lambda e: self.kbm_caught(e.keysym, 0), add=False)
self.root.bind_all("<ButtonPress-1>", lambda e: self.kbm_caught("", 1), add=False)
self.root.bind_all("<ButtonPress-3>", lambda e: self.kbm_caught("", 3), add=False)
def kbm_stop_capture(self):
self.kbm_capturing = None
for sequence in ("<KeyPress>", "<ButtonPress-1>", "<ButtonPress-3>"):
self.root.unbind_all(sequence)
def kbm_caught(self, keysym, button):
index = self.kbm_capturing
if index is None or index >= len(self.kbm_rows):
self.kbm_stop_capture()
return "break"
if keysym == "Escape" and not button and self.kbm_rows[index][1]:
self.kbm_stop_capture()
self.render_kbm()
return "break"
name = kbm_key_of_event(keysym, button)
if name is None or name in KBM_RESERVED:
self.kbm_error.configure(text=t("{key} cannot be bound: it is the runtime's own key or one it "
"cannot read. Press another.", key=name or keysym or "?"))
return "break"
self.kbm_stop_capture()
self.kbm_rows[index][1] = name
self.kbm_rows = [r[:3] for r in self.kbm_rows]
self.render_kbm()
self.kbm_store()
return "break"
def refresh_controls_note(self):
note = getattr(self, "kbm_note", None)
if note is None:
return
typed = "LEONIDA_KBM_BINDS" in parse_advanced(self.settings.get("advanced", ""))[0]
note.configure(text=t("LEONIDA_KBM_BINDS is also in Settings' advanced options: that one wins at PLAY.")
if typed else "", fg=WARN if typed else MUTED)
if typed:
note.grid()
else:
note.grid_remove()
# ---- Tools
def build_tools(self):
px = self.px
page = self.pages["Tools"]
inner = ttk.Frame(page, padding=(px(28), px(22)))
inner.grid(row=0, column=0, sticky="nsew")
ttk.Label(inner, text=t("Tools"), font=("Segoe UI Semibold", 20)).grid(row=0, column=0, columnspan=2,
sticky="w", pady=(0, px(16)))
items = ((t("Update Mandy"), t("git pull, then a rebuild if the runtime changed"), self.update),
(t("Fetch NVIDIA DLSS files"), t("Downloads about 70 MB from NVIDIA's GitHub, once"),
self.fetch_dlss),
(t("Rebuild the runtime"), t("d3d12\\scripts\\build-nvidia.ps1 (a few minutes)"), self.rebuild),
(t("Run in diagnostic mode"), t("PLAY with a log file and crash tracing, then the logs folder"),
self.play_diagnostic),
(t("Copy my info"), t("Your card, driver, Mandy version and options, to paste in a report"),
self.copy_info),
(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"),
lambda: self.open(logs_dir())),
(t("Open the screenshots folder"), t("The F4 menu's screenshots, else the F9 captures"),
self.open_screenshots))
for row, (title, note, command) in enumerate(items, start=1):
ttk.Button(inner, text=title, command=command).grid(row=row, column=0, sticky="ew", pady=(0, px(8)))
ttk.Label(inner, text=note, style="Muted.TLabel").grid(row=row, column=1, sticky="w", padx=(px(16), 0),
pady=(0, px(8)))
def fetch_dlss(self):
if not messagebox.askokcancel(t("Fetch NVIDIA DLSS files"), t(
"This downloads about 70 MB from NVIDIA's GitHub (DLSS and Streamline, under NVIDIA's own "
"licences).\n\nContinue?")):
return
self.run_tool("get_dlss", t("the DLSS download"), "Fetching the DLSS files")
def rebuild(self):
self.run_tool("build", t("the runtime build"), "Rebuilding the runtime")
def clear_cache(self):
"""Tools > Clear shader cache: what and how much, a confirmation, then clear_shader_cache."""
self.collect_settings()
if self.process is not None or game_running():
messagebox.showinfo(t("Clear shader cache"), t("Close the game first: its cache is in use."))
return
path = shader_cache_dir(self.settings)
if not os.path.isdir(path):
messagebox.showinfo(t("Clear shader cache"), t("The shader cache is already empty."))
return
if not messagebox.askokcancel(t("Clear shader cache"), t(
"This deletes {path} ({size}): the shaders and pipelines made so far. The next start makes them "
"again, which takes a while (longer with Precompile every pipeline).\n\nYour saves are not "
"touched.\n\nContinue?", path=path, size=size_text(folder_size(path))), icon="warning"):
return
# The game may have been started (here or elsewhere) while the dialog was open: asked again now.
done, message = clear_shader_cache(self.settings,
running=lambda: self.process is not None or game_running())
(messagebox.showinfo if done else messagebox.showwarning)(t("Clear shader cache"), message)
def run_tool(self, name, what, state):
try:
command = tool_command(name)
except ValueError as exc:
messagebox.showinfo(t("Tools"), str(exc))
return
self.show("Play")
self.run(command, "tool", what, state)
def open(self, path):
try:
open_folder(path)
except OSError as exc:
messagebox.showerror("Mandy", t("Could not open {path}: {error}", path=path, error=exc))
def open_screenshots(self):
shots = [d for d in screenshot_dirs() if os.path.isdir(d)]
self.open(shots[0] if shots else screenshot_dirs()[-1])
# ---- About
def build_about(self):
px = self.px
page = self.pages["About"]
inner = ttk.Frame(page, padding=(px(28), px(22)))
inner.grid(row=0, column=0, sticky="nsew")
ttk.Label(inner, text=t("About"), font=("Segoe UI Semibold", 20)).pack(anchor="w")
ttk.Label(inner, text=t(ABOUT), wraplength=px(700), justify="left").pack(anchor="w", pady=(px(16), 0))
# The credits as secondary text; each " - " line is a list item whose wrapped lines keep its indent.
credits = ttk.Frame(inner)
credits.pack(anchor="w", pady=(px(16), 0))
row, gap = 0, False
for line in CREDITS.split("\n"):
if not line:
gap = True
continue
top = px(12) if gap else 0
if line.startswith(" - "):
ttk.Label(credits, text="–", style="Muted.TLabel").grid(row=row, column=0, sticky="nw",
padx=(px(8), px(8)), pady=(top, 0))
ttk.Label(credits, text=line[4:], wraplength=px(670), justify="left",
style="Muted.TLabel").grid(row=row, column=1, sticky="w", pady=(top, 0))
else:
ttk.Label(credits, text=line, wraplength=px(700), justify="left", style="Muted.TLabel").grid(
row=row, column=0, columnspan=2, sticky="w", pady=(top, 0))
row, gap = row + 1, False
enable_dpi_awareness()
settings = load_settings()
STRINGS.clear()
STRINGS.update(load_strings(pick_language(settings["language"], system_language())))
root = tk.Tk()
try:
Launcher(root, settings)
except Exception:
# The window could not be built: say why in a dialog too, since Launcher.bat's console may be hidden.
text = traceback.format_exc()
print(text, file=sys.stderr)
try:
messagebox.showerror("Mandy Launcher", "The launcher could not open its window:\n\n" + text[-1500:])
except tk.TclError:
pass
return 1
root.mainloop()
return 0
def main() -> int:
if len(sys.argv) >= 2 and sys.argv[1] == "--update":
rest = sys.argv[2:]
paths = [a for a in rest if a != "--install-git"]
def ask() -> bool:
"""A console asks before installing Git; the launcher's window passes --install-git instead."""
if sys.stdin is None or not sys.stdin.isatty():
return False
try:
answer = input("Git is needed and not installed. Install it now with winget? [y/N] ")
except EOFError:
return False
return answer.strip().lower() in ("y", "yes", "o", "oui")
return run_update(paths[0] if paths else REPO, install="--install-git" in rest, ask=ask)
return run_gui()
if __name__ == "__main__":
sys.stdout.reconfigure(errors="replace")
raise SystemExit(main())