From 4cb82adce3d56546042e3a0d10d120cefd497e59 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:17:28 +0100 Subject: [PATCH] refactor: keep detection lines as data Detection now keeps what it says in DETECTION_NOTES and prints it only in line mode. The full screen reads the list under detection_held() instead of capturing stdout and stderr and dropping refusals by comparing text, which said a refusal twice once screen_text escaped its folder. --- install.ps1 | 2 +- install.py | 63 ++++++++++++++++++++++++++--------- install.sh | 2 +- install/launchers/index.json | 16 ++++----- installer/detect_frontends.py | 13 ++++---- installer/detect_os.py | 5 +-- installer/detection_notes.py | 39 ++++++++++++++++++++++ installer/host_fs.py | 4 +-- installer/setups.py | 4 ++- installer/tui_session.py | 11 +++--- tests/test_install_tui.py | 31 +++++++++++++++++ wiki/architecture.md | 2 +- 12 files changed, 148 insertions(+), 44 deletions(-) create mode 100644 installer/detection_notes.py diff --git a/install.ps1 b/install.ps1 index e3d5eaf2c..98e8ffb92 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08" + $defaultInstallSha256 = "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index ae8e3be5f..42df4a838 100644 --- a/install.py +++ b/install.py @@ -66,6 +66,41 @@ except ImportError as _missing: sys.exit(1) +# --- installer/detection_notes.py -------------------------------------------- + +# Each line detection said, in order, other than a folder it could not look +# in (_DETECTION_REFUSED keeps those): a system found with no folder, a +# configuration naming a folder nobody can type, an Android folder out of +# reach, a card that fits two systems. +DETECTION_NOTES: list[str] = [] +# Set while the full screen runs detection: it shows the notes and the +# refusals itself, and a line printed under it would tear the screen. +_HELD = {"active": False} + + +def echo_detection(line: str, stream: TextIO | None = None) -> None: + """Print a line detection says, unless the screen shows it itself.""" + if not _HELD["active"]: + print(line, file=stream if stream is not None else sys.stderr) + + +def note_detection(line: str, stream: TextIO | None = None) -> None: + """Keep a line detection says, and print it in line mode.""" + DETECTION_NOTES.append(line) + echo_detection(line, stream) + + +@contextlib.contextmanager +def detection_held() -> Iterator[None]: + """Detection that keeps its lines without printing them.""" + outer = _HELD["active"] + _HELD["active"] = True + try: + yield + finally: + _HELD["active"] = outer + + # --- installer/embedded.py --------------------------------------------------- # Frontends whose BIOS live on their SD card, installed from a computer the @@ -1690,7 +1725,7 @@ def _note_refused(path: Path, exc: OSError) -> None: _DETECTION_UNREADABLE.add(refused[0]) words = refused_words(*refused) EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words) - print(f" {screen_text(words)}", file=sys.stderr) + echo_detection(f" {screen_text(words)}") def _held(path: Path) -> bool: @@ -4947,7 +4982,7 @@ def _detect_embedded() -> list[tuple[str, Path]]: reason = _NO_FOLDER.get( name, "nothing on it names the folder its RetroArch reads") closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest." - print(f"{name} found here, but {reason}.{closing}", file=sys.stderr) + note_detection(f"{name} found here, but {reason}.{closing}") continue _DETECTED_OS[(plat, folder)] = name found.append((plat, folder)) @@ -5029,7 +5064,7 @@ def _note_windows_unasked() -> None: _DETECTION_REFUSED.append(refused) words = refused_words(*refused) EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words) - print(f" {screen_text(words)}", file=sys.stderr) + echo_detection(f" {screen_text(words)}") def _winreg_value(key: str, value: str) -> str | None: @@ -5743,10 +5778,9 @@ def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None: if not rd_home: # A home moved to an SD card lives only in this file: the # default is a guess, and the user is told so. - print( + note_detection( f"Warning: could not read paths.rd_home_path from " f"{retrodeck_json}: assuming {home / 'retrodeck'}", - file=sys.stderr, ) rd_root = Path(rd_home) if rd_home else home / "retrodeck" _record_moved_folders(rd_root, retrodeck_json) @@ -5868,9 +5902,9 @@ def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]] # setup reads the folder named. if name not in _UNNAMEABLE: _UNNAMEABLE.append(name) - print(f" {display_name(name)}: the folder its configuration names holds a " - f"control character ({shown_path(path)}). Name its BIOS folder with " - "--dest.", file=sys.stderr) + note_detection(f" {display_name(name)}: the folder its configuration names " + f"holds a control character ({shown_path(path)}). Name its BIOS " + "folder with --dest.") continue kept.append((name, path)) return kept @@ -5886,7 +5920,7 @@ def detect_platforms(os_type: str) -> list[tuple[str, Path]]: if os_type == "android": found.extend(_detect_android()) for line in android_unreachable_folders(): - print(line, file=sys.stderr) + note_detection(line) if os_type in ("linux", "wsl"): found.extend(_detect_embedded()) @@ -14372,7 +14406,7 @@ def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]: # A drive whose files fit two systems is said, never guessed. words = doubt_words(mount) if words: - print(f" {words}") + note_detection(f" {words}", sys.stdout) continue if (card[0], card[1]) not in found and card[2] not in here: _DETECTED_OS.setdefault((card[0], card[1]), card[2]) @@ -30633,19 +30667,18 @@ def _tui_take_args(state: TuiState, args: argparse.Namespace) -> None: def _tui_detect(state: TuiState, os_type: str) -> None: """The setups and cards found here, and what detection said.""" - captured = io.StringIO() - with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured): + start = len(DETECTION_NOTES) + with detection_held(): state.setups, state.mounted_setups = found_setups(os_type) frontends = detect_frontends(os_type) # Said on the normal screen before this one covered it, and kept # above the list: a status line under 18 setups was never drawn. state.refused = [refused_words(folder, why, _short_path(folder, state.home)) for folder, why in _DETECTION_REFUSED] - unsaid = {refused_words(*refused) for refused in _DETECTION_REFUSED} if "esde" in frontends: state.notes.append(TUI_ESDE_NOTE) - state.notes += [line.strip() for line in captured.getvalue().splitlines() - if line.strip() and line.strip() not in unsaid] + state.notes += [line.strip() for note in DETECTION_NOTES[start:] + for line in note.splitlines() if line.strip()] def _start_on_platform(state: TuiState, args: argparse.Namespace, plat: str, diff --git a/install.sh b/install.sh index 4d6f557f1..337b4b83f 100755 --- a/install.sh +++ b/install.sh @@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins # curl or wget stop on a cut transfer before the hash is read: the site's # build rewrites this line there (scripts/sitebootstrap.py). MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." -DEFAULT_INSTALL_SHA256="27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08" +DEFAULT_INSTALL_SHA256="9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. MAX_INSTALLER_BYTES=8388608 diff --git a/install/launchers/index.json b/install/launchers/index.json index 1974da18c..5a84595f0 100644 --- a/install/launchers/index.json +++ b/install/launchers/index.json @@ -27,8 +27,8 @@ { "dest": "roms/ports/retrobios/install.py", "repo_path": "install.py", - "size": 1450927, - "sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08", + "size": 1449987, + "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1504552, - "sha256": "7011d54d1dbf6dbf135f319c17bc3a4ba1d57a479ccb0442086a7a3b0457d86b" + "size": 1503612, + "sha256": "4247f8fe1a0aee1d958ce838701795d176fb4725a32e12a6ce601af4f9a39030" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1450927, - "sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08", + "size": 1449987, + "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1450927, - "sha256": "27533551d40958a3c9405f05d7900478298261dd07a4d3e7d485a59be99d7e08", + "size": 1449987, + "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", "executable": false }, { diff --git a/installer/detect_frontends.py b/installer/detect_frontends.py index 6474aaee5..bceb29c4c 100644 --- a/installer/detect_frontends.py +++ b/installer/detect_frontends.py @@ -5,7 +5,6 @@ import contextlib import functools import os import re -import sys import xml.etree.ElementTree as ET from collections.abc import Callable, Iterator from pathlib import Path @@ -18,6 +17,7 @@ from installer.config_values import ( _retroarch_cfg_dir, _retroarch_cfg_value, ) +from installer.detection_notes import note_detection from installer.detect_os import ( _detect_embedded, _macos_retroarch_base, @@ -693,10 +693,9 @@ def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None: if not rd_home: # A home moved to an SD card lives only in this file: the # default is a guess, and the user is told so. - print( + note_detection( f"Warning: could not read paths.rd_home_path from " f"{retrodeck_json}: assuming {home / 'retrodeck'}", - file=sys.stderr, ) rd_root = Path(rd_home) if rd_home else home / "retrodeck" _record_moved_folders(rd_root, retrodeck_json) @@ -818,9 +817,9 @@ def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]] # setup reads the folder named. if name not in _UNNAMEABLE: _UNNAMEABLE.append(name) - print(f" {display_name(name)}: the folder its configuration names holds a " - f"control character ({shown_path(path)}). Name its BIOS folder with " - "--dest.", file=sys.stderr) + note_detection(f" {display_name(name)}: the folder its configuration names " + f"holds a control character ({shown_path(path)}). Name its BIOS " + "folder with --dest.") continue kept.append((name, path)) return kept @@ -836,7 +835,7 @@ def detect_platforms(os_type: str) -> list[tuple[str, Path]]: if os_type == "android": found.extend(_detect_android()) for line in android_unreachable_folders(): - print(line, file=sys.stderr) + note_detection(line) if os_type in ("linux", "wsl"): found.extend(_detect_embedded()) diff --git a/installer/detect_os.py b/installer/detect_os.py index a9abe5834..fdc24fa46 100644 --- a/installer/detect_os.py +++ b/installer/detect_os.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING from installer.cards import card_platform, setup_bios_folder from installer.config_values import _RETROARCH_CONFIGS, _parse_retroarch_system_dir +from installer.detection_notes import echo_detection, note_detection from installer.embedded import CARD_MARKER, _EMBEDDED_RULES, _NO_FOLDER from installer.events import EVENTS from installer.host_fs import ( @@ -301,7 +302,7 @@ def _detect_embedded() -> list[tuple[str, Path]]: reason = _NO_FOLDER.get( name, "nothing on it names the folder its RetroArch reads") closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest." - print(f"{name} found here, but {reason}.{closing}", file=sys.stderr) + note_detection(f"{name} found here, but {reason}.{closing}") continue _DETECTED_OS[(plat, folder)] = name found.append((plat, folder)) @@ -383,7 +384,7 @@ def _note_windows_unasked() -> None: _DETECTION_REFUSED.append(refused) words = refused_words(*refused) EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words) - print(f" {screen_text(words)}", file=sys.stderr) + echo_detection(f" {screen_text(words)}") def _winreg_value(key: str, value: str) -> str | None: diff --git a/installer/detection_notes.py b/installer/detection_notes.py new file mode 100644 index 000000000..1f0bc9139 --- /dev/null +++ b/installer/detection_notes.py @@ -0,0 +1,39 @@ +"""What detection says, kept as lines the screen reads and printed as it comes in line mode.""" +from __future__ import annotations + +import contextlib +import sys +from collections.abc import Iterator +from typing import TextIO + +# Each line detection said, in order, other than a folder it could not look +# in (_DETECTION_REFUSED keeps those): a system found with no folder, a +# configuration naming a folder nobody can type, an Android folder out of +# reach, a card that fits two systems. +DETECTION_NOTES: list[str] = [] +# Set while the full screen runs detection: it shows the notes and the +# refusals itself, and a line printed under it would tear the screen. +_HELD = {"active": False} + + +def echo_detection(line: str, stream: TextIO | None = None) -> None: + """Print a line detection says, unless the screen shows it itself.""" + if not _HELD["active"]: + print(line, file=stream if stream is not None else sys.stderr) + + +def note_detection(line: str, stream: TextIO | None = None) -> None: + """Keep a line detection says, and print it in line mode.""" + DETECTION_NOTES.append(line) + echo_detection(line, stream) + + +@contextlib.contextmanager +def detection_held() -> Iterator[None]: + """Detection that keeps its lines without printing them.""" + outer = _HELD["active"] + _HELD["active"] = True + try: + yield + finally: + _HELD["active"] = outer diff --git a/installer/host_fs.py b/installer/host_fs.py index d3e233f02..40f8485b3 100644 --- a/installer/host_fs.py +++ b/installer/host_fs.py @@ -7,13 +7,13 @@ import os import re import shutil import stat -import sys import tempfile import threading from collections.abc import Callable from pathlib import Path from typing import Any +from installer.detection_notes import echo_detection from installer.events import EVENTS from installer.text import screen_text @@ -103,7 +103,7 @@ def _note_refused(path: Path, exc: OSError) -> None: _DETECTION_UNREADABLE.add(refused[0]) words = refused_words(*refused) EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words) - print(f" {screen_text(words)}", file=sys.stderr) + echo_detection(f" {screen_text(words)}") def _held(path: Path) -> bool: diff --git a/installer/setups.py b/installer/setups.py index d69c4ac34..ec16d3c5b 100644 --- a/installer/setups.py +++ b/installer/setups.py @@ -3,6 +3,7 @@ from __future__ import annotations import os import re +import sys from pathlib import Path from typing import TYPE_CHECKING @@ -19,6 +20,7 @@ from installer.cards import ( drive_kind, ) from installer.console import _ask, _quit +from installer.detection_notes import note_detection from installer.detect_frontends import _UNNAMEABLE, _android_storage_root, detect_platforms from installer.detect_os import ( _DETECTED_OS, @@ -555,7 +557,7 @@ def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]: # A drive whose files fit two systems is said, never guessed. words = doubt_words(mount) if words: - print(f" {words}") + note_detection(f" {words}", sys.stdout) continue if (card[0], card[1]) not in found and card[2] not in here: _DETECTED_OS.setdefault((card[0], card[1]), card[2]) diff --git a/installer/tui_session.py b/installer/tui_session.py index c780d9ca8..ac7195403 100644 --- a/installer/tui_session.py +++ b/installer/tui_session.py @@ -3,7 +3,6 @@ from __future__ import annotations import argparse import codecs -import contextlib import errno import functools import io @@ -24,6 +23,7 @@ from installer.cards import _SHARE_FOLDERS, _mounted_cards, card_bound, card_pla from installer.console import QUIT_CODE from installer.destination import card_choice, dest_default from installer.detect_frontends import detect_frontends +from installer.detection_notes import DETECTION_NOTES, detection_held from installer.detect_os import _enter_wsl, _wsl_dest, detect_os, detected_os from installer.from_folders import _open_local_sources, from_folder_problem from installer.host_fs import _DETECTION_REFUSED, refused_words @@ -135,19 +135,18 @@ def _tui_take_args(state: TuiState, args: argparse.Namespace) -> None: def _tui_detect(state: TuiState, os_type: str) -> None: """The setups and cards found here, and what detection said.""" - captured = io.StringIO() - with contextlib.redirect_stdout(captured), contextlib.redirect_stderr(captured): + start = len(DETECTION_NOTES) + with detection_held(): state.setups, state.mounted_setups = found_setups(os_type) frontends = detect_frontends(os_type) # Said on the normal screen before this one covered it, and kept # above the list: a status line under 18 setups was never drawn. state.refused = [refused_words(folder, why, _short_path(folder, state.home)) for folder, why in _DETECTION_REFUSED] - unsaid = {refused_words(*refused) for refused in _DETECTION_REFUSED} if "esde" in frontends: state.notes.append(TUI_ESDE_NOTE) - state.notes += [line.strip() for line in captured.getvalue().splitlines() - if line.strip() and line.strip() not in unsaid] + state.notes += [line.strip() for note in DETECTION_NOTES[start:] + for line in note.splitlines() if line.strip()] def _start_on_platform(state: TuiState, args: argparse.Namespace, plat: str, diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 7de95bf2d..28827959b 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -4723,6 +4723,37 @@ class AFolderThisUserCannotOpen(unittest.TestCase): # The list keeps its focused row in view. self.assertIn("RetroArch", screen) + def test_detection_lines_are_read_not_captured(self): + """The screen read detection's lines by capturing stdout and stderr, + and dropped a refusal by comparing its printed text: a folder whose + name the terminal text escapes was then said twice.""" + closed = self.lock.parent / "esc\x1bape" + closed.mkdir() + os.chmod(closed, 0o000) + self.addCleanup(os.chmod, closed, 0o755) + install._DETECTION_REFUSED.clear() + self.addCleanup(install._DETECTION_REFUSED.clear) + + def detect(_os_type: str) -> list: + install._SETUP_SEARCH.active = True + try: + install._is_dir(closed / "bios") + install.note_detection("Batocera found here, but no folder.") + finally: + install._SETUP_SEARCH.active = False + return [] + + with mock.patch.object(install, "detect_platforms", side_effect=detect), \ + mock.patch.object(install, "detect_frontends", return_value=[]), \ + mock.patch.object(install, "_mounted_cards", return_value=[]), \ + contextlib.redirect_stdout(io.StringIO()) as out, \ + contextlib.redirect_stderr(io.StringIO()) as err: + state, _effects = install.tui_start(_args(), "linux") + self.assertEqual((out.getvalue(), err.getvalue()), ("", "")) + self.assertEqual(install._DETECTION_REFUSED, [(closed, "Permission denied")]) + self.assertEqual(len(state.refused), 1) + self.assertEqual(state.notes, ["Batocera found here, but no folder."]) + class AGoesIntoASubfolder(unittest.TestCase): """At HOME or a drive root A went into the first "dir" row: a mounted diff --git a/wiki/architecture.md b/wiki/architecture.md index ebed28cab..4931c53b4 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -500,7 +500,7 @@ those it imports: | Shared words and limits | `remote`, `regions`, `platforms`, `manifest`, `embedded`, `text`, `events`, `invocation` | | Terminal and line output | `terminal`, `console` | | Files and folders | `host_fs`, `paths`, `filesystems`, `config_values`, `local_check`, `safe_replace` | -| This machine | `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | +| This machine | `detection_notes`, `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | | Sources of files | `offline`, `network`, `pack_source`, `from_folders`, `diagnosis`, `download`, `datadirs`, `standalone` | | What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `game_files`, `games`, `tally` | | Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `outcome` |