diff --git a/Launcher.bat b/Launcher.bat index d388853130..fe7de48932 100644 --- a/Launcher.bat +++ b/Launcher.bat @@ -1,26 +1,139 @@ @echo off -title Leonida - Launcher rem Double-click to open the launcher window: play, settings, mods, tools. It never touches the game package. +rem cmd reads a batch file line by line from the byte where it stopped: when the launcher's Update replaces this +rem file while it runs, cmd goes on at that byte of the new file. The :: lines below (labels: cmd skips them, from +rem any byte) cover where the older Launcher.bat stopped (byte 749), and lead to a clean exit. Keep them. +goto :start +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +exit /b +:start +title Leonida - Launcher +rem It needs Python 3.12 or newer with Tcl/Tk (the window). Without one it offers to install Python 3.12 for this +rem user (no admin), as Build.bat does. LEONIDA_PY_INSTALL_DRYRUN=1 prints the install commands and skips them. setlocal cd /d "%~dp0" -set "PY=" -for %%V in (3.14 3.13 3.12 3) do ( - if not defined PY ( - py -%%V -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=py -%%V" - ) -) -if not defined PY ( - where python >nul 2>nul && ( - python -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul && set "PY=python" +set "PY_EXE=" +set "PY_ARG=" +set "PY_NOTK=" +call :find_python +if not defined PY_EXE call :find_user_python +if not defined PY_EXE call :offer_python +if not defined PY_EXE ( + echo. + if defined PY_NOTK ( + echo Python was found, but without Tcl/Tk, which the launcher's window needs. + echo Install Python 3.12 or newer from https://www.python.org/downloads/ with "tcl/tk and IDLE" ticked + echo ^(Customize installation^), or run its installer again and choose Modify to add it. + ) else ( + echo Python 3.12 or newer is needed: https://www.python.org/downloads/ + echo Tick "Add python.exe to PATH" during setup. ) -) -if not defined PY ( - echo Python 3.12 or newer is needed: https://www.python.org/downloads/ - echo Tick "Add python.exe to PATH" during setup. - pause + if not defined LEONIDA_NO_PAUSE pause exit /b 1 ) -%PY% -I "%~dp0tools\leonida_launcher.py" %* -set "RC=%ERRORLEVEL%" -if not "%RC%"=="0" pause -exit /b %RC% +rem One line, read whole before the launcher runs: an update that replaces this file cannot change what follows, +rem the error path included (its code, git's or the build's with --update, goes back to the caller). +"%PY_EXE%" %PY_ARG% -I "%~dp0tools\leonida_launcher.py" %* && exit /b 0 || (call set "RC=%%errorlevel%%" & setlocal EnableDelayedExpansion & echo. & echo The launcher stopped with code !RC!. Read the message above. & (if not defined LEONIDA_NO_PAUSE pause) & exit /b !RC!) + +rem ---- Helpers (only reached by "call"; the script exits above) ---- + + +rem The py launcher's versions, newest first, then python on PATH: the first that is 3.12 or newer and has Tk. +:find_python +for %%V in (3.14 3.13 3.12 3) do call :try_py %%V +if defined PY_EXE exit /b 0 +where python >nul 2>nul || exit /b 0 +call :try_python python +exit /b 0 + +:try_py +if defined PY_EXE exit /b 0 +py -%1 -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul || exit /b 0 +py -%1 -c "import tkinter; tkinter.Tcl()" >nul 2>nul || (set "PY_NOTK=1" & exit /b 0) +set "PY_EXE=py" +set "PY_ARG=-%1" +exit /b 0 + +rem Each per-user install under %LOCALAPPDATA%\Programs\Python (python.org or winget with "Add to PATH" unticked), +rem highest folder name first; each one is checked, so the name order does not matter. +:find_user_python +for /f "delims=" %%D in ('dir /b /ad /o-n "%LOCALAPPDATA%\Programs\Python\Python3*" 2^>nul') do call :try_python "%LOCALAPPDATA%\Programs\Python\%%D\python.exe" +exit /b 0 + +:try_python +if defined PY_EXE exit /b 0 +if /i not "%~1"=="python" if not exist "%~1" exit /b 0 +"%~1" -c "import sys; sys.exit(0 if sys.version_info >= (3, 12) else 1)" >nul 2>nul || exit /b 0 +"%~1" -c "import tkinter; tkinter.Tcl()" >nul 2>nul || (set "PY_NOTK=1" & exit /b 0) +set "PY_EXE=%~1" +set "PY_ARG=" +exit /b 0 + +rem Ask first, then install Python 3.12 (with Tcl/Tk) for this user only: winget if present, else the pinned +rem python.org installer checked against its SHA-256 (the same one Build.bat uses). On "No" or any failure PY_EXE +rem stays unset and the caller prints the manual instructions. +:offer_python +echo. +if defined PY_NOTK ( + echo Python was found without Tcl/Tk, which the launcher's window needs. +) else ( + echo Python 3.12 or newer was not found, and the launcher needs it. +) +choice /c YN /n /t 60 /d N /m "Download and install Python 3.12 with Tcl/Tk for your user account now? (No admin needed) [Y/N] " +if errorlevel 2 exit /b 0 +if not errorlevel 1 exit /b 0 +where winget >nul 2>nul && goto :py_winget +:py_download +set "PYURL=https://www.python.org/ftp/python/3.12.10/python-3.12.10-amd64.exe" +set "PYSHA=67B5635E80EA51072B87941312D00EC8927C4DB9BA18938F7AD2D27B328B95FB" +set "PYTMP=%TEMP%" +if not defined PYTMP set "PYTMP=%LOCALAPPDATA%\Temp" +if not defined PYTMP set "PYTMP=%~dp0" +set "PYEXE=%PYTMP%\leonida-python-3.12.10-amd64.exe" +if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_download +echo Downloading Python 3.12.10 from python.org ... +powershell -NoProfile -Command "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12; Invoke-WebRequest -UseBasicParsing -Uri $env:PYURL -OutFile $env:PYEXE; if ((Get-FileHash -Algorithm SHA256 -LiteralPath $env:PYEXE).Hash -ine $env:PYSHA) { Remove-Item -LiteralPath $env:PYEXE -Force; exit 3 }" +if errorlevel 1 goto :py_download_failed +echo Installing Python 3.12.10 ... +start "" /wait "%PYEXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 Include_tcltk=1 +del /q "%PYEXE%" >nul 2>nul +goto :py_installed + +:py_download_failed +echo The download failed or did not match its checksum, so it was not run. +del /q "%PYEXE%" >nul 2>nul +exit /b 0 + +:py_dry_download +echo [dry run] would download %PYURL% +echo [dry run] would check SHA-256 %PYSHA% +echo [dry run] would run "%PYEXE%" /quiet InstallAllUsers=0 PrependPath=1 Include_launcher=1 Include_tcltk=1 +exit /b 0 + +:py_winget +set "PYWG=winget install --id Python.Python.3.12 -e --scope user --silent --accept-package-agreements --accept-source-agreements" +if defined LEONIDA_PY_INSTALL_DRYRUN goto :py_dry_winget +echo Installing Python 3.12 with winget ... +call %PYWG% +call :find_user_python +if defined PY_EXE exit /b 0 +echo winget did not install a Python with Tcl/Tk; trying the python.org installer instead. +goto :py_download + +:py_dry_winget +echo [dry run] would run %PYWG% +goto :py_download + +:py_installed +call :find_user_python +exit /b 0 diff --git a/docs/launcher.md b/docs/launcher.md index c19de41997..4c6e2bb128 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -1,55 +1,218 @@ -# The Leonida Launcher +# The Mandy Launcher -A desktop window for the port, in the usual shape of a game launcher: a narrow navigation column on the left, a hero -area with a big PLAY button, a status line and pages. It is Leonida's own design: no other company's name, logo, font -or artwork, and no game assets in the repository. The hero shows the newest screenshot you have taken (read at run -time from the runtime's `screenshots` folder next to `leonida.exe`, else `%LOCALAPPDATA%\Leonida\captures`), or a -generated gradient. It is not an official product. +The Python launcher has the Mandy name and the layout of the launcher mockup, its indigo taken toward a neutral night: +violet and pink only on the PLAY pill, the rail's mark and the switches that are on; Mandy in the rail with the +update state (the same coloured dot as the Updates card), commit, card and driver under it; and cards on every page. The folders it +reads and writes keep the Leonida names (`%APPDATA%\Leonida`, `%LOCALAPPDATA%\Leonida`), so no setting, cache or +save moves. + +A desktop window for the port, in the usual shape of a game launcher: a narrow navigation column on the left and +pages of cards. It is Leonida's own design: no other company's name, logo, font or artwork, no picture files, and no +game assets in the repository. It is not an official product. ## Starting it -- Windows: double-click `Launcher.bat` at the repository root (it finds Python 3.12 or newer, like `Mods.bat`). +- Windows: double-click `Launcher.bat` at the repository root. It looks for Python 3.12 or newer **with Tcl/Tk** + (the window needs it): the `py` launcher's versions, `python` on PATH, then the per-user installs under + `%LOCALAPPDATA%\Programs\Python`. Without one it asks, then installs Python 3.12 for your user account only (no + admin): winget if present, else the python.org installer pinned and checked against its SHA-256, the same one + `Build.bat` uses, with Tcl/Tk. `LEONIDA_PY_INSTALL_DRYRUN=1` prints those commands and runs nothing. - Linux: `python3 tools/leonida_launcher.py` (needs Tkinter: the `python3-tk` package). -Standard library only (`tools/leonida_launcher.py`). +Standard library only (`tools/leonida_launcher.py`). The window tells Windows it draws at the screen's own scale, so +its text is sharp at 125-200 %; sizes in pixels follow that scale. Nothing slow runs on the window's thread before +it first draws (no picture is read at all; git and the card's name are read by workers), so it cannot open white. +An error in a button's code is written into the output box instead of being lost. + +## Languages + +English, French, Spanish, Portuguese and German. The launcher follows Windows' display language +(`GetUserDefaultUILanguage`; on Linux the `LANG`-style variables) and falls back to English; **Language** in +Settings overrides it. The translations are `tools/launcher_i18n/.json`, each mapping the English text in +`tools/leonida_launcher.py` to its translation: a text without one shows in English. A new text in the launcher +needs its line in every file, which `tests/test_leonida_launcher.py` checks (same keys, same `{fields}`). ## Pages -- **Play**: PLAY runs `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game - -Data ` plus the switches chosen in Settings (on Linux `scripts/play-linux.sh /game_scarlett_master.exe`, - with `--series-x` if chosen). The script's output goes into the log box. The state line reads a few of the script's - own messages: Starting, Building the runtime, Preparing shaders, Running, Exited with code N (a guess from the text; - the log is the truth). Only one thing runs at a time: while it runs PLAY is replaced by Stop, which, after a - confirmation, ends the process and everything it started (`taskkill /T /F`; on Linux the process group). -- **Settings**: the game folder (a picker, and a check that `game_scarlett_master.exe` is in it), the data folder - (empty = the script's default), the mods folder, and the options of `play-d3d12.ps1`: DLSS (off is `-NoDlss`), - `-RayTracing`, `-SmoothMotion`, shader preparation (off is `-NoPrecompile`), and full pipeline precompilation. - Fresh settings enable both. Unchecking full pipeline precompilation with shader preparation still on uses - `-PrecompileUsed`. The other options include `-SeriesX`, `-Quality`, `-Resolution` - (default = none), `-Capture`, `-Log`. On Linux only the game folder and Series X are used. +- **Play**: three cards. + - *Play*: the PLAY pill runs `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\play-d3d12.ps1 -Game + -Data ` plus the switches chosen in Settings (on Linux `scripts/play-linux.sh + /game_scarlett_master.exe`, with `--series-x` if chosen). Under it: the state, the game folder (or where + to choose it), a one-line warning while the profile the next PLAY runs is Series X and the commit limit is under + 64 GiB (as in Settings, below; that profile is the launcher's when it was changed since the last PLAY, otherwise + the F1 menu's `LEONIDA_MENU_CONSOLE` when the menu saved one, as the scripts decide it, below), the options PLAY + passes and what the in-game F1 menu saved (below). The state reads a + few of the script's own messages: Starting, Building the runtime, Preparing shaders, Running (a guess from the text; + the log is the truth); at the end it says the game closed, closed right after starting (with what to send), or + stopped with an error code. Only one thing runs at a time: while it runs PLAY becomes Stop, which, after a + confirmation, ends the process and everything it started (`taskkill /T /F`; on Linux the process group). + - *Updates*: up to date, how many updates there are, or why it cannot tell (a zip copy, no git, no branch to + follow, a failed fetch); the time of the last check with **Check now**; what is new, one line per new commit on + the followed branch's first-parent line (a merged pull request is named `#N` and its title), six at most and + "+ n more"; and **Update Mandy** when there is something to take. + - *Output*: the script's output, with **Run in diagnostic mode** and **Copy my info**. The window takes at most + 2 000 lines a turn, each run of them in one insert, and comes back after 10 ms while more is waiting, so a run + that floods the pipe (the runtime's stderr without `-Log`) leaves the window answering (`take_output`, the design + of #3192). + + The rail shows the same update state at its bottom, with the time of the last check. +- **Settings**: the page of the launcher mockup OreoFR chose: cards in two columns + with switches, segmented choices and lists, a short line under some options and the longer text when the pointer + rests on one; saved with **Save** (PLAY saves too): + - *Picture*: the profile (Series S is `-SeriesS`; Series X is the script's default), DLSS (off is `-NoDlss`), the + DLSS mode (`-Dlss quality|balanced|performance|ultra`, Auto = none; on Series X DLSS makes the picture only with + one), the resolution (`-Resolution`, Default = none, left out with a DLSS mode), the window shape (`-Aspect`: + Default = none, which is 16:9; your screen's = `auto`, 21:9, 32:9 or 16:10; a shape saved otherwise, `W:H` or a + decimal, is kept as a choice of its own; the game still draws 16:9 inside it), how the picture fills that window + (`-PresentScale`: Fit, the script's default with `-Aspect`, passes nothing, or Stretch; greyed while the shape is + Default, since the script only takes it with `-Aspect`) and `-Quality`. + With Series X chosen and Windows' commit limit (RAM + page file, `GlobalMemoryStatusEx`) under 64 GiB, a + warning-coloured line under the profile gives the PC's RAM and limit: the profile commits about 59 GB, so + expect stutters and frame generation cutting in and out (every frame over 100 ms resets it); it suggests + Series S or a fixed page file that brings the limit to about 80 GB, and the pointer on it shows the steps + (`sysdm.cpl` > Advanced > Performance Settings > Advanced > Virtual memory > Custom size) with a size for + this PC. It follows the profile control before Save, blocks nothing and changes no switch; when the F1 menu saved + another console, the profile's "F1 menu: Series X" line (below) says so. The page-file steps + and the measurements are in [d3d12/docs/windows-memory.md](../d3d12/docs/windows-memory.md). + - *Frame generation*: the mode, DLSS, FSR (`-FsrFrameGen`) or Off (`-NoFrameGen`); the multiplier of DLSS's, + Auto (nothing passed: the script's own choice, 2x on RTX 40 and 50 with NVIDIA's files) or 2x to 6x + (`-FrameGen n`, the range `play-nvidia.ps1` takes), passed with the DLSS mode only (Off wins over FSR, FSR over + the multiplier). 3x and up are marked RTX 50: the scripts pass any of them whatever the card, and the runtime + makes no more than the card does (`fg.rs` asks Streamline for its most), so an RTX 40 makes 2x and logs that it + was asked for more; a card without DLSS frame generation starts none. On Series X a multiplier also brings DLSS + in (`-Dlss quality` unless a mode is chosen), where Auto leaves the title's own path. A multiplier saved by the + older launcher shows as chosen and can be set back to Auto. Then the frame limit, Auto (nothing passed: the + runtime's followed limit), 30, 40, 60 or No limit (`LEONIDA_FG_LIMIT_FPS` through `-More`); `-SmoothMotion`. + With hardware ray tracing the card follows `play-nvidia.ps1`'s rule (#3230): frame generation runs only when + asked for (the script's automatic 2x never comes with ray tracing), so with the DLSS mode and the multiplier on + Auto a muted note says to choose 2x; the launcher never picks it. On the Series X profile with under 20 GB of + video memory the script leaves it off, so the mode, multiplier and limit are greyed with a note giving that + reason, unless the advanced options hold `LEONIDA_FG_WITH_RT=1` (then they stay live and the note says it is + unlocked); `LEONIDA_FG_WITH_RT=0` greys them on both profiles. The profile is the one the next PLAY runs (the + F1 menu's console when the launcher's has not changed since the last PLAY, as for the memory note), and the + video memory is read as the script reads it: `HardwareInformation.qwMemorySize` under the display adapter class + (below), the largest, or the chosen card's when a card is chosen in *Graphics card*; unknown (0) holds nothing + back. The launcher never adds `LEONIDA_FG_WITH_RT` itself. + - *Ray tracing*: Off or Hardware (`-HardwareRT`, a trial). Software ray tracing (`-RayTracing`) is no longer + offered; a software choice saved by an older launcher is dropped at the next Save or PLAY. On an AMD or Intel + card a muted note says it is not tested there yet; it is never greyed. + - *Shaders*: shader preparation (off is `-NoPrecompile`) and full pipeline precompilation; fresh settings enable + both, and turning the full one off with the preparation on passes `-PrecompileUsed`. Turning the full one on + turns the preparation on. With the note on NVIDIA's shader cache size. + - *General, diagnostics & advanced*: the language, the graphics card (`-Adapter`: Default = none, Windows' own + choice; otherwise a card of this PC by its name, which the runtime looks for in each card's name, any case), + `-Log`, crash tracing (`LEONIDA_D3D12_DRED=1`), the update check, and **Advanced options**: `LEONIDA_*` variables as `NAME=value` separated by `;`, for when someone asks + you to try one (they win over the frame limit above). A part that is not such a pair is shown in red and not + passed. With variables to pass, PLAY starts the script with + `powershell -Command "& '...\play-d3d12.ps1' ... -More @{NAME='value'}"`, since `-File` cannot hand over a + hashtable (`play-nvidia.ps1` clears inherited `LEONIDA_*` variables, so `-More` is the way in); every argument + is single-quoted, a quote doubled. + The graphics card list is read from the registry, `DriverDesc` (and the card's memory, + `HardwareInformation.qwMemorySize`, for the rules above) under + `HKLM\SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}\00NN` (`winreg`, about 10 ms + the first time and under 1 ms after), each name once, without Windows' software adapters (Microsoft Basic Render + Driver and the like) and drivers that are not on the PCI bus (virtual displays). A driver left by a card taken out + of the PC can still be listed; chosen, the runtime logs that it names no card and uses Windows' default. Off + Windows, or when nothing reads, the list has Default only; a saved value no card gives (`#1`) is kept as a choice. + **Advanced mode…**, beside that field, opens a second window (one at a time; a second click brings it to the + front) with every `LEONIDA_*` variable of [d3d12/docs/switches.md](../d3d12/docs/switches.md), read from the + repository when it opens (682 names today; without the file the window says so). That file is **not** a list of + recommended settings, and the window opens with that warning and a link to + [d3d12/docs/findings.md](../d3d12/docs/findings.md). Each row has the name, its section, how the code reads it, + whether `LEONIDA_AB` can turn it, the NVIDIA launcher script sets it or findings.md names it, the code's comment + (two lines; the pointer on it shows all of it) and the value: a switch for the kinds "off unless set and not + `0`" (on writes `1`) and "on, `0` turns it off" (off writes `0`), a text otherwise. Names and comments come from + the code and stay in English. A search over names and comments, a section filter, **Only what I set** and **Only + those the play script sets** narrow the list; only the rows on screen exist, so filtering the 682 names takes a few milliseconds. + It edits the same field, nothing else: **Apply** or **Close** writes the changed names into it (a value set adds + or updates its pair, a value cleared removes it), so the field's checks and the frame generation + ray tracing + unlock run as if it had been typed; pairs the list does not know and parts that are not pairs are kept as they + were written, and a value with `"` or `;` is refused. **Reset all** (after a confirmation) clears every listed + name. Nothing is set by default, so PLAY's command does not change until a value is applied. Like the field, + these go through `-More`, which wins over the F1 menu's file at a normal start. + - *Game folders* (not in the mockup, under its cards): the game folder (a picker, and a check that + `game_scarlett_master.exe` is in it), the data folder (empty = the script's default) and the mods folder. + + `-Capture` is in the diagnostics card. + A control another choice makes pointless is greyed (its value is kept, and comes back when that choice is undone): + frame generation's mode, multiplier and limit with hardware ray tracing on the Series X profile under 20 GB of + video memory unless `LEONIDA_FG_WITH_RT=1`, and with `LEONIDA_FG_WITH_RT=0` (see *Frame generation* above; a note + gives the reason), the frame generation multiplier with FSR or Off, the DLSS mode with DLSS off, the resolution + with a DLSS mode, the frame limit with frame generation off, how the picture fills the window while the shape is + Default, and shader preparation, kept on, while every pipeline is precompiled. Without an NVIDIA card (none whose + `DriverDesc` has "NVIDIA" among this PC's, or the card chosen in *Graphics card* is not one) DLSS, the DLSS mode, + the DLSS button of frame generation's mode, the multiplier and Smooth Motion are greyed, with the muted note "DLSS + and Smooth Motion need an NVIDIA RTX card"; FSR stays, and a saved DLSS choice is kept (shown greyed) until another + is clicked. Off Windows, or when no card is read, nothing is greyed for the card. + On Linux only the game folder and Series X are used. + Under frame generation, DLSS, ray tracing, the profile and Smooth Motion a muted line "F1 menu: " says that + the F1 menu's file holds a value for the same setting. +- **Run in diagnostic mode** (Play, Settings and Tools): PLAY with `-Log` and `LEONIDA_D3D12_DRED=1`; when the game + ends the logs folder opens, for the newest file to go with a report. +- **Copy my info** (the same three places): puts on the clipboard what a report needs and shows it first: the + Leonida commit and its date, each graphics card with its driver (NVIDIA's own number, 621.47, from the Windows one, + 32.0.16.2147), Python, Tk and Windows versions, the RAM and Windows' commit limit, the switches and variables PLAY + passes, and whether the game folder holds the game. No folder names: they can carry the user's name. - **Mods**: the `mods\*\mod.json` of the mods folder (this repository's `mods` unless changed), with the enabled flag written back as the mod manager does it (`tools/leonida_mods.py`); a button opens that manager. - **Saves**: the D3D12 runtime's saves under the data folder, `\data\7952987A\saves\\\~\v\{0, 1, manifest}` (`d3d12/crates/leonida-hle/src/modules/xgamesave.rs`; `tools/leonida_saves.py`). Containers and - their blobs are listed with size, modified time and the newest readable version. Actions: back up one container or - all (a ZIP in `\save-backups`), restore from a backup (confirmation, and the current saves are backed up - first), duplicate a container under a new name, delete (the folder is moved to `save-backups\deleted`, not erased), - export and import a single blob, and a read-only hex and strings viewer. All of them are refused while the game - is running. -- **Updates**: at start (unless **Check for updates at start** is off in Settings) the launcher runs `git fetch` in - its own folder and, when the clone is behind the branch it follows, says how many new commits there are on the - Play page with an **Update** button. Update runs `git pull --ff-only` (it stops, changing nothing, if local - changes or another branch are in the way), then, on Windows, rebuilds the runtime when `d3d12/` changed; on Linux - it only says that `d3d12/` changed, and the rebuild is yours to run + their blobs are listed with size, modified time and the newest readable version. Actions: **Import saves** (below), + back up one container or all (a ZIP in `\save-backups`), restore one of those backups (confirmation, and the + current saves are backed up first), duplicate a container under a new name, delete (the folder is moved to + `save-backups\deleted`, not erased), export and import a single blob, and a read-only hex and strings viewer. All of + them are refused while the game is running. +- **Import saves** puts saves this runtime wrote elsewhere (an older install, another data folder, another PC, a kept + copy; never console saves) back where the runtime reads them. The source is a ZIP or a folder, chosen in a small + dialog with one button for each (Windows' pickers choose a file or a folder, not either): a launcher backup, a ZIP or + folder holding saves at any level (the `7952987A\saves` folder, the user folder, a configuration folder, one + `~` container), or a whole old data folder. Every folder named `~<16 hex digits>` with a `v` + whose manifest reads is a save; anything else is ignored and the skipped ones are counted. Each goes to + `\data\7952987A\saves\0009000000000001\\~`: the user folder is the runtime's + constant `xuser::XUID`; the configuration folder is the one the source's path names (`<16 hex>\\ + `), else this PC's only one. The runtime names that folder after the service configuration id the title + passes to `XGameSaveInitializeProvider` (`Provider::open`; `default` when the id is empty), not after a constant of + its own, so with neither the launcher asks you to start the game once and invents no name. A list (name, newest + version, date, new or replaced) is shown before anything is written; when one replaces a save already there, all + the current saves are backed up first (`before-import`). Each container is copied to `import.new` beside the saves + folder and moved in with one rename; a ZIP's entries are checked as Restore checks them (no `..`, drive or absolute + path). +- **Updates**: at every start the launcher runs `git fetch` in + its own folder and, when the clone is behind the branch it follows, lists the new commits in the Play page's + Updates card (`git log --first-parent HEAD..@{u}`) with an **Update Mandy** button. Update runs `git pull --ff-only` + (it stops, changing nothing, if local changes or another branch are in the way), then, on Windows, rebuilds the + runtime when `d3d12/` changed; on Linux it only says that `d3d12/` changed, and the rebuild is yours to run ([linux.md](linux.md#the-runtime-under-wine-or-proton)). A copy downloaded as a zip has no `.git`, and updating - means a `git clone` of the repository instead. A zip copy, a missing git or a failed check (the bar gives git's - reason) is reported in the Play page's status bar instead of an update; on a branch that follows no upstream, - nothing is shown. + means a `git clone` of the repository instead. A zip copy, a missing git, a failed check (with git's reason) or a + branch that follows no upstream is shown in the Updates card and the rail instead of an update. - **Tools**: update Leonida (as above), fetch NVIDIA's DLSS files (`d3d12\Get-NVIDIA-DLSS.cmd`, after a confirmation: about 70 MB from NVIDIA's GitHub), rebuild the runtime (`d3d12\scripts\build-nvidia.ps1`), open the logs folder (`%LOCALAPPDATA%\Leonida\logs`) and the screenshots folder. The two scripts are Windows only. - **About**: what the port is, that it runs your own copy, the credits (see `d3d12/README.md`) and the licence. +## The launcher and the F1 menu: which one wins + +The in-game F1 menu saves its choices in `d3d12\leonida-settings.txt` (`LEONIDA_*=value` lines; +`d3d12/scripts/play-nvidia.ps1` reads it at every start), and the launcher keeps its own options in `launcher.json` +and passes them as switches at every PLAY. For one setting, the newest choice wins: + +- an option you **changed in the launcher since the last PLAY** is passed as chosen (`-Chosen`): it wins over the F1 + menu's value for the same setting, and the script drops that value from the menu file; +- an option you **did not change** is passed again but does not count as chosen: the F1 menu's saved value, if there + is one, wins; +- the **advanced options**, the frame limit and crash tracing (`-More`) always win at a normal start. + +So the launcher can show one value while the game starts with the F1 menu's. The Play card lists what the F1 menu +saved ("Saved in the F1 menu", read again when the window comes back to the front and when a run ends), and +**Clear F1 settings** deletes that file, after a confirmation and only while the game is not running: the next start +then uses the launcher's options and the game's defaults. With no file or nothing in it the card says "Nothing saved +in the F1 menu" rather than hiding the section, so a clear shows its result where it was asked for. + +The Play card's commit-limit warning uses the same order for the console (`effective_console`): the launcher's +profile if it changed since the last PLAY, otherwise the menu's `LEONIDA_MENU_CONSOLE` (`series-x` or `series-s`) +when the file holds one, otherwise the launcher's. At the first PLAY nothing counts as changed (`-Chosen none`), so +the menu's console wins there too. It is read again with the menu file (focus, end of a run). + ## Settings file `%APPDATA%\Leonida\launcher.json` (Linux: `~/.config/leonida/launcher.json`), written when you press Save or close the @@ -58,8 +221,14 @@ window. Unknown or mistyped keys are ignored. ## Tests `python -I tests/test_leonida_saves.py` does the same for the Saves page on fake save trees. `python -I tests/test_leonida_launcher.py` covers the parts without a window: reading and writing the settings, the -command line each option produces (checked against the switch names in `scripts/play-d3d12.ps1`), the mod list and -the newest-picture search. +command line each option produces (checked against the switch names in `scripts/play-d3d12.ps1`), the advanced +options and their quoting, the Advanced mode window's reading of `switches.md` and its edits of the advanced +options (unknown pairs kept, `"` and `;` refused), the F1 menu's file (reading it and deleting only that file), which +console the warning follows, Settings' greying (`settings_rules`: frame generation with hardware ray tracing over +Series S / X, 8 / 16 / 24 GB and `LEONIDA_FG_WITH_RT` unset / 1 / 0, and the NVIDIA-only controls on NVIDIA, AMD, +Intel or a chosen card, the registry stubbed), the output pump's batches (`take_output`: 10 001 lines are one insert a turn), the +translations (every text of the window in every language), the language choice, the driver number, Copy my info, the +mod list, what is new upstream (the pull requests' titles) and the Python offer of `Launcher.bat`. ## Saves: what the bytes are, and what is not edited diff --git a/tests/test_leonida_launcher.py b/tests/test_leonida_launcher.py index b3f5df5c51..259efe8ffb 100644 --- a/tests/test_leonida_launcher.py +++ b/tests/test_leonida_launcher.py @@ -190,19 +190,6 @@ def test_list_and_toggle_mods(self): self.assertFalse(launcher.list_mods(tmp)[0][0]["enabled"]) self.assertEqual(launcher.list_mods(os.path.join(tmp, "missing")), ([], [])) - def test_newest_picture(self): - with tempfile.TemporaryDirectory() as tmp: - old, new = Path(tmp, "a", "old.png"), Path(tmp, "b", "new.png") - old.parent.mkdir() - new.parent.mkdir() - old.write_bytes(b"x") - new.write_bytes(b"x") - Path(tmp, "note.txt").write_bytes(b"x") - os.utime(old, (1000, 1000)) - os.utime(new, (2000, 2000)) - self.assertEqual(launcher.newest_picture([tmp]), str(new)) - self.assertIsNone(launcher.newest_picture([os.path.join(tmp, "none")])) - class FakeGit: """`git -C repo ` answered from a table of the first argument; records each call.""" @@ -231,15 +218,45 @@ def test_a_zip_copy_is_told_to_clone(self): self.assertEqual(status["kind"], "zip") self.assertIn("git clone", launcher.update_note(status)) + def test_the_count_is_one_per_merged_pull_request(self): + # rev-list answers 9 for every commit, 2 for the first-parent ones: the launcher shows 2. + git = FakeGit({"rev-list": (0, lambda a: "2" if "--first-parent" in a else "9")}) + with tempfile.TemporaryDirectory() as tmp: + status = launcher.update_status(self.repo(tmp), git) + self.assertEqual((status["kind"], status["behind"]), ("behind", 2)) + def test_behind_counts_the_new_commits_after_a_fetch(self): git = FakeGit({"rev-list": (0, "3\n")}) with tempfile.TemporaryDirectory() as tmp: status = launcher.update_status(self.repo(tmp), git) self.assertEqual((status["kind"], status["behind"]), ("behind", 3)) self.assertIn(("fetch", "--quiet"), git.calls) - self.assertIn("3 new commits", launcher.update_note(status)) + self.assertIn("3 new commit", launcher.update_note(status)) self.assertEqual(launcher.update_note({"kind": "current", "behind": 0}), "") + def test_behind_lists_what_is_new(self): + log = ("abc1234\x1fMerge pull request #3097 from OreoFR/feat/compare-on-sender\x1f" + "d3d12 host: compare on the sender thread\n\nlonger text\n\x1e\n" + "def5678\x1fdocs: a fix straight on main\x1f\x1e\n") + git = FakeGit({"rev-list": (0, "2\n"), "log": (0, log)}) + with tempfile.TemporaryDirectory() as tmp: + status = launcher.update_status(self.repo(tmp), git) + self.assertEqual(status["changes"], [ + {"title": "d3d12 host: compare on the sender thread", "pr": 3097, "hash": "abc1234"}, + {"title": "docs: a fix straight on main", "pr": None, "hash": "def5678"}]) + log_call = [c for c in git.calls if c[0] == "log"][0] + self.assertIn("--first-parent", log_call) + self.assertEqual(log_call[-1], "HEAD..@{u}") + self.assertEqual(launcher.change_line(status["changes"][0]), "#3097 d3d12 host: compare on the sender thread") + self.assertEqual(launcher.change_line(status["changes"][1]), "docs: a fix straight on main") + self.assertEqual(len(launcher.change_line({"title": "x" * 200, "pr": None}, limit=40)), 40) + # A merge without a body keeps its subject; a log that fails leaves the list empty, still behind. + self.assertEqual(launcher.parse_changes("a1\x1fMerge pull request #5 from x/y\x1f\x1e")[0]["title"], + "Merge pull request #5 from x/y") + with tempfile.TemporaryDirectory() as tmp: + failed = launcher.update_status(self.repo(tmp), FakeGit({"rev-list": (0, "4\n"), "log": (128, "")})) + self.assertEqual((failed["kind"], failed["behind"], failed["changes"]), ("behind", 4, [])) + def test_a_failed_fetch_or_no_upstream_is_said_not_raised(self): with tempfile.TemporaryDirectory() as tmp: repo = self.repo(tmp) @@ -278,6 +295,132 @@ def test_the_check_can_be_turned_off(self): self.assertFalse(launcher.normalise({"check_updates": False})["check_updates"]) +class OutputPumpTests(unittest.TestCase): + """Issue #3175: with -Log off the runtime's stderr comes through the pipe, and the window's pump drained the whole + queue in one turn with one insert per line, so the window stopped answering clicks while it caught up.""" + + def queued(self, items): + lines = launcher.queue.Queue() + for item in items: + lines.put(item) + return lines + + def test_a_turn_takes_at_most_the_batch_and_leaves_the_rest_queued(self): + game = object() + lines = self.queued(("line", game, f"{i}\n") for i in range(launcher.OUTPUT_BATCH * 3 + 5)) + turn = launcher.take_output(lines) + # One insert's worth: the whole batch in one item, in order, and the rest left for the next turns. + self.assertEqual(len(turn), 1) + self.assertEqual(turn[0][:2], ("lines", game)) + self.assertEqual(turn[0][2], [f"{i}\n" for i in range(launcher.OUTPUT_BATCH)]) + self.assertEqual(lines.qsize(), launcher.OUTPUT_BATCH * 2 + 5) + self.assertEqual(launcher.take_output(lines, limit=3)[0][2], + [f"{launcher.OUTPUT_BATCH + i}\n" for i in range(3)]) + self.assertEqual(launcher.take_output(self.queued([])), []) + + def test_runs_are_joined_per_process_and_kept_in_order(self): + old, new = object(), object() + status = {"kind": "current", "behind": 0} + lines = self.queued([("line", old, "a\n"), ("line", old, "b\n"), ("exit", old, 0), ("update", None, status), + ("line", old, "late\n"), ("line", new, "c\n"), ("line", new, "d\n")]) + turn = launcher.take_output(lines) + self.assertEqual([(k, p, v) for k, p, v in turn], + [("lines", old, ["a\n", "b\n"]), ("exit", old, 0), ("update", None, status), + ("lines", old, ["late\n"]), ("lines", new, ["c\n", "d\n"])]) + self.assertTrue(lines.empty()) + + # The two tests above are #3192's (1mshy), as written there; those below are this launcher's. + + def test_info_and_rail_items_keep_their_place(self): + game = object() + lines = self.queued([("line", game, "a\n"), ("info", None, "info"), ("line", game, "b\n"), + ("rail", None, "abc1234"), ("line", game, "c\n"), ("line", game, "d\n")]) + self.assertEqual(launcher.take_output(lines), + [("lines", game, ["a\n"]), ("info", None, "info"), ("lines", game, ["b\n"]), + ("rail", None, "abc1234"), ("lines", game, ["c\n", "d\n"])]) + + def test_a_flood_of_10001_lines_is_one_insert_a_turn(self): + game = object() + lines = self.queued(("line", game, "x\n") for _ in range(10_001)) + turns = [] + while not lines.empty(): + turns.append(launcher.take_output(lines)) + self.assertEqual([len(turn) for turn in turns], [1] * 6) # 5 full batches and the last line + self.assertEqual(sum(len(turn[0][2]) for turn in turns), 10_001) + self.assertEqual(launcher.OUTPUT_RESUME_MS, 10) + + def test_the_window_pump_goes_through_take_output(self): + # The pump lives in run_gui (Tk only): its source must take the queue through take_output, never drain it + # line by line, and come back after OUTPUT_RESUME_MS while more is queued. + import ast + tree = ast.parse((ROOT / "tools" / "leonida_launcher.py").read_text(encoding="utf-8")) + pumps = [n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "pump"] + self.assertEqual(len(pumps), 1) + calls = {c.func.id if isinstance(c.func, ast.Name) else getattr(c.func, "attr", "") + for c in ast.walk(pumps[0]) if isinstance(c, ast.Call)} + self.assertIn("take_output", calls) + self.assertNotIn("get_nowait", calls) + self.assertIn("OUTPUT_RESUME_MS", {n.id for n in ast.walk(pumps[0]) if isinstance(n, ast.Name)}) + + +class EffectiveConsoleTests(unittest.TestCase): + """The Play card's commit-limit warning follows the profile the next PLAY runs: the launcher's when it was changed + since the last PLAY (-Chosen), else the F1 menu's LEONIDA_MENU_CONSOLE (play-nvidia.ps1).""" + + LOW, RAM = 40 * 1024 ** 3, 32 * 1024 ** 3 + + def unchanged(self, **values): + s = settings(**values) + s["last_switches"] = launcher.json.dumps(launcher.switch_args(s)) + return s + + def warns(self, s, menu): + x = launcher.effective_console(s, menu, windows=True) == "series-x" + return launcher.memory_note(x, self.LOW, self.RAM, short=True) is not None + + def test_an_unchanged_launcher_profile_leaves_the_f1_menus(self): + s = self.unchanged(series_s=True) + self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=True), "series-x") + self.assertTrue(self.warns(s, {"LEONIDA_MENU_CONSOLE": "series-x"})) + x = self.unchanged(series_x=True) + self.assertEqual(launcher.effective_console(x, {"LEONIDA_MENU_CONSOLE": "series-s"}, windows=True), "series-s") + self.assertFalse(self.warns(x, {"LEONIDA_MENU_CONSOLE": "series-s"})) + + def test_a_profile_changed_since_the_last_play_wins(self): + s = settings(series_s=True) + s["last_switches"] = launcher.json.dumps(launcher.switch_args(settings())) # Series X at the last PLAY + self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=True), "series-s") + self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": "series-x"})) + x = settings() + x["last_switches"] = launcher.json.dumps(launcher.switch_args(settings(series_s=True))) + self.assertTrue(self.warns(x, {"LEONIDA_MENU_CONSOLE": "series-s"})) + # Another option changed since: the profile still counts as unchanged. + other = self.unchanged(series_s=True) + other["dlss"] = False + self.assertTrue(self.warns(other, {"LEONIDA_MENU_CONSOLE": "series-x"})) + + def test_without_a_menu_console_the_launchers(self): + for s in (self.unchanged(series_s=True), settings(series_s=True)): + self.assertEqual(launcher.effective_console(s, {}, windows=True), "series-s") + self.assertFalse(self.warns(s, {})) + self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": ""})) # unset: the command line's + self.assertFalse(self.warns(s, {"LEONIDA_MENU_CONSOLE": "xbox"})) + self.assertEqual(launcher.effective_console(self.unchanged(), {}, windows=True), "series-x") + + def test_the_first_play_follows_the_menu(self): + # No last PLAY: the launcher passes -Chosen none, so play-d3d12.ps1 counts nothing as typed. + s = settings(series_s=True) + self.assertEqual(launcher.chosen_switches(launcher.switch_args(s), s["last_switches"]), []) + self.assertIn("none", launcher.play_command(s, repo="R", windows=True, chosen=[])) + self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "Series-X"}, windows=True), + "series-x") + + def test_linux_reads_no_menu_file(self): + s = settings(series_x=False) + self.assertEqual(launcher.effective_console(s, {"LEONIDA_MENU_CONSOLE": "series-x"}, windows=False), + "series-s") + + class NvidiaCacheNoteTests(unittest.TestCase): def test_the_note_names_the_setting_and_where_it_is(self): note = launcher.NVIDIA_CACHE_NOTE @@ -285,5 +428,746 @@ def test_the_note_names_the_setting_and_where_it_is(self): self.assertIn(words, note) +class AdvancedOptionTests(unittest.TestCase): + def test_pairs_are_read_and_the_rest_is_reported(self): + values, wrong = launcher.parse_advanced( + "LEONIDA_SUBMIT_SENDER=1; LEONIDA_TIMELINE='420+480,20,t.txt'\nPATH=C:\\x;nothing; lower_case=1;" + 'LEONIDA_Q="a"b"') + self.assertEqual(values, {"LEONIDA_SUBMIT_SENDER": "1", "LEONIDA_TIMELINE": "420+480,20,t.txt"}) + self.assertEqual(wrong, ["PATH=C:\\x", "nothing", "lower_case=1", 'LEONIDA_Q="a"b"']) + self.assertEqual(launcher.parse_advanced(""), ({}, [])) + + def test_variables_go_to_more_through_command(self): + s = settings(game_dir=r"C:\it's here", advanced="LEONIDA_X=o'k", dred=True) + command = launcher.play_command(s, repo="R", windows=True, chosen=["Log"], extra={"LEONIDA_Y": "2"}) + self.assertEqual(command[:5], ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command"]) + self.assertEqual(len(command), 6) + script = os.path.join("R", "scripts", "play-d3d12.ps1") + self.assertEqual(command[5], "& " + launcher.ps_quote(script) + " -Game 'C:\\it''s here' -Chosen 'Log' " + "-More @{LEONIDA_X='o''k'; LEONIDA_D3D12_DRED='1'; LEONIDA_Y='2'}; exit $LASTEXITCODE") + # Nothing to pass: the plain -File command, as before. + self.assertIn("-File", launcher.play_command(settings(advanced="junk"), repo="R", windows=True)) + + def test_typographic_quotes_are_doubled(self): + # PowerShell ends a single-quoted string at U+2018-U+201B too. + self.assertEqual(launcher.ps_quote("Tony’s; x"), "'Tony’’s; x'") + self.assertEqual(launcher.ps_quote("a'b‘c"), "'a''b‘‘c'") + + def test_the_script_takes_more_as_a_table(self): + text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8") + self.assertIn("[hashtable]$More", text) + self.assertIn("$NoFrameGen", text) + + def test_frame_generation_off(self): + self.assertEqual(launcher.switch_args(settings(no_frame_gen=True)), ["-NoFrameGen"]) + # Off in Settings wins over a multiplier saved earlier; FSR replaces DLSS's. + self.assertEqual(launcher.switch_args(settings(no_frame_gen=True, frame_gen=2)), ["-NoFrameGen"]) + self.assertEqual(launcher.switch_args(settings(fsr_frame_gen=True, frame_gen=2)), ["-FsrFrameGen"]) + self.assertEqual(launcher.switch_args(settings(frame_gen=2)), ["-FrameGen", "2"]) + + def test_frame_limit_goes_to_more_and_advanced_wins(self): + self.assertEqual(launcher.extra_variables(settings()), {}) + self.assertEqual(launcher.extra_variables(settings(fg_limit="40")), {"LEONIDA_FG_LIMIT_FPS": "40"}) + self.assertEqual(launcher.extra_variables(settings(fg_limit="40", advanced="LEONIDA_FG_LIMIT_FPS=28")), + {"LEONIDA_FG_LIMIT_FPS": "28"}) + self.assertEqual(launcher.normalise({"fg_limit": "999"})["fg_limit"], "") + text = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8") + self.assertIn("$FsrFrameGen", text) + + def test_new_settings_are_checked(self): + got = launcher.normalise({"language": "xx", "dred": "yes", "advanced": 3, "no_frame_gen": 1}) + self.assertEqual((got["language"], got["dred"], got["advanced"], got["no_frame_gen"]), ("", False, "", False)) + kept = launcher.normalise({"language": "fr", "dred": True, "advanced": "LEONIDA_A=1"}) + self.assertEqual((kept["language"], kept["dred"], kept["advanced"]), ("fr", True, "LEONIDA_A=1")) + + +class NewControlsTests(unittest.TestCase): + """The frame generation multiplier, the window shape with how the picture fills it, and the graphics card: the + lists Settings offers and the switches they give (scripts/play-d3d12.ps1, d3d12/scripts/play-nvidia.ps1).""" + + def test_the_multiplier_goes_with_dlss_frame_generation_only(self): + # Mode DLSS (neither flag) with a multiplier: -FrameGen n; FSR and Off drop it (-NoFrameGen wins over both). + for n in (2, 3, 4, 5, 6): + self.assertEqual(launcher.switch_args(settings(frame_gen=n)), ["-FrameGen", str(n)]) + self.assertEqual(launcher.switch_args(settings(frame_gen=3, fsr_frame_gen=True)), ["-FsrFrameGen"]) + self.assertEqual(launcher.switch_args(settings(frame_gen=3, no_frame_gen=True)), ["-NoFrameGen"]) + self.assertEqual(launcher.switch_args(settings(frame_gen=3, no_frame_gen=True, fsr_frame_gen=True)), + ["-NoFrameGen"]) + self.assertEqual(launcher.switch_args(settings(frame_gen=0)), []) # Auto: the script's own choice + + def test_the_multiplier_list_is_what_the_scripts_take(self): + options = launcher.frame_gen_options() + self.assertEqual([v for v, _ in options], ["0", "2", "3", "4", "5", "6"]) + self.assertEqual(dict(options)["2"], "2x") + self.assertTrue(all("RTX 50" in label for v, label in options if v in "3456")) + wrapper = (ROOT / "scripts" / "play-d3d12.ps1").read_text(encoding="utf-8") + self.assertIn("[ValidateSet(0, 2, 3, 4, 5, 6)][int]$FrameGen", wrapper) + nvidia = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8") + self.assertIn("[ValidateRange(2, 6)][int]$FrameGen", nvidia) + + def test_an_old_file_with_frame_gen_2_shows_2x(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "launcher.json") + Path(path).write_text('{"game_dir": "D:/g", "frame_gen": 2}', encoding="utf-8") + loaded = launcher.load_settings(path) + self.assertEqual(loaded["frame_gen"], 2) + self.assertEqual(dict(launcher.frame_gen_options())[str(loaded["frame_gen"])], "2x") + self.assertEqual(launcher.switch_args(loaded), ["-FrameGen", "2"]) + + def test_window_shape_and_how_the_picture_fills_it(self): + self.assertEqual(launcher.switch_args(settings(aspect="21:9")), ["-Aspect", "21:9"]) + self.assertEqual(launcher.switch_args(settings(aspect="auto", present_scale="stretch")), + ["-Aspect", "auto", "-PresentScale", "stretch"]) + self.assertEqual(launcher.switch_args(settings(present_scale="stretch")), []) # only with -Aspect + # Every shape offered is one the script's pattern takes; a saved shape of another kind stays a choice. + nvidia = (ROOT / "d3d12" / "scripts" / "play-nvidia.ps1").read_text(encoding="utf-8") + self.assertIn("[ValidatePattern('" + launcher.ASPECT.pattern + "')][string]$Aspect", nvidia) + values = [v for v, _ in launcher.aspect_options("")] + self.assertEqual(values, ["", "auto", "21:9", "32:9", "16:10"]) + self.assertTrue(all(launcher.ASPECT.match(v) for v in values if v)) + self.assertEqual(launcher.aspect_options("2.39")[-1], ("2.39", "2.39")) + self.assertEqual(len(launcher.aspect_options("21:9")), 5) + + def test_the_card_list_from_the_registry(self): + entries = [ + {"DriverDesc": "Intel(R) Arc(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_8086&DEV_7D55"}, + {"DriverDesc": "NVIDIA GeForce RTX 4070 Laptop GPU", "MatchingDeviceId": r"pci\ven_10de&dev_2820"}, + {"DriverDesc": "nvidia geforce rtx 4070 laptop gpu", "MatchingDeviceId": r"pci\ven_10de&dev_2820"}, + {"DriverDesc": "Microsoft Basic Render Driver"}, + {"DriverDesc": "Microsoft Basic Display Adapter", "MatchingDeviceId": r"PCI\CC_0300"}, + {"DriverDesc": "Parsec Virtual Display Adapter", "MatchingDeviceId": r"Root\Parsec\VDA"}, + {"DriverDesc": " ", "MatchingDeviceId": r"PCI\VEN_1002"}, + {"MatchingDeviceId": r"PCI\VEN_1002"}, + {"DriverDesc": 7}, + "not a dict", + {"DriverDesc": "AMD Radeon RX 7800 XT"}, + ] + self.assertEqual(launcher.display_adapters(lambda: entries), + ["Intel(R) Arc(TM) Graphics", "NVIDIA GeForce RTX 4070 Laptop GPU", "AMD Radeon RX 7800 XT"]) + + def broken(): + raise OSError("no registry") + self.assertEqual(launcher.display_adapters(broken), []) + self.assertEqual(launcher.display_adapters(lambda: []), []) + self.assertEqual(launcher.read_display_class(windows=False), []) + + def test_a_card_is_stored_as_text_the_script_and_adapter_take(self): + self.assertEqual(launcher.adapter_value("NVIDIA GeForce RTX 5070"), "NVIDIA GeForce RTX 5070") + self.assertEqual(launcher.adapter_value("Intel(R) Arc(TM) Graphics"), "Intel(R) Arc(TM) Graphics") + # Characters ADAPTER refuses: the longest part it takes, which the card's name still contains (the runtime + # looks for the text in each card's name). + odd = "Radeon® RX 7800 XT Graphics" + self.assertEqual(launcher.adapter_value(odd), "RX 7800 XT Graphics") + long = "A" * 70 + self.assertEqual(launcher.adapter_value(long), "A" * 64) + for name in (odd, long, "NVIDIA GeForce RTX 5070", '"quoted"; calc'): + value = launcher.adapter_value(name) + self.assertTrue(launcher.ADAPTER.match(value), name) + self.assertIn(value.lower(), name.lower()) + self.assertEqual(launcher.adapter_value("®™"), "") + options = launcher.adapter_options(["NVIDIA GeForce RTX 5070", "®™"], "") + self.assertEqual(options, [("", "Default"), ("NVIDIA GeForce RTX 5070", "NVIDIA GeForce RTX 5070")]) + # A saved value no card gives (an index, a card taken out) is kept as a choice. + self.assertEqual(launcher.adapter_options([], "#1"), [("", "Default"), ("#1", "#1")]) + self.assertEqual(launcher.switch_args(settings(adapter="NVIDIA GeForce RTX 5070")), + ["-Adapter", "NVIDIA GeForce RTX 5070"]) + + def test_the_default_command_is_unchanged(self): + fresh = launcher.normalise({"game_dir": "D:/Games/GTA"}) + self.assertEqual((fresh["frame_gen"], fresh["aspect"], fresh["present_scale"], fresh["adapter"]), + (0, "", "", "")) + command = launcher.play_command(fresh, repo="R", windows=True) + self.assertEqual(command, ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", + os.path.join("R", "scripts", "play-d3d12.ps1"), "-Game", "D:/Games/GTA"]) + + +GB = 1024 ** 3 + + +def card_class(*cards): + """Display class entries (read_display_class) for (name, memory in GB or None) pairs, on the PCI bus.""" + entries = [] + for name, memory in cards: + entry = {"DriverDesc": name, "MatchingDeviceId": r"PCI\VEN_0000&DEV_0000"} + if memory is not None: + entry[launcher.CARD_MEMORY] = int(memory * GB) + entries.append(entry) + return entries + + +def rule_values(**changes): + values = {"rt": "hw", "dlss": True, "dlss_mode": "", "fg_mode": "dlss", "frame_gen": "0", "aspect": "", + "precompile_all": False, "advanced": ""} + values.update(changes) + return values + + +class SettingsRulesTests(unittest.TestCase): + """settings_rules: frame generation with hardware ray tracing as play-nvidia.ps1 of #3230 decides it (Series X + under 20 GB of video memory off unless LEONIDA_FG_WITH_RT=1, =0 off everywhere, never the automatic 2x), and the + NVIDIA-only controls greyed without an NVIDIA card. The registry is stubbed: no hardware is read.""" + + CHOOSE = "With ray tracing, frame generation runs only when asked: choose 2x" + MEMORY = "Series X with ray tracing needs 20 GB of video memory for frame generation" + UNLOCKED = "Frame generation with ray tracing: unlocked in Advanced (LEONIDA_FG_WITH_RT=1)" + OFF = "Frame generation is off with ray tracing: LEONIDA_FG_WITH_RT=0 in Advanced" + NVIDIA = "DLSS and Smooth Motion need an NVIDIA RTX card" + UNTESTED = "Not tested on AMD/Intel cards yet" + + def test_the_matrix_of_console_memory_and_unlock(self): + rows = [] + for console in ("series-s", "series-x"): + for memory in (8, 16, 24): + card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4070", memory))) + for unlock in (None, "1", "0"): + for multiplier in ("2", "0"): + advanced = "" if unlock is None else f"LEONIDA_FG_WITH_RT={unlock}" + enabled, notes = launcher.settings_rules( + rule_values(advanced=advanced, frame_gen=multiplier), card, console) + held = unlock == "0" or (console == "series-x" and memory < 20 and unlock != "1") + name = (console, memory, unlock, multiplier) + rows.append(name) + self.assertEqual(enabled["fg_mode"], not held, name) + self.assertEqual(enabled["frame_gen"], not held, name) + self.assertEqual(enabled["fg_limit"], not held, name) + lines = notes["fg"][0].split("\n") if notes["fg"] else [] + if unlock == "0": + self.assertEqual(notes["fg"], (self.OFF, True), name) + elif held: + self.assertEqual(notes["fg"], (self.MEMORY, True), name) + else: + unlocked = console == "series-x" and memory < 20 and unlock == "1" + want = ([self.UNLOCKED] if unlocked else []) + ([self.CHOOSE] if multiplier == "0" else []) + self.assertEqual(lines, want, name) + self.assertFalse(notes["fg"] and notes["fg"][1], name) # muted, not a warning + # Nothing NVIDIA-only greyed on an NVIDIA card, and no card note. + self.assertTrue(enabled["dlss"] and enabled["fg_dlss"] and enabled["smooth_motion"], name) + self.assertIsNone(notes["nvidia"], name) + self.assertIsNone(notes["rt"], name) + self.assertEqual(len(rows), 2 * 3 * 3 * 2) + + def test_without_ray_tracing_nothing_changes(self): + card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4060", 8))) + for advanced in ("", "LEONIDA_FG_WITH_RT=0", "LEONIDA_FG_WITH_RT=1"): + enabled, notes = launcher.settings_rules(rule_values(rt="off", advanced=advanced), card, "series-x") + self.assertTrue(enabled["fg_mode"] and enabled["frame_gen"] and enabled["fg_limit"], advanced) + self.assertIsNone(notes["fg"], advanced) + + def test_the_script_rule(self): + self.assertEqual(launcher.fg_with_rt(False, "series-x", 8 * GB, None), "") + self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, " 0 "), "off") + self.assertEqual(launcher.fg_with_rt(True, "series-s", 8 * GB, "0"), "off") + self.assertEqual(launcher.fg_with_rt(True, "series-x", 20 * GB - 1, None), "memory") + self.assertEqual(launcher.fg_with_rt(True, "series-x", 20 * GB, None), "asked") # -lt 20GB in the script + self.assertEqual(launcher.fg_with_rt(True, "series-x", 0, None), "asked") # unknown: not held back + self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, "1"), "unlocked") + self.assertEqual(launcher.fg_with_rt(True, "series-s", 8 * GB, "1"), "asked") + self.assertEqual(launcher.fg_with_rt(True, "series-x", 8 * GB, "2"), "memory") # only 1 unlocks + + def test_fsr_or_off_gives_no_choose_note(self): + card = launcher.card_facts(card_class(("NVIDIA GeForce RTX 4070", 8))) + for mode in ("fsr", "off"): + enabled, notes = launcher.settings_rules(rule_values(fg_mode=mode), card, "series-s") + self.assertTrue(enabled["fg_mode"], mode) + self.assertFalse(enabled["frame_gen"], mode) + self.assertIsNone(notes["fg"], mode) + self.assertFalse(launcher.settings_rules(rule_values(fg_mode="off"), card, "series-s")[0]["fg_limit"]) + + def test_the_memory_of_the_chosen_card(self): + entries = card_class(("NVIDIA GeForce RTX 4090", 24), ("NVIDIA GeForce RTX 4060", 8)) + self.assertEqual(launcher.card_facts(entries)["memory"], 24 * GB) # Default: the largest + self.assertEqual(launcher.card_facts(entries, "RTX 4060")["memory"], 8 * GB) # the chosen card's + self.assertEqual(launcher.card_facts(entries, "#1")["memory"], 24 * GB) # no card has it + x = launcher.settings_rules(rule_values(), launcher.card_facts(entries), "series-x")[0] + self.assertTrue(x["fg_mode"]) + x = launcher.settings_rules(rule_values(), launcher.card_facts(entries, "nvidia geforce rtx 4060"), "series-x") + self.assertFalse(x[0]["fg_mode"]) + # A binary qwMemorySize, a value of another kind, and none at all. + self.assertEqual(launcher.card_memory((16 * GB).to_bytes(8, "little")), 16 * GB) + self.assertEqual(launcher.card_memory("16"), 0) + self.assertEqual(launcher.card_memory(True), 0) + self.assertEqual(launcher.card_facts(card_class(("NVIDIA GeForce RTX 3090", None)))["memory"], 0) + # The largest of the class counts every subkey, as the script's does. + entries = card_class(("NVIDIA GeForce RTX 4060", 8)) + [{"DriverDesc": "Parsec Virtual Display Adapter", + "MatchingDeviceId": r"Root\Parsec\VDA", + launcher.CARD_MEMORY: 24 * GB}] + self.assertEqual(launcher.card_facts(entries)["memory"], 24 * GB) + + def test_nvidia_amd_intel_and_a_chosen_card(self): + nvidia = launcher.card_facts(card_class(("NVIDIA GeForce RTX 5070", 12))) + amd = launcher.card_facts(card_class(("AMD Radeon RX 7800 XT", 16))) + intel = launcher.card_facts(card_class(("Intel(R) Arc(TM) B580 Graphics", 12))) + both = card_class(("Intel(R) Arc(TM) Graphics", None), ("NVIDIA GeForce RTX 4070 Laptop GPU", 8)) + nvidia_only = ("dlss", "dlss_mode", "smooth_motion", "fg_dlss", "frame_gen") + for name, card, vendor in (("nvidia", nvidia, "nvidia"), ("amd", amd, "amd"), ("intel", intel, "intel"), + ("default of both", launcher.card_facts(both), "nvidia"), + ("Intel chosen", launcher.card_facts(both, "Intel(R) Arc(TM) Graphics"), "intel"), + ("NVIDIA chosen", launcher.card_facts(both, "RTX 4070"), "nvidia")): + self.assertEqual(card["vendor"], vendor, name) + enabled, notes = launcher.settings_rules(rule_values(rt="off"), card, "series-s") + on_nvidia = vendor == "nvidia" + for key in nvidia_only: + self.assertEqual(enabled[key], on_nvidia, (name, key)) + self.assertTrue(enabled["fg_mode"] and enabled["fg_limit"], name) # FSR stays + self.assertEqual(notes["nvidia"], None if on_nvidia else self.NVIDIA, name) + self.assertEqual(notes["rt"], None if on_nvidia else self.UNTESTED, name) # ray tracing never greyed + # With ray tracing on Series S: no "choose 2x" without DLSS frame generation to choose it for. + enabled, notes = launcher.settings_rules(rule_values(), card, "series-s") + self.assertEqual(notes["fg"], (self.CHOOSE, False) if on_nvidia else None, name) + # Another maker: DLSS greyed (no NVIDIA card), no ray-tracing note. + other = launcher.card_facts(card_class(("Qualcomm Adreno X1-85 GPU", 4))) + enabled, notes = launcher.settings_rules(rule_values(rt="off"), other, "series-s") + self.assertFalse(enabled["dlss"]) + self.assertIsNone(notes["rt"]) + + def test_nothing_read_greys_nothing(self): + for entries in ([], [{"DriverDesc": "Microsoft Basic Render Driver"}], ["not a dict"]): + card = launcher.card_facts(entries) + self.assertFalse(card["known"]) + enabled, notes = launcher.settings_rules(rule_values(rt="off"), card, "series-x") + self.assertTrue(all(enabled[k] for k in ("dlss", "dlss_mode", "smooth_motion", "fg_dlss", "frame_gen"))) + self.assertEqual((notes["nvidia"], notes["rt"]), (None, None)) + # Video memory unknown: Series X with ray tracing is not held back. + self.assertTrue(launcher.settings_rules(rule_values(), card, "series-x")[0]["fg_mode"]) + + def broken(): + raise OSError("no registry") + self.assertEqual(launcher.read_entries(broken), []) + self.assertEqual(launcher.read_entries(lambda: None), []) + + def test_the_launcher_never_adds_the_unlock(self): + for series in ({"series_s": True}, {"series_x": True}, {}): + for frame_gen in (0, 2): + value = settings(hardware_rt=True, frame_gen=frame_gen, **series) + self.assertNotIn("LEONIDA_FG_WITH_RT", launcher.extra_variables(value)) + self.assertNotIn("LEONIDA_FG_WITH_RT", " ".join(launcher.play_command(value, repo="R", windows=True))) + # Typed in Advanced, it is passed as typed. + value = settings(hardware_rt=True, advanced="LEONIDA_FG_WITH_RT=1") + self.assertEqual(launcher.extra_variables(value), {"LEONIDA_FG_WITH_RT": "1"}) + + +SWITCHES_SNIPPET = """# The D3D12 runtime's `LEONIDA_*` variables + +It is **not** a list of recommended settings. + +## leonida + +| Name | Kind | A/B | L | F | Named in | In the code's words | +|---|---|---|---|---|---|---| +| `LEONIDA_AB` | see the code | | | yes | `leonida/leonida.rs` +41 | `LEONIDA_AB=<s>,<n>`: A & B | +| `LEONIDA_D3D12_DRED` | off unless set and not `0` | | yes | yes | `leonida/replay.rs` +8 | Whether DRED is on. | + +## leonida-gpu + +| Name | Kind | A/B | L | F | Named in | In the code's words | +|---|---|---|---|---|---|---| +| `LEONIDA_AHEAD_INDEX` | on, `0` turns it off | yes | | | `leonida-gpu/watch.rs` | `x=<a>\\|<b>` or `0` | +| `LEONIDA_lower` | see the code | | | | `x.rs` | not a name the advanced options take | +| `LEONIDA_SHORT` | see the code | +| `LEONIDA_EMPTY` | see the code | | | | `scripts/play-nvidia.ps1` | | + +## Only in tests + +Read by test code alone: `LEONIDA_A`, `LEONIDA_B`. +""" + + +class AdvancedModeTests(unittest.TestCase): + """The Advanced mode window's pure parts: reading d3d12/docs/switches.md and writing edits into the advanced + options (settings["advanced"]) that PLAY passes to -More.""" + + def test_the_table_is_read_with_its_sections_and_escapes(self): + rows = launcher.parse_switches(SWITCHES_SNIPPET) + self.assertEqual([r["name"] for r in rows], + ["LEONIDA_AB", "LEONIDA_D3D12_DRED", "LEONIDA_AHEAD_INDEX", "LEONIDA_EMPTY"]) + self.assertEqual([r["section"] for r in rows], ["leonida", "leonida", "leonida-gpu", "leonida-gpu"]) + ab, dred, ahead, empty = rows + self.assertEqual(ab["text"], "LEONIDA_AB=,: A & B") + self.assertEqual((ab["kind"], ab["ab"], ab["launcher"], ab["findings"]), ("see the code", False, False, True)) + self.assertEqual(dred["kind"], launcher.KIND_OFF_UNLESS_SET) + self.assertEqual((dred["launcher"], dred["findings"]), (True, True)) + self.assertEqual(ahead["kind"], launcher.KIND_ON_UNLESS_ZERO) + self.assertTrue(ahead["ab"]) + self.assertEqual(ahead["text"], "x=| or 0") # an escaped | stays in the cell + self.assertEqual(empty["text"], "") + self.assertEqual(launcher.parse_switches(""), []) + + def test_a_missing_file_reads_as_none(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertIsNone(launcher.read_switches(tmp)) + os.makedirs(os.path.join(tmp, "d3d12", "docs")) + Path(launcher.switches_file(tmp)).write_text(SWITCHES_SNIPPET, encoding="utf-8") + self.assertEqual(len(launcher.read_switches(tmp)), 4) + + def test_the_repositorys_list_reads_whole(self): + """Every LEONIDA_* row of switches.md is read, and the kinds are the generator's own words. The rows are + counted, not the header's "N names": a row added by hand (main's LEONIDA_TITLE_RANGE, 683 rows under a + header of 682) must not fail the launcher.""" + import re + path = ROOT / "d3d12" / "docs" / "switches.md" + if not path.is_file(): + self.skipTest("no d3d12/docs/switches.md") + text = path.read_text(encoding="utf-8") + rows = launcher.parse_switches(text) + self.assertEqual(len(rows), len(re.findall(r"^\| `LEONIDA_[A-Z0-9_]+` \|", text, re.M))) + self.assertGreater(len(rows), 600) + self.assertEqual(len({r["name"] for r in rows}), len(rows)) + generator = (ROOT / "tools" / "d3d12_switches.py").read_text(encoding="utf-8").replace("`", "") + for kind in (launcher.KIND_OFF_UNLESS_SET, launcher.KIND_ON_UNLESS_ZERO): + self.assertIn(f'"{kind}"', generator) + self.assertIn("not** a list of recommended", text) + + def test_edits_add_update_and_remove_pairs(self): + text = "LEONIDA_A=1; LEONIDA_B=2" + self.assertEqual(launcher.merge_advanced(text, {}), text) + self.assertEqual(launcher.merge_advanced("", {"LEONIDA_X": "1"}), "LEONIDA_X=1") + self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_C": " 3 "}), "LEONIDA_A=1; LEONIDA_B=2; LEONIDA_C=3") + self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_A": "9"}), "LEONIDA_A=9; LEONIDA_B=2") + self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_A": ""}), "LEONIDA_B=2") + self.assertEqual(launcher.merge_advanced(text, {"LEONIDA_B": None, "LEONIDA_A": ""}), "") + # A name twice: the first place takes the value, the later pair goes (parse_advanced kept the last one). + self.assertEqual(launcher.merge_advanced("LEONIDA_A=1;LEONIDA_A=2", {"LEONIDA_A": "5"}), "LEONIDA_A=5") + # Removing a name that is not there changes nothing but the separators. + self.assertEqual(launcher.merge_advanced("LEONIDA_A=1\nLEONIDA_B=2", {"LEONIDA_Z": ""}), + "LEONIDA_A=1; LEONIDA_B=2") + + def test_unknown_pairs_and_wrong_parts_are_kept_as_typed(self): + text = "LEONIDA_NOT_LISTED='a b'; junk; lower=1; LEONIDA_Q=\"x\"y\"; LEONIDA_A=1" + merged = launcher.merge_advanced(text, {"LEONIDA_A": "2", "LEONIDA_NEW": "on"}) + self.assertEqual(merged, "LEONIDA_NOT_LISTED='a b'; junk; lower=1; LEONIDA_Q=\"x\"y\"; LEONIDA_A=2; " + "LEONIDA_NEW=on") + values, wrong = launcher.parse_advanced(merged) + self.assertEqual(values, {"LEONIDA_NOT_LISTED": "a b", "LEONIDA_A": "2", "LEONIDA_NEW": "on"}) + self.assertEqual(wrong, ["junk", "lower=1", 'LEONIDA_Q="x"y"']) + + def test_values_that_cannot_be_passed_are_refused(self): + for value in ('a"b', '"', "a;b", "a\nb", "a\x00"): + self.assertTrue(launcher.advanced_value_problem(value), repr(value)) + with self.assertRaises(ValueError): + launcher.merge_advanced("LEONIDA_A=1", {"LEONIDA_A": value}) + for value in ("1", "o'k", "420+480,20,t.txt", "C:\\x y", "a|b"): + self.assertEqual(launcher.advanced_value_problem(value), "", repr(value)) + with self.assertRaises(ValueError): + launcher.merge_advanced("", {"PATH": "1"}) + # Removing a pair whose value parse_advanced refuses is allowed: that is how it gets fixed. + self.assertEqual(launcher.merge_advanced('LEONIDA_Q="a"b"', {"LEONIDA_Q": ""}), "") + + def test_the_value_hint_is_the_format_after_the_name(self): + hint = launcher.value_hint + # A bare number is an example, not a format: no hint (the field shows "value"). + self.assertEqual(hint("LEONIDA_FPS_LINE", "Whether the line is shown (LEONIDA_FPS_LINE=0: not; the menu changes it)."), "") + self.assertEqual(hint("LEONIDA_AB", "LEONIDA_AB=,[,..]: turns each switch on, then " + "off, every "), ",[,..]") + self.assertEqual(hint("LEONIDA_CAPTURE", "Saves frames to LEONIDA_CAPTURE=, one file each."), + "") + self.assertEqual(hint("LEONIDA_FG_LIMIT_FPS", "LEONIDA_FG_LIMIT_FPS=: Reflex holds the frames **shown** to " + "n a second"), "") + # A space inside <...> belongs to the format; a colon inside the format stays. + self.assertEqual(hint("LEONIDA_TELEPORT", "LEONIDA_TELEPORT=,,, moves the player"), + ",,,") + self.assertEqual(hint("LEONIDA_POKE", "LEONIDA_POKE=:,... writes bytes"), ":,...") + self.assertEqual(hint("LEONIDA_ASPECT", "LEONIDA_ASPECT=21:9|32:9||auto: the ratio"), + "21:9|32:9||auto") + # The sentence's own punctuation is not part of it. + self.assertEqual(hint("LEONIDA_X", "(set LEONIDA_X=). Then"), "") + self.assertEqual(hint("LEONIDA_X", "LEONIDA_X=flag|off) picks"), "flag|off") + self.assertEqual(hint("LEONIDA_X", "LEONIDA_X=<0..1>.... sharper"), "<0..1>") + self.assertEqual(hint("LEONIDA_X", 'LEONIDA_X=":;..." runs'), ":;...") + # Another name that ends the same, or no NAME= at all: no hint. + self.assertEqual(hint("LEONIDA_AB", "LEONIDA_FG_AB=1 does"), "") + self.assertEqual(hint("LEONIDA_X", "Reads LEONIDA_X once at start."), "") + self.assertEqual(hint("LEONIDA_X", ""), "") + long = hint("LEONIDA_X", "LEONIDA_X=