From 6b597f85a0973fb708db0cdd69eab56ea9dcd044 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:54:19 +0100 Subject: [PATCH] refactor: give each installer module one role The split had pushed each helper down into the lowest module using it. Names now sit with the concern they belong to (68 modules, 45 before), each with a one-line docstring saying it, and the import graph stays acyclic. Statement source and comments moved unchanged: every top-level statement of install.py keeps an identical ast.dump. --- install.ps1 | 2 +- install.py | 31727 ++++++++-------- install.sh | 2 +- install/launchers/index.json | 16 +- installer/arguments.py | 4 +- installer/cards.py | 1310 +- installer/choices.py | 354 +- installer/cli.py | 22 +- installer/config_values.py | 177 + installer/console.py | 275 + installer/constants.py | 256 - installer/cores.py | 368 +- installer/datadirs.py | 51 +- installer/destination.py | 722 + installer/detect_frontends.py | 149 +- installer/detect_os.py | 572 +- installer/device.py | 264 + installer/diagnosis.py | 358 + installer/download.py | 133 +- installer/embedded.py | 611 +- installer/events.py | 9 + installer/filesystems.py | 186 + installer/from_folders.py | 439 +- .../{local_files.py => frontend_folders.py} | 237 +- installer/game_files.py | 716 + installer/games.py | 754 +- installer/{app.py => handheld_app.py} | 27 +- installer/{probe.py => host_fs.py} | 119 +- installer/{record.py => install_record.py} | 374 +- installer/invocation.py | 2 +- installer/line_folder.py | 418 + installer/line_menu.py | 649 + installer/line_ui.py | 1456 - installer/local_check.py | 176 + installer/manifest.py | 67 +- installer/narrowing.py | 243 +- installer/network.py | 83 +- installer/offline.py | 8 +- installer/outcome.py | 208 +- installer/pack.py | 124 +- installer/pack_source.py | 222 +- installer/paths.py | 57 +- installer/plan.py | 191 +- installer/plan_words.py | 307 + installer/platform_choice.py | 154 - installer/platforms.py | 293 + installer/prompt.py | 68 - installer/regions.py | 124 + installer/remote.py | 85 + installer/removal.py | 52 +- installer/romm.py | 160 + installer/run.py | 1446 +- installer/run_files.py | 844 + installer/run_setups.py | 486 + installer/safe_replace.py | 464 + installer/setups.py | 224 +- installer/standalone.py | 40 +- installer/tally.py | 146 +- installer/terminal.py | 192 +- installer/text.py | 41 +- installer/tui_actions.py | 594 +- installer/tui_choice.py | 570 + installer/tui_commands.py | 321 + installer/tui_engine.py | 311 + installer/tui_frame.py | 584 + installer/{tui_update.py => tui_input.py} | 481 +- installer/{tui_text.py => tui_keys.py} | 211 +- installer/tui_outcome.py | 555 + installer/tui_paint.py | 224 + installer/tui_plan_view.py | 781 + installer/tui_receive.py | 325 + installer/tui_results.py | 648 - installer/tui_routes.py | 331 + installer/tui_rows.py | 1033 +- installer/tui_screens.py | 1024 + installer/tui_session.py | 452 +- installer/tui_state.py | 655 +- installer/tui_view.py | 2334 -- 78 files changed, 30571 insertions(+), 30127 deletions(-) create mode 100644 installer/config_values.py create mode 100644 installer/console.py delete mode 100644 installer/constants.py create mode 100644 installer/destination.py create mode 100644 installer/device.py create mode 100644 installer/diagnosis.py create mode 100644 installer/filesystems.py rename installer/{local_files.py => frontend_folders.py} (63%) create mode 100644 installer/game_files.py rename installer/{app.py => handheld_app.py} (94%) rename installer/{probe.py => host_fs.py} (62%) rename installer/{record.py => install_record.py} (68%) create mode 100644 installer/line_folder.py create mode 100644 installer/line_menu.py delete mode 100644 installer/line_ui.py create mode 100644 installer/local_check.py create mode 100644 installer/plan_words.py delete mode 100644 installer/platform_choice.py create mode 100644 installer/platforms.py delete mode 100644 installer/prompt.py create mode 100644 installer/regions.py create mode 100644 installer/remote.py create mode 100644 installer/romm.py create mode 100644 installer/run_files.py create mode 100644 installer/run_setups.py create mode 100644 installer/safe_replace.py create mode 100644 installer/tui_choice.py create mode 100644 installer/tui_commands.py create mode 100644 installer/tui_engine.py create mode 100644 installer/tui_frame.py rename installer/{tui_update.py => tui_input.py} (65%) rename installer/{tui_text.py => tui_keys.py} (51%) create mode 100644 installer/tui_outcome.py create mode 100644 installer/tui_paint.py create mode 100644 installer/tui_plan_view.py create mode 100644 installer/tui_receive.py delete mode 100644 installer/tui_results.py create mode 100644 installer/tui_routes.py create mode 100644 installer/tui_screens.py delete mode 100644 installer/tui_view.py diff --git a/install.ps1 b/install.ps1 index 62fb41c14..e8501a919 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 = "23d7586b7fac5e0e98e9f5e68cc389e2557cc448fc6e4329bd6ee322e8df32a6" + $defaultInstallSha256 = "0c27d4025521677f3fe1d3435f794921d4d4187e50585553d5f5d5a6e21ed935" # 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 b01d5549b..0be61cbbf 100644 --- a/install.py +++ b/install.py @@ -66,103 +66,253 @@ except ImportError as _missing: sys.exit(1) -# --- installer/constants.py -------------------------------------------------- +# --- installer/embedded.py --------------------------------------------------- -# File lists are read from main, the newest ones, whichever commit the -# installer came from. RETROBIOS_REF pins them to a tag or a commit when -# reproducibility matters. -DEFAULT_RELEASE_REF = "main" -RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF) -DEFAULT_BASE_URL = ( - "https://raw.githubusercontent.com/Abdess/retrobios/" - + urllib.parse.quote(RELEASE_REF, safe="") +# Frontends whose BIOS live on their SD card, installed from a computer the +# card is mounted on. Each release unpacks as .system/ at the card root and +# writes its release name as the first line of .system/version.txt (MinUI +# makefile:22-24 and 152-157, NextUI makefile:33-35 and 249, MyMinUI +# makefile:16-19 and 124). The registry publishes the same rules as each +# manifest's `detect` (card_marker), and a test holds the two equal. +CARD_MARKER = ".system/version.txt" +_CARD_RULES: tuple[tuple[str, str, str], ...] = ( + ("minui", CARD_MARKER, "MinUI-"), + ("nextui", CARD_MARKER, "NextUI-"), + ("myminui", CARD_MARKER, "MyMinUI-"), ) +CARD_PLATFORMS = frozenset(name for name, _file, _prefix in _CARD_RULES) -_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1") +class _OsRule(NamedTuple): + """One piece of evidence that names an embedded system. - -def _checked_base_url(value: str) -> str: - """Refuse a base URL that is neither HTTPS nor loopback. - - This base serves the manifest and the files it declares, so whoever - controls it controls the expected hashes too and verification stops - proving anything. install.sh and install.ps1 make the same check on the - URL they fetch the installer from. - - Plain HTTP to loopback stays allowed: nothing sits between the two ends - to intercept it, and it is how the installer is exercised end to end. + manifest is the platform whose files it gets, "" for a system the + installer does not lay out. name is the system's own name. values are the + KEY=value pairs of os_release (any one), the files of file_exists (all), + or the file and the pattern of file_matches. bios is the folder used when + none of configs (retroarch.cfg files, read in order, `*` allowed) names a + system_directory. home is what `~` means to that system's RetroArch. + base is the system this one is built on: both match, this one is meant. """ - parsed = urllib.parse.urlparse(value) - if parsed.scheme == "https": - return value - host = (parsed.hostname or "").lower() - if parsed.scheme == "http" and host in _LOOPBACK_HOSTS: - return value - print( - f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}", - file=sys.stderr, - ) - sys.exit(1) + + manifest: str + name: str + method: str + values: tuple[str, ...] + bios: str | None + configs: tuple[str, ...] = () + home: str = "" + base: str = "" -BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL)) -MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json" -TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json" -# What --standalone reads, apart from the list every run downloads. -STANDALONE_DIR = "standalone" -STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json" -# The platforms that publish a core list per board, install/targets/ in the -# repository: a test holds the two equal. Offline, a platform outside it -# has no hardware targets, where the run sent the user after a list that -# exists nowhere. -TARGET_PLATFORMS = frozenset({ - "amberelec", "batocera", "emudeck", "emuelec", "knulli", "lakka", "recalbox", "retroarch", - "retrobat", "retrodeck", "retropie", "rocknix", "romm", -}) -RAW_FILE_URL = f"{BASE_URL}/{{path}}" -RELEASE_URL = ( - "https://github.com/Abdess/retrobios/releases/download/large-files/{asset}" -) -MAX_RETRIES = 3 -# Seconds a connection has to open. A dropped network cost three tries of a -# 30-second timeout, 93 s, before the error: a connection that does not open -# now fails in this time, and once open a read waits as long as before, so -# a slow line is not cut. -CONNECT_TIMEOUT = 4.0 -MAX_MANIFEST_BYTES = 16 * 1024 * 1024 -MAX_TARGETS_BYTES = 4 * 1024 * 1024 -MAX_STANDALONE_BYTES = 16 * 1024 * 1024 -MAX_MANIFEST_FILES = 100_000 -MAX_DOWNLOAD_SIZE = 1024 * 1024 * 1024 -# A data directory's source archive: PCSX2's source tarball is the largest. -MAX_DATA_ARCHIVE_SIZE = 4 * 1024 * 1024 * 1024 -MAX_TOTAL_DOWNLOAD_SIZE = 64 * 1024 * 1024 * 1024 -# Why a manifest leaves a file out, as the installer words it. The manifest -# schema and the generator are held to this list by the tests. -OMISSION_REASONS = { - "hash_mismatch": "hash mismatch", - "not_found": "not found", - "external": "external", - "user_provided": "user provided", - "no_platform_slug": "no platform folder", - "below_platform_folder": "below the platform folder", - "no_save_directory": "no save directory", - "no_core_folder": "no core folder", - "no_save_system": "no system runs the core", - "outside_bios_folder": "read outside the BIOS folder", - "no_roms_directory": "no roms folder", - "no_configs_directory": "no configs folder", - "no_emulators_directory": "no emulator folder", +# The platform whose files each of these systems gets. They publish their own +# BIOS list, and these platforms transcribe it. +_STANDIN_MANIFESTS = { + "AmberELEC": "amberelec", + "EmuELEC": "emuelec", + "KNULLI": "knulli", } -# What a file is when it is not firmware, as the manifest's category field -# says, and as the installer words it. Firmware carries no category. -GAME_DATA = "game_data" -CATEGORY_LABELS = {GAME_DATA: "game data"} -# The manifest writes its digests in lowercase, as hashlib gives them, and -# every comparison reads them as written. -_SHA1_RE = re.compile(r"^[0-9a-f]{40}$") -_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + +# Where the ELEC family keeps RetroArch: the config runemu writes and copies +# back on every launch, and HOME=/storage for the services that start it. +_ELEC_CONFIGS = ("/storage/.config/retroarch/retroarch.cfg",) +# ArkOS and dArkOS: the 64-bit and the 32-bit RetroArch. "Switch to SD2 for +# Roms" rewrites /roms/ to /roms2/ in both (darkos daecf488, +# scripts/Switch to SD2 for Roms.sh:91-92), so a second card is read here. +_ARK_CONFIGS = ("/home/ark/.config/retroarch/retroarch.cfg", + "/home/ark/.config/retroarch32/retroarch.cfg") +_PLYMOUTH_TITLE = "/usr/share/plymouth/themes/text.plymouth" + +# muOS runs RetroArch on the config it copies from its default on first launch +# (internal f41f4a89, script/control/retroarch.sh:8-20). The default names +# /run/muos/storage/bios, a bind mount of MUOS/bios on the second card when +# that card holds one, else on the first (script/device/bind.sh:4,116-150), +# and loads cores from /opt/muos/share/core (retroarch.default.cfg:2806,3151). +MUOS_RETROARCH_CONFIGS = ( + "/opt/muos/share/info/config/retroarch.cfg", + "/opt/muos/share/emulator/retroarch/retroarch.default.cfg", +) + +# Embedded systems, by what their own builds write. The registry publishes the +# same rules as each manifest's `detect`, and a test holds the two equal. +# MiSTer is a path rule below. +_EMBEDDED_RULES: tuple[_OsRule, ...] = ( + # ROCKNIX writes OS_NAME and no ID since 2025 (scripts/image). Older + # images wrote ID=rocknix. + _OsRule("rocknix", "ROCKNIX", "os_release", ("OS_NAME=rocknix", "ID=rocknix"), + "/storage/roms/bios"), + # Knulli (knulli-linux 57afa662): OS_NAME in os-release + # (board/scripts/post-build-script.sh:233-236) and knulli.version + # (package/system/knulli-system/knulli-system.mk:98-102). + _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "os_release", ("OS_NAME=knulli",), + "/userdata/bios", base="Batocera"), + _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "file_exists", + ("/usr/share/knulli/knulli.version",), "/userdata/bios", base="Batocera"), + _OsRule("lakka", "Lakka", "os_release", ("ID=lakka",), "/storage/system"), + # batocera.linux 38845725, batocera-system.mk:21-22 (the same lines in + # batocera-30): batocera.arch and batocera.version. + _OsRule("batocera", "Batocera", "file_exists", ("/usr/share/batocera/batocera.version",), + "/userdata/bios"), + _OsRule("recalbox", "Recalbox", "file_exists", ("/recalbox/recalbox.version",), + "/recalbox/share/bios"), + _OsRule("recalbox", "Recalbox", "file_exists", ("/usr/bin/recalbox-settings",), + "/recalbox/share/bios"), + _OsRule("retroarch", "muOS", "file_exists", ("/opt/muos",), "/run/muos/storage/bios", + configs=MUOS_RETROARCH_CONFIGS), + _OsRule("retroarch", "muOS", "file_exists", ("/mnt/mmc/MUOS",), "/mnt/mmc/MUOS/bios"), + # AmberELEC 5a3882cb: scripts/image:150-152 writes NAME="${DISTRONAME}", + # AmberELEC in distributions/AmberELEC/options:17. CHAos (tech4bot/AmberELEC + # c0a4b0c6) is built from the same tree and writes the same name + # (distributions/AmberELEC/options:14). runemu.py:22 launches with + # /storage/.config/retroarch/retroarch.cfg, whose default is "~/roms/bios" + # (packages/games/tools/retroarch/sources/retroarch.cfg:611), and + # emustation.service:6 sets HOME=/storage. + _OsRule(_STANDIN_MANIFESTS["AmberELEC"], "AmberELEC", "os_release", ("NAME=AmberELEC",), + "/storage/roms"), + # PAN4ELEC (Kegg1701/P4ELEC 9c19bfb2), an overlay on an AmberELEC image: + # AmberELEC/usr/bin/batocera-info:101 prints its name. + _OsRule(_STANDIN_MANIFESTS["AmberELEC"], "PAN4ELEC", "file_matches", + ("/usr/bin/batocera-info", r"OPERATING SYSTEM: PAN4ELEC"), + "/storage/roms", base="AmberELEC"), + # EmuELEC d4c7b2f1: scripts/image:172-176 NAME and ID from DISTRONAME, + # EmuELEC in distributions/EmuELEC/options:4. setsettings.sh:22 names the + # config, and libretro_base/retroarch/package.mk:117 sets its + # system_directory to /storage/roms/bios. + _OsRule(_STANDIN_MANIFESTS["EmuELEC"], "EmuELEC", "os_release", ("NAME=EmuELEC",), + "/storage/roms"), + # JELOS 7b2e116c: scripts/image:118-120 OS_NAME="${DISTRONAME}", JELOS in + # distributions/JELOS/options:17. runemu.sh:37 names the config, whose + # default is "~/roms/bios" (retroarch/sources/RK3566/retroarch.cfg:716), + # and emustation.service:8 sets HOME=/storage. + _OsRule("retroarch", "JELOS", "os_release", ("OS_NAME=JELOS",), + "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), + # KOLOS (AnonLinuxOS/KOLOS 7daf5950) keeps OS_NAME=JELOS + # (distributions/JELOS/options:17) and adds jelos-ready.service + # ("KOLOS system ready script"), installed by scripts/install:100-102. + _OsRule("retroarch", "KOLOS", "file_exists", + ("/usr/lib/systemd/system/jelos-ready.service",), + "/storage/roms/bios", _ELEC_CONFIGS, "/storage", base="JELOS"), + # UnofficialOS 22635796: scripts/image:119-120 OS_NAME, UnofficialOS in + # distributions/UnofficialOS/options:17, config at + # packages/unofficialos/sources/scripts/runemu.sh:37. + _OsRule("retroarch", "UnofficialOS", "os_release", ("OS_NAME=UnofficialOS",), + "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), + # Arch R (archr-linux/Arch-R dbd45d45): scripts/image:164-177 NAME and + # OS_NAME, ArchR in distributions/ArchR/options:17. factoryreset:9-10 + # names the config, whose default is "~/roms/bios" + # (retroarch/sources/RK3326/retroarch.cfg:718). + _OsRule("retroarch", "ArchR", "os_release", ("OS_NAME=ArchR",), + "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), + # ArkOS: the user and the menu folder, and the boot splash title its + # updates write (christianhaitian/arkos dedf4278, Update-RGB10.sh:76). + _OsRule("retroarch", "ArkOS", "file_exists", ("/home/ark", "/opt/system"), "/roms/bios", + _ARK_CONFIGS), + _OsRule("retroarch", "ArkOS", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*ArkOS\b"), + "/roms/bios", _ARK_CONFIGS), + # dArkOS daecf488: finishing_touches.sh:359-361 writes "title=dArkOS + # ()", kept by the dArkOSRE, dArkOSen and ArkOS4Clone overlays. + # Default system_directory "/roms/bios" (retroarch.cfg.rgb10:3043). + _OsRule("retroarch", "dArkOS", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*dArkOS"), + "/roms/bios", _ARK_CONFIGS, base="ArkOS"), + # RetroOZ 0.60 image (no build source is published): title=RetroOZ in + # the splash theme, /opt/.retrooz/version, and /etc/retrooz_version, the + # file PortMaster reads (device_info.txt:95). RetroArch is started with + # --config /home/odroid/.config/retroarch/retroarch.cfg (es_systems.cfg), + # system_directory "/roms/bios" (retroarch32/retroarch.cfg:3046). + _OsRule("retroarch", "RetroOZ", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*RetroOZ"), + "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", + "/home/odroid/.config/retroarch32/retroarch.cfg")), + _OsRule("retroarch", "RetroOZ", "file_exists", ("/opt/.retrooz",), + "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", + "/home/odroid/.config/retroarch32/retroarch.cfg")), + _OsRule("retroarch", "RetroOZ", "file_exists", ("/etc/retrooz_version",), + "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", + "/home/odroid/.config/retroarch32/retroarch.cfg")), + # TheRA is left undetected: no image or source of its Odroid Go builds is + # published, so neither its markers nor its folder could be read. + # spruceOS 824b1aae: the spruce folder at the card root. RetroArch reads + # Saves/ra-configs/retroarch-.cfg (spruce/scripts/ + # helperFunctions.sh:157-165), seeded with system_directory + # "/mnt/SDCARD/BIOS" (RetroArch/platform/retroarch-Brick.cfg.bak:3279). + _OsRule("retroarch", "spruceOS", "file_exists", ("/mnt/SDCARD/spruce",), + "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/Saves/ra-configs/retroarch-*.cfg",), + base="TrimUI"), + # CrossMix-OS 206d612f: crossmix-version.txt (System/usr/trimui/scripts/ + # update_common.sh:20), RetroArch/retroarch.cfg:3202 (patch_ra_cfg.sh:5). + _OsRule("retroarch", "CrossMix-OS", "file_exists", + ("/mnt/SDCARD/System/usr/trimui/crossmix-version.txt",), + "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/retroarch.cfg",), base="TrimUI"), + # Onion 07505ea5: Makefile:75-76 writes onionVersion/version.txt, and + # static/build/.tmp_update/script/patch_ra_cfg.sh:6 names the config + # (system_directory at static/configs/RetroArch/.retroarch/retroarch.cfg:3009). + _OsRule("retroarch", "Onion", "file_exists", + ("/mnt/SDCARD/.tmp_update/onionVersion/version.txt",), + "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), + # Allium ee0dda97: its base folder /mnt/SDCARD/.allium + # (crates/common/src/constants.rs:19-34). RetroArch runs with + # HOME=/mnt/SDCARD/RetroArch on .retroarch/retroarch.cfg + # (static/.allium/cores/retroarch/launch_without_savestate_auto_load.sh:2-7), + # and Allium's RetroArch patch makes $ROOT/BIOS the default system folder. + _OsRule("retroarch", "Allium", "file_exists", ("/mnt/SDCARD/.allium",), + "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), + # Koriki 8513071c: src/systemInfo/main.c:106 reads Koriki/version.txt, + # .tmp_update/runtime.sh:271 installs RetroArch/.retroarch/retroarch.cfg + # (system_directory at base/RetroArch/.retroarch/retroarch.cfg:3191). + _OsRule("retroarch", "Koriki", "file_exists", ("/mnt/SDCARD/Koriki/version.txt",), + "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), + # MiyooCFW (buildroot d5912eeb): board/miyoo/rootfs/etc/main sets HOME=/mnt + # (line 4), package/miyoo/miyoo-ctl/miyoo-ctl.mk:12 installs miyooctl. + # RetroArch is a DINGUX build: $HOME/.retroarch/retroarch.cfg, and + # $HOME/.retroarch/system when no config names a folder. + _OsRule("retroarch", "MiyooCFW", "file_exists", ("/etc/main", "/usr/bin/miyooctl"), + "/mnt/.retroarch/system", ("/mnt/.retroarch/retroarch.cfg",), "/mnt"), + # plumOS: os-release ID=plumos (game-de-it/plumOS-pixel2_v2 dec872c0, + # rootfs/pixel2/etc/os-release:2, PortMaster device_info.txt:101). Each + # device build appends its own system_directory at launch: the Pixel 2 + # build /mnt/plumos-user/bios (package/app-layer-pixel2/bin/ + # plumos-retroarch-launch:342, mount point made by rootfs/pixel2/sbin/ + # init:29), the MF build /BIOS (plumOS-MF 0095017c, + # plumos-retroarch-launch:15). Only the first is told apart by a file. + _OsRule("retroarch", "plumOS", "file_exists", ("/mnt/plumos-user",), + "/mnt/plumos-user/bios"), + _OsRule("retroarch", "plumOS", "os_release", ("ID=plumos",), None), + # TrimUI's stock firmware publishes no source naming its RetroArch BIOS + # folder. PortMaster finds its libraries in /usr/trimui + # (trimui/launch_hooks.txt:37). Named so that what runs on top of it is + # told apart, never installed to by a guess. + _OsRule("", "TrimUI", "file_exists", ("/usr/trimui",), None), + # MinUI, MyMinUI and NextUI keep their system in .system at the card root + # (MinUI dbf89435, workspace/all/common/defines.h:14-16) and give each core + # Bios// (workspace/all/minarch/minarch.c:2942). Their file lists + # write that layout below the card root, and the card's version.txt + # says which of the three it is (card_platform). + _OsRule("", "MinUI", "file_exists", ("/mnt/SDCARD/.system/res",), None, base="TrimUI"), + _OsRule("", "MinUI", "file_exists", ("/mnt/sdcard/.system/res",), None, base="TrimUI"), + _OsRule("retroarch", "Anbernic stock firmware", "file_exists", + ("/mnt/vendor/bin/dmenu.bin",), "/mnt/mmc/bios"), +) + + +def _a(name: str) -> str: + """A name with its article: an Onion, a muOS.""" + return f"{'an' if name[:1].lower() in 'aeiou' else 'a'} {name}" + + +def _built_on(name: str) -> str: + """The system name is built on (dArkOS on ArkOS), "" for none.""" + return next((rule.base for rule in _EMBEDDED_RULES if rule.name == name and rule.base), "") + + +# Why a system found here gets no folder: said once per run. +_NO_FOLDER = { + "TrimUI": "its firmware publishes no source naming the folder its RetroArch reads", + "MinUI": f"its card names no release in {CARD_MARKER}, which tells MinUI, NextUI " + "and MyMinUI apart. Name the card's root and the one it runs: " + "--platform minui (or nextui, myminui) --dest /mnt/SDCARD", +} + + +# --- installer/regions.py ---------------------------------------------------- # The region vocabulary of scripts/region.py, which this file cannot import. # A test holds the two copies equal. @@ -226,50 +376,134 @@ _REGION_PARENT = { member: parent for parent, members in REGION_TREE.items() for member in members } REGIONS = frozenset({WORLD_REGION} | set(REGION_TREE) | set(_REGION_PARENT)) -# Marks a region group named after one file that no system names. -FILE_GROUP = ":file:" -MAX_SELECTION_TAGS = 1000 -SELECTION_FIELDS = ("systems", "regions", "region_groups", "region_system_groups") -# The files cores load for systems the platform does not list (game engines, -# computers): no system of the platform owns them, and choosing systems -# leaves them out unless this name is chosen too. -OTHER_SYSTEMS = "other" -# Platforms with a manifest in install/. Manifest URLs are case sensitive, -# so user input is normalized against this list before any fetch. -AVAILABLE_PLATFORMS = ( - "retroarch", "batocera", "recalbox", "retrobat", "emudeck", - "lakka", "retrodeck", "rocknix", "romm", "bizhawk", "misterfpga", - "retropie", "amberelec", "emuelec", "knulli", - "minui", "nextui", "myminui", + +def canonical_region(raw: str) -> str: + """One region name or alias, spelled the way manifests spell it.""" + key = raw.strip().lower() + key = REGION_ALIASES.get(key, key) + if key not in REGIONS: + import difflib + + close = difflib.get_close_matches(key, [*REGION_ALIASES, *REGIONS], n=3, cutoff=0.5) + hint = f" Close matches: {', '.join(close)}." if close else "" + raise ValueError( + f"unknown region: {raw.strip()}.{hint} " + f"Short forms: {', '.join(REGION_ALIASES)}. Regions: " + f"{', '.join(sorted(REGIONS))}" + ) + return key + + +def _region_comparable(a: str, b: str) -> bool: + return ( + a == b + or _REGION_PARENT.get(a) == b + or _REGION_PARENT.get(b) == a + or a in AREA_TERRITORIES.get(b, ()) + or b in AREA_TERRITORIES.get(a, ()) + ) + + +def _region_rank(file_regions: set[str], requested: list[str]) -> int: + for index, wanted in enumerate(requested): + if any(_region_comparable(wanted, region) for region in file_regions): + return index + return len(requested) + + +def resolve_regions(values: list[str]) -> list[str]: + """A region priority list, best first, from names or aliases.""" + chosen: list[str] = [] + for value in values: + for token in value.split(","): + if token.strip(): + region = canonical_region(token) + if region not in chosen: + chosen.append(region) + if values and not chosen: + raise ValueError("--region needs at least one region") + return chosen + + +# Region names as a person writes them, where title case alone is wrong. +_REGION_TITLES = {"asia-ntsc": "Asia (NTSC)", "asia-pal": "Asia (PAL)", + "uk": "United Kingdom", WORLD_REGION: "World"} + + +def region_title(name: str) -> str: + """north-america as North America, asia-ntsc as Asia (NTSC).""" + return _REGION_TITLES.get(name) or " ".join( + word.capitalize() for word in name.split("-")) + + +# --- installer/remote.py ----------------------------------------------------- + +# File lists are read from main, the newest ones, whichever commit the +# installer came from. RETROBIOS_REF pins them to a tag or a commit when +# reproducibility matters. +DEFAULT_RELEASE_REF = "main" +RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF) +DEFAULT_BASE_URL = ( + "https://raw.githubusercontent.com/Abdess/retrobios/" + + urllib.parse.quote(RELEASE_REF, safe="") ) -# The names the frontends give themselves, as each manifest's display_name -# spells them (a test holds the two equal). Detection and the platform menu -# come before any manifest is fetched, and str.capitalize() wrote Retroarch, -# Retrodeck and Misterfpga. -PLATFORM_NAMES = { - "retroarch": "RetroArch", "batocera": "Batocera", "recalbox": "Recalbox", - "retrobat": "RetroBat", "emudeck": "EmuDeck", "lakka": "Lakka", - "retrodeck": "RetroDECK", "rocknix": "ROCKNIX", "romm": "RomM", - "bizhawk": "BizHawk", "misterfpga": "MiSTer FPGA", "retropie": "RetroPie", - "amberelec": "AmberELEC", "emuelec": "EmuELEC", "knulli": "KNULLI", - "minui": "MinUI", "nextui": "NextUI", "myminui": "MyMinUI", -} -# Frontends whose BIOS live on their SD card, installed from a computer the -# card is mounted on. Each release unpacks as .system/ at the card root and -# writes its release name as the first line of .system/version.txt (MinUI -# makefile:22-24 and 152-157, NextUI makefile:33-35 and 249, MyMinUI -# makefile:16-19 and 124). The registry publishes the same rules as each -# manifest's `detect` (card_marker), and a test holds the two equal. -CARD_MARKER = ".system/version.txt" -_CARD_RULES: tuple[tuple[str, str, str], ...] = ( - ("minui", CARD_MARKER, "MinUI-"), - ("nextui", CARD_MARKER, "NextUI-"), - ("myminui", CARD_MARKER, "MyMinUI-"), +_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1") + + +def _checked_base_url(value: str) -> str: + """Refuse a base URL that is neither HTTPS nor loopback. + + This base serves the manifest and the files it declares, so whoever + controls it controls the expected hashes too and verification stops + proving anything. install.sh and install.ps1 make the same check on the + URL they fetch the installer from. + + Plain HTTP to loopback stays allowed: nothing sits between the two ends + to intercept it, and it is how the installer is exercised end to end. + """ + parsed = urllib.parse.urlparse(value) + if parsed.scheme == "https": + return value + host = (parsed.hostname or "").lower() + if parsed.scheme == "http" and host in _LOOPBACK_HOSTS: + return value + print( + f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}", + file=sys.stderr, + ) + sys.exit(1) + + +BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL)) +MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json" +TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json" +# What --standalone reads, apart from the list every run downloads. +STANDALONE_DIR = "standalone" +STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json" + + +RAW_FILE_URL = f"{BASE_URL}/{{path}}" +RELEASE_URL = ( + "https://github.com/Abdess/retrobios/releases/download/large-files/{asset}" ) -CARD_PLATFORMS = frozenset(name for name, _file, _prefix in _CARD_RULES) +MAX_RETRIES = 3 +# Seconds a connection has to open. A dropped network cost three tries of a +# 30-second timeout, 93 s, before the error: a connection that does not open +# now fails in this time, and once open a read waits as long as before, so +# a slow line is not cut. +CONNECT_TIMEOUT = 4.0 +MAX_MANIFEST_BYTES = 16 * 1024 * 1024 +MAX_TARGETS_BYTES = 4 * 1024 * 1024 +MAX_STANDALONE_BYTES = 16 * 1024 * 1024 +MAX_MANIFEST_FILES = 100_000 +MAX_DOWNLOAD_SIZE = 1024 * 1024 * 1024 +# A data directory's source archive: PCSX2's source tarball is the largest. +MAX_DATA_ARCHIVE_SIZE = 4 * 1024 * 1024 * 1024 +MAX_TOTAL_DOWNLOAD_SIZE = 64 * 1024 * 1024 * 1024 + SITE_URL = "https://abdess.github.io/retrobios/" INSTALLER_PAGE = f"{SITE_URL}wiki/installer/" @@ -278,42 +512,11 @@ TROUBLESHOOTING_PAGE = f"{SITE_URL}wiki/troubleshooting/" # for PowerShell (scripts/sitebootstrap.py). BOOTSTRAP_URL = f"{SITE_URL}i" -# Fallback BIOS destination per platform when --platform is forced -# but auto-detection finds nothing on the machine. -DEFAULT_DESTS = { - "batocera": Path("/userdata/bios"), - "recalbox": Path("/recalbox/share/bios"), - "lakka": Path("/storage/system"), - "retrodeck": Path.home() / "retrodeck", - "emudeck": Path.home() / "Emulation" / "bios", - "rocknix": Path("/storage/roms/bios"), - # Their BIOS lists name files under /storage/roms beside bios/. - "amberelec": Path("/storage/roms"), - "emuelec": Path("/storage/roms"), - "knulli": Path("/userdata/bios"), - "misterfpga": Path("/media/fat/games"), - "retropie": Path.home() / "RetroPie" / "BIOS", - "romm": Path("/romm/library/bios"), -} - -# Set when the run is interrupted, so queued downloads end instead of draining -# the pool: every future is submitted before the first one completes. -_stop = threading.Event() -# Set once a run starts writing: Ctrl+C before that has nothing to carry on. -_writing = threading.Event() - - -class _Interrupted(Exception): - """Raised inside a worker once the run has been stopped.""" - # A file this size or larger keeps its partial download when a transfer # stops, and the next run asks the server for the rest: the release assets # run to hundreds of megabytes. Smaller files simply start over. RESUME_FROM_SIZE = 16 * 1024 * 1024 -# Read once, before any download thread runs: reading the umask sets it. -_UMASK = os.umask(0) -os.umask(_UMASK) # --- installer/invocation.py ------------------------------------------------- @@ -495,105 +698,326 @@ def offline_requested() -> bool: return os.environ.get(OFFLINE_VARIABLE, "") not in ("", "0") -# --- installer/offline.py ---------------------------------------------------- +# --- installer/terminal.py --------------------------------------------------- -class LocalSources: - """Where this run reads instead of the network: a file list, a pack, the - folders it copies BIOS files from.""" +def _kernel32() -> Any: + """kernel32 from ctypes.windll, which typeshed declares for win32 only. + AttributeError where the system has no windll.""" + import importlib - def __init__(self) -> None: - self.manifest: Path | None = None - self.pack: PackSource | None = None - # The folders named with --from, read once for every platform. - self.folders: list[FolderIndex] = [] - # The reads at once of the files in place (--jobs). - self.jobs: int = 8 - # Every folder index of the run still in use, closed at its end. - self.indexes: weakref.WeakSet[FolderIndex] = weakref.WeakSet() - self._serves: tuple = (None, None, frozenset()) - - def serves(self) -> frozenset: - """The platforms the file list or pack given to this run is for, - empty when none is given. The setup list offers those alone: after - o, Batocera was listed for a RetroArch list, and refused once its - folder was asked.""" - if self._serves[:2] != (self.manifest, self.pack): - named = (local_manifest_platform(self.manifest) if self.manifest is not None - else None) - found = ({named} if named else set()) if self.manifest is not None \ - else set(self.pack.platforms()) if self.pack is not None else set() - self._serves = (self.manifest, self.pack, frozenset(found)) - return self._serves[2] - - @property - def offline(self) -> bool: - """No network request in this run: a pack is read, or --offline.""" - return self.pack is not None or offline_requested() - - def reset(self) -> None: - if self.pack is not None: - self.pack.close() - self.close_indexes() - self.manifest = None - self.pack = None - self.folders = [] - self.jobs = 8 - - def close_indexes(self) -> None: - for index in list(self.indexes): - index.close() - self.indexes = weakref.WeakSet() + return importlib.import_module("ctypes").windll.kernel32 -LOCAL = LocalSources() +def _enable_ansi() -> bool: + """Whether escape sequences reach the terminal as colour and redraws. - -class _Offline(OSError): - """A network request in a run told to make none.""" - - -OFFLINE_WORDS = "this run makes no network request" -# The value --offline gives the variable: the words then name the option, -# and the variable itself where it was set. -OFFLINE_FLAG_VALUE = "--offline" - - -def offline_named() -> str: - """What made this run offline, as the words name it.""" - value = os.environ.get(OFFLINE_VARIABLE, "") - return (f"{OFFLINE_VARIABLE}={value}" if value not in ("", "0", OFFLINE_FLAG_VALUE) - else "--offline") - - -def offline_undo() -> str: - """How a run gets the network back: without the option, or with the - variable unset. "without --offline" told a user who never typed it to - remove it.""" - return ("without --offline" if offline_named() == "--offline" - else f"with {OFFLINE_VARIABLE} unset") - - -def offline_words() -> str: - """This run makes no network request, and what said so.""" - return f"{OFFLINE_WORDS} ({offline_named()})" - - -def _network_allowed(what: str) -> None: - if LOCAL.pack is not None: - raise _Offline(f"{what}: this run reads a pack and makes no network request") - if offline_requested(): - raise _Offline(f"{what}: {offline_words()}") - - -def local_manifest_platform(path: Path) -> str | None: - """The platform a saved file list names, None when it names none.""" + Windows 10 consoles interpret them once virtual terminal processing is + switched on. Older ones print them raw, so the answer is then no. + """ + if os.name != "nt": + return True try: - with open(path, "rb") as handle: - data = json.loads(handle.read(MAX_MANIFEST_BYTES).decode("utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError): + import ctypes + + kernel32 = _kernel32() + handle = kernel32.GetStdHandle(-11) + mode = ctypes.c_uint32() + if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): + return False + return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004)) + except (AttributeError, OSError): + return False + + +# The roles text is painted with, from the 16 basic colours only: a +# handheld's Linux console has no more. The screens and the line questions +# name a role, never a code. Magenta is the hue that stays legible on black +# and on white in the xterm, VGA, Tango and Campbell palettes, so it is the +# accent, bold. Yellow reads poorly on white: it paints a status word, never +# a sentence. Bold red is bright red on the Linux console, where plain red on +# black is the weakest pair. +COLOUR_ROLES = { + "accent": "1;35", + "success": "32", + "warning": "33", + "failure": "1;31", + "muted": "2", + "strong": "1", + # The accent reversed: the row in focus, its > kept for no colour. + "selected": "7;35", +} + +# The words a status takes its role from, wherever it is said. A count of +# zero is no news and stays plain: "0 missing" is not a warning. +_STATUS_WORDS = tuple((re.compile(pattern), role) for pattern, role in ( + (r"(? list[tuple[int, int, str]]: + """The spans in order, none empty, the longer kept where two overlap.""" + kept: list[tuple[int, int, str]] = [] + for span in sorted(spans, key=lambda span: (span[0], -span[1])): + if span[1] > span[0] and (not kept or span[0] >= kept[-1][1]): + kept.append(span) + return kept + + +def status_spans(text: str) -> list[tuple[int, int, str]]: + """(start, end, role) of the status words in text, in order, apart.""" + return _apart([(match.start(), match.end(), role) for pattern, role in _STATUS_WORDS + for match in pattern.finditer(text)]) + + +def _sgr(role: str) -> str: + """The SGR sequence of a role, or of roles joined by + ("strong+success").""" + return "\033[0;" + ";".join(COLOUR_ROLES[name] for name in role.split("+")) + "m" + + +def painted(text: str, spans: list[tuple[int, int, str]], base: str = "") -> str: + """text with each span in its role and the rest in the base role, a code + written where the role changes and the colours reset at the end. The + characters are those of text, in the same order. A span in "plain" + takes the terminal's own colours.""" + pieces: list[tuple[str, str]] = [] + at = 0 + for start, end, role in spans: + pieces += [(text[at:start], base), (text[start:end], role)] + at = end + pieces.append((text[at:], base)) + out: list[str] = [] + current = "" + for piece, role in pieces: + role = "" if role == "plain" else role + if not piece: + continue + if role != current: + out.append(_sgr(role) if role else "\033[0m") + current = role + out.append(piece) + if current: + out.append("\033[0m") + return "".join(out) + + +_SGR = re.compile(r"\x1b\[[0-9;]*m") + + +def unpainted(text: str) -> str: + """text without its SGR codes.""" + return _SGR.sub("", text) + + +class Terminal: + """What the output stream can show: a live line, colour, or neither. + + A pipe or a log gets plain lines, and NO_COLOR and TERM=dumb or unset are + honoured, as is a terminal whose description moves no cursor the ANSI way + (vt52), or names fewer than 8 colours (vt100), which keeps the line live + and plain. + As no-color.org reads it, an empty NO_COLOR is not set: `NO_COLOR= cmd` + turned colour off. FORCE_COLOR or CLICOLOR_FORCE paints a pipe, for a + log viewer that shows colour, and never makes the line live. + """ + + def __init__(self, stream: TextIO | None = None, quiet: bool = False) -> None: + self.stream = stream or sys.stdout + self.quiet = quiet + isatty = getattr(self.stream, "isatty", None) + # An unset TERM is a dumb one, as the full screen reads it. A Windows + # console sets none and draws the sequences once _enable_ansi is on. + term = os.environ.get("TERM", "") + self.live = (bool(isatty and isatty()) and term != "dumb" + and (bool(term) or os.name == "nt") + and not terminal_without_ansi(os.environ)) + forced = any(os.environ.get(name, "0") not in ("", "0") + for name in ("FORCE_COLOR", "CLICOLOR_FORCE")) + self.colour = ( + ((self.live and not terminal_few_colours(os.environ)) or forced) + and not os.environ.get("NO_COLOR") and _enable_ansi() + ) + if not self.colour: + self.live = self.live and os.name != "nt" + + def paint(self, text: str, role: str) -> str: + return f"\033[{COLOUR_ROLES[role]}m{text}\033[0m" if self.colour else text + + def status(self, text: str) -> str: + """text with its status words in their roles (status_spans).""" + return painted(text, status_spans(text)) if self.colour else text + + def ok(self, text: str) -> str: + return self.paint(text, "success") + + def bad(self, text: str) -> str: + return self.paint(text, "failure") + + def dim(self, text: str) -> str: + return self.paint(text, "muted") + + def bold(self, text: str) -> str: + return self.paint(text, "strong") + + +# The fewest columns a line question lays itself out in: below it a row is +# all number, and the terminal folds what is printed whatever it is. +LINE_MIN_COLS = 20 + + +def terminal_size() -> tuple[int, int]: + """(columns, lines) of the terminal line mode prints to, the one reading + every layout of it makes. Python 3.8 gives a pty of no size as 0 and 0, + where 3.11 falls back to 80 and 24: a list laid out in 0 columns never + ended, the plan printed an empty heading, and the progress line lost + every figure but its percentage.""" + size = shutil.get_terminal_size((80, 24)) + return max(size.columns or 80, LINE_MIN_COLS), size.lines or 24 + + +# Where ncurses finds a terminal's compiled description after $TERMINFO, +# ~/.terminfo and $TERMINFO_DIRS. +_TERMINFO_DIRS = ("/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo", + "/usr/lib/terminfo", "/usr/share/lib/terminfo") +# cursor_address, string capability 10 of term(5). +_TERMINFO_CUP = 10 +# max_colors, numeric capability 13. +_TERMINFO_COLORS = 13 + + +def _terminfo_folders(env: Mapping[str, str]) -> list[Path]: + folders = [Path(env["TERMINFO"])] if env.get("TERMINFO") else [] + if env.get("HOME"): + folders.append(Path(env["HOME"]) / ".terminfo") + # An empty entry stands for the system's folders, which come last anyway. + folders += [Path(part) for part in env.get("TERMINFO_DIRS", "").split(":") if part] + return folders + [Path(folder) for folder in _TERMINFO_DIRS] + + +def _terminfo_header(data: bytes) -> tuple[int, int, int, int, int] | None: + """Of a compiled term(5) entry: the width of a number, the counts of + names bytes, booleans, numbers and strings. None when data is none.""" + if len(data) < 12: return None - plat = data.get("platform") if isinstance(data, dict) else None - return plat if plat in AVAILABLE_PLATFORMS else None + # The legacy format stores numbers in 2 bytes, the extended one in 4. + width = {0o432: 2, 0o1036: 4}.get(int.from_bytes(data[0:2], "little", signed=True)) + if width is None: + return None + names, bools, numbers, strings = (int.from_bytes(data[at:at + 2], "little", signed=True) + for at in (2, 4, 6, 8)) + return width, names, bools, numbers, strings + + +def terminfo_number(data: bytes, index: int) -> int | None: + """Numeric capability index of a compiled term(5) entry, -1 when the + entry lacks it, None when data is no compiled entry.""" + header = _terminfo_header(data) + if header is None: + return None + width, names, bools, numbers, _strings = header + if index >= numbers: + return -1 + start = 12 + names + bools + start += start % 2 + index * width + if start + width > len(data): + return None + value = int.from_bytes(data[start:start + width], "little", signed=True) + return value if value >= 0 else -1 + + +def terminfo_string(data: bytes, index: int) -> str | None: + """String capability index of a compiled term(5) entry, "" when the + entry lacks it, None when data is no compiled entry.""" + def short(at: int) -> int: + return int.from_bytes(data[at:at + 2], "little", signed=True) + + header = _terminfo_header(data) + if header is None: + return None + width, names, bools, numbers, strings = header + offsets = 12 + names + bools + offsets += offsets % 2 + numbers * width + if index >= strings: + return "" + at = short(offsets + 2 * index) + if at < 0: + return "" + start = offsets + 2 * strings + at + end = data.find(b"\0", start) + if end < 0: + return None + return data[start:end].decode("latin-1") + + +def _terminfo_data(term: str, env: Mapping[str, str]) -> bytes | None: + """TERM's compiled description, the first found, None when none is: + Windows, Android and many handheld images carry none.""" + if not term or "/" in term or term.startswith("."): + return None + for folder in _terminfo_folders(env): + # Linux files xterm under x/, macOS under 78/. + for sub in (term[0], f"{ord(term[0]):02x}"): + try: + return (folder / sub / term).read_bytes() + except (OSError, ValueError): + continue + return None + + +def terminal_cursor_address(term: str, env: Mapping[str, str]) -> str | None: + """How TERM's description here moves the cursor, "" when it cannot, + None when no description is found, and the screen is not held back + for it.""" + data = _terminfo_data(term, env) + return None if data is None else terminfo_string(data, _TERMINFO_CUP) + + +def terminal_colours(term: str, env: Mapping[str, str]) -> int | None: + """The colours TERM's description here names, 0 when it names none + (vt100), None when no description is found or it cannot be read.""" + data = _terminfo_data(term, env) + if data is None: + return None + count = terminfo_number(data, _TERMINFO_COLORS) + return None if count is None else max(count, 0) + + +def terminal_few_colours(env: Mapping[str, str]) -> str: + """Why TERM's description here leaves colour off, "" when it does not: + no description is no refusal, as for the cursor.""" + if os.name == "nt": + return "" + term = env.get("TERM", "") + count = terminal_colours(term, env) + if count is not None and count < 8: + return f"TERM={term} names {count} colours, fewer than 8" + return "" + + +def terminal_without_ansi(env: Mapping[str, str]) -> str: + """Why TERM's description here says the ANSI sequences the screen and + the progress line write would print as text, "" when it does not.""" + if os.name == "nt": + return "" + term = env.get("TERM", "") + cup = terminal_cursor_address(term, env) + if cup == "": + return f"TERM={term} cannot move the cursor" + if cup is not None and not cup.startswith(("\x1b[", "\x9b")): + return f"TERM={term} does not take the escape sequences the screen is drawn with" + return "" + + +TUI_MIN_COLS = 40 + + +TUI_MIN_ROWS = 12 # --- installer/text.py ------------------------------------------------------- @@ -872,6 +1296,45 @@ def _wrap(text: str, width: int, indent: str = " ", whole: str = "", return lines +def _names_and(names: list[str]) -> str: + """Names in a sentence: A, A and B, A, B and C.""" + return " and ".join(names) if len(names) < 3 else f"{', '.join(names[:-1])} and {names[-1]}" + + +def _no_widow(lines: list[str], room: int) -> list[str]: + """Wrapped lines whose last one is not a word alone: "shared" stood on a + line of its own under its size at 40 columns. The + word before it goes down with it where both fit.""" + if len(lines) < 2 or len(_glued_words(lines[-1])) > 1: + return lines + # A size goes down with its unit: "1.4" / "MB shared" split it. + words = _glued_words(lines[-2]) + lead = lines[-2][:len(lines[-2]) - len(lines[-2].lstrip(" "))] + moved = f"{words[-1]} {lines[-1].strip()}" + if len(words) < 2 or cell_width(moved) > room: + return lines + return [*lines[:-2], lead + " ".join(words[:-1]), moved] + + +def format_duration(seconds: float) -> str: + """0:42, 3:05 or 1:02:09.""" + seconds = max(0, int(seconds + 0.5)) + hours, rest = divmod(seconds, 3600) + minutes, secs = divmod(rest, 60) + return f"{hours}:{minutes:02}:{secs:02}" if hours else f"{minutes}:{secs:02}" + + +def shown_lines(lines: list[str]) -> list[str]: + """Lines for the terminal, a blank line opening one kept as it is: the + paths in them come from folders anyone may have filled.""" + return [("\n" + screen_text(line[1:])) if line.startswith("\n") else screen_text(line) + for line in lines] + + +def _pad(text: str, width: int) -> str: + return text + " " * max(0, width - cell_width(text)) + + # --- installer/events.py ----------------------------------------------------- EVENT_KEYS: dict[str, tuple[str, ...]] = { @@ -1119,44 +1582,728 @@ def _clean_mapping(value: dict, keep: str = "") -> dict: for key, item in value.items()} -# --- installer/paths.py ------------------------------------------------------ +# --events: one JSON object per line on stdout, for a program driving the +# installer (the handheld port shows its screens from them). Each kind has +# exactly these keys besides "event", in this order, and nothing else. +EVENT_SCHEMA = 1 -def _read_limited_json( - response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False -) -> object: - """Read a bounded UTF-8 JSON response, its bytes as they came with raw. +# Seconds between two progress events while bytes arrive. +EVENT_PROGRESS_INTERVAL = 0.5 - A body shorter than its Content-Length is a dropped connection, raised - as one so the caller retries: parsed, the cut read as an invalid file - list and the run ended without the network advice. + +# --- installer/host_fs.py ---------------------------------------------------- + +# Set when the run is interrupted, so queued downloads end instead of draining +# the pool: every future is submitted before the first one completes. +_stop = threading.Event() +# Set once a run starts writing: Ctrl+C before that has nothing to carry on. +_writing = threading.Event() + + +class _Interrupted(Exception): + """Raised inside a worker once the run has been stopped.""" + + +# Read once, before any download thread runs: reading the umask sets it. +_UMASK = os.umask(0) +os.umask(_UMASK) + + +# Set under WSL: a Windows path read from a config or a rule names a drive +# that Linux sees under /mnt (drvfs). C:\\RetroBat\\bios was used as a relative +# path and nothing Windows-side was ever found from WSL. +# unasked: why Windows could not be asked for its folders, said once by +# detection. +_WSL: dict[str, Any] = {"active": False, "root": "/mnt", "unasked": ""} + + +def _host_path(text: str) -> Path: + """A path as this machine opens it: under WSL, C:\\X is /mnt/c/X.""" + match = re.match(r"^([A-Za-z]):(?:[\\/]+(.*))?$", text) if _WSL["active"] else None + if match: + rest = [part for part in re.split(r"[\\/]", match.group(2) or "") if part] + return Path(_WSL["root"], match.group(1).lower(), *rest) + return Path(text) + + +# Set while detection runs on this thread: a probe this user may not make +# is then said once, and the probes of other threads (the files being +# hashed) stay silent. +_SETUP_SEARCH = threading.local() + +# (folder, why in words) for each folder detection could not look in. +_DETECTION_REFUSED: list[tuple[Path, str]] = [] +# Those of them that failed for another cause than a permission: a read +# error from a failing card, a link that loops. +_DETECTION_UNREADABLE: set[Path] = set() +# The errors that say a place is not there, as against one that is there +# and could not be read. +_ABSENT_ERRNOS = (errno.ENOENT, errno.ENOTDIR, errno.EINVAL, errno.ENAMETOOLONG) + + +def refused_words(folder: Path, why: str, shown: str = "") -> str: + """The line said for a folder detection could not look in. shown is + the folder as the screen writes it (~/.config/EmuDeck), the full path + by default.""" + if _WSL["active"] and why == _WSL["unasked"] and folder == Path(_WSL["root"]): + return (f"Could not look for setups on the Windows side: {why}. " + "Run it again once Windows answers, or name the BIOS folder with --dest.") + if folder in _DETECTION_UNREADABLE: + return (f"Could not look for setups: {shown or folder} could not be read ({why}). " + "A failing card or a link that loops gives this: check it, or name the " + "BIOS folder with --dest.") + return (f"Could not look for setups: this user cannot open {shown or folder} ({why}). " + "Run as its owner (su - or sudo -H), or name the BIOS folder " + "with --dest.") + + +def _note_refused(path: Path, exc: OSError) -> None: + """Say once that a folder detection looks in is closed to this user, + or could not be read. + + A probe refused there counts as absent and the others go on: a config + folder a sudo run left at 0700 (~/.config/EmuDeck) hid a RetroArch whose + retroarch.cfg was readable, and the run fell back to a folder it does + not read. """ - raw_length = response.headers.get("Content-Length") if response.headers else None - expected: int | None = None - if raw_length: - try: - expected = int(raw_length) - except ValueError: - expected = None - if expected is not None and expected > limit: - raise ValueError(f"{label} exceeds {limit} bytes") - try: - payload = response.read(limit + 1) - except http.client.IncompleteRead as exc: - raise ConnectionError( - f"{label} cut after {len(exc.partial)} bytes" - ) from exc - if len(payload) > limit: - raise ValueError(f"{label} exceeds {limit} bytes") - if expected is not None and len(payload) < expected: - raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes") - if raw: - return payload - try: - return json.loads(payload.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ValueError(f"invalid {label}: {exc}") from exc + if (not getattr(_SETUP_SEARCH, "active", False) or getattr(_SETUP_SEARCH, "quiet", False) + or exc.errno in _ABSENT_ERRNOS): + return + refused = closed_folder(path) or (path, exc.strerror or str(exc)) + if refused in _DETECTION_REFUSED: + return + _DETECTION_REFUSED.append(refused) + if not isinstance(exc, PermissionError): + # An EIO on retroarch.cfg counted as absent: the card about to be + # written to failed, and the run said nothing was detected. + _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) +def _held(path: Path) -> bool: + """Whether something may sit at path. A place that cannot be looked at + (a folder above it this user cannot enter, a card that answers a read + error) counts as held, so the file is reported unreadable and the run + goes on with the others: Path.exists() lets PermissionError through.""" + try: + return path.exists() + except OSError: + return True + + +def _probed(probe: Callable[[], bool], path: Path) -> bool: + """probe() for path, False where the place cannot be looked at. A + refusal met while looking for setups is said once (_note_refused).""" + try: + found = probe() + except OSError as exc: + _note_refused(path, exc) + return False + if not found: + # Python 3.14's Path.exists() answers False where earlier ones + # raised: a refusal is told from absence by the stat it hides. + try: + os.stat(path) + except OSError as exc: + _note_refused(path, exc) + return found + + +def _exists(path: Path) -> bool: + """Path.exists(), False where the place cannot be looked at.""" + return _probed(path.exists, path) + + +def _is_dir(path: Path) -> bool: + """Path.is_dir(), False where the place cannot be looked at.""" + return _probed(path.is_dir, path) + + +def _is_file(path: Path) -> bool: + """Path.is_file(), False where the place cannot be looked at.""" + return _probed(path.is_file, path) + + +def _closed_to_this_user(path: Path) -> OSError | None: + """The error that keeps path from being looked at, None when it can + be, there or not.""" + try: + os.stat(path) + except OSError as exc: + return None if exc.errno in _ABSENT_ERRNOS else exc + return None + + +def closed_folder(path: Path) -> tuple[Path, str] | None: + """The folder above path this user cannot open, and why in words, or + None when path can be looked at, there or not. + + A BIOS folder under /root run without sudo, or a card mounted at 0700 + for another user: Path.exists() raised PermissionError before the + first line said where. + """ + try: + os.stat(path) + return None + except OSError as exc: + failure = exc + probe = path.absolute() + for folder in (*reversed(probe.parents), probe): + try: + os.stat(folder) + except OSError as exc: + if exc.errno in (errno.ENOENT, errno.ENOTDIR): + return None + why = exc.strerror or str(exc) + if exc.errno == errno.ELOOP: + # The link that loops, not the open folder holding it. + return folder, why + real = Path(os.path.realpath(folder)) + if real != folder: + # ~/Emulation linked into a closed card: the closed folder + # is under the link's target, and naming the link's + # parent told the user they cannot open their own HOME. + return closed_folder(real) or (real.parent, why) + return folder.parent, why + return probe, failure.strerror or str(failure) + + +def _is_link(info: os.stat_result) -> bool: + """Whether what lstat read is a link: a symbolic link, or on Windows a + junction or any other reparse point.""" + return stat.S_ISLNK(info.st_mode) or bool( + getattr(info, "st_file_attributes", 0) & _REPARSE_POINT) + + +def _clear_read_only(dest: Path) -> None: + """Let the verified copy replace a read-only file the user already has. + + Windows refuses to replace a file carrying the read-only attribute + (WinError 5) even in a writable folder. The file is about to be replaced + by the copy the manifest names, so its attribute is cleared first. + Elsewhere a rename only needs the folder to be writable. + """ + if os.name != "nt": + return + try: + if dest.is_file() and not os.access(dest, os.W_OK): + os.chmod(dest, stat.S_IREAD | stat.S_IWRITE) + except OSError: + pass # the replace that follows reports the refusal with its reason + + +def _replace_with_copy(src: Path, dest: Path) -> None: + """Put a copy of src at dest's name without following what is there.""" + fd, scratch = tempfile.mkstemp(dir=dest.parent, prefix=f".{dest.name}.", suffix=".part") + os.close(fd) + try: + shutil.copy2(src, scratch) + os.replace(scratch, dest) + except OSError: + if os.path.lexists(scratch): + os.unlink(scratch) + raise + + +# FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows. +# Before Python 3.12 lstat does not report a junction as a link, and +# os.walk(followlinks=False) descends into it. +_REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) + + +_SHARING_VIOLATIONS = (32, 33) + +# A write refused by the file system: retrying cannot change it, and the +# summary names the two ways out. +NOT_WRITABLE = "folder not writable" + + +def _write_refused(exc: OSError) -> bool: + # A sharing violation is a file another process holds open, which a + # later attempt can find released: no refusal of the folder. + if getattr(exc, "winerror", None) in _SHARING_VIOLATIONS: + return False + return isinstance(exc, PermissionError) or exc.errno == errno.EROFS + + +# A file already at the destination, marked read-only, whose content differs, +# and whose attribute could not be cleared: replacing it is refused while its +# folder stays writable. +READ_ONLY = "file in place is read-only" + + +def _read_only_file(dest: Path) -> bool: + return _is_file(dest) and not os.access(dest, os.W_OK) and _folder_writable(dest.parent) + + +def _folder_writable(path: Path) -> bool: + """Whether a file can be created under path, read from its nearest + existing folder: a BIOS folder not created yet is as writable as the + folder it would go in.""" + probe = path + while not _exists(probe) and probe.parent != probe: + probe = probe.parent + return os.access(probe, os.W_OK) + + +# A write the drive had no room for: the same run fails the same way until +# space is freed or another drive is named. +DRIVE_FULL = "the drive is full" + + +_FULL_ERRNOS = (errno.ENOSPC, getattr(errno, "EDQUOT", errno.ENOSPC)) + + +def _drive_full(exc: BaseException) -> bool: + return isinstance(exc, OSError) and exc.errno in _FULL_ERRNOS + + +def _nearest_folder(path: Path) -> Path: + """The deepest folder on path that exists and can be looked at.""" + probe = path.absolute() + while not _is_dir(probe) and probe.parent != probe: + probe = probe.parent + return probe + + +# --- installer/config_values.py ---------------------------------------------- + +def _expand_retroarch_path(value: str, app_dir: Path, home: Path | None = None) -> Path: + """Expand the notations RetroArch writes into its config values. + + fill_pathname_expand_special (libretro-common/file/file_path.c) maps a + leading '~' to the home directory and a leading ':' to the application + directory, dropping the two leading characters in both cases. + """ + if value[:1] == "~": + return (home or Path(str(Path.home()))) / value[2:] + if value[:1] == ":": + return app_dir / value[2:] + return _host_path(os.path.expandvars(os.path.expanduser(value))) + + +def _retroarch_cfg_dir( + cfg_path: Path, key: str, app_dir: Path, default: str, home: Path | None = None +) -> Path | None: + """A directory setting of retroarch.cfg, as RetroArch expands it. + + A value left empty or at `default` is the directory RetroArch falls back + on, `default` under app_dir. None when the config is unreadable or does + not set the key. A config this user cannot read is said once, like a + closed folder: a retroarch.cfg a `sudo retroarch` left to root hid the + setup without a word. + """ + try: + lines = cfg_path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError as exc: + _note_refused(cfg_path, exc) + return None + for line in lines: + line = line.strip() + name, sep, value = line.partition("=") + if sep and name.strip() == key: + value = value.strip().strip('"').strip("'") + if not value or value == "default": + return app_dir / default + return _expand_retroarch_path(value, app_dir, home) + return None + + +# System directory -> the retroarch.cfg it was read from and the directory +# ':' expands to there, for finding the cores of the same installation. +_RETROARCH_CONFIGS: dict[Path, tuple[Path, Path]] = {} + + +def _parse_retroarch_system_dir( + cfg_path: Path, app_dir: Path | None = None, home: Path | None = None +) -> Path | None: + """Parse system_directory from retroarch.cfg. + + app_dir is RetroArch's application directory, used to expand ':' values. + It defaults to the directory holding the config, which is where a portable + install keeps both. home is what '~' means to that RetroArch, the user's + home when not given. + """ + if not _exists(cfg_path): + return None + app_dir = app_dir or cfg_path.parent + system_dir = _retroarch_cfg_dir(cfg_path, "system_directory", app_dir, "system", home) + if system_dir is not None: + _RETROARCH_CONFIGS.setdefault(system_dir, (cfg_path, app_dir)) + return system_dir + + +def _shell_unquote(value: str) -> str: + """Resolve a shell right-hand side into its effective string value. + + Handles concatenated quoted/unquoted segments the way bash does + (e.g. "/run/media/deck/EmuSD"/Emulation), expands variables in + double-quoted and unquoted segments, and stops at unquoted + whitespace or a comment. + """ + parts: list[str] = [] + i = 0 + n = len(value) + while i < n: + c = value[i] + if c == '"': + end = value.find('"', i + 1) + if end == -1: + parts.append(os.path.expandvars(value[i + 1:])) + break + parts.append(os.path.expandvars(value[i + 1:end])) + i = end + 1 + elif c == "'": + end = value.find("'", i + 1) + if end == -1: + parts.append(value[i + 1:]) + break + parts.append(value[i + 1:end]) + i = end + 1 + elif c.isspace() or c == "#": + break + else: + end = i + while end < n and value[end] not in "\"'#" and not value[end].isspace(): + end += 1 + parts.append(os.path.expandvars(value[i:end])) + i = end + return os.path.expanduser("".join(parts)) + + +def _parse_bash_var(path: Path, key: str) -> str | None: + """Extract the effective value of key= from a bash/shell file.""" + if not _exists(path): + return None + try: + for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if line.startswith(f"{key}="): + _, _, value = line.partition("=") + return _shell_unquote(value) + except OSError as exc: + # A settings.sh a sudo EmuDeck run left to root hid the setup. + _note_refused(path, exc) + return None + + +def _parse_json_path(path: Path, *keys: str) -> str | None: + """Extract a nested string value from a JSON file.""" + if not _exists(path): + return None + try: + data = json.loads(path.read_text(encoding="utf-8", errors="replace")) + for key in keys: + data = data[key] + return data if isinstance(data, str) and data else None + except (OSError, json.JSONDecodeError, KeyError, TypeError): + return None + + +def _parse_ps1_var(path: Path, key: str) -> str | None: + """Extract value of $key= or key= from a PowerShell file.""" + if not _exists(path): + return None + normalized = key.lstrip("$") + try: + raw = path.read_bytes() + # Windows PowerShell's Out-File writes UTF-16, Set-Content -Encoding + # UTF8 a byte order mark: EmuDeck's settings.ps1 passes through both. + encoding = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig" + for line in raw.decode(encoding, errors="replace").splitlines(): + line = line.strip() + check = line.lstrip("$") + if check.startswith(f"{normalized}="): + _, _, value = check.partition("=") + return value.strip('"').strip("'") + except OSError as exc: + _note_refused(path, exc) + return None + + +def _cfg_true(value: str | None) -> bool: + return (value or "").strip().lower() == "true" + + +def _config_keys(path: Path) -> set[str]: + """The keys an emulatorLauncher-style key=value file sets, lowercased.""" + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + return set() + return { + line.split("=", 1)[0].strip().lower() + for line in text.splitlines() if "=" in line and line.split("=", 1)[1].strip() + } + + +# --- installer/console.py ---------------------------------------------------- + +def _typed_folder(raw: str) -> Path: + """A folder typed at a question, read as a shell reads an argument. + + Explorer's "Copy as path" puts quotes around it, and users quote a path + with spaces: kept, they sent the files into a folder named `"` under + the current directory, and the run said Done. + """ + text = raw.strip() + if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"": + text = text[1:-1].strip() + # Under WSL, D: and D:\ are the Windows drive the screen calls D:. + return _host_path(os.path.expandvars(os.path.expanduser(text))) + + +def _ask(prompt: str) -> str: + """An answer, or a stop: Ctrl+D at a question is Ctrl+C. + + Both used to leave with 0, so `install.sh && retroarch` went on with no + BIOS. They now end where Ctrl+C ends everywhere else, on 130. + """ + try: + return input(prompt).strip() + except EOFError: + print() + raise KeyboardInterrupt from None + + +# A quit chosen at a question or on the screen: nothing was installed, as +# gh ends a prompt cancelled. 130 is 128 plus SIGINT, which shells read as a +# run killed by Ctrl-C, and 0 let `install.sh && retroarch` start RetroArch +# on no BIOS. Ctrl-C and Ctrl-D keep 130. +QUIT_CODE = 2 + + +def _quit() -> None: + """q at a question ends the run on QUIT_CODE.""" + sys.exit(QUIT_CODE) + + +class _Output: + """What a run's text says. By default: what will happen, where, the + progress, the result and the next step. --verbose adds every step, list + and reason, the lines a beginner lost the result among. where_said is + set once the BIOS folder was named before the result.""" + + verbose = False + where_said = False + + +OUTPUT = _Output() + + +def detail(*args: Any, **kwargs: Any) -> None: + """Print a line only --verbose shows.""" + if OUTPUT.verbose: + print(*args, **kwargs) + + +class Progress: + """Bytes and files across the parallel downloads, shown as they move. + + On a terminal one line redraws in place: a bar, the bytes, the speed and + the time left. Elsewhere each finished file gets its line with --verbose, + as a log wants it. Failures are always printed, quiet or not. + """ + + BAR = 24 + + def __init__(self, total_files: int, total_bytes: int, term: Terminal, + events: bool = True) -> None: + self.total_files = total_files + self.expected_bytes = total_bytes + self.total_bytes = max(total_bytes, 1) + self.term = term + self.files = 0 + self.bytes = 0 + self.resumed = 0 + # Bytes that came from this machine and not the network: a copy + # found here, the pack, a resumed partial copy. + self.local = 0 + # Files written to their place, which a stopped run counts: the + # queue's length said "118 files installed" over 8 on disk. + self.installed = 0 + # The entries of those files, which the end of the run counts apart. + self.landed: list[dict] = [] + self.start = time.monotonic() + self._drawn = 0.0 + self._evented = self.start + self._lock = threading.Lock() + # A data tree's archive draws the line and writes no event: the + # progress events count the files of the download event. + self.events = events + + def expect(self, total_bytes: int) -> None: + """The size the transfer turns out to have, once its server says it.""" + with self._lock: + self.expected_bytes = total_bytes + self.total_bytes = max(total_bytes, 1) + + def add(self, count: int, resumed: bool = False, network: bool | None = None) -> None: + """count bytes written, resumed ones left out of the speed. network + is whether they came over the network, by default unless resumed.""" + with self._lock: + self.bytes += count + if resumed: + self.resumed += count + fetched = not resumed if network is None else network + if not fetched: + self.local += count + now = time.monotonic() + if self.term.live and not self.term.quiet and now - self._drawn >= 0.1: + self._drawn = now + self._draw() + if self.events and EVENTS.on and now - self._evented >= EVENT_PROGRESS_INTERVAL: + self._evented = now + EVENTS.emit("progress", files_done=self.files, files_total=self.total_files, + bytes_done=self.bytes, bytes_total=self.expected_bytes) + self.emit_transfer() + + def emit_transfer(self) -> None: + """The transfer event: of the bytes done, those this machine held + and those the network brought.""" + EVENTS.emit("transfer", bytes_local=self.local, + bytes_network=self.bytes - self.local) + + def forget_resumed(self, count: int) -> None: + with self._lock: + self.resumed -= count + self.local -= count + + def transferred(self) -> int: + """Bytes fetched by this run, a resumed partial copy excluded.""" + return self.bytes - self.resumed + + def done(self, dest: str, ok: bool, reason: str = "") -> None: + with self._lock: + self.files += 1 + line = None + if not ok and not self.term.quiet: + why = f" ({reason})" if reason else "" + line = f" {self.term.bad('FAILED')} {dest}{why}" + SAID_FAILED.add(dest) + elif not self.term.live and not self.term.quiet and OUTPUT.verbose: + line = f" [{self.files}/{self.total_files}] {dest} {self.term.ok('ok')}" + if line is not None: + self._clear() + print(line, file=self.term.stream, flush=True) + if self.term.live and not self.term.quiet: + self._draw() + + def finish(self) -> None: + with self._lock: + self._clear() + + def elapsed(self) -> float: + return time.monotonic() - self.start + + def _clear(self) -> None: + if self.term.live and not self.term.quiet: + print("\r\033[K", end="", file=self.term.stream, flush=True) + + def _draw(self) -> None: + share = min(self.bytes / self.total_bytes, 1.0) + elapsed = self.elapsed() + # A resumed partial copy was on disk before the run started: counted + # in the share, never in the speed. + speed = self.transferred() / elapsed if elapsed > 0 else 0 + left = (self.total_bytes - self.bytes) / speed if speed > 0 else 0 + # Copies from a folder here count in no speed: "0 B/s 0:00 left" + # was drawn under them, as the screen does not. + timed = [f"{format_size(int(speed))}/s", f"{format_duration(left)} left"] \ + if self.transferred() > 0 else [] + parts = [ + f"{share * 100:5.1f}%", + f"{format_size(self.bytes)} / {format_size(self.total_bytes)}", + *timed, + f"({self.files}/{self.total_files} files)", + ] + # One physical line, whatever the width: \r\033[K clears only the + # line the cursor is on, so a wrapped line left a ghost per redraw + # on an 80-column console. The bar gives way first, then the least + # telling figures. + width = terminal_size()[0] - 1 + while True: + tail = " ".join(parts) + room = width - len(tail) - 6 + if room >= 10 or len(parts) == 1: + break + parts.pop() + if room >= 10: + bar_width = min(self.BAR, room) + filled = int(share * bar_width) + text = f" [{'#' * filled}{'-' * (bar_width - filled)}] {tail}" + else: + text = f" {tail}" + print(f"\r\033[K{text[:width]}", end="", file=self.term.stream, flush=True) + + +# The files a FAILED line of the progress named in this run: the end of +# the run names the others. +SAID_FAILED: set[str] = set() + + +# Answers that stop: every menu before this one taught q as quit. +_REFUSALS = ("n", "q", "quit", "exit", "stop", "abort") + + +def fold_line(text: str, hang: str = " ") -> str: + """A line wrapped between words at the terminal's width, the lines after + the first indented by hang under its own lead, a word wider than a line + cut after a slash: left to the terminal, below 40 columns "Found Onion + at /media/moi/ONION/BIOS" broke inside "(RetroArch files)" and a folder + inside its name.""" + width = terminal_size()[0] + cols = max(width - 1, 8) + if cell_width(text) <= cols or width >= TUI_MIN_COLS or not _is_terminal(sys.stdout): + # A pipe or a log folds nothing, and from 40 columns a folder is left + # whole for the terminal to fold, copied as one line. + return text + lead = text[:len(text) - len(text.lstrip(" "))] + prefix = lead + hang + lines: list[str] = [] + line = lead + for word in text.split(): + joined = f"{line} {word}" if line.strip() else line + word + if cell_width(joined) <= cols: + line = joined + continue + if line.strip(): + lines.append(line) + pieces = _split_word(word, max(cols - len(prefix), 1)) + lines += [prefix + piece for piece in pieces[:-1]] + line = prefix + pieces[-1] + lines.append(line) + return "\n".join(lines) + + +def _live_stdout() -> bool: + """Whether the standard output draws a moving line (Terminal.live).""" + return Terminal(sys.stdout).live + + +def _is_terminal(stream: TextIO) -> bool: + isatty = getattr(stream, "isatty", None) + try: + return bool(isatty and isatty()) + except (OSError, ValueError): + return False + + +def _confirm(prompt: str) -> bool: + """Yes unless the answer refuses: n, no, or one of the quit words.""" + answer = _ask(prompt).strip().lower() + return not (answer.startswith("n") or answer in _REFUSALS) + + +def _answer_yes(prompt: str) -> bool: + """Yes only to y or yes: a removal is never the default answer.""" + return _ask(prompt).strip().lower() in ("y", "yes") + + +# --- installer/paths.py ------------------------------------------------------ + def _path_characters(value: object, field: str, colons: bool = True) -> str: """The character rules every manifest-controlled relative path meets. @@ -1442,8 +2589,397 @@ def _entry_key(entry: dict) -> str: return f"{root}\0{dest}" if root in ("save", "emulators", *RELATIVE_ROOTS) else dest +def shown_path(path: Path | str) -> str: + """A path as the person names it: under WSL, /mnt/d/BIOS is D:\\BIOS, the + drive the card row calls D:.""" + text = str(spelled(path)) if os.path.isabs(str(path)) else str(path) + root = _WSL["root"].rstrip("/") + "/" + match = (re.match(rf"^{re.escape(root)}([a-z])(?:/(.*))?$", text) + if _WSL["active"] else None) + if match: + text = f"{match.group(1).upper()}:\\" + (match.group(2) or "").replace("/", "\\") + # A folder's name comes from whoever named it: a card's label, a + # retroarch.cfg, a pack. Printed raw, a control character in it is a + # terminal command. + return screen_text(text) + + +# --- installer/filesystems.py ------------------------------------------------ + +def keeps_case(directory: Path) -> bool: + """Whether names differing only by case are distinct files there. + + Probed on the nearest existing directory, since the filesystem decides, + not the operating system: an ext4 drive mounted on macOS keeps case and + a casefolded ext4 directory folds it. Unprobeable: the system's default. + """ + probe_dir = directory + while not _is_dir(probe_dir) and probe_dir != probe_dir.parent: + probe_dir = probe_dir.parent + try: + handle, name = tempfile.mkstemp(prefix=".retrobios-case-", dir=str(probe_dir)) + except OSError: + return sys.platform not in ("win32", "darwin") + os.close(handle) + try: + twin = os.path.join(os.path.dirname(name), os.path.basename(name).upper()) + return not os.path.exists(twin) + finally: + os.unlink(name) + + +def fold_case_twins(files: list[dict]) -> tuple[list[dict], list[str]]: + """One file per name where the directory folds case, the others named. + + The first in manifest order stays, as the pack's own order places it. + """ + kept: list[dict] = [] + seen: set[str] = set() + folded: list[str] = [] + for entry in files: + key = str(entry.get("dest", "")).casefold() + if key in seen: + folded.append(str(entry.get("dest", ""))) + continue + seen.add(key) + kept.append(entry) + return kept, folded + + +# The characters FAT and exFAT refuse in a name, as Windows does on any drive +# (Linux 7475ea8b, fs/fat/namei_vfat.c:201-207 and fs/exfat/nls.c:396-403; +# "Naming Files, Paths, and Namespaces" in the Win32 documentation). The +# slash, the backslash and the controls never reach a destination +# (_safe_relative_path). RetroDECK names three files zxs:48.rom, +# zxs:if1-2.rom and snes:st018.data.rom (its retroarch component manifest): +# on an exFAT card each write failed, on every run. +FAT_REFUSED = re.compile(r'[<>:"|?*]') +FAT_REFUSED_SHOWN = '< > : " | ? *' + + +def holds_fat_refused_names(directory: Path) -> bool: + """Whether a name holding a colon can be created there. + + Probed on the nearest existing directory, as keeps_case is: an ext4 + card on a Steam Deck holds one, an exFAT card refuses it with EINVAL. + Windows refuses it on every drive. A probe refused for another cause + (a folder this user cannot write) decides nothing. + """ + if os.name == "nt": + return False + probe_dir = directory + while not _is_dir(probe_dir) and probe_dir != probe_dir.parent: + probe_dir = probe_dir.parent + try: + handle, name = tempfile.mkstemp(prefix=".retrobios-name-", suffix=":", + dir=str(probe_dir)) + except OSError as exc: + return exc.errno != errno.EINVAL + os.close(handle) + os.unlink(name) + return True + + +def split_fat_refused(files: list[dict]) -> tuple[list[dict], list[str]]: + """The entries whose destination a FAT, exFAT or Windows folder can + hold, and the destinations it cannot.""" + kept = [entry for entry in files if not FAT_REFUSED.search(str(entry.get("dest", "")))] + refused = [str(entry.get("dest", "")) for entry in files + if FAT_REFUSED.search(str(entry.get("dest", "")))] + return kept, refused + + +# Android's media scanner marks a folder holding a .nomedia file hidden, and +# every folder below it (MediaProvider a183e2b9, FileUtils.java:1587-1629 +# isDirectoryHidden, ModernMediaScanner.java:845-846 and 1017-1020). Without +# one, the samples, overlays and videos of a BIOS folder in shared storage +# showed in the phone's gallery and music apps. RetroArch writes none +# (libretro-common/file/file_path_io.c:194 only skips one). +NOMEDIA = ".nomedia" + + +def hide_from_media_scanner(folder: Path) -> bool: + """Leave an empty .nomedia in folder, True when this call wrote it.""" + marker = folder / NOMEDIA + if not _is_dir(folder) or _exists(marker): + return False + try: + marker.touch() + except OSError as exc: + print(f" {NOMEDIA} not written in {shown_path(folder)}: {exc.strerror}", + file=sys.stderr) + return False + return True + + +def mountinfo_types(text: str) -> list[tuple[str, str]]: + """(mount point, file system type) of each line of /proc/self/mountinfo: + the point is field 5, its space, tab and backslash written as octal + escapes, the type the first field after the " - " separator (proc(5)).""" + mounts = [] + for line in text.splitlines(): + head, _sep, tail = line.partition(" - ") + fields = head.split(" ") + if len(fields) > 4 and tail: + point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), fields[4]) + mounts.append((point, tail.split(" ")[0])) + return mounts + + +def mount_list_types(text: str) -> list[tuple[str, str]]: + """(mount point, file system type) of each line macOS's mount prints: + "/dev/disk4s1 on /Volumes/CARD (msdos, local, nodev)".""" + return [(found[1], found[2]) for found in + (re.match(r".+? on (.+) \(([^,)]+)", line) for line in text.splitlines()) + if found] + + +def fat_mounted(target: Path, mounts: list[tuple[str, str]]) -> bool: + """Whether the deepest mount holding target is FAT (vfat on Linux, + msdos on macOS).""" + best = "" + kind = "" + for point, fstype in mounts: + mount = Path(point) + if (target == mount or mount in target.parents) and len(point) >= len(best): + best, kind = point, fstype + return kind.lower() in ("vfat", "msdos", "fat") + + +def fat32_drive(folder: Path) -> bool: + """Whether folder is on a FAT32 (or FAT16) drive, which holds no file of + 4 GiB: the mount table's type on Linux, the volume's file system on + Windows, the mount list on macOS. False where the system does not say.""" + probe = folder + while not _is_dir(probe) and probe != probe.parent: + probe = probe.parent + if os.name == "nt": + try: + import ctypes + root = ctypes.create_unicode_buffer(261) + kind = ctypes.create_unicode_buffer(261) + kernel = _kernel32() + if not kernel.GetVolumePathNameW(str(probe), root, 261): + return False + if not kernel.GetVolumeInformationW(root, None, 0, None, None, None, kind, 261): + return False + except (AttributeError, OSError): + return False + return kind.value.upper() in ("FAT32", "FAT") + try: + target = probe.resolve() + if sys.platform == "darwin": + listing = subprocess.run(["/sbin/mount"], capture_output=True, text=True, + timeout=5, check=False).stdout + return fat_mounted(target, mount_list_types(listing)) + text = Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace") + except (OSError, subprocess.SubprocessError): + return False + return fat_mounted(target, mountinfo_types(text)) + + +# --- installer/local_check.py ------------------------------------------------ + +def _digest_file(path: Path, algorithms: tuple[str, ...]) -> dict[str, str]: + """Compute several digests of a file in a single read. + + Checking a 3 GB collection against both a SHA-1 and a SHA-256 used to walk + every file twice, single threaded. Hashing is cheap next to the I/O, so + the read is what has to happen once. + """ + with open(path, "rb") as fh: + return _digest_handle(fh, algorithms) + + +def _digest_handle(fh: IO[bytes], algorithms: tuple[str, ...]) -> dict[str, str]: + """Digests of an open file, read from its start.""" + hashers = {name: hashlib.new(name) for name in algorithms} + fh.seek(0) + for chunk in iter(lambda: fh.read(1024 * 1024), b""): + for hasher in hashers.values(): + hasher.update(chunk) + return {name: hasher.hexdigest() for name, hasher in hashers.items()} + + +def _sha1_file(path: Path) -> str: + """Compute SHA1 of a file.""" + return _digest_file(path, ("sha1",))["sha1"] + + +def _sha256_file(path: Path) -> str: + """Compute SHA256 of a file.""" + return _digest_file(path, ("sha256",))["sha256"] + + +# The digests the line menu's head read of the files in place, by path and +# by what stat says of the file, kept for the check that follows Enter: the +# head named a wrong copy of the right size in place, +# and a card read twice is read at the speed of its reader. Emptied once +# that check has read them (head_reads_done). +_HEAD_READS: dict[tuple, dict[str, str]] = {} + + +def _stat_key(path: Path) -> tuple | None: + """What tells a file apart from the same path rewritten: None for none.""" + try: + info = path.stat() + except OSError: + return None + return (str(path), info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_ino) + + +def _read_digests(path: Path, algorithms: tuple[str, ...], remember: bool = False) -> dict: + """_digest_file, answered from what the head read when the file is the + same one, and remembered for the check when remember is set.""" + key = _stat_key(path) + known = _HEAD_READS.get((key, algorithms)) if key is not None else None + if known is not None: + return known + digests = _digest_file(path, algorithms) + if remember and key is not None: + _HEAD_READS[(key, algorithms)] = digests + return digests + + +def head_reads_done() -> None: + """The check after the head has read what it holds: nothing more is + answered from it, a file the run writes being read again.""" + _HEAD_READS.clear() + + +def _classify_local(entry: dict, dest: Path, remember: bool = False) -> str: + """Return 'up_to_date' or 'mismatched' for a file already on disk. + remember keeps what was read for the check after the line menu.""" + expected = { + name: entry.get(name, "").lower() + for name in ("sha256", "sha1") + if entry.get(name) + } + try: + is_file = dest.is_file() + except OSError: + # A folder above it this user cannot enter: what sits there is not + # known to be the right file. + return "mismatched" + if not is_file: + # A folder at the file's place: --check says so, an install fails + # on that file alone. + return "mismatched" + if not expected: + return "up_to_date" + try: + actual = _read_digests(dest, tuple(expected), remember) + except OSError: + # Unreadable (no permission, a read error on a failing card): its + # contents are not known to be the right ones. + return "mismatched" + if all(actual[name] == value for name, value in expected.items()): + return "up_to_date" + return "mismatched" + + +def closed_folder_words(dest: Path, closed: tuple[Path, str]) -> str: + folder, why = closed + return f"this user cannot open {folder} ({why}), which holds {dest}" + + +def unreachable_words(exc: OSError) -> str: + """Why the place of a file could not be looked at, in words.""" + return (f"could not be read ({exc.strerror or exc}): this user may not " + f"have access to its folder") + + +def check_local( + files: list[dict], bios_path: Path, jobs: int = 8, + term: "Terminal | None" = None, +) -> tuple[list[dict], list[dict], list[dict]]: + """Check which files exist locally and have correct hashes. + + Returns (to_download, up_to_date, mismatched). With a terminal, a count + moves while the files are read: 3.9 GB on an SD card went by in minutes + of silence, read as a hung run and stopped with Ctrl+C. + """ + to_download: list[dict] = [] + present: list[tuple[dict, Path]] = [] + + for f in files: + dest = _entry_path(bios_path, f) + if _held(dest): + present.append((f, dest)) + else: + to_download.append(f) + + up_to_date: list[dict] = [] + mismatched: list[dict] = [] + if present: + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + verdicts = pool.map( + lambda item: (item[0], _classify_local(item[0], item[1])), present + ) + shown = term if term is not None and term.live and not term.quiet else None + last = evented = 0.0 + for done, (entry, verdict) in enumerate(verdicts, 1): + if verdict == "up_to_date": + up_to_date.append(entry) + else: + mismatched.append(entry) + now = time.monotonic() + # The program driving the installer gets the count the + # terminal gets: a screen with a bare timer over 6 GB on an + # SD card read as hung. + if EVENTS.on and (now - evented >= EVENT_PROGRESS_INTERVAL + or done == len(present)): + evented = now + EVENTS.emit("checking", files_done=done, files_total=len(present)) + if shown is not None and (now - last >= 0.1 or done == len(present)): + last = now + print(f"\r read {done}/{len(present)}", end="", file=shown.stream, + flush=True) + if shown is not None: + print("\r\033[K", end="", file=shown.stream, flush=True) + + return to_download, up_to_date, mismatched + + # --- installer/manifest.py --------------------------------------------------- +# Why a manifest leaves a file out, as the installer words it. The manifest +# schema and the generator are held to this list by the tests. +OMISSION_REASONS = { + "hash_mismatch": "hash mismatch", + "not_found": "not found", + "external": "external", + "user_provided": "user provided", + "no_platform_slug": "no platform folder", + "below_platform_folder": "below the platform folder", + "no_save_directory": "no save directory", + "no_core_folder": "no core folder", + "no_save_system": "no system runs the core", + "outside_bios_folder": "read outside the BIOS folder", + "no_roms_directory": "no roms folder", + "no_configs_directory": "no configs folder", + "no_emulators_directory": "no emulator folder", +} +# What a file is when it is not firmware, as the manifest's category field +# says, and as the installer words it. Firmware carries no category. +GAME_DATA = "game_data" +CATEGORY_LABELS = {GAME_DATA: "game data"} +# The manifest writes its digests in lowercase, as hashlib gives them, and +# every comparison reads them as written. +_SHA1_RE = re.compile(r"^[0-9a-f]{40}$") +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") + + +# Marks a region group named after one file that no system names. +FILE_GROUP = ":file:" +MAX_SELECTION_TAGS = 1000 +SELECTION_FIELDS = ("systems", "regions", "region_groups", "region_system_groups") +# The files cores load for systems the platform does not list (game engines, +# computers): no system of the platform owns them, and choosing systems +# leaves them out unless this name is chosen too. +OTHER_SYSTEMS = "other" + + def _check_root(entry: dict, dest: str, omitted: bool = False) -> None: """root is absent or save, emulator only on a file left out (a path in the emulator's own folder, outside the BIOS tree), and core_folder one @@ -2178,965 +3714,58 @@ def _validate_targets(data: object) -> dict[str, dict]: return normalized -def board_target(board: str, targets: dict[str, dict]) -> str | None: - """The target a board name stands for: the name itself, else the one - target whose images carry it. A card names its image (Batocera writes - anbernic-rg35xx-plus for the h700 target, x86-64-v3 for zen3).""" - if board in targets: - return board - owners = [name for name, info in targets.items() if board in info.get("images", ())] - return owners[0] if len(owners) == 1 else None - - -NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a " - "proxy, then run the same command again.\n" - f" More help: {TROUBLESHOOTING_PAGE}") - - -# --- installer/probe.py ------------------------------------------------------ - -# Set under WSL: a Windows path read from a config or a rule names a drive -# that Linux sees under /mnt (drvfs). C:\\RetroBat\\bios was used as a relative -# path and nothing Windows-side was ever found from WSL. -# unasked: why Windows could not be asked for its folders, said once by -# detection. -_WSL: dict[str, Any] = {"active": False, "root": "/mnt", "unasked": ""} - - -def _host_path(text: str) -> Path: - """A path as this machine opens it: under WSL, C:\\X is /mnt/c/X.""" - match = re.match(r"^([A-Za-z]):(?:[\\/]+(.*))?$", text) if _WSL["active"] else None - if match: - rest = [part for part in re.split(r"[\\/]", match.group(2) or "") if part] - return Path(_WSL["root"], match.group(1).lower(), *rest) - return Path(text) - - -# Set while detection runs on this thread: a probe this user may not make -# is then said once, and the probes of other threads (the files being -# hashed) stay silent. -_SETUP_SEARCH = threading.local() - -# (folder, why in words) for each folder detection could not look in. -_DETECTION_REFUSED: list[tuple[Path, str]] = [] -# Those of them that failed for another cause than a permission: a read -# error from a failing card, a link that loops. -_DETECTION_UNREADABLE: set[Path] = set() -# The errors that say a place is not there, as against one that is there -# and could not be read. -_ABSENT_ERRNOS = (errno.ENOENT, errno.ENOTDIR, errno.EINVAL, errno.ENAMETOOLONG) - - -def refused_words(folder: Path, why: str, shown: str = "") -> str: - """The line said for a folder detection could not look in. shown is - the folder as the screen writes it (~/.config/EmuDeck), the full path - by default.""" - if _WSL["active"] and why == _WSL["unasked"] and folder == Path(_WSL["root"]): - return (f"Could not look for setups on the Windows side: {why}. " - "Run it again once Windows answers, or name the BIOS folder with --dest.") - if folder in _DETECTION_UNREADABLE: - return (f"Could not look for setups: {shown or folder} could not be read ({why}). " - "A failing card or a link that loops gives this: check it, or name the " - "BIOS folder with --dest.") - return (f"Could not look for setups: this user cannot open {shown or folder} ({why}). " - "Run as its owner (su - or sudo -H), or name the BIOS folder " - "with --dest.") - - -def _note_refused(path: Path, exc: OSError) -> None: - """Say once that a folder detection looks in is closed to this user, - or could not be read. - - A probe refused there counts as absent and the others go on: a config - folder a sudo run left at 0700 (~/.config/EmuDeck) hid a RetroArch whose - retroarch.cfg was readable, and the run fell back to a folder it does - not read. - """ - if (not getattr(_SETUP_SEARCH, "active", False) or getattr(_SETUP_SEARCH, "quiet", False) - or exc.errno in _ABSENT_ERRNOS): - return - refused = closed_folder(path) or (path, exc.strerror or str(exc)) - if refused in _DETECTION_REFUSED: - return - _DETECTION_REFUSED.append(refused) - if not isinstance(exc, PermissionError): - # An EIO on retroarch.cfg counted as absent: the card about to be - # written to failed, and the run said nothing was detected. - _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) - - -def _held(path: Path) -> bool: - """Whether something may sit at path. A place that cannot be looked at - (a folder above it this user cannot enter, a card that answers a read - error) counts as held, so the file is reported unreadable and the run - goes on with the others: Path.exists() lets PermissionError through.""" - try: - return path.exists() - except OSError: - return True - - -def _probed(probe: Callable[[], bool], path: Path) -> bool: - """probe() for path, False where the place cannot be looked at. A - refusal met while looking for setups is said once (_note_refused).""" - try: - found = probe() - except OSError as exc: - _note_refused(path, exc) - return False - if not found: - # Python 3.14's Path.exists() answers False where earlier ones - # raised: a refusal is told from absence by the stat it hides. - try: - os.stat(path) - except OSError as exc: - _note_refused(path, exc) - return found - - -def _exists(path: Path) -> bool: - """Path.exists(), False where the place cannot be looked at.""" - return _probed(path.exists, path) - - -def _is_dir(path: Path) -> bool: - """Path.is_dir(), False where the place cannot be looked at.""" - return _probed(path.is_dir, path) - - -def _is_file(path: Path) -> bool: - """Path.is_file(), False where the place cannot be looked at.""" - return _probed(path.is_file, path) - - -def _closed_to_this_user(path: Path) -> OSError | None: - """The error that keeps path from being looked at, None when it can - be, there or not.""" - try: - os.stat(path) - except OSError as exc: - return None if exc.errno in _ABSENT_ERRNOS else exc - return None - - -def closed_folder(path: Path) -> tuple[Path, str] | None: - """The folder above path this user cannot open, and why in words, or - None when path can be looked at, there or not. - - A BIOS folder under /root run without sudo, or a card mounted at 0700 - for another user: Path.exists() raised PermissionError before the - first line said where. - """ - try: - os.stat(path) - return None - except OSError as exc: - failure = exc - probe = path.absolute() - for folder in (*reversed(probe.parents), probe): - try: - os.stat(folder) - except OSError as exc: - if exc.errno in (errno.ENOENT, errno.ENOTDIR): - return None - why = exc.strerror or str(exc) - if exc.errno == errno.ELOOP: - # The link that loops, not the open folder holding it. - return folder, why - real = Path(os.path.realpath(folder)) - if real != folder: - # ~/Emulation linked into a closed card: the closed folder - # is under the link's target, and naming the link's - # parent told the user they cannot open their own HOME. - return closed_folder(real) or (real.parent, why) - return folder.parent, why - return probe, failure.strerror or str(failure) - - -# --- installer/prompt.py ----------------------------------------------------- - -def _names_and(names: list[str]) -> str: - """Names in a sentence: A, A and B, A, B and C.""" - return " and ".join(names) if len(names) < 3 else f"{', '.join(names[:-1])} and {names[-1]}" - - -def _typed_folder(raw: str) -> Path: - """A folder typed at a question, read as a shell reads an argument. - - Explorer's "Copy as path" puts quotes around it, and users quote a path - with spaces: kept, they sent the files into a folder named `"` under - the current directory, and the run said Done. - """ - text = raw.strip() - if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"": - text = text[1:-1].strip() - # Under WSL, D: and D:\ are the Windows drive the screen calls D:. - return _host_path(os.path.expandvars(os.path.expanduser(text))) - - -def _ask(prompt: str) -> str: - """An answer, or a stop: Ctrl+D at a question is Ctrl+C. - - Both used to leave with 0, so `install.sh && retroarch` went on with no - BIOS. They now end where Ctrl+C ends everywhere else, on 130. - """ - try: - return input(prompt).strip() - except EOFError: - print() - raise KeyboardInterrupt from None - - -# A quit chosen at a question or on the screen: nothing was installed, as -# gh ends a prompt cancelled. 130 is 128 plus SIGINT, which shells read as a -# run killed by Ctrl-C, and 0 let `install.sh && retroarch` start RetroArch -# on no BIOS. Ctrl-C and Ctrl-D keep 130. -QUIT_CODE = 2 - - -def _quit() -> None: - """q at a question ends the run on QUIT_CODE.""" - sys.exit(QUIT_CODE) - - -def _no_widow(lines: list[str], room: int) -> list[str]: - """Wrapped lines whose last one is not a word alone: "shared" stood on a - line of its own under its size at 40 columns. The - word before it goes down with it where both fit.""" - if len(lines) < 2 or len(_glued_words(lines[-1])) > 1: - return lines - # A size goes down with its unit: "1.4" / "MB shared" split it. - words = _glued_words(lines[-2]) - lead = lines[-2][:len(lines[-2]) - len(lines[-2].lstrip(" "))] - moved = f"{words[-1]} {lines[-1].strip()}" - if len(words) < 2 or cell_width(moved) > room: - return lines - return [*lines[:-2], lead + " ".join(words[:-1]), moved] - - -# --- installer/terminal.py --------------------------------------------------- - -def _kernel32() -> Any: - """kernel32 from ctypes.windll, which typeshed declares for win32 only. - AttributeError where the system has no windll.""" - import importlib - - return importlib.import_module("ctypes").windll.kernel32 - - -def _enable_ansi() -> bool: - """Whether escape sequences reach the terminal as colour and redraws. - - Windows 10 consoles interpret them once virtual terminal processing is - switched on. Older ones print them raw, so the answer is then no. - """ - if os.name != "nt": - return True - try: - import ctypes - - kernel32 = _kernel32() - handle = kernel32.GetStdHandle(-11) - mode = ctypes.c_uint32() - if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): - return False - return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004)) - except (AttributeError, OSError): - return False - - -# The roles text is painted with, from the 16 basic colours only: a -# handheld's Linux console has no more. The screens and the line questions -# name a role, never a code. Magenta is the hue that stays legible on black -# and on white in the xterm, VGA, Tango and Campbell palettes, so it is the -# accent, bold. Yellow reads poorly on white: it paints a status word, never -# a sentence. Bold red is bright red on the Linux console, where plain red on -# black is the weakest pair. -COLOUR_ROLES = { - "accent": "1;35", - "success": "32", - "warning": "33", - "failure": "1;31", - "muted": "2", - "strong": "1", - # The accent reversed: the row in focus, its > kept for no colour. - "selected": "7;35", -} - -# The words a status takes its role from, wherever it is said. A count of -# zero is no news and stays plain: "0 missing" is not a warning. -_STATUS_WORDS = tuple((re.compile(pattern), role) for pattern, role in ( - (r"(? list[tuple[int, int, str]]: - """The spans in order, none empty, the longer kept where two overlap.""" - kept: list[tuple[int, int, str]] = [] - for span in sorted(spans, key=lambda span: (span[0], -span[1])): - if span[1] > span[0] and (not kept or span[0] >= kept[-1][1]): - kept.append(span) - return kept - - -def status_spans(text: str) -> list[tuple[int, int, str]]: - """(start, end, role) of the status words in text, in order, apart.""" - return _apart([(match.start(), match.end(), role) for pattern, role in _STATUS_WORDS - for match in pattern.finditer(text)]) - - -def _sgr(role: str) -> str: - """The SGR sequence of a role, or of roles joined by + ("strong+success").""" - return "\033[0;" + ";".join(COLOUR_ROLES[name] for name in role.split("+")) + "m" - - -def painted(text: str, spans: list[tuple[int, int, str]], base: str = "") -> str: - """text with each span in its role and the rest in the base role, a code - written where the role changes and the colours reset at the end. The - characters are those of text, in the same order. A span in "plain" - takes the terminal's own colours.""" - pieces: list[tuple[str, str]] = [] - at = 0 - for start, end, role in spans: - pieces += [(text[at:start], base), (text[start:end], role)] - at = end - pieces.append((text[at:], base)) - out: list[str] = [] - current = "" - for piece, role in pieces: - role = "" if role == "plain" else role - if not piece: - continue - if role != current: - out.append(_sgr(role) if role else "\033[0m") - current = role - out.append(piece) - if current: - out.append("\033[0m") - return "".join(out) - - -_SGR = re.compile(r"\x1b\[[0-9;]*m") - - -def unpainted(text: str) -> str: - """text without its SGR codes.""" - return _SGR.sub("", text) - - -class Terminal: - """What the output stream can show: a live line, colour, or neither. - - A pipe or a log gets plain lines, and NO_COLOR and TERM=dumb or unset are - honoured, as is a terminal whose description moves no cursor the ANSI way - (vt52), or names fewer than 8 colours (vt100), which keeps the line live - and plain. - As no-color.org reads it, an empty NO_COLOR is not set: `NO_COLOR= cmd` - turned colour off. FORCE_COLOR or CLICOLOR_FORCE paints a pipe, for a - log viewer that shows colour, and never makes the line live. - """ - - def __init__(self, stream: TextIO | None = None, quiet: bool = False) -> None: - self.stream = stream or sys.stdout - self.quiet = quiet - isatty = getattr(self.stream, "isatty", None) - # An unset TERM is a dumb one, as the full screen reads it. A Windows - # console sets none and draws the sequences once _enable_ansi is on. - term = os.environ.get("TERM", "") - self.live = (bool(isatty and isatty()) and term != "dumb" - and (bool(term) or os.name == "nt") - and not terminal_without_ansi(os.environ)) - forced = any(os.environ.get(name, "0") not in ("", "0") - for name in ("FORCE_COLOR", "CLICOLOR_FORCE")) - self.colour = ( - ((self.live and not terminal_few_colours(os.environ)) or forced) - and not os.environ.get("NO_COLOR") and _enable_ansi() - ) - if not self.colour: - self.live = self.live and os.name != "nt" - - def paint(self, text: str, role: str) -> str: - return f"\033[{COLOUR_ROLES[role]}m{text}\033[0m" if self.colour else text - - def status(self, text: str) -> str: - """text with its status words in their roles (status_spans).""" - return painted(text, status_spans(text)) if self.colour else text - - def ok(self, text: str) -> str: - return self.paint(text, "success") - - def bad(self, text: str) -> str: - return self.paint(text, "failure") - - def dim(self, text: str) -> str: - return self.paint(text, "muted") - - def bold(self, text: str) -> str: - return self.paint(text, "strong") - - -class _Output: - """What a run's text says. By default: what will happen, where, the - progress, the result and the next step. --verbose adds every step, list - and reason, the lines a beginner lost the result among. where_said is - set once the BIOS folder was named before the result.""" - - verbose = False - where_said = False - - -OUTPUT = _Output() - - -def detail(*args: Any, **kwargs: Any) -> None: - """Print a line only --verbose shows.""" - if OUTPUT.verbose: - print(*args, **kwargs) - - -def format_duration(seconds: float) -> str: - """0:42, 3:05 or 1:02:09.""" - seconds = max(0, int(seconds + 0.5)) - hours, rest = divmod(seconds, 3600) - minutes, secs = divmod(rest, 60) - return f"{hours}:{minutes:02}:{secs:02}" if hours else f"{minutes}:{secs:02}" - - -# The fewest columns a line question lays itself out in: below it a row is -# all number, and the terminal folds what is printed whatever it is. -LINE_MIN_COLS = 20 - - -def terminal_size() -> tuple[int, int]: - """(columns, lines) of the terminal line mode prints to, the one reading - every layout of it makes. Python 3.8 gives a pty of no size as 0 and 0, - where 3.11 falls back to 80 and 24: a list laid out in 0 columns never - ended, the plan printed an empty heading, and the progress line lost - every figure but its percentage.""" - size = shutil.get_terminal_size((80, 24)) - return max(size.columns or 80, LINE_MIN_COLS), size.lines or 24 - - -class Progress: - """Bytes and files across the parallel downloads, shown as they move. - - On a terminal one line redraws in place: a bar, the bytes, the speed and - the time left. Elsewhere each finished file gets its line with --verbose, - as a log wants it. Failures are always printed, quiet or not. - """ - - BAR = 24 - - def __init__(self, total_files: int, total_bytes: int, term: Terminal, - events: bool = True) -> None: - self.total_files = total_files - self.expected_bytes = total_bytes - self.total_bytes = max(total_bytes, 1) - self.term = term - self.files = 0 - self.bytes = 0 - self.resumed = 0 - # Bytes that came from this machine and not the network: a copy - # found here, the pack, a resumed partial copy. - self.local = 0 - # Files written to their place, which a stopped run counts: the - # queue's length said "118 files installed" over 8 on disk. - self.installed = 0 - # The entries of those files, which the end of the run counts apart. - self.landed: list[dict] = [] - self.start = time.monotonic() - self._drawn = 0.0 - self._evented = self.start - self._lock = threading.Lock() - # A data tree's archive draws the line and writes no event: the - # progress events count the files of the download event. - self.events = events - - def expect(self, total_bytes: int) -> None: - """The size the transfer turns out to have, once its server says it.""" - with self._lock: - self.expected_bytes = total_bytes - self.total_bytes = max(total_bytes, 1) - - def add(self, count: int, resumed: bool = False, network: bool | None = None) -> None: - """count bytes written, resumed ones left out of the speed. network - is whether they came over the network, by default unless resumed.""" - with self._lock: - self.bytes += count - if resumed: - self.resumed += count - fetched = not resumed if network is None else network - if not fetched: - self.local += count - now = time.monotonic() - if self.term.live and not self.term.quiet and now - self._drawn >= 0.1: - self._drawn = now - self._draw() - if self.events and EVENTS.on and now - self._evented >= EVENT_PROGRESS_INTERVAL: - self._evented = now - EVENTS.emit("progress", files_done=self.files, files_total=self.total_files, - bytes_done=self.bytes, bytes_total=self.expected_bytes) - self.emit_transfer() - - def emit_transfer(self) -> None: - """The transfer event: of the bytes done, those this machine held - and those the network brought.""" - EVENTS.emit("transfer", bytes_local=self.local, - bytes_network=self.bytes - self.local) - - def forget_resumed(self, count: int) -> None: - with self._lock: - self.resumed -= count - self.local -= count - - def transferred(self) -> int: - """Bytes fetched by this run, a resumed partial copy excluded.""" - return self.bytes - self.resumed - - def done(self, dest: str, ok: bool, reason: str = "") -> None: - with self._lock: - self.files += 1 - line = None - if not ok and not self.term.quiet: - why = f" ({reason})" if reason else "" - line = f" {self.term.bad('FAILED')} {dest}{why}" - SAID_FAILED.add(dest) - elif not self.term.live and not self.term.quiet and OUTPUT.verbose: - line = f" [{self.files}/{self.total_files}] {dest} {self.term.ok('ok')}" - if line is not None: - self._clear() - print(line, file=self.term.stream, flush=True) - if self.term.live and not self.term.quiet: - self._draw() - - def finish(self) -> None: - with self._lock: - self._clear() - - def elapsed(self) -> float: - return time.monotonic() - self.start - - def _clear(self) -> None: - if self.term.live and not self.term.quiet: - print("\r\033[K", end="", file=self.term.stream, flush=True) - - def _draw(self) -> None: - share = min(self.bytes / self.total_bytes, 1.0) - elapsed = self.elapsed() - # A resumed partial copy was on disk before the run started: counted - # in the share, never in the speed. - speed = self.transferred() / elapsed if elapsed > 0 else 0 - left = (self.total_bytes - self.bytes) / speed if speed > 0 else 0 - # Copies from a folder here count in no speed: "0 B/s 0:00 left" - # was drawn under them, as the screen does not. - timed = [f"{format_size(int(speed))}/s", f"{format_duration(left)} left"] \ - if self.transferred() > 0 else [] - parts = [ - f"{share * 100:5.1f}%", - f"{format_size(self.bytes)} / {format_size(self.total_bytes)}", - *timed, - f"({self.files}/{self.total_files} files)", - ] - # One physical line, whatever the width: \r\033[K clears only the - # line the cursor is on, so a wrapped line left a ghost per redraw - # on an 80-column console. The bar gives way first, then the least - # telling figures. - width = terminal_size()[0] - 1 - while True: - tail = " ".join(parts) - room = width - len(tail) - 6 - if room >= 10 or len(parts) == 1: - break - parts.pop() - if room >= 10: - bar_width = min(self.BAR, room) - filled = int(share * bar_width) - text = f" [{'#' * filled}{'-' * (bar_width - filled)}] {tail}" - else: - text = f" {tail}" - print(f"\r\033[K{text[:width]}", end="", file=self.term.stream, flush=True) - - -# --events: one JSON object per line on stdout, for a program driving the -# installer (the handheld port shows its screens from them). Each kind has -# exactly these keys besides "event", in this order, and nothing else. -EVENT_SCHEMA = 1 - -# Seconds between two progress events while bytes arrive. -EVENT_PROGRESS_INTERVAL = 0.5 - -# The files a FAILED line of the progress named in this run: the end of -# the run names the others. -SAID_FAILED: set[str] = set() - -# Where ncurses finds a terminal's compiled description after $TERMINFO, -# ~/.terminfo and $TERMINFO_DIRS. -_TERMINFO_DIRS = ("/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo", - "/usr/lib/terminfo", "/usr/share/lib/terminfo") -# cursor_address, string capability 10 of term(5). -_TERMINFO_CUP = 10 -# max_colors, numeric capability 13. -_TERMINFO_COLORS = 13 - - -def _terminfo_folders(env: Mapping[str, str]) -> list[Path]: - folders = [Path(env["TERMINFO"])] if env.get("TERMINFO") else [] - if env.get("HOME"): - folders.append(Path(env["HOME"]) / ".terminfo") - # An empty entry stands for the system's folders, which come last anyway. - folders += [Path(part) for part in env.get("TERMINFO_DIRS", "").split(":") if part] - return folders + [Path(folder) for folder in _TERMINFO_DIRS] - - -def _terminfo_header(data: bytes) -> tuple[int, int, int, int, int] | None: - """Of a compiled term(5) entry: the width of a number, the counts of - names bytes, booleans, numbers and strings. None when data is none.""" - if len(data) < 12: - return None - # The legacy format stores numbers in 2 bytes, the extended one in 4. - width = {0o432: 2, 0o1036: 4}.get(int.from_bytes(data[0:2], "little", signed=True)) - if width is None: - return None - names, bools, numbers, strings = (int.from_bytes(data[at:at + 2], "little", signed=True) - for at in (2, 4, 6, 8)) - return width, names, bools, numbers, strings - - -def terminfo_number(data: bytes, index: int) -> int | None: - """Numeric capability index of a compiled term(5) entry, -1 when the - entry lacks it, None when data is no compiled entry.""" - header = _terminfo_header(data) - if header is None: - return None - width, names, bools, numbers, _strings = header - if index >= numbers: - return -1 - start = 12 + names + bools - start += start % 2 + index * width - if start + width > len(data): - return None - value = int.from_bytes(data[start:start + width], "little", signed=True) - return value if value >= 0 else -1 - - -def terminfo_string(data: bytes, index: int) -> str | None: - """String capability index of a compiled term(5) entry, "" when the - entry lacks it, None when data is no compiled entry.""" - def short(at: int) -> int: - return int.from_bytes(data[at:at + 2], "little", signed=True) - - header = _terminfo_header(data) - if header is None: - return None - width, names, bools, numbers, strings = header - offsets = 12 + names + bools - offsets += offsets % 2 + numbers * width - if index >= strings: - return "" - at = short(offsets + 2 * index) - if at < 0: - return "" - start = offsets + 2 * strings + at - end = data.find(b"\0", start) - if end < 0: - return None - return data[start:end].decode("latin-1") - - -def _terminfo_data(term: str, env: Mapping[str, str]) -> bytes | None: - """TERM's compiled description, the first found, None when none is: - Windows, Android and many handheld images carry none.""" - if not term or "/" in term or term.startswith("."): - return None - for folder in _terminfo_folders(env): - # Linux files xterm under x/, macOS under 78/. - for sub in (term[0], f"{ord(term[0]):02x}"): - try: - return (folder / sub / term).read_bytes() - except (OSError, ValueError): - continue - return None - - -def terminal_cursor_address(term: str, env: Mapping[str, str]) -> str | None: - """How TERM's description here moves the cursor, "" when it cannot, - None when no description is found, and the screen is not held back - for it.""" - data = _terminfo_data(term, env) - return None if data is None else terminfo_string(data, _TERMINFO_CUP) - - -def terminal_colours(term: str, env: Mapping[str, str]) -> int | None: - """The colours TERM's description here names, 0 when it names none - (vt100), None when no description is found or it cannot be read.""" - data = _terminfo_data(term, env) - if data is None: - return None - count = terminfo_number(data, _TERMINFO_COLORS) - return None if count is None else max(count, 0) - - -def terminal_few_colours(env: Mapping[str, str]) -> str: - """Why TERM's description here leaves colour off, "" when it does not: - no description is no refusal, as for the cursor.""" - if os.name == "nt": - return "" - term = env.get("TERM", "") - count = terminal_colours(term, env) - if count is not None and count < 8: - return f"TERM={term} names {count} colours, fewer than 8" - return "" - - -def terminal_without_ansi(env: Mapping[str, str]) -> str: - """Why TERM's description here says the ANSI sequences the screen and - the progress line write would print as text, "" when it does not.""" - if os.name == "nt": - return "" - term = env.get("TERM", "") - cup = terminal_cursor_address(term, env) - if cup == "": - return f"TERM={term} cannot move the cursor" - if cup is not None and not cup.startswith(("\x1b[", "\x9b")): - return f"TERM={term} does not take the escape sequences the screen is drawn with" - return "" - - -# --- installer/embedded.py --------------------------------------------------- - -def shown_path(path: Path | str) -> str: - """A path as the person names it: under WSL, /mnt/d/BIOS is D:\\BIOS, the - drive the card row calls D:.""" - text = str(spelled(path)) if os.path.isabs(str(path)) else str(path) - root = _WSL["root"].rstrip("/") + "/" - match = (re.match(rf"^{re.escape(root)}([a-z])(?:/(.*))?$", text) - if _WSL["active"] else None) - if match: - text = f"{match.group(1).upper()}:\\" + (match.group(2) or "").replace("/", "\\") - # A folder's name comes from whoever named it: a card's label, a - # retroarch.cfg, a pack. Printed raw, a control character in it is a - # terminal command. - return screen_text(text) - - -class _OsRule(NamedTuple): - """One piece of evidence that names an embedded system. - - manifest is the platform whose files it gets, "" for a system the - installer does not lay out. name is the system's own name. values are the - KEY=value pairs of os_release (any one), the files of file_exists (all), - or the file and the pattern of file_matches. bios is the folder used when - none of configs (retroarch.cfg files, read in order, `*` allowed) names a - system_directory. home is what `~` means to that system's RetroArch. - base is the system this one is built on: both match, this one is meant. - """ - - manifest: str - name: str - method: str - values: tuple[str, ...] - bios: str | None - configs: tuple[str, ...] = () - home: str = "" - base: str = "" - - -# The platform whose files each of these systems gets. They publish their own -# BIOS list, and these platforms transcribe it. -_STANDIN_MANIFESTS = { - "AmberELEC": "amberelec", - "EmuELEC": "emuelec", - "KNULLI": "knulli", -} - -# Where the ELEC family keeps RetroArch: the config runemu writes and copies -# back on every launch, and HOME=/storage for the services that start it. -_ELEC_CONFIGS = ("/storage/.config/retroarch/retroarch.cfg",) -# ArkOS and dArkOS: the 64-bit and the 32-bit RetroArch. "Switch to SD2 for -# Roms" rewrites /roms/ to /roms2/ in both (darkos daecf488, -# scripts/Switch to SD2 for Roms.sh:91-92), so a second card is read here. -_ARK_CONFIGS = ("/home/ark/.config/retroarch/retroarch.cfg", - "/home/ark/.config/retroarch32/retroarch.cfg") -_PLYMOUTH_TITLE = "/usr/share/plymouth/themes/text.plymouth" - -# muOS runs RetroArch on the config it copies from its default on first launch -# (internal f41f4a89, script/control/retroarch.sh:8-20). The default names -# /run/muos/storage/bios, a bind mount of MUOS/bios on the second card when -# that card holds one, else on the first (script/device/bind.sh:4,116-150), -# and loads cores from /opt/muos/share/core (retroarch.default.cfg:2806,3151). -MUOS_RETROARCH_CONFIGS = ( - "/opt/muos/share/info/config/retroarch.cfg", - "/opt/muos/share/emulator/retroarch/retroarch.default.cfg", +# --- installer/platforms.py -------------------------------------------------- + +# The platforms that publish a core list per board, install/targets/ in the +# repository: a test holds the two equal. Offline, a platform outside it +# has no hardware targets, where the run sent the user after a list that +# exists nowhere. +TARGET_PLATFORMS = frozenset({ + "amberelec", "batocera", "emudeck", "emuelec", "knulli", "lakka", "recalbox", "retroarch", + "retrobat", "retrodeck", "retropie", "rocknix", "romm", +}) + + +# Platforms with a manifest in install/. Manifest URLs are case sensitive, +# so user input is normalized against this list before any fetch. +AVAILABLE_PLATFORMS = ( + "retroarch", "batocera", "recalbox", "retrobat", "emudeck", + "lakka", "retrodeck", "rocknix", "romm", "bizhawk", "misterfpga", + "retropie", "amberelec", "emuelec", "knulli", + "minui", "nextui", "myminui", ) -# Embedded systems, by what their own builds write. The registry publishes the -# same rules as each manifest's `detect`, and a test holds the two equal. -# MiSTer is a path rule below. -_EMBEDDED_RULES: tuple[_OsRule, ...] = ( - # ROCKNIX writes OS_NAME and no ID since 2025 (scripts/image). Older - # images wrote ID=rocknix. - _OsRule("rocknix", "ROCKNIX", "os_release", ("OS_NAME=rocknix", "ID=rocknix"), - "/storage/roms/bios"), - # Knulli (knulli-linux 57afa662): OS_NAME in os-release - # (board/scripts/post-build-script.sh:233-236) and knulli.version - # (package/system/knulli-system/knulli-system.mk:98-102). - _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "os_release", ("OS_NAME=knulli",), - "/userdata/bios", base="Batocera"), - _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "file_exists", - ("/usr/share/knulli/knulli.version",), "/userdata/bios", base="Batocera"), - _OsRule("lakka", "Lakka", "os_release", ("ID=lakka",), "/storage/system"), - # batocera.linux 38845725, batocera-system.mk:21-22 (the same lines in - # batocera-30): batocera.arch and batocera.version. - _OsRule("batocera", "Batocera", "file_exists", ("/usr/share/batocera/batocera.version",), - "/userdata/bios"), - _OsRule("recalbox", "Recalbox", "file_exists", ("/recalbox/recalbox.version",), - "/recalbox/share/bios"), - _OsRule("recalbox", "Recalbox", "file_exists", ("/usr/bin/recalbox-settings",), - "/recalbox/share/bios"), - _OsRule("retroarch", "muOS", "file_exists", ("/opt/muos",), "/run/muos/storage/bios", - configs=MUOS_RETROARCH_CONFIGS), - _OsRule("retroarch", "muOS", "file_exists", ("/mnt/mmc/MUOS",), "/mnt/mmc/MUOS/bios"), - # AmberELEC 5a3882cb: scripts/image:150-152 writes NAME="${DISTRONAME}", - # AmberELEC in distributions/AmberELEC/options:17. CHAos (tech4bot/AmberELEC - # c0a4b0c6) is built from the same tree and writes the same name - # (distributions/AmberELEC/options:14). runemu.py:22 launches with - # /storage/.config/retroarch/retroarch.cfg, whose default is "~/roms/bios" - # (packages/games/tools/retroarch/sources/retroarch.cfg:611), and - # emustation.service:6 sets HOME=/storage. - _OsRule(_STANDIN_MANIFESTS["AmberELEC"], "AmberELEC", "os_release", ("NAME=AmberELEC",), - "/storage/roms"), - # PAN4ELEC (Kegg1701/P4ELEC 9c19bfb2), an overlay on an AmberELEC image: - # AmberELEC/usr/bin/batocera-info:101 prints its name. - _OsRule(_STANDIN_MANIFESTS["AmberELEC"], "PAN4ELEC", "file_matches", - ("/usr/bin/batocera-info", r"OPERATING SYSTEM: PAN4ELEC"), - "/storage/roms", base="AmberELEC"), - # EmuELEC d4c7b2f1: scripts/image:172-176 NAME and ID from DISTRONAME, - # EmuELEC in distributions/EmuELEC/options:4. setsettings.sh:22 names the - # config, and libretro_base/retroarch/package.mk:117 sets its - # system_directory to /storage/roms/bios. - _OsRule(_STANDIN_MANIFESTS["EmuELEC"], "EmuELEC", "os_release", ("NAME=EmuELEC",), - "/storage/roms"), - # JELOS 7b2e116c: scripts/image:118-120 OS_NAME="${DISTRONAME}", JELOS in - # distributions/JELOS/options:17. runemu.sh:37 names the config, whose - # default is "~/roms/bios" (retroarch/sources/RK3566/retroarch.cfg:716), - # and emustation.service:8 sets HOME=/storage. - _OsRule("retroarch", "JELOS", "os_release", ("OS_NAME=JELOS",), - "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), - # KOLOS (AnonLinuxOS/KOLOS 7daf5950) keeps OS_NAME=JELOS - # (distributions/JELOS/options:17) and adds jelos-ready.service - # ("KOLOS system ready script"), installed by scripts/install:100-102. - _OsRule("retroarch", "KOLOS", "file_exists", - ("/usr/lib/systemd/system/jelos-ready.service",), - "/storage/roms/bios", _ELEC_CONFIGS, "/storage", base="JELOS"), - # UnofficialOS 22635796: scripts/image:119-120 OS_NAME, UnofficialOS in - # distributions/UnofficialOS/options:17, config at - # packages/unofficialos/sources/scripts/runemu.sh:37. - _OsRule("retroarch", "UnofficialOS", "os_release", ("OS_NAME=UnofficialOS",), - "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), - # Arch R (archr-linux/Arch-R dbd45d45): scripts/image:164-177 NAME and - # OS_NAME, ArchR in distributions/ArchR/options:17. factoryreset:9-10 - # names the config, whose default is "~/roms/bios" - # (retroarch/sources/RK3326/retroarch.cfg:718). - _OsRule("retroarch", "ArchR", "os_release", ("OS_NAME=ArchR",), - "/storage/roms/bios", _ELEC_CONFIGS, "/storage"), - # ArkOS: the user and the menu folder, and the boot splash title its - # updates write (christianhaitian/arkos dedf4278, Update-RGB10.sh:76). - _OsRule("retroarch", "ArkOS", "file_exists", ("/home/ark", "/opt/system"), "/roms/bios", - _ARK_CONFIGS), - _OsRule("retroarch", "ArkOS", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*ArkOS\b"), - "/roms/bios", _ARK_CONFIGS), - # dArkOS daecf488: finishing_touches.sh:359-361 writes "title=dArkOS - # ()", kept by the dArkOSRE, dArkOSen and ArkOS4Clone overlays. - # Default system_directory "/roms/bios" (retroarch.cfg.rgb10:3043). - _OsRule("retroarch", "dArkOS", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*dArkOS"), - "/roms/bios", _ARK_CONFIGS, base="ArkOS"), - # RetroOZ 0.60 image (no build source is published): title=RetroOZ in - # the splash theme, /opt/.retrooz/version, and /etc/retrooz_version, the - # file PortMaster reads (device_info.txt:95). RetroArch is started with - # --config /home/odroid/.config/retroarch/retroarch.cfg (es_systems.cfg), - # system_directory "/roms/bios" (retroarch32/retroarch.cfg:3046). - _OsRule("retroarch", "RetroOZ", "file_matches", (_PLYMOUTH_TITLE, r"^title=\s*RetroOZ"), - "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", - "/home/odroid/.config/retroarch32/retroarch.cfg")), - _OsRule("retroarch", "RetroOZ", "file_exists", ("/opt/.retrooz",), - "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", - "/home/odroid/.config/retroarch32/retroarch.cfg")), - _OsRule("retroarch", "RetroOZ", "file_exists", ("/etc/retrooz_version",), - "/roms/bios", ("/home/odroid/.config/retroarch/retroarch.cfg", - "/home/odroid/.config/retroarch32/retroarch.cfg")), - # TheRA is left undetected: no image or source of its Odroid Go builds is - # published, so neither its markers nor its folder could be read. - # spruceOS 824b1aae: the spruce folder at the card root. RetroArch reads - # Saves/ra-configs/retroarch-.cfg (spruce/scripts/ - # helperFunctions.sh:157-165), seeded with system_directory - # "/mnt/SDCARD/BIOS" (RetroArch/platform/retroarch-Brick.cfg.bak:3279). - _OsRule("retroarch", "spruceOS", "file_exists", ("/mnt/SDCARD/spruce",), - "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/Saves/ra-configs/retroarch-*.cfg",), - base="TrimUI"), - # CrossMix-OS 206d612f: crossmix-version.txt (System/usr/trimui/scripts/ - # update_common.sh:20), RetroArch/retroarch.cfg:3202 (patch_ra_cfg.sh:5). - _OsRule("retroarch", "CrossMix-OS", "file_exists", - ("/mnt/SDCARD/System/usr/trimui/crossmix-version.txt",), - "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/retroarch.cfg",), base="TrimUI"), - # Onion 07505ea5: Makefile:75-76 writes onionVersion/version.txt, and - # static/build/.tmp_update/script/patch_ra_cfg.sh:6 names the config - # (system_directory at static/configs/RetroArch/.retroarch/retroarch.cfg:3009). - _OsRule("retroarch", "Onion", "file_exists", - ("/mnt/SDCARD/.tmp_update/onionVersion/version.txt",), - "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), - # Allium ee0dda97: its base folder /mnt/SDCARD/.allium - # (crates/common/src/constants.rs:19-34). RetroArch runs with - # HOME=/mnt/SDCARD/RetroArch on .retroarch/retroarch.cfg - # (static/.allium/cores/retroarch/launch_without_savestate_auto_load.sh:2-7), - # and Allium's RetroArch patch makes $ROOT/BIOS the default system folder. - _OsRule("retroarch", "Allium", "file_exists", ("/mnt/SDCARD/.allium",), - "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), - # Koriki 8513071c: src/systemInfo/main.c:106 reads Koriki/version.txt, - # .tmp_update/runtime.sh:271 installs RetroArch/.retroarch/retroarch.cfg - # (system_directory at base/RetroArch/.retroarch/retroarch.cfg:3191). - _OsRule("retroarch", "Koriki", "file_exists", ("/mnt/SDCARD/Koriki/version.txt",), - "/mnt/SDCARD/BIOS", ("/mnt/SDCARD/RetroArch/.retroarch/retroarch.cfg",)), - # MiyooCFW (buildroot d5912eeb): board/miyoo/rootfs/etc/main sets HOME=/mnt - # (line 4), package/miyoo/miyoo-ctl/miyoo-ctl.mk:12 installs miyooctl. - # RetroArch is a DINGUX build: $HOME/.retroarch/retroarch.cfg, and - # $HOME/.retroarch/system when no config names a folder. - _OsRule("retroarch", "MiyooCFW", "file_exists", ("/etc/main", "/usr/bin/miyooctl"), - "/mnt/.retroarch/system", ("/mnt/.retroarch/retroarch.cfg",), "/mnt"), - # plumOS: os-release ID=plumos (game-de-it/plumOS-pixel2_v2 dec872c0, - # rootfs/pixel2/etc/os-release:2, PortMaster device_info.txt:101). Each - # device build appends its own system_directory at launch: the Pixel 2 - # build /mnt/plumos-user/bios (package/app-layer-pixel2/bin/ - # plumos-retroarch-launch:342, mount point made by rootfs/pixel2/sbin/ - # init:29), the MF build /BIOS (plumOS-MF 0095017c, - # plumos-retroarch-launch:15). Only the first is told apart by a file. - _OsRule("retroarch", "plumOS", "file_exists", ("/mnt/plumos-user",), - "/mnt/plumos-user/bios"), - _OsRule("retroarch", "plumOS", "os_release", ("ID=plumos",), None), - # TrimUI's stock firmware publishes no source naming its RetroArch BIOS - # folder. PortMaster finds its libraries in /usr/trimui - # (trimui/launch_hooks.txt:37). Named so that what runs on top of it is - # told apart, never installed to by a guess. - _OsRule("", "TrimUI", "file_exists", ("/usr/trimui",), None), - # MinUI, MyMinUI and NextUI keep their system in .system at the card root - # (MinUI dbf89435, workspace/all/common/defines.h:14-16) and give each core - # Bios// (workspace/all/minarch/minarch.c:2942). Their file lists - # write that layout below the card root, and the card's version.txt - # says which of the three it is (card_platform). - _OsRule("", "MinUI", "file_exists", ("/mnt/SDCARD/.system/res",), None, base="TrimUI"), - _OsRule("", "MinUI", "file_exists", ("/mnt/sdcard/.system/res",), None, base="TrimUI"), - _OsRule("retroarch", "Anbernic stock firmware", "file_exists", - ("/mnt/vendor/bin/dmenu.bin",), "/mnt/mmc/bios"), -) +# The names the frontends give themselves, as each manifest's display_name +# spells them (a test holds the two equal). Detection and the platform menu +# come before any manifest is fetched, and str.capitalize() wrote Retroarch, +# Retrodeck and Misterfpga. +PLATFORM_NAMES = { + "retroarch": "RetroArch", "batocera": "Batocera", "recalbox": "Recalbox", + "retrobat": "RetroBat", "emudeck": "EmuDeck", "lakka": "Lakka", + "retrodeck": "RetroDECK", "rocknix": "ROCKNIX", "romm": "RomM", + "bizhawk": "BizHawk", "misterfpga": "MiSTer FPGA", "retropie": "RetroPie", + "amberelec": "AmberELEC", "emuelec": "EmuELEC", "knulli": "KNULLI", + "minui": "MinUI", "nextui": "NextUI", "myminui": "MyMinUI", +} + + +# Fallback BIOS destination per platform when --platform is forced +# but auto-detection finds nothing on the machine. +DEFAULT_DESTS = { + "batocera": Path("/userdata/bios"), + "recalbox": Path("/recalbox/share/bios"), + "lakka": Path("/storage/system"), + "retrodeck": Path.home() / "retrodeck", + "emudeck": Path.home() / "Emulation" / "bios", + "rocknix": Path("/storage/roms/bios"), + # Their BIOS lists name files under /storage/roms beside bios/. + "amberelec": Path("/storage/roms"), + "emuelec": Path("/storage/roms"), + "knulli": Path("/userdata/bios"), + "misterfpga": Path("/media/fat/games"), + "retropie": Path.home() / "RetroPie" / "BIOS", + "romm": Path("/romm/library/bios"), +} def display_name(plat: str, manifest: dict | None = None) -> str: @@ -3152,6 +3781,226 @@ def _name_key(name: str) -> str: return re.sub(r"[^a-z0-9]", "", name.lower()) +# A list this short is printed whole rather than pointed at. +SHORT_LIST = 12 + + +# Names people type for a system, each with its id. Only ever suggested: +# --system gba, psx and ps1 were refused with no hint on RetroArch, whose +# list names no system that way, and taking one in silence could install +# another console than the one meant. +SYSTEM_SHORT_NAMES = { + **dict.fromkeys(("psx", "ps1", "ps", "playstation1"), "sony-playstation"), + "ps2": "sony-playstation-2", "ps3": "sony-playstation-3", "psp": "sony-psp", + **dict.fromkeys(("vita", "psvita"), "sony-playstation-vita"), + "gb": "nintendo-gb", "gbc": "nintendo-gbc", "gba": "nintendo-gba", + **dict.fromkeys(("nes", "famicom", "fc"), "nintendo-nes"), "fds": "nintendo-fds", + **dict.fromkeys(("snes", "sfc", "superfamicom"), "nintendo-snes"), + "n64": "nintendo-64", "n64dd": "nintendo-64dd", "sgb": "nintendo-sgb", + **dict.fromkeys(("nds", "ds"), "nintendo-ds"), "dsi": "nintendo-dsi", + "3ds": "nintendo-3ds", "wiiu": "nintendo-wii-u", "switch": "nintendo-switch", + **dict.fromkeys(("gc", "ngc", "gcn", "gamecube"), "nintendo-gamecube"), + "pokemini": "nintendo-pokemon-mini", + **dict.fromkeys(("md", "gen", "genesis", "megadrive"), "sega-mega-drive"), + **dict.fromkeys(("scd", "segacd", "megacd"), "sega-mega-cd"), + "32x": "sega-32x", **dict.fromkeys(("sms", "mastersystem"), "sega-master-system"), + **dict.fromkeys(("gg", "gamegear"), "sega-game-gear"), + **dict.fromkeys(("ss", "saturn"), "sega-saturn"), + **dict.fromkeys(("dc", "dreamcast"), "sega-dreamcast"), + **dict.fromkeys(("naomi", "atomiswave"), "sega-dreamcast-arcade"), + **dict.fromkeys(("pce", "tg16", "turbografx", "turbografx16", "pcengine", + "supergrafx"), "nec-pc-engine"), + **dict.fromkeys(("pcecd", "tgcd", "turbografxcd"), "nec-pc-engine-cd"), + "pcfx": "nec-pc-fx", + **dict.fromkeys(("neogeo", "mvs", "aes"), "snk-neogeo"), + **dict.fromkeys(("neocd", "neogeocd"), "snk-neogeo-cd"), + **dict.fromkeys(("msx", "msx2"), "microsoft-msx"), + "c64": "commodore-c64", "c128": "commodore-c128", + **dict.fromkeys(("amiga", "cd32"), "commodore-amiga"), + "x68k": "sharp-x68000", **dict.fromkeys(("jag", "jaguar"), "atari-jaguar"), + **dict.fromkeys(("st", "atarist"), "atari-st"), "a800": "atari-400-800", + **dict.fromkeys(("coleco", "colecovision"), "coleco-colecovision"), + **dict.fromkeys(("intv", "intellivision"), "mattel-intellivision"), + "o2": "magnavox-odyssey2", "channelf": "fairchild-channel-f", + **dict.fromkeys(("zx", "spectrum", "zxspectrum"), "sinclair-zx-spectrum"), + "cpc": "amstrad-cpc", "bbc": "acorn-bbc-micro", "apple2": "apple-ii", +} + +# A system some lists file under another id, by the file that stands for it. +# The Neo Geo card offers --system snk-neogeo, and RetroArch's list keeps +# neogeo.zip under arcade: the run suggests arcade, never takes it. +SYSTEM_KEY_FILES = {"snk-neogeo": "neogeo.zip"} + + +def key_file_holders(files: list[dict], omitted: list[dict]) -> dict[str, list[str]]: + """The systems a list files each SYSTEM_KEY_FILES file under, for the + systems the list does not name itself.""" + entries = files + omitted + known = {system for entry in entries for system in entry_systems(entry)} + holders: dict[str, list[str]] = {} + for system, name in SYSTEM_KEY_FILES.items(): + if system in known: + continue + held = sorted({ + holder for entry in entries + if PurePosixPath(str(entry.get("dest", ""))).name.lower() == name + for holder in entry_systems(entry) + }) + if held: + holders[system] = held + return holders + + +def did_you_mean( + typed: list[str], known: list[str], listing: str, + aliases: dict[str, str] | None = None, inside_from: int = 4, + meant: dict[str, list[str]] | None = None, +) -> str: + """The closest known names to what was typed, and the option listing them all. + + A typo was answered with every name the platform has, up to 400 on one + line, with no hint that playstation is sony-playstation. An alias close + to what was typed suggests the name it stands for. A name holding what + was typed, inside_from letters or more, is suggested too. meant gives, + by the letters and digits of a typed name, the names it stands for + here, suggested instead of the close ones. + """ + import difflib + + by_key: dict[str, str] = {} + for name in known: + by_key.setdefault(_name_key(name), name) + for alias, name in (aliases or {}).items(): + by_key.setdefault(_name_key(alias), name) + close: list[str] = [] + for word in typed: + key = _name_key(word) + if not key: + continue + if meant and key in meant: + close += [name for name in meant[key] if name not in close] + continue + matches = difflib.get_close_matches(key, list(by_key), n=3, cutoff=0.6) + if len(key) >= inside_from: + matches += sorted(k for k in by_key if key in k and k not in matches) + for k in matches: + # Two aliases of one system (psx, ps1) name it once. + if by_key[k] not in close: + close.append(by_key[k]) + if close: + return f"Close matches: {', '.join(close[:3])}. {listing} lists all {len(known)}." + if len(known) <= SHORT_LIST: + return f"Known: {', '.join(known)}." + return f"{listing} lists all {len(known)}." + + +def refuse_name(platform: str, *lines: str) -> NoReturn: + """End the run on a name it cannot use (a platform, target, system, core + or emulator), refused before any download. + + The reason went to stderr only: a reader of --events got start, then + end with code 1, and could not tell a typo from a failed download. Code + 2, as for an option argparse refuses: 1 also means --check found files + to fetch, and a script reading it reran the install on a typo forever. + """ + message = " ".join(line.strip() for line in lines) + if message.startswith("Error: "): + message = message[len("Error: "):] + EVENTS.emit("error", stage="option", reason="unknown", platform=platform, + message=message) + for line in lines: + print(line, file=sys.stderr) + sys.exit(2) + + +# Frontends and systems that keep no BIOS folder of their own: each +# emulator they start reads its own, which a run without --platform finds. +# --platform es-de was "Unknown platform", the answer left unsaid. +_NO_BIOS_FOLDER = ("ES-DE", "LaunchBox", "Android") + + +def normalize_platform(name: str, say: bool = True) -> str: + """Return the canonical platform id for user-supplied input. + + The site writes MiSTer FPGA and RetroArch: letters and digits decide, + as they do for verify.py and generate_pack.py. say is False where the + name is read again later, which says it once. + """ + key = _name_key(name) + for plat in AVAILABLE_PLATFORMS: + if key and key in (_name_key(plat), _name_key(display_name(plat))): + return plat + # --list-platforms prints `muOS: retroarch`, and --platform muos was + # refused: a system named there stands for the list it gets. + for rule in _EMBEDDED_RULES: + if key and rule.manifest and key == _name_key(rule.name): + if say: + print(f" {rule.name} gets the {display_name(rule.manifest)} file list: " + f"--platform {rule.manifest}.") + return rule.manifest + for frontend in _NO_BIOS_FOLDER: + if key and key == _name_key(frontend): + refuse_name(name.strip(), f"{frontend} has no BIOS folder of its own: run again " + "without --platform, and the installer fills the folder of each " + "emulator it finds here.") + # --list-platforms prints TrimUI with why it gets no folder, and naming + # it answered "Unknown platform". + for rule in _EMBEDDED_RULES: + if key and not rule.manifest and key == _name_key(rule.name): + refuse_name(name.strip(), f"{rule.name} is not installed to: " + f"{_NO_FOLDER.get(rule.name, 'no source names its BIOS folder')}.", + " Name that folder: --platform retroarch " + "--dest FOLDER") + # Every name --list-platforms prints, so that spruce suggests spruceOS + # and the count is the one the listing shows. + known = list(AVAILABLE_PLATFORMS) + list(dict.fromkeys( + rule.name for rule in _EMBEDDED_RULES + if _name_key(rule.name) not in {_name_key(plat) for plat in AVAILABLE_PLATFORMS} + )) + list(_NO_BIOS_FOLDER) + refuse_name(name.strip(), f"Unknown platform '{name.strip()}'. " + + did_you_mean([name], known, "--list-platforms")) + + +def entry_systems(entry: dict) -> list[str]: + """The platform systems a file or an omission belongs to. + + An omission's `system` is spelled the way its profile spells it. Only + `systems` names the platform's own, the ones --system accepts. + """ + return list(entry.get("systems") or []) + + +def system_title(system: str, manifest: dict | None) -> str: + """A system as the screen's Choose systems names it (_tui_system_label).""" + names = ((manifest or {}).get("system_names") or {}).get(system) + titles = (manifest or {}).get("system_titles") + return _tui_system_label({"system": system, "name": ", ".join(names or [system])}, + titles if isinstance(titles, dict) else {}) + + +def _tui_system_label(row: dict, titles: dict | None = None) -> str: + """The name a person reads: the file list's title when it has one, the + platform's own name when it is one (Sony - PlayStation), the id with the + platform's short name otherwise (psx).""" + title = (titles or {}).get(row["system"]) + if isinstance(title, str) and title.strip(): + return title.strip() + if row["system"] == OTHER_SYSTEMS: + return OTHER_TITLE + name = row.get("name") or row["system"] + if name == row["system"]: + return name + if " " in name or any(char.isupper() for char in name): + return name + return f"{row['system']} ({name})" + + +# What the "other" row of the systems holds, in words (OTHER_SYSTEMS). +OTHER_TITLE = "Other systems and game engines" + + +# --- installer/cards.py ------------------------------------------------------ + # Systems a computer reaches over the network or on their SHARE drive: their # own folder (/userdata/bios) exists only on the machine that runs them, and # was offered on a computer as where they read. _guides.yml, folders. @@ -3614,16 +4463,6 @@ def card_setup(named: str, plat: str) -> CardSetup | None: plat in CARD_PLATFORMS or (key and key == _name_key(setup.name)))), None) -def _a(name: str) -> str: - """A name with its article: an Onion, a muOS.""" - return f"{'an' if name[:1].lower() in 'aeiou' else 'a'} {name}" - - -def _built_on(name: str) -> str: - """The system name is built on (dArkOS on ArkOS), "" for none.""" - return next((rule.base for rule in _EMBEDDED_RULES if rule.name == name and rule.base), "") - - def _mount_points() -> frozenset: """Every mount point this process sees, from /proc/self/mountinfo where it exists: os.path.ismount compares devices, and misses a bind mount @@ -3751,16 +4590,6 @@ def _os_default_dests(os_type: str) -> dict[str, Path]: } -# The three RetroArch packages published for Android, newest ABI first. -ANDROID_RETROARCH_PACKAGES = ( - "com.retroarch.aarch64", - "com.retroarch", - "com.retroarch.ra32", -) -# Where Android keeps each app's private data. -ANDROID_APP_DATA = Path("/data/data") - - def _is_android() -> bool: """Android reports itself as Linux, so the runtime is named instead. @@ -3872,119 +4701,6 @@ def _windows_unasked(tool: str, exc: Exception) -> None: _WSL["unasked"] = _WSL["unasked"] or why -def _expand_retroarch_path(value: str, app_dir: Path, home: Path | None = None) -> Path: - """Expand the notations RetroArch writes into its config values. - - fill_pathname_expand_special (libretro-common/file/file_path.c) maps a - leading '~' to the home directory and a leading ':' to the application - directory, dropping the two leading characters in both cases. - """ - if value[:1] == "~": - return (home or Path(str(Path.home()))) / value[2:] - if value[:1] == ":": - return app_dir / value[2:] - return _host_path(os.path.expandvars(os.path.expanduser(value))) - - -def _retroarch_cfg_dir( - cfg_path: Path, key: str, app_dir: Path, default: str, home: Path | None = None -) -> Path | None: - """A directory setting of retroarch.cfg, as RetroArch expands it. - - A value left empty or at `default` is the directory RetroArch falls back - on, `default` under app_dir. None when the config is unreadable or does - not set the key. A config this user cannot read is said once, like a - closed folder: a retroarch.cfg a `sudo retroarch` left to root hid the - setup without a word. - """ - try: - lines = cfg_path.read_text(encoding="utf-8", errors="replace").splitlines() - except OSError as exc: - _note_refused(cfg_path, exc) - return None - for line in lines: - line = line.strip() - name, sep, value = line.partition("=") - if sep and name.strip() == key: - value = value.strip().strip('"').strip("'") - if not value or value == "default": - return app_dir / default - return _expand_retroarch_path(value, app_dir, home) - return None - - -def _steam_libraries() -> list[Path]: - """Every Steam library, the default one first. - - Steam lists the others in steamapps/libraryfolders.vdf, each as a - "path" line. A RetroArch installed on D:/SteamLibrary was not found - when only Program Files was searched. The client's own folder is the - SteamPath value it writes under HKCU\\Software\\Valve\\Steam, read the - same way by Playnite (PlayniteExtensions 886468f6, - source/Libraries/SteamLibrary/Steam.cs:34-38): a client installed in - D:\\Steam hid every library. - """ - roots: list[Path] = [] - steam_path = _read_registry("HKCU\\Software\\Valve\\Steam", "SteamPath") - candidates = [_host_path(steam_path.replace("/", "\\"))] if steam_path else [] - for var in ("ProgramFiles(x86)", "ProgramFiles"): - base = os.environ.get(var, "") - if base: - candidates.append(Path(base) / "Steam") - for candidate in candidates: - if candidate not in roots and _is_dir(candidate): - roots.append(candidate) - libraries = list(roots) - for root in roots: - vdf = root / "steamapps" / "libraryfolders.vdf" - try: - text = vdf.read_text(encoding="utf-8", errors="replace") - except OSError: - continue - for raw in re.findall(r'"path"\s+"([^"]+)"', text): - library = Path(raw.replace("\\\\", "\\")) - if library not in libraries: - libraries.append(library) - return libraries - - -def _scoop_root(variable: str, parent: str) -> str: - """%variable%, else %parent%\\scoop, else nothing.""" - folder = os.environ.get(parent) - return os.environ.get(variable) or (str(Path(folder) / "scoop") if folder else "") - - -def _windows_retroarch_dirs() -> list[Path]: - """Folders holding retroarch.exe where its installers put it. - - C:/RetroArch-Win64 by default, C:/RetroArch for 32-bit builds, the same - names under Program Files, every Steam library, the Emulators folder of - an installed ES-DE (es_find_rules.xml lists all of them), and a Scoop - install, user or global. - """ - candidates = [_host_path("C:/RetroArch-Win64"), _host_path("C:/RetroArch")] - for var in ("ProgramFiles", "ProgramFiles(x86)"): - root = os.environ.get(var, "") - if root: - candidates += [Path(root) / "RetroArch-Win64", Path(root) / "RetroArch"] - candidates += [ - Path(root) / "ES-DE" / "Emulators" / name - for name in ("RetroArch-Win64", "RetroArch") - ] - candidates += [ - library / "steamapps" / "common" / "RetroArch" for library in _steam_libraries() - ] - # Scoop's Extras bucket: \apps\retroarch\current, the root being - # %SCOOP% or ~\scoop for a user install, %SCOOP_GLOBAL% or - # %ProgramData%\scoop for a global one. Its system folder is persisted - # through a junction, so the folder beside retroarch.exe is the real one. - scoop_roots = [_scoop_root("SCOOP", "USERPROFILE"), _scoop_root("SCOOP_GLOBAL", "ProgramData")] - candidates += [ - Path(root) / "apps" / "retroarch" / "current" for root in scoop_roots if root - ] - return [folder for folder in candidates if _is_file(folder / "retroarch.exe")] - - def _macos_retroarch_base() -> Path: """Where RetroArch on macOS keeps its system folder by default: ~/Documents/RetroArch, or Application Support/RetroArch for a portable @@ -4003,49 +4719,6 @@ def _macos_retroarch_base() -> Path: return Path.home() / "Documents" / "RetroArch" -def _retroarch_appimage_dirs(home: Path) -> list[Path]: - """The system folder of each RetroArch AppImage kept with a portable - folder, up to two folders below home. - - The buildbot's Linux build unpacks RetroArch-Linux-x86_64.AppImage beside - RetroArch-Linux-x86_64.AppImage.home/.config/retroarch. The AppImage - runtime sets HOME to .home and XDG_CONFIG_HOME to - .config when those folders exist (type2-runtime fedfad51, - src/runtime/runtime.c:1449-1462), so this RetroArch never reads - ~/.config/retroarch. The archive holds no retroarch.cfg: until the first - run writes one, the system folder is the base folder's (frontend_unix_get_env - in platform_unix.c). - """ - images: list[Path] = [] - for depth in ("", "*/", "*/*/"): - for suffix in (".home", ".config"): - try: - hits = sorted(home.glob(f"{depth}*.AppImage{suffix}")) - except OSError: - continue - for hit in hits: - image = hit.with_name(hit.name[:-len(suffix)]) - if image not in images and _is_file(image): - images.append(image) - dirs: list[Path] = [] - for image in images: - portable_home = image.with_name(image.name + ".home") - portable_config = image.with_name(image.name + ".config") - if _is_dir(portable_config): - base = portable_config / "retroarch" - elif _is_dir(portable_home) and "XDG_CONFIG_HOME" not in os.environ: - base = portable_home / ".config" / "retroarch" - else: - continue - tilde = portable_home if _is_dir(portable_home) else home - system = _parse_retroarch_system_dir(base / "retroarch.cfg", base, tilde) - if system is None and _is_dir(base): - system = base / "system" - if system is not None and system not in dirs: - dirs.append(system) - return dirs - - def _unix_retroarch_base() -> Path: """RetroArch's base folder on Linux: $XDG_CONFIG_HOME/retroarch when the variable is set, else ~/.config/retroarch (fill_pathname_application_data @@ -4057,245 +4730,6 @@ def _unix_retroarch_base() -> Path: return Path.home() / ".config" / "retroarch" -# System directory -> the retroarch.cfg it was read from and the directory -# ':' expands to there, for finding the cores of the same installation. -_RETROARCH_CONFIGS: dict[Path, tuple[Path, Path]] = {} - - -def _parse_retroarch_system_dir( - cfg_path: Path, app_dir: Path | None = None, home: Path | None = None -) -> Path | None: - """Parse system_directory from retroarch.cfg. - - app_dir is RetroArch's application directory, used to expand ':' values. - It defaults to the directory holding the config, which is where a portable - install keeps both. home is what '~' means to that RetroArch, the user's - home when not given. - """ - if not _exists(cfg_path): - return None - app_dir = app_dir or cfg_path.parent - system_dir = _retroarch_cfg_dir(cfg_path, "system_directory", app_dir, "system", home) - if system_dir is not None: - _RETROARCH_CONFIGS.setdefault(system_dir, (cfg_path, app_dir)) - return system_dir - - -def _shell_unquote(value: str) -> str: - """Resolve a shell right-hand side into its effective string value. - - Handles concatenated quoted/unquoted segments the way bash does - (e.g. "/run/media/deck/EmuSD"/Emulation), expands variables in - double-quoted and unquoted segments, and stops at unquoted - whitespace or a comment. - """ - parts: list[str] = [] - i = 0 - n = len(value) - while i < n: - c = value[i] - if c == '"': - end = value.find('"', i + 1) - if end == -1: - parts.append(os.path.expandvars(value[i + 1:])) - break - parts.append(os.path.expandvars(value[i + 1:end])) - i = end + 1 - elif c == "'": - end = value.find("'", i + 1) - if end == -1: - parts.append(value[i + 1:]) - break - parts.append(value[i + 1:end]) - i = end + 1 - elif c.isspace() or c == "#": - break - else: - end = i - while end < n and value[end] not in "\"'#" and not value[end].isspace(): - end += 1 - parts.append(os.path.expandvars(value[i:end])) - i = end - return os.path.expanduser("".join(parts)) - - -def _parse_bash_var(path: Path, key: str) -> str | None: - """Extract the effective value of key= from a bash/shell file.""" - if not _exists(path): - return None - try: - for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): - line = line.strip() - if line.startswith(f"{key}="): - _, _, value = line.partition("=") - return _shell_unquote(value) - except OSError as exc: - # A settings.sh a sudo EmuDeck run left to root hid the setup. - _note_refused(path, exc) - return None - - -# Where an embedded system names the board it was built for, in the words -# of our target lists: batocera-system.mk writes BATOCERA_SYSTEM_ARCH, -# recalbox-system.mk RECALBOX_SYSTEM_PLATFORM, ROCKNIX's scripts/image puts -# HW_DEVICE in os-release (RK3326, our rk3326). Lakka's scripts/image writes -# LIBREELEC_DEVICE when the image is built for a device (RPi4) and always -# LIBREELEC_PROJECT (Generic): the first one set is the board. KNULLI moves -# /usr/share/batocera to /usr/share/knulli (knulli-linux 57afa662, -# board/scripts/post-build-script.sh:264-278) and writes KNULLI_SYSTEM_ARCH -# to knulli.arch (package/system/knulli-system/knulli-system.mk:98-99). -# AmberELEC's scripts/image writes COREELEC_DEVICE (a21975bf, line 168), the -# DEVICE its Makefile builds (RG351P). EmuELEC's writes the same line (v4.8, -# line 189), the DEVICE of the release image (OdroidGoAdvance). -_BOARD_SOURCES: dict[str, tuple[str, str]] = { - "amberelec": ("os_release", "COREELEC_DEVICE"), - "emuelec": ("os_release", "COREELEC_DEVICE"), - "batocera": ("file", "/usr/share/batocera/batocera.arch"), - "recalbox": ("file", "/recalbox/recalbox.arch"), - "rocknix": ("os_release", "HW_DEVICE"), - "lakka": ("os_release", "LIBREELEC_DEVICE|LIBREELEC_PROJECT"), - "knulli": ("file", "/usr/share/knulli/knulli.arch"), - "retropie": ("retropie", ""), -} - -# The board a system's own name stands for, where the two differ: the -# target lists are named for the board files (configs/knulli-rk3566.board), -# and the arch file for the TARGET flag the board sets. knulli-rk3566.board -# sets BR2_PACKAGE_BATOCERA_TARGET_RK3568, which knulli-system.mk:22-23 -# (20260511) writes as rk3568. batocera-zen3.board sets TARGET_ZEN3, which -# batocera-system.mk:56-57 (batocera-43.1) writes as x86-64-v3. -_BOARD_NAMES: dict[str, dict[str, str]] = { - "batocera": {"x86-64-v3": "zen3"}, - "knulli": {"rk3568": "rk3566"}, -} - - -# The board a card names on a partition a computer reads. Batocera writes -# its image's board to boot/batocera.board on the BATOCERA boot partition, -# the FAT one beside SHARE (batocera-43.1, board/batocera/scripts/ -# post-image-script.sh:60), and reads it there itself (package/batocera/ -# core/batocera-scripts/scripts/batocera-info). batocera.arch is inside the -# image, out of a computer's reach. KNULLI writes boot/knulli.board the same -# way (knulli-linux 20260511, board/scripts/post-image-script.sh:66). Both -# write the image's name, which the target list maps to its board. -_CARD_BOARD_FILES: dict[str, str] = {"batocera": "boot/batocera.board", - "knulli": "boot/knulli.board"} - - -def card_board(platform: str) -> str | None: - """The board the card mounted here names, None where no card or two - cards of different boards do: a card is most often prepared on a - computer, where the system's own board file does not exist.""" - where = _CARD_BOARD_FILES.get(platform) - if where is None: - return None - boards: set[str] = set() - for mount in _mounted_cards(): - try: - value = (mount / where).read_text(encoding="utf-8", errors="replace") - except OSError: - continue - if value.strip() and not _CONTROLS.search(value.strip()): - boards.add(value.strip().lower()) - return boards.pop() if len(boards) == 1 else None - - -def detect_board(platform: str) -> str | None: - """The board this system was built for, or None where it names none.""" - kind, where = _BOARD_SOURCES.get(platform, ("", "")) - if kind == "file": - try: - value = Path(where).read_text(encoding="utf-8", errors="replace") - except OSError: - return None - elif kind == "os_release": - release = _parse_os_release() - value = next((release[key] for key in where.split("|") if release.get(key)), "") - elif kind == "retropie": - value = _retropie_board() or "" - else: - return None - board = value.strip().lower() - # A board no TARGET line names is written "unknown" (KNULLI's r16). - if board == "unknown": - return None - return _BOARD_NAMES.get(platform, {}).get(board, board) or None - - -# RetroPie names its board as get_platform does (RetroPie-Setup f5ebfba6, -# scriptmodules/system.sh:396-424 and 425-513): a Pi by the BCM Hardware -# line of /proc/cpuinfo or raspberrypi in its device tree, its model by the -# CPU field (bits 12-15) of a revision code with bit 23 set, rpi1 without -# it. With neither a Hardware line nor a device tree, the machine: x86_64. -# Read only where RetroPie is installed (rootdir /opt/retropie, -# retropie_packages.sh:17): a computer preparing a Pi's card is no Pi. -_RPI_MODELS = {0: "rpi1", 1: "rpi2", 2: "rpi3", 3: "rpi4", 4: "rpi5"} - - -def _retropie_board() -> str | None: - """The target RetroPie's own reading of this machine names, or None.""" - if not _is_dir(_on_device("/opt/retropie")): - return None - try: - cpuinfo = _on_device("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace") - except OSError: - cpuinfo = "" - fields = {key.strip(): value.strip() for key, sep, value in - (line.partition(":") for line in cpuinfo.splitlines()) if sep} - tree = _on_device("/proc/device-tree/compatible") - try: - compatible = tree.read_bytes().decode("ascii", errors="replace") - except OSError: - compatible = None - hardware = fields.get("Hardware", "") - if hardware.startswith("BCM") or (not hardware and compatible is not None - and "raspberrypi" in compatible): - try: - revision = int(fields.get("Revision", ""), 16) - except ValueError: - return None - if not (revision >> 23) & 1: - return "rpi1" - return _RPI_MODELS.get((revision >> 12) & 15) - if hardware or compatible is not None: - return None - return "x86_64" if platform.machine() == "x86_64" else None - - -def _parse_json_path(path: Path, *keys: str) -> str | None: - """Extract a nested string value from a JSON file.""" - if not _exists(path): - return None - try: - data = json.loads(path.read_text(encoding="utf-8", errors="replace")) - for key in keys: - data = data[key] - return data if isinstance(data, str) and data else None - except (OSError, json.JSONDecodeError, KeyError, TypeError): - return None - - -def _parse_ps1_var(path: Path, key: str) -> str | None: - """Extract value of $key= or key= from a PowerShell file.""" - if not _exists(path): - return None - normalized = key.lstrip("$") - try: - raw = path.read_bytes() - # Windows PowerShell's Out-File writes UTF-16, Set-Content -Encoding - # UTF8 a byte order mark: EmuDeck's settings.ps1 passes through both. - encoding = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig" - for line in raw.decode(encoding, errors="replace").splitlines(): - line = line.strip() - check = line.lstrip("$") - if check.startswith(f"{normalized}="): - _, _, value = check.partition("=") - return value.strip('"').strip("'") - except OSError as exc: - _note_refused(path, exc) - return None - - # The root the embedded rules read under: "/" on a device, a folder holding a # copy of one in the tests. _SYSTEM_ROOT = Path("/") @@ -4308,13 +4742,6 @@ def _on_device(path: str) -> Path: return _SYSTEM_ROOT / path.lstrip("/") -# Why a system found here gets no folder: said once per run. -_NO_FOLDER = { - "TrimUI": "its firmware publishes no source naming the folder its RetroArch reads", - "MinUI": f"its card names no release in {CARD_MARKER}, which tells MinUI, NextUI " - "and MyMinUI apart. Name the card's root and the one it runs: " - "--platform minui (or nextui, myminui) --dest /mnt/SDCARD", -} # A system found by its card, with the end of the path that proves it: the # card root is what comes before. _CARD_SYSTEMS = {"MinUI": "/.system/res"} @@ -4323,130 +4750,6 @@ _CARD_SYSTEMS = {"MinUI": "/.system/res"} _DETECTED_OS: dict[tuple[str, Path], str] = {} -# A version as a list or a system writes it: v1.22.2, 43.1, 8.3.1.1. -_VERSION_TEXT = re.compile(r"[0-9A-Za-z][0-9A-Za-z._+-]{0,39}") -# What generate_pack.py wrote as every list's version until it recorded the -# platform's own: not a version, so a list holding it names none. -_NO_LIST_VERSION = "1.0" -# What the platform's own check does, not a verdict on it: it compares the -# files with the list of its own version, and no run proved them working. -_MD5_CHECK = ("{name}'s own BIOS check reads the list of the version it runs, and " - "may show some files as not matching it.") - - -def _version_line(path: Path) -> str: - """The first line of a small version file, "" when it cannot be read.""" - if not _is_file(path): - return "" - try: - with path.open("rb") as fh: - head = fh.read(4096) - except OSError: - return "" - lines = head.decode("utf-8", errors="replace").strip().splitlines() - return lines[0].strip() if lines else "" - - -def _batocera_version(_bios_path: Path) -> str: - # batocera-system.mk:9,100-102 (batocera-43.1): the version, then the - # date and time of the build. - words = _version_line(_on_device("/usr/share/batocera/batocera.version")).split() - return words[0] if words else "" - - -def _recalbox_version(_bios_path: Path) -> str: - # Dockerfile:31 (recalbox 10.1.1) writes RECALBOX_VERSION, which - # .gitlab-ci.yml:723 sets to the release tag, or for a build of a branch - # to its date and name. A build from a working tree says "development" - # (projects/configgen/configgen/challenge/RuleScript.py:64). Only a - # release is a version a list is built for. - text = _version_line(_on_device("/recalbox/recalbox.version")) - return text if re.fullmatch(r"\d+(?:\.\d+)+", text) else "" - - -def _retrobat_version(bios_path: Path) -> str: - # /system/version.info, which es-update writes and es-checkversion - # reads (emulatorlauncher 48cdc616, es-update/RetrobatVersion.cs:66-92). - # The 8.3.1 installer holds "8.3.1.1-stable-win64". - text = _version_line(bios_path.parent / "system" / "version.info") - head = text.split("-", 1)[0] - return head if re.fullmatch(r"\d+(?:\.\d+)+", head) else "" - - -def _os_release_version(key: str, value: str) -> Callable[[Path], str]: - """VERSION_ID from os-release, on the system that names itself so.""" - def read(_bios_path: Path) -> str: - release = _parse_os_release() - if release.get(key, "").lower() != value: - return "" - return release.get("VERSION_ID", "") - return read - - -def _same_release(installed: str, listed: str) -> bool: - return installed == listed - - -def _retrobat_release(installed: str, listed: str) -> bool: - # The release tagged 8.3.1 ships 8.3.1.1: a fourth number is a build of - # the tagged version. - return installed == listed or installed.startswith(listed + ".") - - -class _VersionSource(NamedTuple): - """Where a system states the version it runs, and what a different one means.""" - - read: Callable[[Path], str] - meaning: str - same: Callable[[str, str], bool] = _same_release - # Written by the list (v6.1) and not by the system (6.1). - prefix: str = "" - - -# The systems whose version a file states, read without running anything. -# RetroArch writes its version in no file: its lists come from core info -# files the online updater replaces, so its version is not compared. KNULLI -# writes its codename (knulli-system.mk:9,100-102, "scarab") and ROCKNIX the -# date of the build (scripts/image:82), not the release their lists name. -# AmberELEC's list names a prerelease tag, and how that tag maps to the -# VERSION its image writes is not established. -_VERSION_SOURCES: dict[str, _VersionSource] = { - "batocera": _VersionSource(_batocera_version, _MD5_CHECK), - "recalbox": _VersionSource(_recalbox_version, _MD5_CHECK), - "retrobat": _VersionSource(_retrobat_version, _MD5_CHECK, _retrobat_release), - # scripts/image:159-164 (Lakka-LibreELEC v6.1) writes VERSION_ID from - # OS_VERSION, "6.1" in distributions/Lakka/version, and ID=lakka. - "lakka": _VersionSource( - _os_release_version("ID", "lakka"), - "Lakka checks only that a file is there, so this matters only where a core " - "of the version it runs reads a file this list does not name.", prefix="v"), - # scripts/image:172-177 (EmuELEC v4.8): VERSION_ID from OS_VERSION, 4.8 in - # distributions/EmuELEC/version, and NAME=EmuELEC. - "emuelec": _VersionSource(_os_release_version("NAME", "emuelec"), _MD5_CHECK), -} - - -def version_note(plat: str, bios_path: Path, manifest: dict) -> tuple[str, str, str] | None: - """(list version, installed version, sentence) when the system here runs - another version than the one the list was built for, else None: an - unknown version on either side says nothing.""" - source = _VERSION_SOURCES.get(plat) - listed = manifest.get("version") - if (source is None or not isinstance(listed, str) or listed == _NO_LIST_VERSION - or not _VERSION_TEXT.fullmatch(listed)): - return None - installed = source.read(bios_path) - if not _VERSION_TEXT.fullmatch(installed): - return None - compared = listed[len(source.prefix):] if listed.startswith(source.prefix) else listed - if source.same(installed, compared): - return None - name = display_name(plat, manifest) - return listed, installed, ( - f"This list was built for {name} {listed}, this machine runs {installed}. " - + source.meaning.format(name=name)) - - def _rule_matches(rule: _OsRule, release: dict[str, str]) -> bool: if rule.method == "os_release": # Any of the KEY=value pairs, the value compared without case. @@ -4649,8 +4952,139 @@ def _read_registry(key: str, value: str) -> str | None: return match.group(1) if match else None +def _os_name() -> str: + """The OS's own name, from os-release, else the kernel's.""" + release = _parse_os_release() + return release.get("PRETTY_NAME") or release.get("NAME") or platform.system() + + # --- installer/detect_frontends.py ------------------------------------------- +# The three RetroArch packages published for Android, newest ABI first. +ANDROID_RETROARCH_PACKAGES = ( + "com.retroarch.aarch64", + "com.retroarch", + "com.retroarch.ra32", +) +# Where Android keeps each app's private data. +ANDROID_APP_DATA = Path("/data/data") + + +def _steam_libraries() -> list[Path]: + """Every Steam library, the default one first. + + Steam lists the others in steamapps/libraryfolders.vdf, each as a + "path" line. A RetroArch installed on D:/SteamLibrary was not found + when only Program Files was searched. The client's own folder is the + SteamPath value it writes under HKCU\\Software\\Valve\\Steam, read the + same way by Playnite (PlayniteExtensions 886468f6, + source/Libraries/SteamLibrary/Steam.cs:34-38): a client installed in + D:\\Steam hid every library. + """ + roots: list[Path] = [] + steam_path = _read_registry("HKCU\\Software\\Valve\\Steam", "SteamPath") + candidates = [_host_path(steam_path.replace("/", "\\"))] if steam_path else [] + for var in ("ProgramFiles(x86)", "ProgramFiles"): + base = os.environ.get(var, "") + if base: + candidates.append(Path(base) / "Steam") + for candidate in candidates: + if candidate not in roots and _is_dir(candidate): + roots.append(candidate) + libraries = list(roots) + for root in roots: + vdf = root / "steamapps" / "libraryfolders.vdf" + try: + text = vdf.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + for raw in re.findall(r'"path"\s+"([^"]+)"', text): + library = Path(raw.replace("\\\\", "\\")) + if library not in libraries: + libraries.append(library) + return libraries + + +def _scoop_root(variable: str, parent: str) -> str: + """%variable%, else %parent%\\scoop, else nothing.""" + folder = os.environ.get(parent) + return os.environ.get(variable) or (str(Path(folder) / "scoop") if folder else "") + + +def _windows_retroarch_dirs() -> list[Path]: + """Folders holding retroarch.exe where its installers put it. + + C:/RetroArch-Win64 by default, C:/RetroArch for 32-bit builds, the same + names under Program Files, every Steam library, the Emulators folder of + an installed ES-DE (es_find_rules.xml lists all of them), and a Scoop + install, user or global. + """ + candidates = [_host_path("C:/RetroArch-Win64"), _host_path("C:/RetroArch")] + for var in ("ProgramFiles", "ProgramFiles(x86)"): + root = os.environ.get(var, "") + if root: + candidates += [Path(root) / "RetroArch-Win64", Path(root) / "RetroArch"] + candidates += [ + Path(root) / "ES-DE" / "Emulators" / name + for name in ("RetroArch-Win64", "RetroArch") + ] + candidates += [ + library / "steamapps" / "common" / "RetroArch" for library in _steam_libraries() + ] + # Scoop's Extras bucket: \apps\retroarch\current, the root being + # %SCOOP% or ~\scoop for a user install, %SCOOP_GLOBAL% or + # %ProgramData%\scoop for a global one. Its system folder is persisted + # through a junction, so the folder beside retroarch.exe is the real one. + scoop_roots = [_scoop_root("SCOOP", "USERPROFILE"), _scoop_root("SCOOP_GLOBAL", "ProgramData")] + candidates += [ + Path(root) / "apps" / "retroarch" / "current" for root in scoop_roots if root + ] + return [folder for folder in candidates if _is_file(folder / "retroarch.exe")] + + +def _retroarch_appimage_dirs(home: Path) -> list[Path]: + """The system folder of each RetroArch AppImage kept with a portable + folder, up to two folders below home. + + The buildbot's Linux build unpacks RetroArch-Linux-x86_64.AppImage beside + RetroArch-Linux-x86_64.AppImage.home/.config/retroarch. The AppImage + runtime sets HOME to .home and XDG_CONFIG_HOME to + .config when those folders exist (type2-runtime fedfad51, + src/runtime/runtime.c:1449-1462), so this RetroArch never reads + ~/.config/retroarch. The archive holds no retroarch.cfg: until the first + run writes one, the system folder is the base folder's (frontend_unix_get_env + in platform_unix.c). + """ + images: list[Path] = [] + for depth in ("", "*/", "*/*/"): + for suffix in (".home", ".config"): + try: + hits = sorted(home.glob(f"{depth}*.AppImage{suffix}")) + except OSError: + continue + for hit in hits: + image = hit.with_name(hit.name[:-len(suffix)]) + if image not in images and _is_file(image): + images.append(image) + dirs: list[Path] = [] + for image in images: + portable_home = image.with_name(image.name + ".home") + portable_config = image.with_name(image.name + ".config") + if _is_dir(portable_config): + base = portable_config / "retroarch" + elif _is_dir(portable_home) and "XDG_CONFIG_HOME" not in os.environ: + base = portable_home / ".config" / "retroarch" + else: + continue + tilde = portable_home if _is_dir(portable_home) else home + system = _parse_retroarch_system_dir(base / "retroarch.cfg", base, tilde) + if system is None and _is_dir(base): + system = base / "system" + if system is not None and system not in dirs: + dirs.append(system) + return dirs + + def _android_storage_root() -> Path: """Shared storage root, the parent RetroArch builds its defaults from.""" value = os.environ.get("EXTERNAL_STORAGE", "").strip() @@ -5446,43 +5880,261 @@ def _bizhawk_unix_firmware() -> Path | None: return homes[-1] / "Firmware" if homes else None -# --- installer/local_files.py ------------------------------------------------ +# --- installer/device.py ----------------------------------------------------- -def _digest_file(path: Path, algorithms: tuple[str, ...]) -> dict[str, str]: - """Compute several digests of a file in a single read. +# Where an embedded system names the board it was built for, in the words +# of our target lists: batocera-system.mk writes BATOCERA_SYSTEM_ARCH, +# recalbox-system.mk RECALBOX_SYSTEM_PLATFORM, ROCKNIX's scripts/image puts +# HW_DEVICE in os-release (RK3326, our rk3326). Lakka's scripts/image writes +# LIBREELEC_DEVICE when the image is built for a device (RPi4) and always +# LIBREELEC_PROJECT (Generic): the first one set is the board. KNULLI moves +# /usr/share/batocera to /usr/share/knulli (knulli-linux 57afa662, +# board/scripts/post-build-script.sh:264-278) and writes KNULLI_SYSTEM_ARCH +# to knulli.arch (package/system/knulli-system/knulli-system.mk:98-99). +# AmberELEC's scripts/image writes COREELEC_DEVICE (a21975bf, line 168), the +# DEVICE its Makefile builds (RG351P). EmuELEC's writes the same line (v4.8, +# line 189), the DEVICE of the release image (OdroidGoAdvance). +_BOARD_SOURCES: dict[str, tuple[str, str]] = { + "amberelec": ("os_release", "COREELEC_DEVICE"), + "emuelec": ("os_release", "COREELEC_DEVICE"), + "batocera": ("file", "/usr/share/batocera/batocera.arch"), + "recalbox": ("file", "/recalbox/recalbox.arch"), + "rocknix": ("os_release", "HW_DEVICE"), + "lakka": ("os_release", "LIBREELEC_DEVICE|LIBREELEC_PROJECT"), + "knulli": ("file", "/usr/share/knulli/knulli.arch"), + "retropie": ("retropie", ""), +} - Checking a 3 GB collection against both a SHA-1 and a SHA-256 used to walk - every file twice, single threaded. Hashing is cheap next to the I/O, so - the read is what has to happen once. - """ - with open(path, "rb") as fh: - return _digest_handle(fh, algorithms) +# The board a system's own name stands for, where the two differ: the +# target lists are named for the board files (configs/knulli-rk3566.board), +# and the arch file for the TARGET flag the board sets. knulli-rk3566.board +# sets BR2_PACKAGE_BATOCERA_TARGET_RK3568, which knulli-system.mk:22-23 +# (20260511) writes as rk3568. batocera-zen3.board sets TARGET_ZEN3, which +# batocera-system.mk:56-57 (batocera-43.1) writes as x86-64-v3. +_BOARD_NAMES: dict[str, dict[str, str]] = { + "batocera": {"x86-64-v3": "zen3"}, + "knulli": {"rk3568": "rk3566"}, +} -def _digest_handle(fh: IO[bytes], algorithms: tuple[str, ...]) -> dict[str, str]: - """Digests of an open file, read from its start.""" - hashers = {name: hashlib.new(name) for name in algorithms} - fh.seek(0) - for chunk in iter(lambda: fh.read(1024 * 1024), b""): - for hasher in hashers.values(): - hasher.update(chunk) - return {name: hasher.hexdigest() for name, hasher in hashers.items()} +# The board a card names on a partition a computer reads. Batocera writes +# its image's board to boot/batocera.board on the BATOCERA boot partition, +# the FAT one beside SHARE (batocera-43.1, board/batocera/scripts/ +# post-image-script.sh:60), and reads it there itself (package/batocera/ +# core/batocera-scripts/scripts/batocera-info). batocera.arch is inside the +# image, out of a computer's reach. KNULLI writes boot/knulli.board the same +# way (knulli-linux 20260511, board/scripts/post-image-script.sh:66). Both +# write the image's name, which the target list maps to its board. +_CARD_BOARD_FILES: dict[str, str] = {"batocera": "boot/batocera.board", + "knulli": "boot/knulli.board"} -def _sha1_file(path: Path) -> str: - """Compute SHA1 of a file.""" - return _digest_file(path, ("sha1",))["sha1"] +def card_board(platform: str) -> str | None: + """The board the card mounted here names, None where no card or two + cards of different boards do: a card is most often prepared on a + computer, where the system's own board file does not exist.""" + where = _CARD_BOARD_FILES.get(platform) + if where is None: + return None + boards: set[str] = set() + for mount in _mounted_cards(): + try: + value = (mount / where).read_text(encoding="utf-8", errors="replace") + except OSError: + continue + if value.strip() and not _CONTROLS.search(value.strip()): + boards.add(value.strip().lower()) + return boards.pop() if len(boards) == 1 else None -def _sha256_file(path: Path) -> str: - """Compute SHA256 of a file.""" - return _digest_file(path, ("sha256",))["sha256"] +def detect_board(platform: str) -> str | None: + """The board this system was built for, or None where it names none.""" + kind, where = _BOARD_SOURCES.get(platform, ("", "")) + if kind == "file": + try: + value = Path(where).read_text(encoding="utf-8", errors="replace") + except OSError: + return None + elif kind == "os_release": + release = _parse_os_release() + value = next((release[key] for key in where.split("|") if release.get(key)), "") + elif kind == "retropie": + value = _retropie_board() or "" + else: + return None + board = value.strip().lower() + # A board no TARGET line names is written "unknown" (KNULLI's r16). + if board == "unknown": + return None + return _BOARD_NAMES.get(platform, {}).get(board, board) or None -def _cfg_true(value: str | None) -> bool: - return (value or "").strip().lower() == "true" +# RetroPie names its board as get_platform does (RetroPie-Setup f5ebfba6, +# scriptmodules/system.sh:396-424 and 425-513): a Pi by the BCM Hardware +# line of /proc/cpuinfo or raspberrypi in its device tree, its model by the +# CPU field (bits 12-15) of a revision code with bit 23 set, rpi1 without +# it. With neither a Hardware line nor a device tree, the machine: x86_64. +# Read only where RetroPie is installed (rootdir /opt/retropie, +# retropie_packages.sh:17): a computer preparing a Pi's card is no Pi. +_RPI_MODELS = {0: "rpi1", 1: "rpi2", 2: "rpi3", 3: "rpi4", 4: "rpi5"} +def _retropie_board() -> str | None: + """The target RetroPie's own reading of this machine names, or None.""" + if not _is_dir(_on_device("/opt/retropie")): + return None + try: + cpuinfo = _on_device("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace") + except OSError: + cpuinfo = "" + fields = {key.strip(): value.strip() for key, sep, value in + (line.partition(":") for line in cpuinfo.splitlines()) if sep} + tree = _on_device("/proc/device-tree/compatible") + try: + compatible = tree.read_bytes().decode("ascii", errors="replace") + except OSError: + compatible = None + hardware = fields.get("Hardware", "") + if hardware.startswith("BCM") or (not hardware and compatible is not None + and "raspberrypi" in compatible): + try: + revision = int(fields.get("Revision", ""), 16) + except ValueError: + return None + if not (revision >> 23) & 1: + return "rpi1" + return _RPI_MODELS.get((revision >> 12) & 15) + if hardware or compatible is not None: + return None + return "x86_64" if platform.machine() == "x86_64" else None + + +# A version as a list or a system writes it: v1.22.2, 43.1, 8.3.1.1. +_VERSION_TEXT = re.compile(r"[0-9A-Za-z][0-9A-Za-z._+-]{0,39}") +# What generate_pack.py wrote as every list's version until it recorded the +# platform's own: not a version, so a list holding it names none. +_NO_LIST_VERSION = "1.0" +# What the platform's own check does, not a verdict on it: it compares the +# files with the list of its own version, and no run proved them working. +_MD5_CHECK = ("{name}'s own BIOS check reads the list of the version it runs, and " + "may show some files as not matching it.") + + +def _version_line(path: Path) -> str: + """The first line of a small version file, "" when it cannot be read.""" + if not _is_file(path): + return "" + try: + with path.open("rb") as fh: + head = fh.read(4096) + except OSError: + return "" + lines = head.decode("utf-8", errors="replace").strip().splitlines() + return lines[0].strip() if lines else "" + + +def _batocera_version(_bios_path: Path) -> str: + # batocera-system.mk:9,100-102 (batocera-43.1): the version, then the + # date and time of the build. + words = _version_line(_on_device("/usr/share/batocera/batocera.version")).split() + return words[0] if words else "" + + +def _recalbox_version(_bios_path: Path) -> str: + # Dockerfile:31 (recalbox 10.1.1) writes RECALBOX_VERSION, which + # .gitlab-ci.yml:723 sets to the release tag, or for a build of a branch + # to its date and name. A build from a working tree says "development" + # (projects/configgen/configgen/challenge/RuleScript.py:64). Only a + # release is a version a list is built for. + text = _version_line(_on_device("/recalbox/recalbox.version")) + return text if re.fullmatch(r"\d+(?:\.\d+)+", text) else "" + + +def _retrobat_version(bios_path: Path) -> str: + # /system/version.info, which es-update writes and es-checkversion + # reads (emulatorlauncher 48cdc616, es-update/RetrobatVersion.cs:66-92). + # The 8.3.1 installer holds "8.3.1.1-stable-win64". + text = _version_line(bios_path.parent / "system" / "version.info") + head = text.split("-", 1)[0] + return head if re.fullmatch(r"\d+(?:\.\d+)+", head) else "" + + +def _os_release_version(key: str, value: str) -> Callable[[Path], str]: + """VERSION_ID from os-release, on the system that names itself so.""" + def read(_bios_path: Path) -> str: + release = _parse_os_release() + if release.get(key, "").lower() != value: + return "" + return release.get("VERSION_ID", "") + return read + + +def _same_release(installed: str, listed: str) -> bool: + return installed == listed + + +def _retrobat_release(installed: str, listed: str) -> bool: + # The release tagged 8.3.1 ships 8.3.1.1: a fourth number is a build of + # the tagged version. + return installed == listed or installed.startswith(listed + ".") + + +class _VersionSource(NamedTuple): + """Where a system states the version it runs, and what a different one means.""" + + read: Callable[[Path], str] + meaning: str + same: Callable[[str, str], bool] = _same_release + # Written by the list (v6.1) and not by the system (6.1). + prefix: str = "" + + +# The systems whose version a file states, read without running anything. +# RetroArch writes its version in no file: its lists come from core info +# files the online updater replaces, so its version is not compared. KNULLI +# writes its codename (knulli-system.mk:9,100-102, "scarab") and ROCKNIX the +# date of the build (scripts/image:82), not the release their lists name. +# AmberELEC's list names a prerelease tag, and how that tag maps to the +# VERSION its image writes is not established. +_VERSION_SOURCES: dict[str, _VersionSource] = { + "batocera": _VersionSource(_batocera_version, _MD5_CHECK), + "recalbox": _VersionSource(_recalbox_version, _MD5_CHECK), + "retrobat": _VersionSource(_retrobat_version, _MD5_CHECK, _retrobat_release), + # scripts/image:159-164 (Lakka-LibreELEC v6.1) writes VERSION_ID from + # OS_VERSION, "6.1" in distributions/Lakka/version, and ID=lakka. + "lakka": _VersionSource( + _os_release_version("ID", "lakka"), + "Lakka checks only that a file is there, so this matters only where a core " + "of the version it runs reads a file this list does not name.", prefix="v"), + # scripts/image:172-177 (EmuELEC v4.8): VERSION_ID from OS_VERSION, 4.8 in + # distributions/EmuELEC/version, and NAME=EmuELEC. + "emuelec": _VersionSource(_os_release_version("NAME", "emuelec"), _MD5_CHECK), +} + + +def version_note(plat: str, bios_path: Path, manifest: dict) -> tuple[str, str, str] | None: + """(list version, installed version, sentence) when the system here runs + another version than the one the list was built for, else None: an + unknown version on either side says nothing.""" + source = _VERSION_SOURCES.get(plat) + listed = manifest.get("version") + if (source is None or not isinstance(listed, str) or listed == _NO_LIST_VERSION + or not _VERSION_TEXT.fullmatch(listed)): + return None + installed = source.read(bios_path) + if not _VERSION_TEXT.fullmatch(installed): + return None + compared = listed[len(source.prefix):] if listed.startswith(source.prefix) else listed + if source.same(installed, compared): + return None + name = display_name(plat, manifest) + return listed, installed, ( + f"This list was built for {name} {listed}, this machine runs {installed}. " + + source.meaning.format(name=name)) + + +# --- installer/frontend_folders.py ------------------------------------------- + _CONFIGS_READ: list[bool] = [] @@ -5680,18 +6332,6 @@ def place_relative_entries( return files, unplaced -def _config_keys(path: Path) -> set[str]: - """The keys an emulatorLauncher-style key=value file sets, lowercased.""" - try: - text = path.read_text(encoding="utf-8", errors="replace") - except OSError: - return set() - return { - line.split("=", 1)[0].strip().lower() - for line in text.splitlines() if "=" in line and line.split("=", 1)[1].strip() - } - - def place_emulator_entries( files: list[dict], bios_path: Path, manifest: dict, display: str, say: bool = True, ) -> tuple[list[dict], list[dict]]: @@ -5781,177 +6421,6 @@ def say_saves(plat: str, files: list[dict], omitted: list[dict], bios_path: Path detail(f" {line}") -# The digests the line menu's head read of the files in place, by path and -# by what stat says of the file, kept for the check that follows Enter: the -# head named a wrong copy of the right size in place, -# and a card read twice is read at the speed of its reader. Emptied once -# that check has read them (head_reads_done). -_HEAD_READS: dict[tuple, dict[str, str]] = {} - - -def _stat_key(path: Path) -> tuple | None: - """What tells a file apart from the same path rewritten: None for none.""" - try: - info = path.stat() - except OSError: - return None - return (str(path), info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_ino) - - -def _read_digests(path: Path, algorithms: tuple[str, ...], remember: bool = False) -> dict: - """_digest_file, answered from what the head read when the file is the - same one, and remembered for the check when remember is set.""" - key = _stat_key(path) - known = _HEAD_READS.get((key, algorithms)) if key is not None else None - if known is not None: - return known - digests = _digest_file(path, algorithms) - if remember and key is not None: - _HEAD_READS[(key, algorithms)] = digests - return digests - - -def head_reads_done() -> None: - """The check after the head has read what it holds: nothing more is - answered from it, a file the run writes being read again.""" - _HEAD_READS.clear() - - -def _classify_local(entry: dict, dest: Path, remember: bool = False) -> str: - """Return 'up_to_date' or 'mismatched' for a file already on disk. - remember keeps what was read for the check after the line menu.""" - expected = { - name: entry.get(name, "").lower() - for name in ("sha256", "sha1") - if entry.get(name) - } - try: - is_file = dest.is_file() - except OSError: - # A folder above it this user cannot enter: what sits there is not - # known to be the right file. - return "mismatched" - if not is_file: - # A folder at the file's place: --check says so, an install fails - # on that file alone. - return "mismatched" - if not expected: - return "up_to_date" - try: - actual = _read_digests(dest, tuple(expected), remember) - except OSError: - # Unreadable (no permission, a read error on a failing card): its - # contents are not known to be the right ones. - return "mismatched" - if all(actual[name] == value for name, value in expected.items()): - return "up_to_date" - return "mismatched" - - -def closed_folder_words(dest: Path, closed: tuple[Path, str]) -> str: - folder, why = closed - return f"this user cannot open {folder} ({why}), which holds {dest}" - - -def unreachable_words(exc: OSError) -> str: - """Why the place of a file could not be looked at, in words.""" - return (f"could not be read ({exc.strerror or exc}): this user may not " - f"have access to its folder") - - -def check_local( - files: list[dict], bios_path: Path, jobs: int = 8, - term: "Terminal | None" = None, -) -> tuple[list[dict], list[dict], list[dict]]: - """Check which files exist locally and have correct hashes. - - Returns (to_download, up_to_date, mismatched). With a terminal, a count - moves while the files are read: 3.9 GB on an SD card went by in minutes - of silence, read as a hung run and stopped with Ctrl+C. - """ - to_download: list[dict] = [] - present: list[tuple[dict, Path]] = [] - - for f in files: - dest = _entry_path(bios_path, f) - if _held(dest): - present.append((f, dest)) - else: - to_download.append(f) - - up_to_date: list[dict] = [] - mismatched: list[dict] = [] - if present: - with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: - verdicts = pool.map( - lambda item: (item[0], _classify_local(item[0], item[1])), present - ) - shown = term if term is not None and term.live and not term.quiet else None - last = evented = 0.0 - for done, (entry, verdict) in enumerate(verdicts, 1): - if verdict == "up_to_date": - up_to_date.append(entry) - else: - mismatched.append(entry) - now = time.monotonic() - # The program driving the installer gets the count the - # terminal gets: a screen with a bare timer over 6 GB on an - # SD card read as hung. - if EVENTS.on and (now - evented >= EVENT_PROGRESS_INTERVAL - or done == len(present)): - evented = now - EVENTS.emit("checking", files_done=done, files_total=len(present)) - if shown is not None and (now - last >= 0.1 or done == len(present)): - last = now - print(f"\r read {done}/{len(present)}", end="", file=shown.stream, - flush=True) - if shown is not None: - print("\r\033[K", end="", file=shown.stream, flush=True) - - return to_download, up_to_date, mismatched - - -# Where a file in place that this run replaces is kept: a folder beside the -# one written to, never inside it. Several emulators find their BIOS by -# content, not by name: DuckStation, SwanStation and Rustation read every -# file of the BIOS folder, BizHawk walks its firmware folder recursively. A -# kept copy anywhere under that folder could be taken for the BIOS. -BACKUP_DIR = "retrobios-backup" -# Written into every run folder the installer creates. --restore only accepts -# a folder holding it, so a folder someone else placed (a shared BIOS folder -# on a network share) is never copied over the user's files. -BACKUP_MARKER = ".retrobios-backup" - - -def _check_holder(holder: Path) -> os.stat_result: - """Refuse a backup holder the user's files must not go into. - - A link would send them wherever it points. On a system with user ids, a - folder another user owns was not made by this user's runs, and its owner - could read or swap what is moved in. A storage that keeps no owner per - file gives every file one owner: Android's shared storage shows a folder - Termux has just made as another user's, as does a FAT card. A holder - owned like the folder it sits in is that storage's owner, not someone - else's folder. Returns what was checked, so the caller can confirm the - same folder is still there once it has written into it. - """ - info = os.lstat(holder) - if not stat.S_ISDIR(info.st_mode): - raise OSError(errno.ELOOP, f"{holder} is a link or not a folder") - getuid = getattr(os, "getuid", None) - if (getuid is not None and info.st_uid != getuid() - and info.st_uid != os.lstat(holder.parent).st_uid): - raise OSError(errno.EPERM, f"{holder} belongs to another user") - return info - - -def _same_folder(path: Path, checked: os.stat_result) -> bool: - """Whether path is still the folder checked, not a link swapped in since.""" - now = os.lstat(path) - return (stat.S_ISDIR(now.st_mode) - and (now.st_dev, now.st_ino) == (checked.st_dev, checked.st_ino)) - - _SAVE_SPLITS = {(True, True): "a folder per system, then one per core, under", (True, False): "a folder per system under", (False, True): "a folder per core under"} @@ -6006,411 +6475,6 @@ def save_lines(files: list[dict], omitted: list[dict], bios_path: Path | None, return lines -# --- installer/arguments.py -------------------------------------------------- - -# --pack writes the narrowed choice as a pack --from-pack reads: each file -# once by its SHA-1, at its destination (a file of another root under that -# root's name), each data tree at its place, and manifest.json carrying the -# list narrowed to the choice. For one zlib the bytes depend on the inputs -# alone: members in a fixed order, a fixed date and mode, one compression -# level set on each member. Another deflate gives other bytes for the same -# members (zlib-ng, which CPython 3.14 on Windows ships). -PACK_NAME_END = "_BIOS_Pack.zip" - -MIN_PART_BYTES = 64 * 1024 - - -def parse_part_size(text: str) -> int: - """--split SIZE: bytes, or a number with K, M or G (powers of 1024).""" - match = re.fullmatch(r"\s*(\d+)\s*([KMG]?)(?:I?B)?\s*", text, re.IGNORECASE) - if match is None: - raise argparse.ArgumentTypeError( - f"{text!r} is not a size: give bytes, or a number with K, M or G (1900M)") - size = int(match[1]) * 1024 ** " KMG".index((match[2] or " ").upper()) - if size < MIN_PART_BYTES: - raise argparse.ArgumentTypeError( - f"a part of {format_size(size)} is too small: give {format_size(MIN_PART_BYTES)} " - "or more") - return size - - -def _help_epilog() -> str: - """Examples in the form the run was started with, and where the rest is.""" - run = _INVOCATION.launcher() - card = "E:\\bios" if _INVOCATION.powershell() else "/media/SHARE/bios" - examples = ( - ("install for the platforms found here", run), - ("prepare a card or a share for another device", - f"{run} --platform batocera --dest {card}"), - ("only some systems (names: --list-systems)", - f"{run} --platform retroarch --system sony-playstation,nintendo-gba"), - ("check what is installed, writing nothing", f"{run} --check"), - ) - lines = ["examples:"] - for what, command in examples: - lines += [f" {what}", f" {command}"] - lines += ["", f"Every option, the environment variables and the exit codes: {INSTALLER_PAGE}"] - return "\n".join(lines) - - -def build_parser() -> argparse.ArgumentParser: - """The options, in the order --help and wiki/installer.md list them - (scripts/generate_installer_doc.py writes its table from this parser).""" - parser = argparse.ArgumentParser( - # Never the file's own name: install.ps1 runs a copy named - # retrobios-install-.py, which usage and errors printed. - prog="install.py", - allow_abbrev=False, - description="Download missing BIOS files for retrogaming emulators. " - "For questions line by line, as a screen reader reads them, " - "add --plain.", - epilog=_help_epilog(), - formatter_class=argparse.RawDescriptionHelpFormatter, - ) - parser.add_argument( - "--platform", - metavar="NAME", - help="target platform (retroarch, batocera, emudeck, ...)", - ) - parser.add_argument( - "--dest", - metavar="PATH", - type=Path, - help="BIOS folder to install into. Without --platform, the file list is " - "the platform detected here, asked at a terminal, RetroArch's when " - "nothing is detected", - ) - parser.add_argument( - "--target", - metavar="NAME", - help="hardware target for core filtering (switch, rpi4, ...). " - "On AmberELEC, EmuELEC, Batocera, Recalbox, ROCKNIX, Lakka, KNULLI and RetroPie " - "the board is read from the system", - ) - parser.add_argument( - "--every-board", - action="store_true", - help="install the files of every board, not only the detected one", - ) - parser.add_argument( - "--installed-cores", - action="store_true", - help="install only what the cores already installed read " - "(RetroArch, Lakka, RetroPie)", - ) - parser.add_argument( - "--cores-dir", - type=Path, - metavar="PATH", - help="the folder RetroArch loads its cores from, when it is not found " - "(implies --installed-cores)", - ) - parser.add_argument( - "--save-dir", - type=Path, - metavar="PATH", - help="the frontend's save directory (RetroArch: savefile_directory), " - "for the files some cores read there (Azahar's keys and system " - "data), when it is not found", - ) - parser.add_argument( - "--system", - action="append", - metavar="NAMES", - help="install only these systems (repeat or comma-separate, see " - "--list-systems)", - ) - parser.add_argument( - "--core", - action="append", - metavar="NAMES", - help="keep only the extra files these cores load (see --list-cores)", - ) - parser.add_argument( - "--emulator", - action="append", - metavar="NAMES", - help="install what these emulators read on the platform, as a pack " - "built for them carries (names: --list-emulators)", - ) - parser.add_argument( - "--region", - action="append", - metavar="LIST", - help="preferred regions, best first, e.g. us,eu,jp: keep one BIOS per " - "region where a system has several", - ) - parser.add_argument( - "--for-games", - nargs="?", - const=True, - type=Path, - metavar="FOLDER", - help="install only what the games on the card need: the systems of its " - "game folders, one region where a game's content proves it, an " - "arcade set's BIOS sets. FOLDER names a games folder (on a computer, " - "one subfolder per system), else the card's own beside the BIOS folder", - ) - parser.add_argument( - "--required-only", - action="store_true", - help="with --for-games, only the files the games cannot start without", - ) - parser.add_argument( - "--all-files", - action="store_true", - help="install the whole list even when the card holds games. A run that " - "asks nothing (--yes, --no-input, --events) otherwise installs only " - "what the card's games need, the plan's first choice", - ) - parser.add_argument( - "--no-game-data", - action="store_true", - help="leave out game data (files a game reads, not firmware) and " - "install the firmware only", - ) - parser.add_argument( - "--declared-only", - action="store_true", - help="keep only the files the platform's own list names, not the extra " - "files cores load: --check then answers for the list the platform checks", - ) - parser.add_argument( - "--one-per-slot", - action="store_true", - help="keep one BIOS per console and region, the one the emulators' own " - "search order ranks first (a slot no order decides keeps every file)", - ) - parser.add_argument( - "--standalone", - action="store_true", - help="with --emulator: the files each emulator's standalone build reads, " - "where that build reads them", - ) - parser.add_argument( - "--source", - choices=("full", "truth"), - default="full", - help="truth: only the files the emulator profiles prove a core reads " - "(default full: the platform's list and what its cores read)", - ) - parser.add_argument( - "--find", - metavar="HASH", - help="install the file of the list with this sha1 or sha256, or md5 or " - "crc32 where the list records them", - ) - parser.add_argument( - "--json", - action="store_true", - help="with --find: print the matching files as JSON and install nothing", - ) - parser.add_argument( - "--list-systems", - action="store_true", - help="list a platform's systems with their file counts and exit", - ) - parser.add_argument( - "--list-cores", - action="store_true", - help="list the cores whose extra files a platform installs and exit", - ) - parser.add_argument( - "--list-emulators", - action="store_true", - help="list every name --emulator accepts for a platform and exit", - ) - parser.add_argument( - "--romm-firmware", - metavar="TEMPLATE", - help="RomM: where each platform's firmware goes in the library, as " - "filesystem.structure.firmware in its config.yml (default: read " - "from config.yml, else bios/{platform})", - ) - parser.add_argument( - "--no-input", - action="store_true", - help="never ask a question and fail where an answer is needed", - ) - parser.add_argument( - "--check", - action="store_true", - help="check existing files without downloading", - ) - parser.add_argument( - "--dry-run", - action="store_true", - help="show what would be downloaded, and how much, without writing anything", - ) - parser.add_argument( - "--yes", "-y", - action="store_true", - help="do not ask before a large download, nor anything else (implies --no-input)", - ) - parser.add_argument( - "--quiet", "-q", - action="store_true", - help="print only errors and the final summary (implies --no-input)", - ) - parser.add_argument( - "--events", - action="store_true", - help="write the run as JSON events on stdout, one per line, and the " - "usual text on stderr (implies --no-input)", - ) - parser.add_argument( - "--from", - action="append", - type=Path, - metavar="FOLDER", - help="copy the BIOS files found in FOLDER (an old SD card, a backup, a " - "ZIP) instead of downloading them: every file recognised by its " - "hash, never moved. Repeat for several folders", - ) - parser.add_argument( - "--from-pack", - action="append", - type=Path, - metavar="PATH", - help="install from a pack already downloaded: its ZIP, one of its parts " - "(the others are found beside it) or the folder holding them. " - "Makes no network request, and checks every file's hash", - ) - parser.add_argument( - "--offline", - action="store_true", - help="make no network request: --check, --from, --from-pack and --manifest " - "work without one, and a file the run would download fails at once " - f"({OFFLINE_VARIABLE}=1 does the same)", - ) - parser.add_argument( - "--manifest", - type=Path, - metavar="FILE", - help="read the file list from FILE (install/.json) instead " - "of downloading it", - ) - parser.add_argument( - "--restore", - type=Path, - metavar="FOLDER", - help=f"put back the files an earlier run replaced and kept in FOLDER " - f"(a dated folder inside {BACKUP_DIR})", - ) - parser.add_argument( - "--remove", - action="store_true", - help="remove what the installer placed in the BIOS folder, as its install " - "record proves it: every file, or those of --system, --core, --emulator " - "or --file. A file changed since, added by hand, still needed by " - "something kept, or that the collection cannot give again stays", - ) - parser.add_argument( - "--file", - action="append", - type=Path, - metavar="PATH", - help="with --remove, one file of the BIOS folder (its path there, or the " - "full path). Repeat for several", - ) - parser.add_argument( - "--misplaced", - action="store_true", - help="with --remove, delete instead the copies left in the wrong place of the " - "BIOS folder: each one whose bytes the installer placed where the cores " - "read them. A place a list reads, or a setup of the folder recorded, stays", - ) - parser.add_argument( - "--backup", - action="store_true", - help=f"with --remove, move the files into a dated folder of {BACKUP_DIR} " - "instead of deleting them, for --restore to put back", - ) - parser.add_argument( - "--backups", - action="store_true", - help="list the backups of the BIOS folder, newest first, and exit", - ) - parser.add_argument( - "--delete-backup", - type=Path, - metavar="FOLDER", - help=f"delete one backup (a dated folder inside {BACKUP_DIR}) after one " - "question, to free its space", - ) - parser.add_argument( - "--pack", - type=Path, - metavar="PATH", - help=f"download the choice into a pack ZIP at PATH instead of a BIOS folder, for " - f"another device or an install without the internet (--from-pack reads it). " - f"A folder takes {PACK_NAME_END}. The narrowing options apply, and " - "--dry-run lists what the pack would hold", - ) - parser.add_argument( - "--split", - type=parse_part_size, - metavar="SIZE", - help="with --pack, write parts of at most SIZE (1900M, 4G), each a whole ZIP. " - "A pack that would pass 4 GiB on a FAT32 drive is split by itself", - ) - parser.add_argument( - "--tui", - action="store_true", - help="open the full-screen interface, which a keyboard or a controller " - "drives. It opens by itself for an install at a terminal of 40x12 " - "or more", - ) - parser.add_argument( - "--plain", - action="store_true", - help="ask the questions line by line instead of the full-screen " - "interface, as a screen reader reads them (RETROBIOS_PLAIN=1 or " - "ACCESSIBLE=1 do the same)", - ) - parser.add_argument( - "--version", - action="version", - version=f"retrobios installer {installer_id()} (ref {RELEASE_REF})", - help="print the installer version and exit", - ) - parser.add_argument( - "--list-platforms", - action="store_true", - help="list detected platforms and exit", - ) - parser.add_argument( - "--list-targets", - action="store_true", - help="list available targets for a platform and exit", - ) - parser.add_argument( - "--jobs", "-j", - metavar="N", - type=int, - default=8, - help="parallel download threads (default: 8)", - ) - parser.add_argument( - "--verbose", "-v", - action="store_true", - help="verbose output", - ) - parser.add_argument( - "--standalone-copies", - action="store_true", - help="opt in to copies into detected standalone-emulator directories", - ) - parser.add_argument( - "--add-app", - action="store_true", - help="after the install, put the RetroBIOS app on the handheld card the BIOS " - "folder is on (muOS, KNULLI, ROCKNIX), to check and update the BIOS " - "files from the console later", - ) - return parser - - # --- installer/cores.py ------------------------------------------------------ # A libretro core as RetroArch loads it: _libretro.so|dll|dylib, and @@ -6451,112 +6515,6 @@ def core_dirs(plat: str, bios_path: Path) -> list[Path]: return list(dict.fromkeys(dirs)) -def keeps_case(directory: Path) -> bool: - """Whether names differing only by case are distinct files there. - - Probed on the nearest existing directory, since the filesystem decides, - not the operating system: an ext4 drive mounted on macOS keeps case and - a casefolded ext4 directory folds it. Unprobeable: the system's default. - """ - probe_dir = directory - while not _is_dir(probe_dir) and probe_dir != probe_dir.parent: - probe_dir = probe_dir.parent - try: - handle, name = tempfile.mkstemp(prefix=".retrobios-case-", dir=str(probe_dir)) - except OSError: - return sys.platform not in ("win32", "darwin") - os.close(handle) - try: - twin = os.path.join(os.path.dirname(name), os.path.basename(name).upper()) - return not os.path.exists(twin) - finally: - os.unlink(name) - - -def fold_case_twins(files: list[dict]) -> tuple[list[dict], list[str]]: - """One file per name where the directory folds case, the others named. - - The first in manifest order stays, as the pack's own order places it. - """ - kept: list[dict] = [] - seen: set[str] = set() - folded: list[str] = [] - for entry in files: - key = str(entry.get("dest", "")).casefold() - if key in seen: - folded.append(str(entry.get("dest", ""))) - continue - seen.add(key) - kept.append(entry) - return kept, folded - - -# The characters FAT and exFAT refuse in a name, as Windows does on any drive -# (Linux 7475ea8b, fs/fat/namei_vfat.c:201-207 and fs/exfat/nls.c:396-403; -# "Naming Files, Paths, and Namespaces" in the Win32 documentation). The -# slash, the backslash and the controls never reach a destination -# (_safe_relative_path). RetroDECK names three files zxs:48.rom, -# zxs:if1-2.rom and snes:st018.data.rom (its retroarch component manifest): -# on an exFAT card each write failed, on every run. -FAT_REFUSED = re.compile(r'[<>:"|?*]') -FAT_REFUSED_SHOWN = '< > : " | ? *' - - -def holds_fat_refused_names(directory: Path) -> bool: - """Whether a name holding a colon can be created there. - - Probed on the nearest existing directory, as keeps_case is: an ext4 - card on a Steam Deck holds one, an exFAT card refuses it with EINVAL. - Windows refuses it on every drive. A probe refused for another cause - (a folder this user cannot write) decides nothing. - """ - if os.name == "nt": - return False - probe_dir = directory - while not _is_dir(probe_dir) and probe_dir != probe_dir.parent: - probe_dir = probe_dir.parent - try: - handle, name = tempfile.mkstemp(prefix=".retrobios-name-", suffix=":", - dir=str(probe_dir)) - except OSError as exc: - return exc.errno != errno.EINVAL - os.close(handle) - os.unlink(name) - return True - - -def split_fat_refused(files: list[dict]) -> tuple[list[dict], list[str]]: - """The entries whose destination a FAT, exFAT or Windows folder can - hold, and the destinations it cannot.""" - kept = [entry for entry in files if not FAT_REFUSED.search(str(entry.get("dest", "")))] - refused = [str(entry.get("dest", "")) for entry in files - if FAT_REFUSED.search(str(entry.get("dest", "")))] - return kept, refused - - -# Android's media scanner marks a folder holding a .nomedia file hidden, and -# every folder below it (MediaProvider a183e2b9, FileUtils.java:1587-1629 -# isDirectoryHidden, ModernMediaScanner.java:845-846 and 1017-1020). Without -# one, the samples, overlays and videos of a BIOS folder in shared storage -# showed in the phone's gallery and music apps. RetroArch writes none -# (libretro-common/file/file_path_io.c:194 only skips one). -NOMEDIA = ".nomedia" - - -def hide_from_media_scanner(folder: Path) -> bool: - """Leave an empty .nomedia in folder, True when this call wrote it.""" - marker = folder / NOMEDIA - if not _is_dir(folder) or _exists(marker): - return False - try: - marker.touch() - except OSError as exc: - print(f" {NOMEDIA} not written in {shown_path(folder)}: {exc.strerror}", - file=sys.stderr) - return False - return True - - def installed_cores(dirs: list[Path]) -> list[str]: """The cores present in these directories, by the name the buildbot uses. @@ -6644,197 +6602,92 @@ def unknown_cores(manifest: dict, names: list[str]) -> list[str]: return sorted(name for name in names if name not in known) -# A list this short is printed whole rather than pointed at. -SHORT_LIST = 12 +def _check_cores_dir(folder: Path) -> None: + """Refuse a --cores-dir that cannot be listed, saying why: a typo + (core/ for cores/) or a closed folder read as an empty one, and the + run said "none in" and asked for the --cores-dir it was given.""" + try: + with os.scandir(folder): + return + except FileNotFoundError: + why = "does not exist" + except NotADirectoryError: + why = "is not a folder" + except PermissionError as exc: + closed = closed_folder(folder) + why = (f"cannot be opened by this user ({exc.strerror or exc})" + if closed is None or closed[0] == folder + else f"cannot be opened: {closed_folder_words(folder, closed)}") + except OSError as exc: + why = f"could not be read ({exc.strerror or exc})" + print(f"Error: --cores-dir {screen_text(str(folder))} {why}.", file=sys.stderr) + print(" Name the folder RetroArch loads cores from (libretro_directory in " + "retroarch.cfg, cores/ beside RetroArch by default).", file=sys.stderr) + sys.exit(1) -# Names people type for a system, each with its id. Only ever suggested: -# --system gba, psx and ps1 were refused with no hint on RetroArch, whose -# list names no system that way, and taking one in silence could install -# another console than the one meant. -SYSTEM_SHORT_NAMES = { - **dict.fromkeys(("psx", "ps1", "ps", "playstation1"), "sony-playstation"), - "ps2": "sony-playstation-2", "ps3": "sony-playstation-3", "psp": "sony-psp", - **dict.fromkeys(("vita", "psvita"), "sony-playstation-vita"), - "gb": "nintendo-gb", "gbc": "nintendo-gbc", "gba": "nintendo-gba", - **dict.fromkeys(("nes", "famicom", "fc"), "nintendo-nes"), "fds": "nintendo-fds", - **dict.fromkeys(("snes", "sfc", "superfamicom"), "nintendo-snes"), - "n64": "nintendo-64", "n64dd": "nintendo-64dd", "sgb": "nintendo-sgb", - **dict.fromkeys(("nds", "ds"), "nintendo-ds"), "dsi": "nintendo-dsi", - "3ds": "nintendo-3ds", "wiiu": "nintendo-wii-u", "switch": "nintendo-switch", - **dict.fromkeys(("gc", "ngc", "gcn", "gamecube"), "nintendo-gamecube"), - "pokemini": "nintendo-pokemon-mini", - **dict.fromkeys(("md", "gen", "genesis", "megadrive"), "sega-mega-drive"), - **dict.fromkeys(("scd", "segacd", "megacd"), "sega-mega-cd"), - "32x": "sega-32x", **dict.fromkeys(("sms", "mastersystem"), "sega-master-system"), - **dict.fromkeys(("gg", "gamegear"), "sega-game-gear"), - **dict.fromkeys(("ss", "saturn"), "sega-saturn"), - **dict.fromkeys(("dc", "dreamcast"), "sega-dreamcast"), - **dict.fromkeys(("naomi", "atomiswave"), "sega-dreamcast-arcade"), - **dict.fromkeys(("pce", "tg16", "turbografx", "turbografx16", "pcengine", - "supergrafx"), "nec-pc-engine"), - **dict.fromkeys(("pcecd", "tgcd", "turbografxcd"), "nec-pc-engine-cd"), - "pcfx": "nec-pc-fx", - **dict.fromkeys(("neogeo", "mvs", "aes"), "snk-neogeo"), - **dict.fromkeys(("neocd", "neogeocd"), "snk-neogeo-cd"), - **dict.fromkeys(("msx", "msx2"), "microsoft-msx"), - "c64": "commodore-c64", "c128": "commodore-c128", - **dict.fromkeys(("amiga", "cd32"), "commodore-amiga"), - "x68k": "sharp-x68000", **dict.fromkeys(("jag", "jaguar"), "atari-jaguar"), - **dict.fromkeys(("st", "atarist"), "atari-st"), "a800": "atari-400-800", - **dict.fromkeys(("coleco", "colecovision"), "coleco-colecovision"), - **dict.fromkeys(("intv", "intellivision"), "mattel-intellivision"), - "o2": "magnavox-odyssey2", "channelf": "fairchild-channel-f", - **dict.fromkeys(("zx", "spectrum", "zxspectrum"), "sinclair-zx-spectrum"), - "cpc": "amstrad-cpc", "bbc": "acorn-bbc-micro", "apple2": "apple-ii", -} +def _unprofiled_cores_firmware( + plat: str, bios_path: Path, manifest: dict, found: list[str], searched: list[Path], +) -> list[str]: + """What the installed cores the list has no profile for declare, each said. -# A system some lists file under another id, by the file that stands for it. -# The Neo Geo card offers --system snk-neogeo, and RetroArch's list keeps -# neogeo.zip under arcade: the run suggests arcade, never takes it. -SYSTEM_KEY_FILES = {"snk-neogeo": "neogeo.zip"} - - -def key_file_holders(files: list[dict], omitted: list[dict]) -> dict[str, list[str]]: - """The systems a list files each SYSTEM_KEY_FILES file under, for the - systems the list does not name itself.""" - entries = files + omitted - known = {system for entry in entries for system in entry_systems(entry)} - holders: dict[str, list[str]] = {} - for system, name in SYSTEM_KEY_FILES.items(): - if system in known: - continue - held = sorted({ - holder for entry in entries - if PurePosixPath(str(entry.get("dest", ""))).name.lower() == name - for holder in entry_systems(entry) - }) - if held: - holders[system] = held - return holders - - -def did_you_mean( - typed: list[str], known: list[str], listing: str, - aliases: dict[str, str] | None = None, inside_from: int = 4, - meant: dict[str, list[str]] | None = None, -) -> str: - """The closest known names to what was typed, and the option listing them all. - - A typo was answered with every name the platform has, up to 400 on one - line, with no hint that playstation is sony-playstation. An alias close - to what was typed suggests the name it stands for. A name holding what - was typed, inside_from letters or more, is suggested too. meant gives, - by the letters and digits of a typed name, the names it stands for - here, suggested instead of the close ones. + Such a core reads systems the list cannot name, and narrowing to the + installed cores dropped its BIOS without a word (issue 87, parallel_dc + before its profile). Its .info is what RetroArch itself checks, so the + files it declares are kept. A core without one is named. """ - import difflib - - by_key: dict[str, str] = {} - for name in known: - by_key.setdefault(_name_key(name), name) - for alias, name in (aliases or {}).items(): - by_key.setdefault(_name_key(alias), name) - close: list[str] = [] - for word in typed: - key = _name_key(word) - if not key: - continue - if meant and key in meant: - close += [name for name in meant[key] if name not in close] - continue - matches = difflib.get_close_matches(key, list(by_key), n=3, cutoff=0.6) - if len(key) >= inside_from: - matches += sorted(k for k in by_key if key in k and k not in matches) - for k in matches: - # Two aliases of one system (psx, ps1) name it once. - if by_key[k] not in close: - close.append(by_key[k]) - if close: - return f"Close matches: {', '.join(close[:3])}. {listing} lists all {len(known)}." - if len(known) <= SHORT_LIST: - return f"Known: {', '.join(known)}." - return f"{listing} lists all {len(known)}." + unknown = unknown_cores(manifest, found) + if not unknown: + return [] + dirs = info_dirs(plat, bios_path, searched) + dests: list[str] = [] + for core in unknown: + declared = info_firmware(dirs, core) + if declared is None: + message = (f"{core}: a core this list does not know, with no .info to read: " + "its files may be missing. Run without --installed-cores " + "to install every file.") + else: + message = (f"{core}: a core this list does not know, " + f"{_plural(len(declared), 'file')} its .info declares kept") + print(f" {message}") + EVENTS.emit("unknown_core", platform=plat, core=core, + info=declared is not None, dests=declared or [], message=message) + dests.extend(declared or []) + return dests -def refuse_name(platform: str, *lines: str) -> NoReturn: - """End the run on a name it cannot use (a platform, target, system, core - or emulator), refused before any download. +def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None: + """Refuse --installed-cores with no core, and say how to point at them. - The reason went to stderr only: a reader of --events got start, then - end with code 1, and could not tell a typo from a failed download. Code - 2, as for an option argparse refuses: 1 also means --check found files - to fetch, and a script reading it reran the install on a typo forever. + With no retroarch.cfg naming the folder as its system_directory, and + none beside it, nothing names the cores folder: the run stopped on "no + known directory" with no way forward. """ - message = " ".join(line.strip() for line in lines) - if message.startswith("Error: "): - message = message[len("Error: "):] - EVENTS.emit("error", stage="option", reason="unknown", platform=platform, - message=message) - for line in lines: - print(line, file=sys.stderr) - sys.exit(2) - - -# Frontends and systems that keep no BIOS folder of their own: each -# emulator they start reads its own, which a run without --platform finds. -# --platform es-de was "Unknown platform", the answer left unsaid. -_NO_BIOS_FOLDER = ("ES-DE", "LaunchBox", "Android") - - -def normalize_platform(name: str, say: bool = True) -> str: - """Return the canonical platform id for user-supplied input. - - The site writes MiSTer FPGA and RetroArch: letters and digits decide, - as they do for verify.py and generate_pack.py. say is False where the - name is read again later, which says it once. - """ - key = _name_key(name) - for plat in AVAILABLE_PLATFORMS: - if key and key in (_name_key(plat), _name_key(display_name(plat))): - return plat - # --list-platforms prints `muOS: retroarch`, and --platform muos was - # refused: a system named there stands for the list it gets. - for rule in _EMBEDDED_RULES: - if key and rule.manifest and key == _name_key(rule.name): - if say: - print(f" {rule.name} gets the {display_name(rule.manifest)} file list: " - f"--platform {rule.manifest}.") - return rule.manifest - for frontend in _NO_BIOS_FOLDER: - if key and key == _name_key(frontend): - refuse_name(name.strip(), f"{frontend} has no BIOS folder of its own: run again " - "without --platform, and the installer fills the folder of each " - "emulator it finds here.") - # --list-platforms prints TrimUI with why it gets no folder, and naming - # it answered "Unknown platform". - for rule in _EMBEDDED_RULES: - if key and not rule.manifest and key == _name_key(rule.name): - refuse_name(name.strip(), f"{rule.name} is not installed to: " - f"{_NO_FOLDER.get(rule.name, 'no source names its BIOS folder')}.", - " Name that folder: --platform retroarch " - "--dest FOLDER") - # Every name --list-platforms prints, so that spruce suggests spruceOS - # and the count is the one the listing shows. - known = list(AVAILABLE_PLATFORMS) + list(dict.fromkeys( - rule.name for rule in _EMBEDDED_RULES - if _name_key(rule.name) not in {_name_key(plat) for plat in AVAILABLE_PLATFORMS} - )) + list(_NO_BIOS_FOLDER) - refuse_name(name.strip(), f"Unknown platform '{name.strip()}'. " - + did_you_mean([name], known, "--list-platforms")) - - -def entry_systems(entry: dict) -> list[str]: - """The platform systems a file or an omission belongs to. - - An omission's `system` is spelled the way its profile spells it. Only - `systems` names the platform's own, the ones --system accepts. - """ - return list(entry.get("systems") or []) + where = (f"none in {', '.join(map(str, searched))}" if searched + else f"no retroarch.cfg was found for {bios_path} to name their folder") + print(f"Error: no installed core found for {display_name(plat)}: {where}.", + file=sys.stderr) + print(" Name the folder RetroArch loads cores from (libretro_directory in " + "retroarch.cfg, cores/ beside RetroArch by default):", file=sys.stderr) + command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir")) + print(f" {command} --cores-dir ", file=sys.stderr) + print(" Or run it without --installed-cores to install every file.", file=sys.stderr) + sys.exit(1) # --- installer/narrowing.py -------------------------------------------------- +def board_target(board: str, targets: dict[str, dict]) -> str | None: + """The target a board name stands for: the name itself, else the one + target whose images carry it. A card names its image (Batocera writes + anbernic-rg35xx-plus for the h700 target, x86-64-v3 for zen3).""" + if board in targets: + return board + owners = [name for name, info in targets.items() if board in info.get("images", ())] + return owners[0] if len(owners) == 1 else None + + def _for_cores(entry: dict, chosen: set[str]) -> dict | None: """The copy of a core file the chosen cores read, or None. @@ -7035,40 +6888,6 @@ def narrow_to_cores( return kept_files, kept(omitted) + displaced -def canonical_region(raw: str) -> str: - """One region name or alias, spelled the way manifests spell it.""" - key = raw.strip().lower() - key = REGION_ALIASES.get(key, key) - if key not in REGIONS: - import difflib - - close = difflib.get_close_matches(key, [*REGION_ALIASES, *REGIONS], n=3, cutoff=0.5) - hint = f" Close matches: {', '.join(close)}." if close else "" - raise ValueError( - f"unknown region: {raw.strip()}.{hint} " - f"Short forms: {', '.join(REGION_ALIASES)}. Regions: " - f"{', '.join(sorted(REGIONS))}" - ) - return key - - -def _region_comparable(a: str, b: str) -> bool: - return ( - a == b - or _REGION_PARENT.get(a) == b - or _REGION_PARENT.get(b) == a - or a in AREA_TERRITORIES.get(b, ()) - or b in AREA_TERRITORIES.get(a, ()) - ) - - -def _region_rank(file_regions: set[str], requested: list[str]) -> int: - for index, wanted in enumerate(requested): - if any(_region_comparable(wanted, region) for region in file_regions): - return index - return len(requested) - - def region_drops( entries: list[dict], requested: list[str], @@ -7378,1505 +7197,153 @@ def find_by_hash(files: list[dict], value: str) -> tuple[str, list[dict], bool]: return kind, matches, recorded -def recorded_axes(files: list[dict], omitted: Iterable[dict] = ()) -> frozenset: - """What a file list lets --system, --core and --region narrow by: its - systems, its cores, its regions. A list from an older release records - none. The MinUI family's records cores and regions and no system: all - three were refused on it, by a remedy that fetched the same list.""" - entries = [*files, *omitted] - systems = any("systems" in entry for entry in entries) - if not systems and not any("regions" in entry for entry in entries): - # Systems and regions came in one release: a list with neither is - # older, its cores read by nothing that narrows. - return frozenset() - # A current list records the regions of the files a region selects, and - # none when it has no such file: --region then keeps every file, as the - # pack built with it does. - axes = {"regions", *(["systems"] if systems else [])} - if any(copy.get("cores") for entry in files - for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]): - axes.add("cores") - return frozenset(axes) +# --- installer/offline.py ---------------------------------------------------- - -def records_selection(files: list[dict]) -> bool: - """Whether a manifest records anything narrowing reads. Older ones do not.""" - return bool(recorded_axes(files)) - - -def available_choices(files: list[dict], omitted: list[dict]) -> dict[str, list[str]]: - """The systems, cores and regions a manifest lets one narrow to.""" - systems = {s for e in files + omitted for s in entry_systems(e)} - ordered = sorted(systems) - if any(not entry_systems(f) for f in files): - ordered.append(OTHER_SYSTEMS) - cores = { - c for f in files - for copy in [f, *f.get("alternatives", []), *f.get("slot_choices", [])] - for c in (copy.get("cores") or []) - } - regions = { - r for e in files + omitted for r in (e.get("regions") or []) - if r != WORLD_REGION - } - return { - "systems": ordered, - "cores": sorted(cores), - "regions": sorted(regions), - } - - -def choosable_cores(files: list[dict], omitted: list[dict], - systems: Collection[str] = ()) -> list[str]: - """The cores a choice is made among, for the files a run keeps once - the save entries it cannot place and the game data --no-game-data cuts - are left out, of the systems chosen (every system for none). Cores on - the screen and c in line mode list these and count "N of M" out of - them: the screen listed the whole file list's 189 where the run - accepted 181.""" - if systems: - files, omitted = narrow(files, omitted, list(systems), [], []) - return available_choices(files, omitted)["cores"] - - -def core_files(files: list[dict], core: str) -> list[dict]: - """The files one core adds to the platform's own: what line mode's - Cores question and the screen's Cores rows size.""" - return _filter_by_target([entry for entry in files if entry.get("cores") is not None], - [core]) - - -def resolve_choices( - values: list[str], known: list[str], label: str, - aliases: dict[str, str] | None = None, - holders: dict[str, list[str]] | None = None, -) -> list[str]: - """Names given on the command line, matched without regard to case. - - Each value is one name or a comma-separated list. A whole value that is - itself a name wins over splitting it: Recalbox names one system - `msx1,msx2,msxturbor`. An unknown name is refused, never ignored, since - carrying on would install something other than what was asked. - aliases maps another name of a known one to it, as Batocera's `psx` - stands for sony-playstation. A known name always wins over an alias. - holders maps a system the list files under other ids to those ids - (key_file_holders): an unknown name for it is answered with them. - """ - aliases = {alias: name for alias, name in (aliases or {}).items() if name in known} - by_lower = {name.lower(): name for name in known} - for alias, name in aliases.items(): - by_lower.setdefault(alias.lower(), name) - # Spelled as the site writes it (Sony PlayStation), a name is still one - # name when no other one reads the same once case and spacing go. - by_key: dict[str, str | None] = {} - for name in known: - key = _name_key(name) - by_key[key] = None if key in by_key else name - for alias, name in aliases.items(): - by_key.setdefault(_name_key(alias), name) - chosen: list[str] = [] - unknown: list[str] = [] - for value in values: - value = value.strip() - tokens = [value] if value.lower() in by_lower else value.split(",") - for token in (t.strip() for t in tokens): - if not token: - continue - picked = by_lower.get(token.lower()) or by_key.get(_name_key(token)) - if picked is None: - unknown.append(token) - elif picked not in chosen: - chosen.append(picked) - if unknown: - if not known: - raise ValueError(f"unknown {label}: {', '.join(unknown)}. This list records none.") - listing = {"system": "--list-systems", "emulator": "--list-emulators"}.get( - label, "--list-cores") - hints, inside_from = aliases, 4 - held = holders or {} - stands_for: dict[str, str] = {} - notes = "" - if label == "system": - # gba is the end of nintendo-gba: three letters are enough here. - hints = {**{short: name for short, name in SYSTEM_SHORT_NAMES.items() - if name in known}, **aliases} - inside_from = 3 - stands_for = {_name_key(system): system for system in held} - for short, name in SYSTEM_SHORT_NAMES.items(): - if name in held: - stands_for.setdefault(_name_key(short), name) - named = dict.fromkeys( - stands_for[_name_key(token)] for token in unknown - if _name_key(token) in stands_for) - notes = "".join( - f"This list files {SYSTEM_KEY_FILES[system]} under " - f"{', '.join(held[system])}. " for system in named) - meant = {key: held[system] for key, system in stands_for.items()} - raise ValueError( - f"unknown {label}: {', '.join(unknown)}. {notes}" - f"{did_you_mean(unknown, known, listing, hints, inside_from, meant)}" - ) - if values and not chosen: - raise ValueError(f"--{label} needs at least one name") - return chosen - - -def resolve_regions(values: list[str]) -> list[str]: - """A region priority list, best first, from names or aliases.""" - chosen: list[str] = [] - for value in values: - for token in value.split(","): - if token.strip(): - region = canonical_region(token) - if region not in chosen: - chosen.append(region) - if values and not chosen: - raise ValueError("--region needs at least one region") - return chosen - - -def parse_selection(text: str, count: int, ordered: bool = False) -> list[int]: - """Numbers typed at a prompt: `3`, `1,4`, `2-5`, or `all`, 1-based. - - Returned sorted, or in the typed order when the order is a priority. - """ - if text.strip().lower() in ("all", "*"): - return list(range(1, count + 1)) - chosen: list[int] = [] - for token in (t.strip() for t in text.split(",")): - if not token: - continue - low, sep, high = token.partition("-") - try: - start = int(low) - end = int(high) if sep else start - except ValueError: - raise ValueError(f"not a number or range: {token}") from None - if start > end or start < 1 or end > count: - raise ValueError(f"out of range: {token} (1-{count})") - for number in range(start, end + 1): - if number not in chosen: - chosen.append(number) - return chosen if ordered else sorted(chosen) - - -# --- installer/record.py ----------------------------------------------------- - -class _NotKept(Exception): - """The file in place differs and could not be set aside: it stays.""" - - -class KeptFiles: - """The files this run moved aside before replacing them. - - A file is kept at ///, - the holder being retrobios-backup beside the folder written to. The run - folder is named by date and time, so a second run never mixes with the - first, and copying its contents into the holder's parent puts every file - back where it was. Only when nothing can be written beside the folder - (a drive root, a read-only parent) does the holder go inside it, with - no folder name, and the same copy puts the files back. - """ +class LocalSources: + """Where this run reads instead of the network: a file list, a pack, the + folders it copies BIOS files from.""" def __init__(self) -> None: - self._lock = threading.Lock() - self.stamp = "" - # Holder -> the run folder this run created in it. - self._runs: dict[Path, Path] = {} - # Run folder -> [files, bytes] kept (or, under --dry-run, to keep). - self.counts: dict[Path, list[int]] = {} + self.manifest: Path | None = None + self.pack: PackSource | None = None + # The folders named with --from, read once for every platform. + self.folders: list[FolderIndex] = [] + # The reads at once of the files in place (--jobs). + self.jobs: int = 8 + # Every folder index of the run still in use, closed at its end. + self.indexes: weakref.WeakSet[FolderIndex] = weakref.WeakSet() + self._serves: tuple = (None, None, frozenset()) + + def serves(self) -> frozenset: + """The platforms the file list or pack given to this run is for, + empty when none is given. The setup list offers those alone: after + o, Batocera was listed for a RetroArch list, and refused once its + folder was asked.""" + if self._serves[:2] != (self.manifest, self.pack): + named = (local_manifest_platform(self.manifest) if self.manifest is not None + else None) + found = ({named} if named else set()) if self.manifest is not None \ + else set(self.pack.platforms()) if self.pack is not None else set() + self._serves = (self.manifest, self.pack, frozenset(found)) + return self._serves[2] + + @property + def offline(self) -> bool: + """No network request in this run: a pack is read, or --offline.""" + return self.pack is not None or offline_requested() def reset(self) -> None: - with self._lock: - self.stamp = "" - self._runs.clear() - self.counts.clear() + if self.pack is not None: + self.pack.close() + self.close_indexes() + self.manifest = None + self.pack = None + self.folders = [] + self.jobs = 8 - def _stamp(self) -> str: - if not self.stamp: - self.stamp = time.strftime("%Y%m%d-%H%M%S") - return self.stamp - - @staticmethod - def _holders(folder: Path) -> list[tuple[Path, str]]: - beside = [(folder.parent / BACKUP_DIR, folder.name)] if ( - folder.name and folder.parent != folder) else [] - return beside + [(folder / BACKUP_DIR, "")] - - def place(self, folder: Path, create: bool) -> tuple[Path, Path]: - """(run folder, folder the relative path goes under) for files of folder.""" - with self._lock: - stamp = self._stamp() - failure: OSError | None = None - for holder, prefix in self._holders(folder): - if not create: - return holder / stamp, holder / stamp / prefix - run = self._runs.get(holder) - if run is None: - try: - holder.mkdir(parents=True, exist_ok=True) - checked = _check_holder(holder) - for n in range(1, 1000): - run = holder / (stamp if n == 1 else f"{stamp}-{n}") - try: - run.mkdir(mode=0o700) - break - except FileExistsError: - continue - else: - # Every name taken: never reuse a folder this run - # did not create. - raise OSError(errno.EEXIST, f"no free folder name in {holder}") - # The holder checked before is still the one the run - # folder was made in, and the run folder is a folder. - if not (_same_folder(holder, checked) - and stat.S_ISDIR(os.lstat(run).st_mode)): - raise OSError(errno.ELOOP, f"{holder} changed while in use") - (run / BACKUP_MARKER).write_text( - "Files the RetroBIOS installer replaced.\n", encoding="utf-8") - except OSError as exc: - failure = exc - continue - self._runs[holder] = run - return run, run / prefix - raise failure or OSError(errno.EEXIST, "no backup folder name left") - - def plan(self, folder: Path, size: int) -> Path: - """Count a file a real run would keep, writing nothing. Returns its run folder.""" - run, _under = self.place(folder, create=False) - with self._lock: - tally = self.counts.setdefault(run, [0, 0]) - tally[0] += 1 - tally[1] += size - return run - - def keep( - self, folder: Path, rel: PurePosixPath, dest: Path, - expected: dict[str, str], fresh: Path | None = None, - ) -> None: - """Move the file at dest aside when its content is not the one coming. - - Nothing is done for a missing file, a link (its target is not - touched by the replace) or a file already holding the content, by - the manifest's hashes or, without them, byte for byte against the - fresh copy. Raises _NotKept when the file could not be set aside: - the replace must not happen then. - """ - try: - info = os.lstat(dest) - except FileNotFoundError: - return - except OSError as exc: - raise _NotKept(exc.strerror or str(exc)) from exc - if not stat.S_ISREG(info.st_mode): - return - try: - if expected: - same = _digest_file(dest, tuple(expected)) == expected - else: - same = fresh is not None and _same_bytes(dest, fresh) - except FileNotFoundError: - return # another run replaced it meanwhile - except OSError as exc: - raise _NotKept(exc.strerror or str(exc)) from exc - if same: - return - try: - run, under = self.place(folder, create=True) - kept = under / Path(*rel.parts) - if os.path.lexists(kept): - # This run kept the user's file at that path already: the - # one in place now is one this run wrote. - return - kept.parent.mkdir(parents=True, exist_ok=True) - _move_aside(dest, kept) - except FileNotFoundError: - if not os.path.lexists(dest): - return # another run moved or replaced it meanwhile - raise _NotKept("the backup folder could not be written") from None - except OSError as exc: - raise _NotKept(exc.strerror or str(exc)) from exc - with self._lock: - tally = self.counts.setdefault(run, [0, 0]) - tally[0] += 1 - tally[1] += info.st_size - - def summary(self) -> list[dict]: - """[{folder, files, bytes}], one per run folder, for the report and events.""" - with self._lock: - # Named as the run names its BIOS folder: /sdcard, not the - # /storage/emulated/0 the link resolves to. - return [{"folder": str(spelled(run)), "files": files, "bytes": size} - for run, (files, size) in sorted(self.counts.items())] + def close_indexes(self) -> None: + for index in list(self.indexes): + index.close() + self.indexes = weakref.WeakSet() -KEPT = KeptFiles() +LOCAL = LocalSources() -def _same_bytes(a: Path, b: Path) -> bool: - if a.stat().st_size != b.stat().st_size: - return False - return _digest_file(a, ("sha1",)) == _digest_file(b, ("sha1",)) +class _Offline(OSError): + """A network request in a run told to make none.""" -def _move_aside(dest: Path, kept: Path) -> None: - """Move dest to kept: a rename on one drive, else a copy then a delete. +OFFLINE_WORDS = "this run makes no network request" +# The value --offline gives the variable: the words then name the option, +# and the variable itself where it was set. +OFFLINE_FLAG_VALUE = "--offline" - The copy goes under a temporary name first, so an interrupted copy - never leaves a cut file under the kept name, and dest is only deleted - once its copy is whole. + +def offline_named() -> str: + """What made this run offline, as the words name it.""" + value = os.environ.get(OFFLINE_VARIABLE, "") + return (f"{OFFLINE_VARIABLE}={value}" if value not in ("", "0", OFFLINE_FLAG_VALUE) + else "--offline") + + +def offline_undo() -> str: + """How a run gets the network back: without the option, or with the + variable unset. "without --offline" told a user who never typed it to + remove it.""" + return ("without --offline" if offline_named() == "--offline" + else f"with {OFFLINE_VARIABLE} unset") + + +def offline_words() -> str: + """This run makes no network request, and what said so.""" + return f"{OFFLINE_WORDS} ({offline_named()})" + + +def _network_allowed(what: str) -> None: + if LOCAL.pack is not None: + raise _Offline(f"{what}: this run reads a pack and makes no network request") + if offline_requested(): + raise _Offline(f"{what}: {offline_words()}") + + +def local_manifest_platform(path: Path) -> str | None: + """The platform a saved file list names, None when it names none.""" + try: + with open(path, "rb") as handle: + data = json.loads(handle.read(MAX_MANIFEST_BYTES).decode("utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return None + plat = data.get("platform") if isinstance(data, dict) else None + return plat if plat in AVAILABLE_PLATFORMS else None + + +def _offline_only() -> bool: + """--offline without a pack: what is not on this machine cannot come.""" + return offline_requested() and LOCAL.pack is None + + +# --- installer/network.py ---------------------------------------------------- + +def _read_limited_json( + response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False +) -> object: + """Read a bounded UTF-8 JSON response, its bytes as they came with raw. + + A body shorter than its Content-Length is a dropped connection, raised + as one so the caller retries: parsed, the cut read as an invalid file + list and the run ended without the network advice. """ - try: - os.rename(dest, kept) - return - except OSError: - if not _is_file(dest): - raise - scratch = kept.parent / f".{kept.name}.part" - try: - shutil.copy2(dest, scratch) - os.replace(scratch, kept) - except OSError: - if os.path.lexists(scratch): - os.unlink(scratch) - raise - dest.unlink() - - -def _kept_slot(root: Path, value: object) -> tuple[Path, PurePosixPath]: - """The folder a manifest destination is written in, and its path below - it, as _destination_path places it: a RetroDECK folder moved elsewhere - is its own folder.""" - relative = _safe_relative_path(value, "dest") - moved = _MOVED_FOLDERS.get(root, {}) - if len(relative.parts) > 1 and relative.parts[0] in moved: - return moved[relative.parts[0]].resolve(), PurePosixPath(*relative.parts[1:]) - return _note_spelling(root), relative - - -def plan_kept(entries: list[dict], root: Path) -> dict[Path, list[int]]: - """Count, under --dry-run, the files in place a real run would keep. - - entries are files whose content check failed. Returns {run folder: - [files, bytes]} for these entries, also counted in KEPT for the summary. - """ - planned: dict[Path, list[int]] = {} - for entry in entries: + raw_length = response.headers.get("Content-Length") if response.headers else None + expected: int | None = None + if raw_length: try: - dest = _entry_path(root, entry) - info = os.lstat(dest) - except (OSError, ValueError): - continue - if stat.S_ISREG(info.st_mode): - run = KEPT.plan(_kept_slot(*_entry_place(root, entry))[0], info.st_size) - tally = planned.setdefault(run, [0, 0]) - tally[0] += 1 - tally[1] += info.st_size - return planned - - -def _kept_lines() -> list[str]: - """Where the files this run replaced are, and how to put them back.""" - lines = [] - for item in KEPT.summary(): - folder = Path(item["folder"]) - lines.append(f"Kept {_plural(item['files'], 'file')} already there " - f"({format_size(item['bytes'])}), which the collection's " - f"copies replaced, in {folder}") - if OUTPUT.verbose: - lines.append(f" To put them back: {_INVOCATION.launcher()} --restore " - f"{_INVOCATION.word(str(folder))}") - return lines - - -# The install record: what the runs placed in a BIOS folder, each file with -# its hash, and the choice they made, which the next run's plan takes. It -# lives in the backup holder beside the folder, never loose in it, for the -# reason the backups do. On a card it travels with the card. -RECORD_SCHEMA = 1 -RECORD_SUFFIX = ".install.json" -# The options a record keeps as the choice: what the list was narrowed to. -RECORD_CHOICE = ("--system", "--core", "--emulator", "--region", "--for-games", - "--required-only", "--all-files", "--target", "--every-board", - "--no-game-data", "--installed-cores", "--declared-only") -# The record's choice options that narrow the list, --all-files aside. -RECORD_NARROWING = tuple(flag for flag in RECORD_CHOICE if flag != "--all-files") -_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", - "Dec") -# The records already said unreadable in this run, said once each. -_RECORD_SAID: set[str] = set() -# Per platform, the record whose choice this run took (apply_record). -_RECORD_TAKEN: dict[str, dict] = {} - - -def record_paths(folder: Path) -> list[Path]: - """Where the record of folder is looked for, in order: the holder beside - it, then the one inside it that a folder with no writable parent gets.""" - folder = Path(os.path.abspath(folder)) - name = f"{folder.name or 'folder'}{RECORD_SUFFIX}" - return [holder / name for holder, _prefix in KeptFiles._holders(folder)] - - -# Read whole, never past this: a record of every file of the longest list -# holds 1.6 MB per setup, and a few setups share one folder. -MAX_RECORD_BYTES = 16 * 1024 * 1024 -# The choice options that take a value. --for-games takes one or none. -_RECORD_VALUED = ("--system", "--core", "--emulator", "--region", "--target") - - -def games_folder_kept(value: str, folder: Path) -> bool: - """Whether a recorded --for-games folder may be read again: an absolute - path under the folder that holds the BIOS folder (a card's root, the - setup's own folder), never another drive or a network share.""" - if not value or value.startswith(("\\\\", "//")) or not os.path.isabs(value): - return False - parent = os.path.normcase(os.path.normpath(os.path.dirname(os.path.abspath(folder)))) - games = os.path.normcase(os.path.normpath(value)) - try: - return os.path.commonpath([parent, games]) == parent - except ValueError: - # Two drives on Windows: no common path. - return False - - -def valid_choice(choice: list[str], folder: Path) -> bool: - """Whether every word of a recorded choice is an option of the choice or - the value right after one: a record naming --dest, --from or --manifest - would put them in the commands printed for the user to copy.""" - words = list(choice) - while words: - flag = words.pop(0) - if flag not in RECORD_CHOICE: - return False - if flag in _RECORD_VALUED: - if not words or words[0].startswith("-") or not words[0].strip(): - return False - value = words.pop(0) - if any(ord(char) < 32 or ord(char) == 127 for char in value): - return False - elif flag == "--for-games" and words and not words[0].startswith("--"): - if not games_folder_kept(words.pop(0), folder): - return False - return True - - -def _valid_setup(setup: object, folder: Path) -> bool: - if not isinstance(setup, dict): - return False - choice, files = setup.get("choice"), setup.get("files") - return (isinstance(setup.get("written"), str) and isinstance(choice, list) - and all(isinstance(word, str) for word in choice) and valid_choice(choice, folder) - and isinstance(files, list) - and all(isinstance(item, dict) and isinstance(item.get("dest"), str) - and isinstance(item.get("sha1"), str) and isinstance(item.get("size"), int) - for item in files)) - - -class RecordRead(NamedTuple): - """What reading a record found: the record with its usable setups, where - it is, why it cannot be used, whether a newer installer wrote it, and - the setups it holds that cannot be used.""" - - data: dict | None - path: Path | None - problem: str - newer: bool = False - dropped: tuple = () - - -def _read_record_bytes(path: Path) -> bytes: - """The bytes of a record that is a regular file of a record's size. A - FIFO, a device or a folder is refused before it is read: reading one - waited forever.""" - info = os.stat(path) - if not stat.S_ISREG(info.st_mode): - raise OSError(errno.EINVAL, "it is not a file") - if info.st_size > MAX_RECORD_BYTES: - raise OSError(errno.EFBIG, "it is larger than any record") - flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) - handle = os.open(path, flags) - try: - # Opened without waiting, then checked again: what is open now is - # what is read, whatever took the name since the stat. - if not stat.S_ISREG(os.fstat(handle).st_mode): - raise OSError(errno.EINVAL, "it is not a file") - chunks, left = [], MAX_RECORD_BYTES + 1 - while left > 0: - chunk = os.read(handle, min(left, 1 << 20)) - if not chunk: - break - chunks.append(chunk) - left -= len(chunk) - finally: - os.close(handle) - data = b"".join(chunks) - if len(data) > MAX_RECORD_BYTES: - raise OSError(errno.EFBIG, "it is larger than any record") - return data - - -def load_record(folder: Path) -> RecordRead: - """The record of folder, read once (RecordRead).""" - for path in record_paths(folder): - try: - text = _read_record_bytes(path).decode("utf-8") - except (FileNotFoundError, NotADirectoryError): - continue - except (OSError, UnicodeDecodeError) as exc: - reason = getattr(exc, "strerror", None) or str(exc) - return RecordRead(None, path, f"The install record {path} cannot be read ({reason})") - try: - data = json.loads(text) + expected = int(raw_length) except ValueError: - return RecordRead(None, path, f"The install record {path} is damaged") - schema = data.get("schema") if isinstance(data, dict) else None - if isinstance(schema, int) and not isinstance(schema, bool) and schema > RECORD_SCHEMA: - # Its shape is the newer installer's: kept for it, never read. - return RecordRead(None, path, f"The install record {path} was written by a newer " - "installer", newer=True) - if (not isinstance(data, dict) or not isinstance(data.get("setups"), dict) - or not isinstance(data.get("folder"), str) or schema != RECORD_SCHEMA): - return RecordRead(None, path, f"The install record {path} is damaged") - setups = {name: setup for name, setup in data["setups"].items() - if _valid_setup(setup, folder)} - dropped = tuple(sorted(str(name) for name in data["setups"] if name not in setups)) - return RecordRead({**data, "setups": setups}, path, "", dropped=dropped) - return RecordRead(None, None, "") - - -def read_record(folder: Path) -> tuple[dict | None, Path | None, str]: - """(the record of folder, where it is, why it cannot be used). Neither a - record nor a reason where there is none.""" - found = load_record(folder) - return found.data, found.path, found.problem - - -def setup_record(plat: str, folder: Path) -> tuple[dict | None, Path | None, str]: - """The record of plat in folder, where it is, and why it cannot be used. - A record written for a folder of another name (copied, or renamed with - it) is not this folder's. A setup of it that cannot be used (an option - the choice has no place for, a games folder elsewhere) is damaged, the - others still read.""" - found = load_record(folder) - if found.data is None: - return None, found.path, found.problem - written_for = str(found.data.get("folder") or "") - if Path(written_for).name != Path(os.path.abspath(folder)).name: - return None, found.path, "" - if plat in found.dropped: - return None, found.path, f"The install record {found.path} is damaged" - return found.data["setups"].get(plat), found.path, "" - - -def record_day(setup: dict) -> str: - """The day a record was written, as the plan says it: 3 Nov.""" + expected = None + if expected is not None and expected > limit: + raise ValueError(f"{label} exceeds {limit} bytes") try: - when = datetime.datetime.fromisoformat(setup["written"].replace("Z", "+00:00")) - # Year 1 or 9999 cannot be moved to local time: an unknown day. - local = when.astimezone() - except (KeyError, TypeError, AttributeError, ValueError, OverflowError, OSError): - return "" - day = f"{local.day} {_MONTHS[local.month - 1]}" - return day if local.year == datetime.datetime.now().year else f"{day} {local.year}" - - -def record_options(argv: list[str]) -> list[tuple[str, str | None]]: - """A record's choice as (option, value) pairs.""" - options: list[tuple[str, str | None]] = [] - words = list(argv) - while words: - flag = words.pop(0) - valued = flag in _VALUED_OPTIONS or ( - flag == "--for-games" and words and not words[0].startswith("--")) - options.append((flag, words.pop(0) if valued and words else None)) - return options - - -def record_argv(options: Iterable[tuple[str, str | None]]) -> list[str]: - """The choice options a record keeps, as words, in the command's order.""" - kept = sorted((option for option in options if option[0] in RECORD_CHOICE), - key=_command_rank) - if not any(flag in RECORD_NARROWING for flag, _value in kept): - # The whole list, chosen as such: a card that holds games later - # still gets what was installed before. - kept = [("--all-files", None)] - return [word for flag, value in kept for word in ([flag] if value is None else [flag, value])] - - -def record_says(setup: dict, manifest: dict | None = None) -> str: - """The recorded choice in words: Game Boy Advance, the games, the - options chosen, every file.""" - options = record_options(setup.get("choice") or []) - systems = [system_title(value, manifest) for flag, value in options - if flag == "--system" and value] - if systems: - shown = ", ".join(systems[:3]) - return shown + (f" and {len(systems) - 3} more" if len(systems) > 3 else "") - if any(flag == "--for-games" for flag, _value in options): - return "the games" - if any(flag in RECORD_NARROWING for flag, _value in options): - return "the options chosen" - return "every file" - - -def record_changes(setup: dict, entries: Iterable[dict]) -> tuple[int, int]: - """Of the files a choice keeps now, those the list changed since the - record and those it did not hold then: (updated, new).""" - recorded = {(str(item.get("root") or ""), item["dest"]): item["sha1"] - for item in setup.get("files") or []} - updated = new = 0 - for entry in entries: - sha1 = recorded.get((str(entry.get("root") or ""), str(entry.get("dest")))) - if sha1 is None: - new += 1 - elif entry.get("sha1") and sha1 != entry.get("sha1"): - updated += 1 - return updated, new - - -def record_file(entry: dict, origin: str, root: str = "") -> dict: - """One file a run wrote, as the record keeps it.""" - return {"dest": str(entry["dest"]), "root": root or str(entry.get("root") or ""), - "sha1": str(entry.get("sha1") or ""), "size": int(entry.get("size") or 0), - "from": origin} - - -def write_record( - folder: Path, plat: str, manifest: dict, choice: list[str], files: list[dict], -) -> tuple[Path | None, dict, str]: - """Write what this run placed in folder for plat, merged with what - earlier runs placed: (where, the record of plat, why it was not - written). A record that cannot be read is replaced.""" - folder = Path(os.path.abspath(folder)) - read = load_record(folder) - if read.newer: - # What a newer installer wrote is kept for it: rewritten here, the - # other setups' history would go. - if str(read.path) not in _RECORD_SAID: - _RECORD_SAID.add(str(read.path)) - print(f" {read.problem}: left as it is.") - return None, {"files": [], "written": ""}, f"{read.problem}: left as it is" - found = read.path - # A record that cannot be read is replaced, said when it was read. One - # with a setup that cannot be used keeps its others. - data = read.data if read.data is not None else {"setups": {}} - previous = data["setups"].get(plat) or {} - merged = {(str(item.get("root") or ""), item["dest"]): item - for item in previous.get("files") or []} - for item in files: - merged[(item["root"], item["dest"])] = item - setup = { - "written": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), - "list": {"version": manifest.get("version"), "generated": manifest.get("generated")}, - "choice": choice, - "files": [merged[key] for key in sorted(merged)], - } - data = {"schema": RECORD_SCHEMA, "installer": installer_id(), "folder": str(folder), - "setups": {**data["setups"], plat: setup}} - where, failure = _save_record(folder, data, found) - if where is None: - return None, setup, f"The install record could not be written ({failure})" - return where, setup, "" - - -def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | None, str]: - """Write a record's data where it was read, else where it goes: (where, - why nothing could be written).""" - text = json.dumps(data, separators=(",", ":"), sort_keys=True) + "\n" - places = record_paths(folder) - if found is not None and found in places: - # Rewritten where it was read: never a second record of one folder. - places = [found] + [place for place in places if place != found] - failure = "nothing could be written beside the folder" - for path in places: - scratch: Path | None = None - try: - path.parent.mkdir(exist_ok=True) - _check_holder(path.parent) - with tempfile.NamedTemporaryFile( - "w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.", - suffix=".part", delete=False) as handle: - scratch = Path(handle.name) - handle.write(text) - os.replace(scratch, path) - except OSError as exc: - failure = exc.strerror or str(exc) - if scratch is not None and os.path.lexists(scratch): - try: - scratch.unlink() - except OSError as left: - failure += f", and {scratch} stays ({left.strerror or left})" - continue - return path, "" - return None, failure - - -def record_menu_words(setup: dict | None) -> str: - """What line mode's menu says of a recorded choice it opens on.""" - if setup is None: - return "" - day = record_day(setup) - return f"Same choice as on {day}." if day else "Same choice as last time." - - -def choice_given(args: argparse.Namespace) -> bool: - """Whether the command line chose what to install, which a record then - never replaces: an option of the choice, or a file list of its own.""" - # A namespace built by a caller that predates an option lacks it. - return (getattr(args, "for_games", None) is not None or LOCAL.manifest is not None - or any(getattr(args, flag[2:].replace("-", "_"), None) - for flag in RECORD_CHOICE if flag != "--for-games")) - - -def say_record_problem(plat: str, folder: Path, path: Path | None, problem: str) -> None: - """A record that cannot be used, said once and ignored.""" - key = str(path) - if not problem or key in _RECORD_SAID: - return - _RECORD_SAID.add(key) - message = f"{problem}, so it is ignored." - print(f" {message}") - EVENTS.emit("record", platform=plat, folder=str(folder), path=key, status="unreadable", - choice=[], date="", files=0, message=message) - - -def by_record(args: argparse.Namespace) -> bool: - """Whether the run's choice came from the install record: nothing of - it was typed, so a part that cannot apply is left out, never refused.""" - return bool(getattr(args, "from_record", False)) - - -def drop_recorded(args: argparse.Namespace, plat: str, flag: str, why: str, - keep: list[str] | None = None) -> None: - """Leave out a recorded option that cannot apply, in one line: the run - goes on, and the record written after it no longer holds it. keep, for - an option of several names, is the names that still apply.""" - name = flag[2:].replace("-", "_") - chosen = _INVOCATION.chosen.get(plat, []) - if keep: - setattr(args, name, list(keep)) - _INVOCATION.chosen[plat] = [option for option in chosen if option[0] != flag] + [ - (flag, value) for value in keep] - else: - setattr(args, name, build_parser().get_default(name)) - _INVOCATION.chosen[plat] = [option for option in chosen if option[0] != flag] - print(f" Left out of the recorded choice: {flag} ({why}).") - - -def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | None: - """Take the choice recorded for plat in folder as the run's, as if its - options had been typed: the plan's first choice. Returns the record, - None where none is taken.""" - setup, path, problem = setup_record(plat, folder) - say_record_problem(plat, folder, path, problem) - if setup is None: - return None + payload = response.read(limit + 1) + except http.client.IncompleteRead as exc: + raise ConnectionError( + f"{label} cut after {len(exc.partial)} bytes" + ) from exc + if len(payload) > limit: + raise ValueError(f"{label} exceeds {limit} bytes") + if expected is not None and len(payload) < expected: + raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes") + if raw: + return payload try: - parsed = build_parser().parse_args(setup["choice"]) - except SystemExit: - say_record_problem(plat, folder, path, - f"The install record {path} names options this installer lacks") - return None - for flag in RECORD_CHOICE: - name = flag[2:].replace("-", "_") - setattr(args, name, getattr(parsed, name)) - if args.for_games is not None: - args.all_files = False - args.from_record = True - options = record_options(setup["choice"]) - if any(flag in RECORD_NARROWING for flag, _value in options): - # Said where it narrows the list: the whole list again is the run - # a person expects, and said nothing new. - _RECORD_TAKEN[plat] = setup - _INVOCATION.chosen[plat] = [option for option in options if option[0] != "--all-files"] - if isinstance(args.for_games, Path) and not _is_dir(args.for_games): - # The games folder recorded is gone: the card's own games are read. - _INVOCATION.chosen[plat] = [(flag, None if flag == "--for-games" else value) - for flag, value in _INVOCATION.chosen[plat]] - args.for_games = True - print(" Left out of the recorded choice: its games folder (no longer there).") - message = record_menu_words(setup) - EVENTS.emit("record", platform=plat, folder=str(folder), path=str(path), status="applied", - choice=list(setup["choice"]), date=setup["written"], - files=len(setup["files"]), message=message) - return setup + return json.loads(payload.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"invalid {label}: {exc}") from exc -def _is_link(info: os.stat_result) -> bool: - """Whether what lstat read is a link: a symbolic link, or on Windows a - junction or any other reparse point.""" - return stat.S_ISLNK(info.st_mode) or bool( - getattr(info, "st_file_attributes", 0) & _REPARSE_POINT) - - -def _tree(top: Path) -> list[tuple[Path, os.stat_result]]: - """Every entry below top with what lstat read of it, children before - their folder. A link (a junction too) is listed, never entered.""" - found: list[tuple[Path, os.stat_result]] = [] - try: - names = sorted(os.listdir(top)) - except OSError: - return found - for name in names: - path = top / name - try: - info = os.lstat(path) - except OSError: - continue - if stat.S_ISDIR(info.st_mode) and not _is_link(info): - found += _tree(path) - found.append((path, info)) - return found - - -def _is_backup_run(run: Path) -> bool: - """Whether run is a dated folder a run of the installer made: a real - folder holding the marker, inside a retrobios-backup holder that is no - link.""" - try: - info, holder = os.lstat(run), os.lstat(run.parent) - marker = os.lstat(run / BACKUP_MARKER) - except OSError: - return False - return (stat.S_ISDIR(info.st_mode) and stat.S_ISDIR(holder.st_mode) - and not _is_link(info) and not _is_link(holder) - and run.parent.name == BACKUP_DIR and stat.S_ISREG(marker.st_mode)) - - -def _backup_files(run: Path) -> list[Path]: - """The files a backup run folder holds, its marker and note aside. Links - inside it, junctions included, are never followed nor put back.""" - return sorted( - path for path, info in _tree(run) - if stat.S_ISREG(info.st_mode) and not _is_link(info) - and not (path.name.startswith(".") and path.name.endswith(".part")) - and not (path.parent == run and path.name in (BACKUP_MARKER, REMOVED_NOTE)) - ) - - -def _backup_note(run: Path) -> dict | None: - """What a removal wrote beside the files it moved into run: the setup, - its folder, its choice before and the record's entries. None for the - backup of files an install replaced, or a note that cannot be read.""" - try: - data = json.loads(_read_record_bytes(run / REMOVED_NOTE).decode("utf-8")) - except (OSError, UnicodeDecodeError, ValueError): - return None - if not isinstance(data, dict) or not isinstance(data.get("platform"), str) \ - or not isinstance(data.get("folder"), str): - return None - setup = {"written": "", "choice": data.get("choice"), "files": data.get("files")} - return data if _valid_setup(setup, Path(data["folder"])) else None - - -def _record_folder(run: Path, path: Path) -> tuple[Path, str] | None: - """The BIOS folder whose record may name a file put back at path, and - its dest there. The holder beside a folder keeps the folder's name as - the first level of each run, the one inside it none.""" - holder, root = run.parent, run.parent.parent - rel = PurePosixPath(*path.relative_to(root).parts) - if len(rel.parts) > 1 and (holder / f"{rel.parts[0]}{RECORD_SUFFIX}").is_file(): - return root / rel.parts[0], PurePosixPath(*rel.parts[1:]).as_posix() - if (holder / f"{root.name or 'folder'}{RECORD_SUFFIX}").is_file(): - return root, rel.as_posix() - return None - - -def _record_without(gone: set[str]) -> Callable[[dict | None], dict | None]: - """The change taking out a setup's entries at the folded dests of gone.""" - def change(setup: dict | None) -> dict | None: - return None if setup is None else { - **setup, "files": [item for item in setup["files"] - if str(item.get("root") or "") not in ("", "data") - or item["dest"].casefold() not in gone]} - return change - - -def _record_after_restore(run: Path, put_back: list[Path]) -> str: - """The record of the folder files went back into, made to say what is - there now: "" once written, else why not. A removal's backup gives its - files back to their setup, with the choice it had. Any other backup - holds the user's own files, which the record never names: its entries - at their places go.""" - note = _backup_note(run) - if note is not None: - folder = Path(note["folder"]) - back = [] - for item in note["files"]: - path = _below(folder, item["dest"])[0] - if path is not None and not _check_ours(path, item)[0]: - back.append(item) - if not back and put_back: - # The files went back, but not where the record's folder is: the - # folder moved or was renamed since the removal. - return f"it is for {folder}, which does not hold the files put back" - if not back: - return "" - return _update_record(folder, note["platform"], - lambda setup: _record_merge(setup, back, note["choice"])) - by_folder: dict[Path, set[str]] = {} - for path in put_back: - found = _record_folder(run, path) - if found is not None: - by_folder.setdefault(found[0], set()).add(found[1].casefold()) - problems = [_update_record(folder, plat, _record_without(gone)) - for folder, gone in by_folder.items() - for plat in sorted((load_record(folder).data or {}).get("setups") or {})] - return next((problem for problem in problems if problem), "") - - -def _recorded_copy(run: Path, dest: Path) -> bool: - """Whether the file at dest is the installer's own copy, as the record - of its folder names it: the collection gives it again, so a restore - replaces it without keeping it.""" - found = _record_folder(run, dest) - if found is None: - return False - try: - info = os.lstat(dest) - except OSError: - return False - if not stat.S_ISREG(info.st_mode) or _is_link(info): - return False - folder, rel = found - items = [item for setup in ((load_record(folder).data or {}).get("setups") or {}).values() - for item in setup.get("files") or [] - if str(item.get("root") or "") in ("", "data") - and item["dest"].casefold() == rel.casefold() and item["size"] == info.st_size] - if not items: - return False - try: - sha1 = _digest_file(dest, ("sha1",))["sha1"] - except OSError: - return False - return any(item["sha1"] == sha1 for item in items) - - -def _record_merge(setup: dict | None, files: list[dict], choice: list[str]) -> dict: - """A setup with files given back and the choice it had before a removal.""" - merged = {(str(item.get("root") or ""), item["dest"]): item - for item in (setup or {}).get("files") or []} - for item in files: - merged[(str(item.get("root") or ""), item["dest"])] = item - return {"list": {"version": None, "generated": None}, **(setup or {}), - "written": _record_now(), "choice": list(choice), - "files": [merged[key] for key in sorted(merged)]} - - -def _record_now() -> str: - return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _update_record(folder: Path, plat: str, - change: Callable[[dict | None], dict | None]) -> str: - """Rewrite the setup plat of folder's record as change makes it, None - taking it out: "" once written, else why not. A record that cannot be - read, or that a newer installer wrote, is left as it is.""" - folder = Path(os.path.abspath(folder)) - read = load_record(folder) - if read.newer or (read.data is None and read.path is not None): - return read.problem - data = read.data or {"setups": {}, "folder": str(folder)} - setups = dict(data["setups"]) - new = change(setups.get(plat)) - if new is None: - setups.pop(plat, None) - else: - setups[plat] = new - if not setups: - if read.path is None: - return "" - # Nothing of ours is left in the folder: the record goes with it. - try: - read.path.unlink() - except OSError as exc: - return exc.strerror or str(exc) - return "" - data = {"schema": RECORD_SCHEMA, "installer": installer_id(), - "folder": str(data.get("folder") or folder), "setups": setups} - where, failure = _save_record(folder, data, read.path) - return "" if where is not None else failure - - -def restore_kept(run: Path, dry_run: bool = False) -> int: - """Put every file of a backup run folder back where it was. - - run is a / folder a run wrote, its holder named - retrobios-backup. Each file goes to the same path below the holder's - parent. A file there with other contents is moved into a new dated - backup first, never lost. The install record of its folder is made to - say so. The backup is left in place. Returns the exit code: - 0 when every file went back, 1 when one failed, 2 when the folder is no - backup. - """ - run = Path(os.path.abspath(os.path.expanduser(str(run)))) - if not _is_backup_run(run): - print(f"Error: {run} is not a folder the installer kept files in.", file=sys.stderr) - print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as " - "--backups lists them.", file=sys.stderr) - return 2 - root = run.parent.parent - files = _backup_files(run) - if not files: - print(f"{run} holds no file. Nothing to put back.") - return 0 - restored = size = failed = 0 - put_back: list[Path] = [] - KEPT.reset() - for src in files: - rel = PurePosixPath(*src.relative_to(run).parts) - dest = root / Path(*rel.parts) - length = src.stat().st_size - if dry_run: - print(f" would put back {dest}") - restored += 1 - size += length - continue - try: - sha1 = _digest_file(src, ("sha1",))["sha1"] - dest.parent.mkdir(parents=True, exist_ok=True) - # A file at the place that is not the backup's copy (a newer one, - # one the user put there) is moved aside first, into a new dated - # backup, as an install keeps what it replaces. Its first level - # is the folder the backup's holder sits in. - holder = (root / rel.parts[0], PurePosixPath(*rel.parts[1:])) \ - if len(rel.parts) > 1 else (root, rel) - if not _recorded_copy(run, dest): - KEPT.keep(*holder, dest, {"sha1": sha1}) - _clear_read_only(dest) - _replace_with_copy(src, dest) - except (OSError, _NotKept) as exc: - reason = getattr(exc, "strerror", None) or str(exc) - print(f" failed: {dest} ({reason})", file=sys.stderr) - EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=False, - reason=reason) - failed += 1 - continue - EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=True, - reason="") - put_back.append(dest) - restored += 1 - size += length - if dry_run: - print(f"\nWould put back {_plural(restored, 'file')} ({format_size(size)}) " - f"under {root}. Nothing was written.") - return 0 - problem = _record_after_restore(run, put_back) - print(f"\nPut back {_plural(restored, 'file')} ({format_size(size)}) under {root}.") - for item in KEPT.summary(): - # The files that sat at those places, never lost. - print(f"Kept {_plural(item['files'], 'file')} that were in their place " - f"({format_size(item['bytes'])}) in {item['folder']}") - if failed: - print(f"{_plural(failed, 'file')} could not be put back.", file=sys.stderr) - if problem: - print(f"The install record could not be updated ({problem}).", file=sys.stderr) - print(f"The copies are still in {run}. To free the space: {_INVOCATION.launcher()} " - f"--delete-backup {_INVOCATION.word(str(run))}") - return 1 if failed or problem else 0 - - -# Written into a backup that a removal made: the setup, its folder, its -# choice before and the record's entries, so --restore gives them back. -REMOVED_NOTE = ".retrobios-removed.json" - - -def _below(folder: Path, dest: str) -> tuple[Path | None, str]: - """The file a record's dest names below folder, reached through no link: - (path, "") or (None, why it is left). A dest that climbs or is absolute - is outside, whatever a record says.""" - try: - rel = _safe_relative_path(dest, "dest") - except ValueError: - return None, "outside" - path = folder - for part in rel.parts[:-1]: - path = path / part - try: - info = os.lstat(path) - except FileNotFoundError: - return None, "gone" - except OSError: - return None, "unreadable" - if _is_link(info): - return None, "link" - if not stat.S_ISDIR(info.st_mode): - return None, "not_a_file" - return path / rel.parts[-1], "" - - -def _check_ours(path: Path, item: dict) -> tuple[str, os.stat_result | None]: - """Why the file at path is not the one the record names, "" when it - is, and what lstat read of it.""" - try: - info = os.lstat(path) - except FileNotFoundError: - return "gone", None - except OSError: - return "unreadable", None - if _is_link(info): - return "link", info - if not stat.S_ISREG(info.st_mode): - return "not_a_file", info - if not re.fullmatch(r"[0-9a-f]{40}", str(item["sha1"])) or info.st_size != item["size"]: - return "changed", info - try: - same = _digest_file(path, ("sha1",))["sha1"] == item["sha1"] - except OSError: - return "unreadable", info - return ("" if same else "changed"), info - - -def _clear_read_only(dest: Path) -> None: - """Let the verified copy replace a read-only file the user already has. - - Windows refuses to replace a file carrying the read-only attribute - (WinError 5) even in a writable folder. The file is about to be replaced - by the copy the manifest names, so its attribute is cleared first. - Elsewhere a rename only needs the folder to be writable. - """ - if os.name != "nt": - return - try: - if dest.is_file() and not os.access(dest, os.W_OK): - os.chmod(dest, stat.S_IREAD | stat.S_IWRITE) - except OSError: - pass # the replace that follows reports the refusal with its reason - - -def _replace_with_copy(src: Path, dest: Path) -> None: - """Put a copy of src at dest's name without following what is there.""" - fd, scratch = tempfile.mkstemp(dir=dest.parent, prefix=f".{dest.name}.", suffix=".part") - os.close(fd) - try: - shutil.copy2(src, scratch) - os.replace(scratch, dest) - except OSError: - if os.path.lexists(scratch): - os.unlink(scratch) - raise - - -def system_title(system: str, manifest: dict | None) -> str: - """A system as the screen's Choose systems names it (_tui_system_label).""" - names = ((manifest or {}).get("system_names") or {}).get(system) - titles = (manifest or {}).get("system_titles") - return _tui_system_label({"system": system, "name": ", ".join(names or [system])}, - titles if isinstance(titles, dict) else {}) - - -# FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows. -# Before Python 3.12 lstat does not report a junction as a link, and -# os.walk(followlinks=False) descends into it. -_REPARSE_POINT = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) - - -def _tui_system_label(row: dict, titles: dict | None = None) -> str: - """The name a person reads: the file list's title when it has one, the - platform's own name when it is one (Sony - PlayStation), the id with the - platform's short name otherwise (psx).""" - title = (titles or {}).get(row["system"]) - if isinstance(title, str) and title.strip(): - return title.strip() - if row["system"] == OTHER_SYSTEMS: - return OTHER_TITLE - name = row.get("name") or row["system"] - if name == row["system"]: - return name - if " " in name or any(char.isupper() for char in name): - return name - return f"{row['system']} ({name})" - - -# What the "other" row of the systems holds, in words (OTHER_SYSTEMS). -OTHER_TITLE = "Other systems and game engines" - - -# --- installer/pack_source.py ------------------------------------------------ - -_SHARING_VIOLATIONS = (32, 33) - -# A write refused by the file system: retrying cannot change it, and the -# summary names the two ways out. -NOT_WRITABLE = "folder not writable" - - -def _write_refused(exc: OSError) -> bool: - # A sharing violation is a file another process holds open, which a - # later attempt can find released: no refusal of the folder. - if getattr(exc, "winerror", None) in _SHARING_VIOLATIONS: - return False - return isinstance(exc, PermissionError) or exc.errno == errno.EROFS - - -# A file already at the destination, marked read-only, whose content differs, -# and whose attribute could not be cleared: replacing it is refused while its -# folder stays writable. -READ_ONLY = "file in place is read-only" -# A file in place whose content differs, which could not be moved aside: it -# is left as it is rather than lost. -NOT_KEPT = "file in place could not be kept aside" - - -def _read_only_file(dest: Path) -> bool: - return _is_file(dest) and not os.access(dest, os.W_OK) and _folder_writable(dest.parent) - - -def _folder_writable(path: Path) -> bool: - """Whether a file can be created under path, read from its nearest - existing folder: a BIOS folder not created yet is as writable as the - folder it would go in.""" - probe = path - while not _exists(probe) and probe.parent != probe: - probe = probe.parent - return os.access(probe, os.W_OK) - - -# A pack too large for one release file is published as ZIP parts -# (scripts/split_pack.py), each holding at its root a marker that names the -# pack, the part and every part with its size. Extracted with the files, -# the markers say which part a folder lacks. -_PART_FILE = re.compile(r"^(?P.+_BIOS_Pack)\.part(?P\d+)of(?P\d+)\.zip$") - -MAX_PARTS = 999 - -# A system id as the file lists write them (sony-playstation, other). -_SYSTEM_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}") - - -class PackSource: - """A pack already downloaded, whole or in parts, read in place of the network. - - Every file it gives is checked against the hashes the file list records, - as a download is. - """ - - def __init__(self, paths: list[Path]) -> None: - self.files = self._resolve(paths) - first = _PART_FILE.match(self.files[0].name) - self.name = f"{first['stem']}.zip" if first else self.files[0].name - self.archives: list[zipfile.ZipFile] = [] - self.members: dict[str, tuple[zipfile.ZipFile, zipfile.ZipInfo]] = {} - # The system titles and names the pack's list records, if any. - self.names: dict[str, dict] = {} - # What its platform's install list narrows by (systems, cores, - # regions), None for a pack that does not say: the remedy for an - # option the pack cannot apply names that list only when it can. - self.list_records: frozenset | None = None - # The version of the platform's list the pack was built from, "" for - # a pack that does not record it. - self.list_version = "" - # The platform's install list and its cores per board, which a pack - # built since carries: with them a pack alone narrows to a board as - # the network list does. None for a pack that carries none. - self.install_list: dict | None = None - self.targets: dict | None = None - try: - for path in self.files: - archive = zipfile.ZipFile(path) - self.archives.append(archive) - for info in archive.infolist(): - if not info.is_dir(): - self.members.setdefault(info.filename, (archive, info)) - except (OSError, zipfile.BadZipFile) as exc: - self.close() - raise ValueError(f"{path.name} cannot be read as a ZIP ({exc}). A download " - "cut short gives this: download it again.") from exc - try: - self.listed = self._pack_list() - except ValueError: - # A ZIP that is no pack: its archives closed, not left open. - self.close() - raise - self.by_sha1 = {f["sha1"]: f["path"] for f in self.listed} - - @staticmethod - def _resolve(paths: list[Path]) -> list[Path]: - """The archives of one pack: a whole ZIP, or every one of its parts.""" - given: list[Path] = [] - for path in paths: - if path.is_dir(): - given += sorted(p for p in path.iterdir() - if p.is_file() and p.name.endswith(".zip") - and "_BIOS_Pack" in p.name) - elif path.is_file(): - given.append(path) - else: - # "X does not exist" named neither the option nor the packs - # beside it, where a typo in the name is the usual cause. - near = sorted(p.name for p in path.parent.glob("*_BIOS_Pack*.zip") - if p.is_file()) if path.parent.is_dir() else [] - beside = (f" The packs in {path.parent}: {', '.join(near[:3])}" - + (f" and {len(near) - 3} more" if len(near) > 3 else "") + "." - if near else "") - raise ValueError(f"{path} does not exist: --from-pack names a pack ZIP, " - f"its parts or the folder holding them.{beside}") - if not given: - raise ValueError(f"no pack ZIP in {', '.join(map(str, paths))}") - packs: dict[str, list[Path]] = {} - for path in given: - part = _PART_FILE.match(path.name) - packs.setdefault(f"{part['stem']}.zip" if part else path.name, []).append(path) - if len(packs) > 1: - raise ValueError(f"these are several packs ({', '.join(sorted(packs))}): " - "name the one to install from") - name, chosen = next(iter(packs.items())) - whole = [p for p in chosen if not _PART_FILE.match(p.name)] - if whole: - return whole[:1] - counts = [int(part["count"]) for part in (_PART_FILE.match(p.name) for p in chosen) - if part is not None] - count = counts[0] - if count > MAX_PARTS or any(other != count for other in counts): - raise ValueError(f"the parts of {name} disagree on how many there are") - stem = name[: -len(".zip")] - folders = list(dict.fromkeys(p.parent for p in chosen)) - found: list[Path] = [] - missing: list[str] = [] - for number in range(1, count + 1): - part_name = f"{stem}.part{number}of{count}.zip" - place = next((folder / part_name for folder in folders - if (folder / part_name).is_file()), None) - if place is None: - missing.append(part_name) - else: - found.append(place) - if missing: - where = ", ".join(map(str, folders)) - raise ValueError(f"{name} comes in {count} parts and {len(missing)} " - f"{'is' if len(missing) == 1 else 'are'} not in {where}: " - f"{', '.join(missing)}") - return found - - def _pack_list(self) -> list[dict]: - """The file list the pack carries, every file with its SHA-1 and size.""" - held = self.members.get("manifest.json") - if held is None: - raise ValueError(f"{self.name} holds no manifest.json. Name the file list " - "with --manifest.") - archive, info = held - if info.file_size > MAX_MANIFEST_BYTES: - raise ValueError(f"the manifest.json of {self.name} exceeds " - f"{MAX_MANIFEST_BYTES} bytes") - try: - data = json.loads(archive.read(info).decode("utf-8")) - except (OSError, zipfile.BadZipFile, UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ValueError(f"the manifest.json of {self.name} cannot be read: {exc}") from exc - files = data.get("files") if isinstance(data, dict) else None - if not isinstance(files, list): - raise ValueError(f"the manifest.json of {self.name} lists no files") - # What a pack built since records of its systems (generate_pack.py - # pack_systems): --system and Choose systems then work with the pack - # alone. An older pack records none, and is read as before. - # A pack is a file anyone can hand over: an id or a name holding a - # control character would reach the terminal as an escape, and is - # dropped. - records = data.get("list_records") - if isinstance(records, list) and all(isinstance(axis, str) for axis in records): - self.list_records = frozenset(records) & {"systems", "cores", "regions"} - version = data.get("list_version") - if isinstance(version, str) and _VERSION_TEXT.fullmatch(version): - self.list_version = version - if isinstance(data.get("install_list"), dict): - self.install_list = data["install_list"] - if data.get("targets") is not None: - try: - self.targets = _validate_targets(data["targets"]) - except ValueError: - # Read as a pack that carries none: --target is then refused - # with the reason, never applied from a broken list. - self.targets = None - for key in ("system_titles", "system_names"): - held = data.get(key) - if isinstance(held, dict): - self.names[key] = { - system: value for system, value in held.items() - if _SYSTEM_ID.fullmatch(str(system)) and ( - isinstance(value, str) and not _CONTROLS.search(value) - or isinstance(value, list) and all( - isinstance(name, str) and not _CONTROLS.search(name) - for name in value))} - listed = [] - for item in files: - if ( - isinstance(item, dict) - and isinstance(item.get("path"), str) - and isinstance(item.get("sha1"), str) - and _SHA1_RE.fullmatch(item["sha1"].lower()) - and isinstance(item.get("size"), int) - ): - entry = {"path": item["path"], "sha1": item["sha1"].lower(), - "size": item["size"]} - systems = item.get("systems") - if isinstance(systems, list) and all( - isinstance(name, str) and _SYSTEM_ID.fullmatch(name) - for name in systems): - entry["systems"] = list(systems) - listed.append(entry) - return listed - - def platforms(self) -> list[str]: - """The platforms the pack's name spells, several for a grouped pack.""" - spelled = pack_name_platforms(self.name) - # A pack made by --pack says its platform inside, which a name of - # the user's, or a file renamed, does not change. - named = (self.install_list or {}).get("platform") - if named in AVAILABLE_PLATFORMS and named not in spelled: - return [named] - return spelled - - def manifest(self, plat: str) -> dict: - """A file list for plat: the install list the pack carries, else one - built from the pack's own, the same files at the same places, as - extracting the pack would leave them, with the systems it records.""" - if self.install_list is not None and self.install_list.get("platform") == plat: - return self.install_list - return { - "manifest_version": 2, - "platform": plat, - **({"version": self.list_version} if self.list_version else {}), - **{key: value for key, value in self.names.items() if value}, - "files": [ - {"dest": f["path"], "sha1": f["sha1"], "size": f["size"], - "repo_path": f"bios/{f['path']}", - **({"systems": f["systems"]} if "systems" in f else {})} - for f in self.listed - ], - } - - def find(self, entry: dict) -> tuple[zipfile.ZipFile, zipfile.ZipInfo] | None: - """The member holding an entry's bytes: by its SHA-1 in the pack's list, - else at its destination. The size has to agree either way.""" - sha1 = str(entry.get("sha1", "")).lower() - for name in (self.by_sha1.get(sha1), entry.get("dest")): - held = self.members.get(name) if isinstance(name, str) else None - if held is not None and held[1].file_size == entry.get("size"): - return held - return None - - def tree(self, prefix: str) -> Iterator[tuple[str, int, Callable[[], IO[bytes]]]]: - """(path in the tree, size, opener) of every member below prefix.""" - lead = f"{prefix.rstrip('/')}/" if prefix else "" - for name, (archive, info) in self.members.items(): - if name.startswith(lead): - yield name[len(lead):], info.file_size, functools.partial(archive.open, info) - - def close(self) -> None: - for archive in self.archives: - archive.close() - self.archives = [] - - -NOT_IN_PACK = "not in the pack" - - -def pack_name_platforms(name: str) -> list[str]: - """The platforms a pack's name spells, as PackSource reads them.""" - if not name.endswith(PACK_NAME_END): - return [] - stem = "_" + name[: -len(PACK_NAME_END)] + "_" - return [plat for plat in AVAILABLE_PLATFORMS - if f"_{PLATFORM_NAMES[plat].replace(' ', '_')}_" in stem] +NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a " + "proxy, then run the same command again.\n" + f" More help: {TROUBLESHOOTING_PAGE}") def read_local_manifest(path: Path, plat: str) -> dict: @@ -8902,1436 +7369,6 @@ def read_local_manifest(path: Path, plat: str) -> dict: sys.exit(1) -def _extract_from_pack( - f: dict, bios_path: Path, dest: Path, progress: Progress | None, -) -> tuple[str, bool, str]: - """Copy one file out of the pack, checked like a download.""" - pack = LOCAL.pack - held = pack.find(f) if pack is not None else None - if held is None: - return f["dest"], False, NOT_IN_PACK - archive, info = held - return _write_verified(f, bios_path, dest, lambda: archive.open(info), progress, - "the pack", named=f"{info.filename} inside {archive.filename}") - - -class _SourceUnreadable(Exception): - """The bytes to write could not be read: the source's fault, never the - folder's, so it falls back like any copy that failed.""" - - -def unreadable_words(exc: BaseException) -> str: - """Why a file or a ZIP member could not be read, in words.""" - if isinstance(exc, RuntimeError) and "encrypted" in str(exc): - return "it is encrypted, a password is needed" - if isinstance(exc, NotImplementedError): - return "it is packed with a compression method this installer cannot read" - if isinstance(exc, (zipfile.BadZipFile, zlib.error, EOFError)): - return "it is damaged" - if isinstance(exc, OSError) and exc.strerror: - return exc.strerror - return str(exc) or type(exc).__name__ - - -def _place_verified(f: dict, bios_path: Path, dest: Path, tmp_path: Path, size: int, - expected: dict[str, str], held_in: str) -> None: - """Put the written file at dest once its size and hashes are the list's.""" - if size != f["size"]: - raise ValueError(f"{held_in} holds {size} bytes, the list records {f['size']}") - actual = _digest_file(tmp_path, tuple(expected)) - for name, label in (("sha256", "SHA-256"), ("sha1", "SHA-1")): - if name in expected and actual[name] != expected[name]: - raise ValueError(f"{label} mismatch in {held_in}") - os.chmod(tmp_path, (0o777 if f.get("executable") else 0o666) & ~_UMASK) - _clear_read_only(dest) - KEPT.keep(*_kept_slot(*_entry_place(bios_path, f)), dest, expected, tmp_path) - os.replace(tmp_path, dest) - - -def _write_verified( - f: dict, bios_path: Path, dest: Path, - source: Callable[[], ContextManager[IO[bytes]]], progress: Progress | None, - held_in: str, local: bool = False, named: str = "", -) -> tuple[str, bool, str]: - """Write the bytes source opens at dest once they match the list's size - and hashes, the file in place kept aside first when it differs. - - The source is opened before the temporary file, and its read errors - are told apart from the write errors: a copy that could not be read - was reported as a folder not writable. named is the source in the - reason then, held_in when empty.""" - expected = {name: f[name].lower() for name in ("sha256", "sha1") if f.get(name)} - tmp_path: Path | None = None - counted = 0 - - def unreadable(exc: BaseException) -> _SourceUnreadable: - return _SourceUnreadable(f"{named or held_in} could not be read: " - f"{unreadable_words(exc)}") - - try: - with contextlib.ExitStack() as stack: - try: - src = stack.enter_context(source()) - except _MEMBER_ERRORS as exc: - raise unreadable(exc) from exc - out = stack.enter_context(tempfile.NamedTemporaryFile( - mode="wb", dir=dest.parent, prefix=f".{dest.name}.", suffix=".part", - delete=False, - )) - tmp_path = Path(out.name) - size = 0 - while True: - if _stop.is_set(): - raise _Interrupted() - try: - chunk = src.read(min(1024 * 1024, f["size"] + 1 - size)) - except _MEMBER_ERRORS as exc: - raise unreadable(exc) from exc - if not chunk: - break - size += len(chunk) - if size > f["size"]: - raise ValueError(f"{held_in} holds more bytes than the list records") - out.write(chunk) - if progress is not None: - progress.add(len(chunk), resumed=local, network=False) - counted += len(chunk) - _place_verified(f, bios_path, dest, tmp_path, size, expected, held_in) - tmp_path = None - return f["dest"], True, "" - except _Interrupted: - return f["dest"], False, "stopped" - except _NotKept as exc: - return f["dest"], False, f"{NOT_KEPT} ({exc})" - except (_SourceUnreadable, ValueError, *_MEMBER_ERRORS) as exc: - if progress is not None and counted: - progress.add(-counted, resumed=local, network=False) - if isinstance(exc, OSError) and _write_refused(exc): - return f["dest"], False, READ_ONLY if _read_only_file(dest) else NOT_WRITABLE - return f["dest"], False, str(exc) - finally: - if tmp_path is not None and tmp_path.exists(): - tmp_path.unlink() - - -# Errors a member of someone's ZIP can raise on reading: damaged, encrypted -# (RuntimeError), or packed with a method zipfile lacks. -_MEMBER_ERRORS = (OSError, EOFError, RuntimeError, NotImplementedError, - zipfile.BadZipFile, zlib.error) - - -# --- installer/from_folders.py ----------------------------------------------- - -FOLDER_IN_PLACE = "a folder sits where this file goes: move it away, then run again" - - -@contextlib.contextmanager -def _open_copy(copy: LocalCopy) -> Iterator[IO[bytes]]: - """The bytes of a copy found on this machine, opened for reading only.""" - if not copy.member: - with open(copy.path, "rb") as handle: - yield handle - return - with copy.index.open_member(copy.path, copy.member) as handle: - yield handle - - -def _copy_local( - f: dict, bios_path: Path, dest: Path, copy: LocalCopy, progress: Progress | None, -) -> tuple[str, bool, str]: - """Copy one file found on this machine to its place, checked like a - download. Its bytes count as already here, not in the download speed.""" - return _write_verified(f, bios_path, dest, lambda: _open_copy(copy), progress, - f"the copy in {shown_path(copy.index.label)}", local=True, - named=copy.named()) - - -# Files --check reads to tell why a file is refused: past these, the folder -# is not one a person filled by hand, and walking it costs more than it tells. -MAX_SCANNED_FILES = 200_000 -_ARCHIVE_SUFFIXES = (".zip", ".7z", ".rar") -# Cores named on the line that says who opens a file, before "and N more". -SHOWN_CORES = 4 - - -# Folders a system writes on a drive for itself. No BIOS file a person -# copied is in them, and a Mac's Spotlight index alone holds thousands. -SYSTEM_FOLDERS = frozenset(name.casefold() for name in ( - ".Spotlight-V100", ".Trashes", ".fseventsd", ".TemporaryItems", - ".DocumentRevisions-V100", "System Volume Information", "$RECYCLE.BIN", -)) -# A Mac copying to a FAT or exFAT card writes ._name beside every file: its -# Finder data, 4 KB, never the file. -APPLE_DOUBLE = "._" -# Folders the kernel makes up on the fly: endless, and never a copy. -PSEUDO_FOLDERS = frozenset() if os.name == "nt" else frozenset(("/proc", "/sys", "/dev")) - - -def shown_lines(lines: list[str]) -> list[str]: - """Lines for the terminal, a blank line opening one kept as it is: the - paths in them come from folders anyone may have filled.""" - return [("\n" + screen_text(line[1:])) if line.startswith("\n") else screen_text(line) - for line in lines] - - -class LocalCopy: - """A file found on this machine with the contents an entry wants.""" - - def __init__(self, index: FolderIndex, path: Path, member: str = "", - misplaced: bool = False) -> None: - self.index = index - self.path = path - # The member holding the bytes when path is a ZIP, else "". - self.member = member - # In the BIOS folder at a place no entry of the list names: a mistake - # the copy fixes. A copy from another entry's place is no mistake. - self.misplaced = misplaced - - def where(self) -> str: - """The copy as the folder it was found in names it.""" - rel = self.index.relative(self.path) - return screen_text(f"{rel}, inside as {self.member}" if self.member else rel) - - def named(self) -> str: - """The copy by its full path, the member first when it is one.""" - return screen_text(f"{self.member} inside {self.path}" if self.member - else str(self.path)) - - -# The archives a FolderIndex keeps open at once. -OPEN_ARCHIVES = 16 - - -class FolderIndex: - """The files under a folder, by name and by size, hashed on demand. - - The folder is only read. A link is followed only where it leads to a - file inside the folder, so an old card holding a link to the home - folder is not walked through it. A ZIP named as the root is read as a - folder holding that one archive. - """ - - def __init__(self, root: Path, label: str = "") -> None: - self.label = label or str(root) - self.root = root = root.resolve() - self.by_name: dict[str, list[Path]] = {} - self.by_size: dict[int, list[Path]] = {} - self.size: dict[Path, int] = {} - self.archives: list[Path] = [] - # Name a ._ file stands beside (casefolded) -> the ._ files. - self.apple_double: dict[str, list[Path]] = {} - LOCAL.indexes.add(self) - # The list's destinations, casefolded (an archive among them is not - # unpacked for its members) and as the list writes them. - self.sealed: set[str] = set() - self.listed: set[str] = set() - self.truncated = False - self.copied = 0 - self.fixed = 0 - self._lock = threading.Lock() - self._sha1: dict[Path, str] = {} - self._digests: dict[tuple[Path, str, str], str] = {} - self._members: dict[Path, list[str]] = {} - self._member_sizes: dict[int, list[tuple[Path, str]]] | None = None - # (size, casefolded name) -> the files and the ZIP members, built - # the first time a copy is looked for. - self._loose_named: dict[tuple[int, str], list[Path]] | None = None - self._member_named: dict[int, dict[str, list[tuple[Path, str]]]] = {} - self._scans: dict[tuple[str, int, str], _HashScan] = {} - self._member_size: dict[tuple[Path, str], int] = {} - # The archives read so far, open, the last read at the end: a ZIP - # was opened again, its directory parsed again, for each member. - self._zips: dict[Path, zipfile.ZipFile] = {} - self._zip_lock = threading.Lock() - # The places this run writes, resolved. An archive among them is - # never kept open: Windows refuses to move aside or replace a file - # a process holds, and a --from folder can hold the BIOS folder. - self._written: set[Path] = set() - # (path, member or "") -> (its size or None when unknown, why) of each - # file, member or folder below root that could not be read. - self.unreadable: dict[tuple[Path, str], tuple[int | None, str]] = {} - # Folders below root on another drive, not entered. - self.other_drives: list[Path] = [] - self.files = 0 - self._walk(root) - - def _walk(self, root: Path) -> None: - """Index the files under root, a ZIP named as root as its one archive.""" - if root.is_file(): - if root.name.casefold().endswith(".zip"): - self.archives.append(root) - self.files = 1 - return - seen = 0 - try: - device = os.stat(root).st_dev - except OSError as exc: - self._unread(root, "", None, exc) - return - - def unlisted(exc: OSError) -> None: - self._unread(Path(exc.filename or root), "", None, exc) - - for folder, dirs, names in os.walk(root, onerror=unlisted): - dirs[:] = sorted(d for d in dirs - if d != BACKUP_DIR and d.casefold() not in SYSTEM_FOLDERS - and self._enters(Path(folder) / d, device)) - for name in sorted(names): - path = Path(folder) / name - if name.startswith(APPLE_DOUBLE): - self.apple_double.setdefault(name[2:].casefold(), []).append(path) - continue - if name.startswith(".") and name.endswith(".part"): - continue # a download of this installer, not finished - try: - if path.is_symlink() and not _inside(path, root): - continue - if not path.is_file(): - continue - size = path.stat().st_size - except OSError as exc: - self._unread(path, "", None, exc) - continue - self.by_name.setdefault(name.casefold(), []).append(path) - self.by_size.setdefault(size, []).append(path) - self.size[path] = size - if name.casefold().endswith(_ARCHIVE_SUFFIXES): - self.archives.append(path) - seen += 1 - self.files = seen - if seen >= MAX_SCANNED_FILES: - self.truncated = True - return - - def _enters(self, path: Path, device: int) -> bool: - """Whether the walk goes into a folder: not a pseudo file system, a - Windows junction or reparse point (a link the walk cannot tell from - a folder, which led out of the folder named), nor another drive - mounted below the root, which is named instead.""" - if str(path) in PSEUDO_FOLDERS: - return False - try: - held = os.lstat(path) - except OSError as exc: - self._unread(path, "", None, exc) - return False - if getattr(held, "st_file_attributes", 0) & _REPARSE_POINT: - return False - if held.st_dev != device: - self.other_drives.append(path) - return False - return True - - def _archive(self, path: Path) -> zipfile.ZipFile: - """The archive at path, opened once. Called with _zip_lock held. - - A few stay open, the least recently read closed first: a card of - MAME sets would otherwise hold a descriptor per archive. Closing - one leaves a member being read open until it is closed itself. - An archive this run writes is never read this way (see writes). - """ - archive = self._zips.pop(path, None) - if archive is None: - archive = zipfile.ZipFile(path) - while len(self._zips) >= OPEN_ARCHIVES: - self._zips.pop(next(iter(self._zips))).close() - self._zips[path] = archive - return archive - - def writes(self, paths: Collection[Path]) -> None: - """Note the places this run writes, resolved, and close the archives - among them: the next read of one opens it and closes it at once.""" - with self._zip_lock: - self._written.update(paths) - for held in [held for held in self._zips if self._is_written(held)]: - self._zips.pop(held).close() - - def _is_written(self, path: Path) -> bool: - return bool(self._written) and ( - path in self._written or Path(os.path.realpath(path)) in self._written) - - def infolist(self, path: Path) -> list[zipfile.ZipInfo]: - with self._zip_lock: - if self._is_written(path): - with zipfile.ZipFile(path) as archive: - return archive.infolist() - return self._archive(path).infolist() - - @contextlib.contextmanager - def open_member(self, path: Path, member: str) -> Iterator[IO[bytes]]: - """A member of an archive under the folder, read from any thread.""" - with self._zip_lock: - if self._is_written(path): - archive = zipfile.ZipFile(path) - try: - handle = archive.open(member) - finally: - # The member holds the file until it is closed itself. - archive.close() - else: - handle = self._archive(path).open(member) - try: - yield handle - finally: - # The archive counts its open members: the count moves under - # the lock, as when the member was opened. - with self._zip_lock: - handle.close() - - def open_archives(self) -> int: - with self._zip_lock: - return len(self._zips) - - def close(self) -> None: - """Close the archives the index holds open.""" - with self._zip_lock: - for archive in self._zips.values(): - archive.close() - self._zips.clear() - - def seed(self, path: Path, sha1: str) -> None: - """A SHA-1 already known, so the file is not read again.""" - self._sha1[path] = sha1 - - def _unread(self, path: Path, member: str, size: int | None, exc: BaseException) -> None: - """Note a file, a member or a folder that could not be read: a copy - the run needs may be the one, and it is named instead of dropped.""" - self.unreadable.setdefault((path, member), (size, unreadable_words(exc))) - - def sha1(self, path: Path) -> str: - if path not in self._sha1: - try: - self._sha1[path] = _sha1_file(path) - except OSError as exc: - self._unread(path, "", self.size.get(path), exc) - self._sha1[path] = "" - return self._sha1[path] - - def digest(self, path: Path, algorithm: str, member: str = "") -> str: - """The file's (or the member's) digest, read once, "" when unreadable.""" - if algorithm == "sha1" and not member: - return self.sha1(path) - key = (path, member, algorithm) - if key not in self._digests: - try: - if member: - with self.open_member(path, member) as handle: - value = _digest_handle(handle, (algorithm,))[algorithm] - else: - value = _digest_file(path, (algorithm,))[algorithm] - except _MEMBER_ERRORS as exc: - size = self._member_size.get((path, member)) if member else self.size.get(path) - self._unread(path, member, size, exc) - value = "" - self._digests[key] = value - return self._digests[key] - - def unreadable_for(self, sizes: Collection[int]) -> list[tuple[Path, str, str]]: - """(path, member, why) of what could not be read and may hold a file - of one of sizes: its size is one of them, or unknown (a folder, an - archive whose list of members could not be read).""" - return sorted((path, member, why) - for (path, member), (size, why) in self.unreadable.items() - if size is None or size in sizes) - - def _scan(self, kind: str, size: int, algorithm: str) -> _HashScan: - """The files (kind "loose") or ZIP members ("member") of one size, - hashed in the order the folder was read, each read once.""" - key = (kind, size, algorithm) - if key not in self._scans: - if kind == "loose": - self._scans[key] = _HashScan( - self.by_size.get(size, []), lambda path: self.digest(path, algorithm)) - else: - self._scans[key] = _HashScan( - self._members_of_size(size), - lambda item: self.digest(item[0], algorithm, item[1])) - return self._scans[key] - - def first_holding(self, sizes: set[int], sha1s: set[str]) -> Path | None: - """The first file whose contents are one of sha1s, the smallest size - first, read only when the size fits.""" - for size in sorted(sizes): - path = self._scan("loose", size, "sha1").first(sha1s) - if path is not None: - return path - return None - - def zip_members(self, path: Path) -> list[str]: - if path not in self._members: - try: - # Read once and closed: the archive may be a file of the - # list, which Windows will not replace while it is open. - with zipfile.ZipFile(path) as archive: - self._members[path] = [n.rsplit("/", 1)[-1].casefold() - for n in archive.namelist()] - except (OSError, zipfile.BadZipFile): - self._members[path] = [] - return self._members[path] - - def _members_of_size(self, size: int) -> list[tuple[Path, str]]: - """(archive, member) of every ZIP member of that size, the - archives' directories read once, the first time one is asked.""" - if self._member_sizes is None: - self._member_sizes = {} - for path in self.archives: - if (not path.name.casefold().endswith(".zip") - or self.relative(path).casefold() in self.sealed): - continue - try: - infos = self.infolist(path) - except OSError as exc: - # A ZIP that will not open may hold anything: named. A - # damaged one is a download cut short, not a copy. - self._unread(path, "", None, exc) - continue - except zipfile.BadZipFile: - continue - for info in infos: - if not info.is_dir(): - self._member_sizes.setdefault(info.file_size, []).append( - (path, info.filename)) - self._member_size[(path, info.filename)] = info.file_size - return self._member_sizes.get(size, []) - - def find(self, entry: dict, skip: Collection[Path] = ()) -> LocalCopy | None: - """A copy of the entry's own contents: its size first, then its hash, - loose files before ZIP members, a file of the same name first.""" - size = entry.get("size") - if not isinstance(size, int) or isinstance(size, bool): - return None - algorithm = "sha1" if entry.get("sha1") else "sha256" - wanted = str(entry.get(algorithm) or "").lower() - if not wanted: - return None - name = str(entry.get("dest", "")).rsplit("/", 1)[-1].casefold() - if self._loose_named is None: - self._loose_named = {} - for path, held in self.size.items(): - self._loose_named.setdefault((held, path.name.casefold()), []).append(path) - for path in self._loose_named.get((size, name), []): - if not _being_written(path, skip) and self.digest(path, algorithm) == wanted: - return LocalCopy(self, path) - path = self._scan("loose", size, algorithm).first({wanted}, skip) - if path is not None: - return LocalCopy(self, path) - if size not in self._member_named: - named = self._member_named[size] = {} - for item in self._members_of_size(size): - named.setdefault(item[1].rsplit("/", 1)[-1].casefold(), []).append(item) - for archive, member in self._member_named[size].get(name, []): - if (not _being_written(archive, skip) - and self.digest(archive, algorithm, member) == wanted): - return LocalCopy(self, archive, member) - held = self._scan("member", size, algorithm).first({wanted}, skip) - if held is not None: - return LocalCopy(self, held[0], held[1]) - return None - - def count_copy(self, misplaced: bool = False) -> None: - with self._lock: - if misplaced: - self.fixed += 1 - else: - self.copied += 1 - - def relative(self, path: Path) -> str: - try: - rel = path.relative_to(self.root).as_posix() - except ValueError: - return str(path) - return rel if rel != "." else path.name - - -def _being_written(path: Path, skip: Collection[Path]) -> bool: - """Whether a file, or the archive holding a member, is one this run - writes: its bytes are being replaced, so they are no source.""" - return bool(skip) and (path in skip or Path(os.path.realpath(path)) in skip) - - -class _HashScan: - """Candidates of one size, hashed in order and each once, so finding - the first that holds a digest never reads the earlier ones again: 3,000 - same-sized files and 3,000 entries of that size cost 3,000 reads, not - nine million comparisons.""" - - def __init__(self, items: list, digest: Callable[[Any], str]) -> None: - self.items = items - self.digest = digest - self.read = 0 - self.at: dict[str, list[int]] = {} - - def first(self, wanted: Collection[str], skip: Collection[Path] = ()) -> Any: - """The first candidate, in the folder's order, whose digest is one of - wanted and that skip does not name, or None.""" - best = None - for value in wanted: - for position in self.at.get(value, ()): - if not _being_written(self._holder(position), skip): - best = position if best is None else min(best, position) - break - if best is not None: - return self.items[best] - while self.read < len(self.items): - position = self.read - self.read += 1 - value = self.digest(self.items[position]) - self.at.setdefault(value, []).append(position) - if value in wanted and not _being_written(self._holder(position), skip): - return self.items[position] - return None - - def _holder(self, position: int) -> Path: - item = self.items[position] - return item[0] if isinstance(item, tuple) else item - - -class _ZippedLookup: - """The archives of a folder not listed as files to install, by the - folder holding them: each one's names read once, so telling that a - missing file is still zipped costs two lookups and never a walk.""" - - def __init__(self, index: FolderIndex, known: set[str]) -> None: - self.index = index - self._by_parent: dict[Path, list[tuple[int, Path]]] = {} - for position, path in enumerate(index.archives): - if index.relative(path).casefold() not in known: - self._by_parent.setdefault(path.parent, []).append((position, path)) - # folder -> (member name -> first archive, stem -> first archive). - self._maps: dict[Path, tuple[dict[str, tuple[int, Path]], - dict[str, tuple[int, Path]]]] = {} - - def _folder(self, folder: Path) -> tuple[dict[str, tuple[int, Path]], - dict[str, tuple[int, Path]]]: - if folder not in self._maps: - members: dict[str, tuple[int, Path]] = {} - stems: dict[str, tuple[int, Path]] = {} - for position, path in self._by_parent.get(folder, []): - lowered = path.name.casefold() - if lowered.endswith(".zip"): - for member in self.index.zip_members(path): - members.setdefault(member, (position, path)) - stems.setdefault(lowered.rsplit(".", 1)[0], (position, path)) - self._maps[folder] = (members, stems) - return self._maps[folder] - - def reason(self, name: str, folders: Collection[Path]) -> str: - """Why name is missing when an archive in folders holds it or carries - its name: the first such archive in the order the folder was read, - and one holding it before one carrying its name.""" - lowered = name.casefold() - stem = lowered.rsplit(".", 1)[0] - best: tuple[int, int, Path] | None = None - for folder in folders: - members, stems = self._folder(folder) - for kind, held in ((0, members.get(lowered)), (1, stems.get(stem))): - if held is not None and (best is None or (held[0], kind) < best[:2]): - best = (held[0], kind, held[1]) - if best is None: - return "" - where = self.index.relative(best[2]) - if best[1] == 0: - return f"still zipped: it is inside {where}" - return f"still zipped: {where} needs extracting" - - -def _inside(path: Path, root: Path) -> bool: - """Whether a link at path leads to a place under root.""" - try: - Path(os.path.realpath(path)).relative_to(root) - except ValueError: - return False - return True - - -def _copies(entry: dict) -> list[dict]: - """Every copy the list knows for an entry: its own, other cores', the - platform's declared one.""" - return [entry, *entry.get("alternatives", []), *entry.get("slot_choices", []), - *entry.get("declared_choices", [])] - - -# id(manifest) -> (manifest, the cores its entries name), read once per list. -_LISTED_CORES: dict[int, tuple[dict, frozenset]] = {} - - -def _listed_cores(manifest: dict) -> frozenset: - """Every core a copy of the list's entries names: the platform's own. - - system_cores reaches every profile, the target rule needing the cores off - the platform too, and the "read by" line named Recalbox's mame0258 on - Batocera and BizHawk on RetroArch. - """ - cached = _LISTED_CORES.get(id(manifest)) - if cached is None or cached[0] is not manifest: - cores = frozenset( - core for entry in [*manifest.get("files", []), *manifest.get("omitted_files", [])] - for copy in _copies(entry) for core in copy.get("cores") or []) - cached = _LISTED_CORES[id(manifest)] = (manifest, cores) - return cached[1] - - -def readers(entry: dict, manifest: dict) -> list[str]: - """The cores that open an entry: as its copies name them, else the cores - of its systems that the platform's own list names.""" - named = sorted({core for copy in _copies(entry) for core in copy.get("cores") or []}) - if named: - return named - system_cores = manifest.get("system_cores") or {} - listed = _listed_cores(manifest) - return sorted({core for system in entry_systems(entry) - for core in system_cores.get(system, []) if core in listed}) - - -def opened_line(entry: dict, manifest: dict, bios_path: Path) -> str: - """Where the emulators read an entry, and which ones: "read by mgba at - ...", "expected at ..." where the list names none. "opened at" under - "missing:" read as a file that was opened.""" - try: - where = _entry_path(bios_path, entry) - except ValueError: - where = bios_path / str(entry.get("dest")) - cores = readers(entry, manifest) - if not cores: - return f"expected at {where}" - shown = ", ".join(cores[:SHOWN_CORES]) - if len(cores) > SHOWN_CORES: - shown += f" and {len(cores) - SHOWN_CORES} more" - return f"read by {shown} at {where}" - - -def _known_destinations(files: list[dict]) -> set[str]: - return {str(f.get("dest", "")).casefold() for f in files} - - -def _content_owners(files: list[dict]) -> dict[str, list[dict]]: - """SHA-1 -> the entries one of whose copies holds it, in the list's order.""" - owners: dict[str, list[dict]] = {} - for other in files: - for sha1 in dict.fromkeys(held for c in _copies(other) if (held := c.get("sha1"))): - owners.setdefault(sha1, []).append(other) - return owners - - -def _content_owner( - sha1: str, entry: dict, files: list[dict], - owners: dict[str, list[dict]] | None = None, -) -> str: - """Why a file holding sha1 is not the one entry wants, if the list knows.""" - for copy in entry.get("alternatives", []) + entry.get("slot_choices", []): - if copy.get("sha1") == sha1 and copy.get("cores"): - return (f"another revision: the copy {', '.join(copy['cores'])} " - "reads, not the one this list installs here") - for copy in entry.get("declared_choices", []): - if copy.get("sha1") == sha1: - return ("another revision: the one the platform's own list declares, " - "not the one the cores read") - if owners is None: - owners = _content_owners(files) - for other in owners.get(sha1, []): - if other is entry or other.get("dest") == entry.get("dest"): - continue - regions = [r for r in other.get("regions") or [] if r != WORLD_REGION] - if regions: - return (f"another region: the contents of {other['dest']} " - f"({', '.join(regions)})") - return f"another file: the contents of {other['dest']}" - return "" - - -def _place_reason( - entry: dict, path: Path, index: FolderIndex, expected: Path, known: set[str], - contents: str = "", -) -> tuple[str, str]: - """(reason, folder too deep) for an entry's file found at path in the - BIOS folder, or ("", "") when that place says nothing. contents is - ", with other contents" for a file of the right name and wrong bytes.""" - dest = str(entry.get("dest", "")) - name = dest.rsplit("/", 1)[-1] - rel = index.relative(path) - # A dest below the save directory is not below this folder: a copy - # here under the same tail is in the wrong place, not too deep. - below = entry.get("root") != "save" - if below and rel.endswith("/" + dest) and path.name == name: - extra = rel[: -len(dest) - 1] - top = index.root.name - if extra.casefold() == top.casefold(): - return (f"nested folder: it is at {top}/{rel}{contents}, a " - f"{top} folder inside {top}"), extra - depth = extra.count("/") + 1 - levels = "one folder" if depth == 1 else f"{depth} folders" - return f"{levels} too deep: it is at {rel}{contents}", extra - if path.name.casefold() == name.casefold(): - if path.parent == expected.parent and path.name != name: - return (f"case of the name: the folder holds {path.name}{contents}, " - f"the cores open {name}"), "" - return f"wrong folder: it is at {rel}{contents}", "" - if contents: - return "", "" - if rel.casefold() in known: - return f"its contents are at {rel}: copy that file to {dest}", "" - return f"a name no core opens: its contents are at {rel}, rename it {name}", "" - - -def _copy_reason(entry: dict, copy: LocalCopy, bios_path: Path, known: set[str]) -> str: - """Why a copy found in the BIOS folder is not at the entry's place.""" - if not copy.misplaced: - # np2kai/2608_bd.wav and np2/2608_bd.wav hold the same bytes. Told - # "wrong folder", a user moved np2's copy and broke that core. - return f"the same file is at {copy.where()}, where the list installs it too" - if copy.member: - return f"still zipped: it is inside {copy.index.relative(copy.path)}" - try: - copy.path.relative_to(copy.index.root) - except ValueError: - return f"one folder too high: it is at {copy.path}" - try: - expected = _entry_path(bios_path, entry) - except ValueError: - return "" - return _place_reason(entry, copy.path, copy.index, expected, known)[0] - - -def _twin_in_place(entry: dict, files: list[dict], bios_path: Path) -> bool: - """Whether the name a case variant shares with another entry, but for - the case (bios.col and BIOS.col), is in place.""" - folded = str(entry.get("dest", "")).casefold() - for twin in files: - if twin is entry or twin.get("case_variant") or \ - str(twin.get("dest", "")).casefold() != folded: - continue - try: - if _is_file(_entry_path(bios_path, twin)): - return True - except ValueError: - continue - return False - - -def _found_elsewhere( - entry: dict, index: FolderIndex, bios_path: Path, files: list[dict], - known: set[str], zipped: _ZippedLookup | None = None, -) -> tuple[str, str]: - """(reason, folder too deep) for an entry missing at its place.""" - dest = str(entry.get("dest", "")) - if entry.get("case_variant") and _twin_in_place(entry, files, bios_path): - # A pack is read on Windows and macOS too, where two names that - # differ only by case are one file: it carries one of the pair. Moving - # the other copy here would take it from the core that opens it. - # Only its twin in place says a pack was used: on an empty folder the - # note named a pack never downloaded and pushed the BIOS files the - # user looked for into "... and N more". - return ("a second name the pack leaves out: Windows and macOS see it " - "as the same file. Run the command without --check to add it"), "" - name = dest.rsplit("/", 1)[-1] - sizes = {size for copy in _copies(entry) if isinstance(size := copy.get("size"), int)} - sha1s = {sha1 for copy in _copies(entry) if (sha1 := copy.get("sha1"))} - try: - expected = _entry_path(bios_path, entry) - except ValueError: - return "", "" - same_name = [p for p in index.by_name.get(name.casefold(), []) if p != expected] - matching = [p for p in same_name if index.size[p] in sizes and index.sha1(p) in sha1s] - held = set(matching) - for path in matching or same_name: - contents = "" if path in held else ", with other contents" - found = _place_reason(entry, path, index, expected, known, contents) - if found[0]: - return found - above = index.root.parent / dest - if index.root.parent != index.root and above.is_file(): - return f"one folder too high: it is at {above}", "" - holder = index.first_holding(sizes, sha1s) - if holder is not None: - return _place_reason(entry, holder, index, expected, known) - if name.casefold().endswith(_ARCHIVE_SUFFIXES): - return "", "" - if zipped is None: - zipped = _ZippedLookup(index, known) - reason = zipped.reason(name, {expected.parent, index.root}) - if reason: - return reason, "" - for path in index.apple_double.get(name.casefold(), []): - if path.parent == expected.parent: - return (f"only a Mac's ._ file: {path.name} holds Finder data, not the " - f"file itself. Copy {name} again"), "" - return "", "" - - -def _wrong_contents( - entry: dict, path: Path, index: FolderIndex, files: list[dict], - owners: dict[str, list[dict]] | None = None, -) -> str: - """Why the file at an entry's place is not the one the list installs.""" - try: - if path.is_dir(): - return FOLDER_IN_PLACE - size = path.stat().st_size - with open(path, "rb") as handle: - head = handle.read(4) - except OSError as exc: - return f"could not be read ({exc.strerror or exc}): its contents are unknown" - sha1 = index.sha1(path) - owner = _content_owner(sha1, entry, files, owners) - if owner: - return owner - if head == b"PK\x03\x04" and not str(entry.get("dest", "")).casefold().endswith(".zip"): - return "still zipped: this file is a ZIP archive, extract what it holds" - expected = {listed for copy in _copies(entry) - if isinstance(listed := copy.get("size"), int)} - if size not in expected: - want = " or ".join(f"{s:,}" for s in sorted(expected)) - return f"wrong size: {size:,} bytes, the list expects {want}" - return "same size, other contents: another dump, or a damaged copy" - - -class Diagnosis(NamedTuple): - reasons: dict[int, str] - deep: dict[str, int] - - -def diagnose( - missing: list[dict], mismatched: list[dict], files: list[dict], bios_path: Path, - verified: list[dict] | None = None, index: FolderIndex | None = None, -) -> Diagnosis: - """The reason --check gives for each file it flags, from what the folder - holds and what the list records: id(entry) -> reason, and the folders - holding files too deep with how many. The files the check verified are - not read again: their SHA-1 is the one the list records.""" - reasons: dict[int, str] = {} - deep: dict[str, int] = {} - if not bios_path.is_dir() or not (missing or mismatched): - return Diagnosis(reasons, deep) - if index is None: - index = bios_folder_index(bios_path, files, verified or []) - if index is None: - return Diagnosis(reasons, deep) - known = _known_destinations(files) - zipped = _ZippedLookup(index, known) - for entry in missing: - reason, extra = _found_elsewhere(entry, index, bios_path, files, known, zipped) - if reason: - reasons[id(entry)] = reason - if extra: - deep[extra] = deep.get(extra, 0) + 1 - owners = _content_owners(files) if mismatched else {} - for entry in mismatched: - try: - path = _entry_path(bios_path, entry) - except ValueError: - continue - reason = _wrong_contents(entry, path, index, files, owners) - if reason: - reasons[id(entry)] = reason - return Diagnosis(reasons, deep) - - -class CheckHeld(NamedTuple): - """What check_lines reads besides the list: the files verified, the BIOS - folder's index and the copies found on this machine.""" - - verified: list[dict] | None = None - bios_index: FolderIndex | None = None - copies: dict[int, LocalCopy] | None = None - - -def check_lines( - missing: list[dict], mismatched: list[dict], files: list[dict], manifest: dict, - bios_path: Path, every: bool, held: CheckHeld | None = None, -) -> list[str]: - """The files --check flags, each with why and where its cores read it. - - "missing: scph5501.bin" left a user with the file one folder too deep, - or still in its ZIP, to guess. A flagged file with a reason is always - listed, and so is one a folder named with --from holds. Plain missing - ones stop at ten unless every is set. - """ - held = held or CheckHeld() - index = held.bios_index - found = diagnose(missing, mismatched, files, bios_path, held.verified, index) - copies = held.copies or {} - known = _known_destinations(files) - lines = [] - for extra, count in sorted(found.deep.items(), key=lambda item: -item[1]): - if count >= 3: - lines.append(f" {_plural(count, 'file')} sit too deep, in " - f"{bios_path / extra}: move what it holds up into {bios_path}.") - lines += _check_copy_lines(missing + mismatched, copies, index) - explained = [e for e in missing if id(e) in found.reasons or id(e) in copies] - plain = [e for e in missing if id(e) not in found.reasons and id(e) not in copies] - # A missing file with no more to say is a list: --verbose names each. - shown = plain if every else [] - - def block(label: str, entry: dict) -> list[str]: - game = " (game data)" if entry.get("category") == GAME_DATA else "" - rows = [f" {label}: {entry['dest']}{game}"] - if id(entry) in found.reasons: - rows.append(f" {found.reasons[id(entry)]}") - copy = copies.get(id(entry)) - if copy is not None and copy.index is index and not copy.misplaced: - rows.append(f" a run without --check copies it from {copy.where()}") - elif copy is not None and copy.index is index: - where = _copy_reason(entry, copy, bios_path, known) - if where and where != found.reasons.get(id(entry)): - rows.append(f" the right file: {where}") - rows.append(" a run without --check copies it into place") - elif copy is not None: - rows.append(f" in {shown_path(copy.index.label)}: {copy.where()}") - rows.append(f" {opened_line(entry, manifest, bios_path)}") - return rows - - for entry in mismatched: - lines += block("wrong copy", entry) - for entry in explained: - lines += block("missing", entry) - for entry in shown: - lines += block("missing", entry) - if len(shown) < len(plain) and lines: - lines.append(f" ... and {len(plain) - len(shown)} more missing " - "(--verbose lists them all)") - return shown_lines(lines) - - -def bios_folder_index( - bios_path: Path, files: list[dict], verified: list[dict], -) -> FolderIndex | None: - """The BIOS folder read for files misplaced in it. The files the check - verified are not read again: their SHA-1 is the one the list records. - An archive the list installs is not unpacked for its members: a MAME - set holding a ROM a core also reads loose is that core's to open.""" - if not bios_path.is_dir(): - return None - index = FolderIndex(bios_path) - for entry in verified: - if entry.get("sha1"): - try: - index.seed(_entry_path(bios_path, entry), entry["sha1"].lower()) - except ValueError: - continue - index.sealed = _known_destinations(files) - index.listed = {str(f.get("dest", "")) for f in files} - return index - - -def _above(entry: dict, index: FolderIndex) -> LocalCopy | None: - """The entry's file at its place one folder above the BIOS folder.""" - if entry.get("root") == "save" or index.root.parent == index.root: - return None - try: - above = index.root.parent / _safe_relative_path(entry.get("dest"), "dest") - if above.stat().st_size != entry.get("size") or not above.is_file(): - return None - except (OSError, ValueError): - return None - algorithm = "sha1" if entry.get("sha1") else "sha256" - if index.digest(above, algorithm) != str(entry.get(algorithm, "")).lower(): - return None - return LocalCopy(index, above) - - -def plan_local_copies( - entries: list[dict], bios_path: Path, bios_index: FolderIndex | None, - folders: list[FolderIndex], -) -> dict[int, LocalCopy]: - """id(entry) -> where this machine already holds the entry's bytes: the - BIOS folder itself first, a file misplaced in it, then each folder named - with --from in turn. Every copy is found by size, then by hash.""" - if not entries or (bios_index is None and not folders): - return {} - # A file this run replaces is no source: its place is being written. - written = set() - for entry in entries: - try: - written.add(Path(os.path.realpath(_entry_path(bios_path, entry)))) - except ValueError: - continue - for index in ([bios_index] if bios_index is not None else []) + folders: - index.writes(written) - copies: dict[int, LocalCopy] = {} - for entry in entries: - copy = None - if bios_index is not None: - copy = bios_index.find(entry, written) or _above(entry, bios_index) - if copy is not None: - copy = LocalCopy(copy.index, copy.path, copy.member, - _misplaced(entry, copy, bios_index)) - for index in folders: - if copy is not None: - break - copy = index.find(entry, written) - if copy is not None: - copies[id(entry)] = copy - return copies - - -def _misplaced(entry: dict, copy: LocalCopy, index: FolderIndex) -> bool: - """Whether a copy in the BIOS folder sits where no other entry of the - list goes: GBA_BIOS.BIN for gba_bios.bin is a mistake, np2/2608_bd.wav - for np2kai/2608_bd.wav is the other core's file.""" - if copy.member: - return True - rel = index.relative(copy.path) - if rel in index.listed: - return False - own = str(entry.get("dest", "")).casefold() - return rel.casefold() not in index.sealed or rel.casefold() == own - - -def _check_copy_lines( - entries: list[dict], copies: dict[int, LocalCopy], bios_index: FolderIndex | None, -) -> list[str]: - """What --check says a run would copy instead of downloading.""" - fixed = sum(1 for e in entries if id(e) in copies and copies[id(e)].misplaced) - lines = [] - if fixed: - verb = "is" if fixed == 1 else "are" - them = "it" if fixed == 1 else "them" - lines.append(f" {fixed} of these files {verb} in the BIOS folder in the wrong place: " - f"a run without --check copies {them} where the cores open {them}, and " - f"leaves the {'copy' if fixed == 1 else 'copies'} found as " - f"{'it is' if fixed == 1 else 'they are'}.") - for label, count in _counts_by_folder(entries, copies, bios_index): - them = "it" if count == 1 else "them" - lines.append(f" {label} holds {count} of these files: a run without --check " - f"copies {them}.") - return shown_lines(lines) - - -def _counts_by_folder( - entries: list[dict], copies: dict[int, LocalCopy], bios_index: FolderIndex | None, -) -> list[tuple[str, int]]: - """(folder, files) for each --from folder that gives some of entries.""" - counts: dict[str, int] = {} - for entry in entries: - copy = copies.get(id(entry)) - if copy is not None and copy.index is not bios_index: - counts[copy.index.label] = counts.get(copy.index.label, 0) + 1 - return list(counts.items()) - - -def copy_plan_lines( - entries: list[dict], copies: dict[int, LocalCopy], bios_index: FolderIndex | None, - bios_path: Path, files: list[dict], every: bool, planned: bool, -) -> list[str]: - """The files a run copies from this machine, by folder: the misplaced - ones with the reason each was not where its cores open it.""" - known = _known_destinations(files) - # By --from folder, "" for the misplaced files and "=" for the ones the - # BIOS folder holds at another entry's place. - groups: dict[str, list[dict]] = {} - for entry in entries: - copy = copies.get(id(entry)) - if copy is not None: - key = (copy.index.label if copy.index is not bios_index - else "" if copy.misplaced else "=") - groups.setdefault(key, []).append(entry) - lines = [] - for key in sorted(groups, key=lambda k: (k != "", k != "=")): - chosen = groups[key] - sized = f"{_plural(len(chosen), 'file')} ({format_size(_bytes(chosen))})" - if key == "": - head = (f"Would fix {sized} misplaced in the BIOS folder, copied where the " - "cores open them:" if planned else - f"Fixing {sized} misplaced in the BIOS folder: copied where the cores " - "open them, the copies found left as they are.") - elif key == "=": - head = (f"Would copy {sized} the BIOS folder already holds at another " - "place of the list:" if planned else - f"{sized} the BIOS folder already holds at another place of the list:") - else: - head = (f"Would copy {sized} from {shown_path(key)}:" if planned else - f"{sized} found in {shown_path(key)}, each one checked by hash:") - lines.append(f"\n {head}" if planned else f" {head}") - for entry in chosen if every else chosen[:10]: - copy = copies[id(entry)] - why = (_copy_reason(entry, copy, bios_path, known) if key == "" - else f"from {copy.where()}" if key == "=" else copy.where()) - lines.append(f" {entry['dest']}: {why}" if why else f" {entry['dest']}") - if len(chosen) > 10 and not every: - lines.append(f" ... and {len(chosen) - 10} more (--verbose lists them all)") - return shown_lines(lines) - - -def emit_copies( - plat: str, entries: list[dict], copies: dict[int, LocalCopy], - bios_index: FolderIndex | None, bios_path: Path, files: list[dict], -) -> None: - """One found event per file this machine holds, before it is copied.""" - known = _known_destinations(files) - for entry in entries: - copy = copies.get(id(entry)) - if copy is None: - continue - reason = (_copy_reason(entry, copy, bios_path, known) - if copy.index is bios_index else "") - EVENTS.emit("found", platform=plat, dest=entry["dest"], folder=copy.index.label, - path=str(copy.path), member=copy.member, reason=reason) - - -class Unreadable: - """A file, ZIP member or folder below a --from folder that could not be - read, and may be a file the run still needs.""" - - def __init__(self, index: FolderIndex, path: Path, member: str, why: str) -> None: - self.index = index - self.path = path - self.member = member - self.why = why - - def line(self) -> str: - where = f"{self.member} inside {self.path}" if self.member else str(self.path) - return screen_text(f"{where} could not be read: {self.why}") - - -def unreadable_copies( - entries: list[dict], copies: dict[int, LocalCopy], folders: list[FolderIndex], -) -> list[Unreadable]: - """What the --from folders hold that could not be read, of the size of - a file no copy was found for, or of no known size: dropped silently, - a file a user had read as one to download.""" - sizes = {e["size"] for e in entries - if id(e) not in copies and isinstance(e.get("size"), int)} - if not sizes: - return [] - return [Unreadable(index, *held) for index in folders - for held in index.unreadable_for(sizes)] - - -def unreadable_lines(found: list[Unreadable], every: bool) -> list[str]: - lines = [f" {item.line()}" for item in (found if every else found[:10])] - if len(found) > len(lines): - lines.append(f" ... and {len(found) - len(lines)} more could not be read " - "(--verbose lists them all)") - return shown_lines(lines) - - -def emit_unreadable(plat: str, found: list[Unreadable]) -> None: - for item in found: - EVENTS.emit("unreadable", platform=plat, folder=item.index.label, - path=str(item.path), member=item.member, reason=item.why) - - -def sources_line( - folders: list[tuple[str, int]], fixed: int, downloaded: int, missing: int, - fetched: str = "downloaded", shared: int = 0, wrong: int = 0, failed: int = 0, -) -> str: - """Where the files of a run that copied some came from, in words: - "38 files copied from E:\\, 4 downloaded, 2 still missing." A file found - in the wrong place of the BIOS folder is "copied", as the plan says: - "fixed" read as a wrong copy, of files that were missing. wrong counts - the wrong copies left in place, apart from missing: "1 still missing" - was said of a file --check counts as a wrong copy. - failed counts the files a run tried and could not write or fetch.""" - parts = [(count, f"copied from {screen_text(shown_path(label))}") for label, count in folders] - parts.append((fixed, "copied from the wrong place in the BIOS folder")) - parts.append((shared, "copied from another place of the BIOS folder")) - if not any(count for count, _what in parts): - return "" - parts += [(downloaded, fetched), (failed, "failed"), (missing, "still missing")] - words: list[str] = [] - for count, what in parts: - if count: - words.append(f"{_plural(count, 'file') if not words else count} {what}") - if wrong: - words.append(f"{_plural(wrong, 'wrong copy')} left") - return ", ".join(words) + "." - - -# Below this a download is small enough that narrowing it is not worth a line. -BULK_HINT_FROM = 100 * 1024 * 1024 - - -def _bytes(files: list[dict]) -> int: - return sum(f.get("size", 0) for f in files) - - -def bulk_hint( - to_download: list[dict], manifest: dict, systems_chosen: bool, cores_chosen: bool, - accepted: Collection[str] = (), -) -> list[str]: - """Name what pulls most of a download, when narrowing saves over half of it. - - `--system 3do` fetched 349 MB for RetroArch, and `--core opera` 12.5 MB: - the arcade cores that also read 3DO pulled the rest, and nothing said so. - accepted holds the names --core takes. Drawn from every core of the - system, the advice named ares, which loads no file of its own, and - `--core ares` was then refused. - """ - total = _bytes(to_download) - if total < BULK_HINT_FROM: - return [] - systems = {s for entry in to_download for s in entry_systems(entry)} - if not cores_chosen and len(systems) == 1: - system = next(iter(systems)) - candidates = [core for core in (manifest.get("system_cores") or {}).get(system) or [] - if core in accepted] - by_core: dict[str, int] = {} - for entry in to_download: - for core in entry.get("cores") or []: - by_core[core] = by_core.get(core, 0) + entry.get("size", 0) - kept = {core: _bytes(_filter_by_target(to_download, [core])) for core in candidates} - if by_core and kept: - heavy = max(sorted(by_core), key=lambda core: by_core[core]) - light = min(sorted(kept), key=lambda core: kept[core]) - saved = total - kept[light] - if saved * 2 > total: - return [ - f" {heavy} pulls {format_size(by_core[heavy])} of this " - f"{format_size(total)} download for {system}. --core {light} " - f"keeps {format_size(kept[light])} of it and saves " - f"{format_size(saved)} ({saved * 100 // total}%)." - ] - if not systems_chosen and len(systems) > 1: - alone: dict[str, int] = {} - for entry in to_download: - own = entry_systems(entry) - if len(own) == 1: - alone[own[0]] = alone.get(own[0], 0) + entry.get("size", 0) - if alone: - heavy = max(sorted(alone), key=lambda system: alone[system]) - if alone[heavy] * 2 > total: - return [ - f" {heavy} pulls {format_size(alone[heavy])} of this " - f"{format_size(total)} download. --system naming the systems " - f"played leaves it out and saves {format_size(alone[heavy])} " - f"({alone[heavy] * 100 // total}%), --list-systems names them." - ] - return [] - - -# The RetroBIOS app on a handheld's card. A card prepared on a computer can -# also carry the launcher of ports/ for its system, so the player checks and -# updates the BIOS files from the console later. The files come from the -# same ref as the file lists, listed with their hashes in -# install/launchers/index.json, which scripts/generate_launcher_index.py -# writes from the members of the launcher archives. -LAUNCHERS_URL = f"{BASE_URL}/install/launchers/index.json" -MAX_LAUNCHERS_BYTES = 256 * 1024 -MAX_APP_FILE_SIZE = 8 * 1024 * 1024 -MAX_APP_FILES = 64 -APP_SCHEMA = 1 - - -def _open_local_sources(args: argparse.Namespace) -> None: - """Take the file list and the pack this run was given, and the platform - they are for when none is named.""" - LOCAL.reset() - LOCAL.jobs = getattr(args, "jobs", 8) or 8 - SAID_FAILED.clear() - _open_from_folders(getattr(args, "from", None) or []) - if args.manifest is not None: - LOCAL.manifest = args.manifest - named = local_manifest_platform(args.manifest) - if args.platform is None and named: - args.platform = named - args.platform_from_list = True - print(f" File list: {args.manifest} ({display_name(named)})") - if not args.from_pack: - return - try: - LOCAL.pack = PackSource(args.from_pack) - except ValueError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) - pack = LOCAL.pack - parts = len(pack.files) - print(f" Pack: {pack.name}" - + (f", {parts} parts" if parts > 1 or _PART_FILE.match(pack.files[0].name) else "")) - spelled = pack.platforms() - if args.platform is not None: - plat = normalize_platform(args.platform, say=False) - if spelled and plat not in spelled: - print(f"Error: {pack.name} is a pack for " - f"{' and '.join(display_name(n) for n in spelled)}, not " - f"{display_name(plat)}.", file=sys.stderr) - sys.exit(1) - elif len(spelled) == 1: - # Named by the pack, not by the user: the setups that read its list - # are offered, as for a --manifest. - args.platform = spelled[0] - args.platform_from_list = True - else: - among = (" (" + ", ".join(spelled) + ")") if spelled else "" - print(f"Error: name the platform {pack.name} is installed for with " - f"--platform{among}.", file=sys.stderr) - sys.exit(1) - - -def _system_folder(folder: Path) -> str: - """Why a --from folder is one of the system's own, in words, or "".""" - try: - resolved = folder.resolve() - except OSError: - return "" - text = str(resolved) - if any(text == pseudo or text.startswith(pseudo + "/") for pseudo in PSEUDO_FOLDERS): - return "is a folder the system makes up, it holds no copy" - system_drive = os.environ.get("SYSTEMDRIVE", "C:") if os.name == "nt" else "" - if resolved == Path(resolved.anchor) and ( - os.name != "nt" or resolved.drive.casefold() == system_drive.casefold()): - return "is the root of the whole system" - return "" - - -def from_folder_problem(label: str) -> tuple[str, str] | None: - """Why a folder named with --from cannot be read, without reading what - it holds: (reason, words), or None when it can. - - reason is the one the error event carries: not_found, not_a_folder (a - file that is no ZIP), unreadable, or system (the root of the system, - /proc, /sys or /dev). words follow the folder as given: "E:\\old does - not exist". Cheap enough for a screen to call before indexing.""" - folder = Path(os.path.expanduser(label)) - zipped = folder.is_file() and folder.name.casefold().endswith(".zip") - if not (folder.is_dir() or zipped): - if folder.exists(): - return "not_a_folder", "is neither a folder nor a ZIP" - return "not_found", "does not exist" - try: - if zipped: - with open(folder, "rb"): - pass - else: - with os.scandir(folder) as listing: - next(listing, None) - except OSError as exc: - return "unreadable", f"could not be read: {unreadable_words(exc)}" - system = "" if zipped else _system_folder(folder) - return ("system", system) if system else None - - -def _open_from_folders(folders: list[Path]) -> None: - """Read each folder named with --from, or stop on one that cannot be.""" - for folder in folders: - label = str(folder) - problem = from_folder_problem(label) - if problem is not None: - reason, what = problem - message = f"{label} {what}: --from names the folder to copy BIOS files from" - EVENTS.emit("error", stage="from", reason=reason, platform="", message=message) - print(f"Error: {screen_text(message)}.", file=sys.stderr) - sys.exit(1) - _read_from_folder(label) - - -def _read_from_folder(label: str) -> FolderIndex: - """Read a folder to copy BIOS files from, one from_folder_problem took.""" - index = FolderIndex(Path(os.path.expanduser(label)), label) - LOCAL.folders.append(index) - print(f" Copying BIOS files from: {screen_text(shown_path(label))}") - if index.truncated: - print(f" Read the first {MAX_SCANNED_FILES:,} files of {screen_text(label)} " - "only. Name the folder that holds the BIOS files to search it all.") - for drive in index.other_drives: - print(f" Did not go into {screen_text(str(drive))}: it is another drive. Name " - "it with --from to read it too.") - EVENTS.emit("scanned", folder=label, files=index.files, truncated=index.truncated, - other_drives=[str(drive) for drive in index.other_drives]) - return index - - -# --- installer/network.py ---------------------------------------------------- - # The installer was written after this day. A clock that reads earlier is # wrong, and TLS then finds every certificate not yet valid: a handheld # with no clock battery boots on 1970 or 1980. @@ -10775,5712 +7812,8 @@ def _read_capped(path: Path, limit: int) -> bytes | None: return data if len(data) <= limit else None -# --- installer/setups.py ----------------------------------------------------- +# --- installer/game_files.py ------------------------------------------------- -def _card_word(system: tuple[str, Path, str]) -> str: - """A mounted drive's kind as the first screen writes it: SD card, or - SHARE drive.""" - return "SD card" if drive_kind(system) == "card" else drive_kind(system) - - -# Platforms with no install location of their own: the BIOS folder sits -# beside the executable, wherever the archive was extracted. -PORTABLE_ONLY = { - "bizhawk": "BizHawk reads the Firmware folder beside EmuHawk, and none was found.", -} - - -def _default_dest(os_type: str, platform_name: str) -> Path | None: - """Fall back path for a platform named on the command line but not found, - or None where no folder on this OS is one the platform reads. - - A home directory is meaningless for RetroArch on Android, where Termux - owns the home and the frontend reads from shared storage. ~/bios is read - by no platform, RetroBat lives on Windows only, and a Batocera or Recalbox - path on Windows resolved to the root of the current drive: 8.7 GB under - C:\\userdata\\bios, reported done. - """ - default = _built_in_dest(os_type, platform_name) - if default is not None and (_refused_near(default) or platform_name in _UNNAMEABLE): - # The Flatpak's own folder at 000 hid the retroarch.cfg naming - # ~/Games/bios, and 6.6 GB were offered to a folder it does not read. - return None - return default - - -def _built_in_dest(os_type: str, platform_name: str) -> Path | None: - """The platform's usual folder on this OS, whatever detection met.""" - if os_type == "android" and platform_name == "retroarch": - return _android_storage_root() / "RetroArch" / "system" - if platform_name in PORTABLE_ONLY or (os_type == "windows" and platform_name - not in _os_default_dests(os_type)): - return None - return (_os_default_dests(os_type).get(platform_name) - or (None if platform_name == "retrobat" else DEFAULT_DESTS.get(platform_name))) - - -def _refused_near(default: Path) -> bool: - """Whether detection met a closed folder under HOME, where configs that - could name another folder live, or above the default itself.""" - home = Path.home() - place = default.absolute() - return any(home in (folder, *folder.parents) or folder in (place, *place.parents) - for folder, _why in _DETECTION_REFUSED) - - -def _folded(text: str) -> str: - """Text compared without case or accents, as a filter reads it.""" - decomposed = unicodedata.normalize("NFKD", text) - return "".join(char for char in decomposed if not unicodedata.combining(char)).casefold() - - -class TuiRow(NamedTuple): - """One row a screen lists: what Enter does on it, and what it shows.""" - - action: str - label: str - right: str = "" - value: object = None - style: str = "" - # Shorter forms of right, longest first, for a narrow screen: the label - # keeps its room before the right-hand text does. - narrow: tuple = () - # A name cut to the room left when no form of narrow but a count fits: - # "1 device" named nothing where "TrimUI Smart P..." fits. - cut: str = "" - # The right-hand text is never cut: the label is, once its shortest - # form does not fit beside it (a system's size). - keep_right: bool = False - # The column the right-hand text starts at, one for the whole list: the - # setup list's devices had three right edges at 120 columns. - align: int = 0 - - -def _matches(text: str, needle: str) -> bool: - return not needle or _folded(needle) in _folded(text) - - -# Every device the setup lists name, once, as its maker or its store spells -# the model, with the maker: a system list writes the model, and the filter -# also finds it by its maker's name. Two lists spelled one device two ways -# (Powkiddy RK2023 and RK2023, RGCUBEXX and RG CubeXX, Flip2 and Flip 2), and -# a device typed as one list wrote it found that system alone. A test holds -# every list to these names and each name to one spelling. -_DEVICES: dict[str, str] = { - **{model: "Anbernic" for model in ( - "RG28XX", "RG34XX", "RG34XX SP", "RG35XX", "RG35XX 2024", "RG35XX H", - "RG35XX Plus", "RG35XX Pro", "RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX", - "RG ARC", "RG ARC-S", "RG 55G1", "RG351", "RG351M", "RG351MP", "RG351P", "RG351V", - "RG353", "RG353M", "RG353P", "RG353PS", "RG353V", "RG353VS", "RG503", "RG552")}, - **{model: "Powkiddy" for model in ( - "RGB10", "RGB10X", "RGB10 Max", "RGB10 Max 2", "RGB10 Max 3", "RGB10 Max 3 Pro", - "RGB20 Pro", "RGB20S", "RGB20SX", "RGB30", "RK2023", "X35H", "X35S", "X55", "V10", - "PowKiddy Q20 Mini", "PowKiddy Q90", "PowKiddy V90")}, - **{model: "Miyoo" for model in ( - "Miyoo A30", "Miyoo Flip", "Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus")}, - **{model: "TrimUI" for model in ("TrimUI Brick", "TrimUI Smart", "TrimUI Smart Pro")}, - **{model: "Retroid" for model in ( - "Retroid Pocket", "Retroid Pocket 5", "Retroid Pocket 6", "Retroid Pocket Flip 2", - "Retroid Pocket Mini", "Retroid Pocket Nova")}, - **{model: "AYN" for model in ( - "AYN Odin", "AYN Odin 2", "AYN Odin 3", "AYN Thor", "AYN Loki Max", - "AYN Loki Mini Pro", "AYN Loki Zero")}, - **{model: "AYANEO" for model in ( - "AYANEO Pocket", "AYANEO Air", "AYANEO Air Plus", "AYANEO Air Pro", "AYANEO 2", - "AYANEO 2S", "AYANEO 2021", "AYANEO Geek", "AYANEO Next")}, - **{model: "Hardkernel" for model in ( - "Odroid Go", "Odroid Go Advance", "Odroid Go Super", "Odroid Go Ultra")}, - **{model: "MagicX" for model in ( - "MagicX XU10", "MagicX XU Mini M", "MagicX XU20 V32", "MagicX Mini Zero 28")}, - **{model: "GameForce" for model in ("GameForce Ace", "GameForce Chi")}, - **{model: "SJGAM" for model in ("SJGAM M21", "SJGAM M22 Pro")}, - **{model: "" for model in ( - "R33S", "R35S", "R36H", "R36S", "R36S Plus", "R36S Soysauce", "R40XX Pro Max", - "XF40H", "K36", "M17", "BittBoy", "Pocket Go", "Sup M3", "XYC Q8", "Android", - # dArkOS names these two by model alone (v08272026 release notes). - "A10 Mini", "Miniloong Pocket 1")}, - "G350": "BattleXP", - "GKD Pixel": "GKD", - "GKD Pixel 2": "GKD", - "Mangmi Air X": "Mangmi", - "Orange Pi Zero 2w": "Orange Pi", - "Steam Deck": "Valve", - "ROG Ally": "ASUS", -} - -# The devices whose own system is Android. On a computer RetroArch's row is -# that computer's RetroArch, and a Retroid Pocket owner found it in one press -# and got the computer's folder. Listed only where RetroBIOS runs on Android. -_ANDROID_DEVICES = ("Android", "Retroid Pocket", "Retroid Pocket 5", "AYN Odin", "AYN Odin 3") - - -def _device_key(text: str) -> str: - """A device name compared without case, spaces or punctuation, + read as - Plus: RG CubeXX, RGCUBEXX and rg-cubexx are one device, Mini+ is Mini Plus.""" - return _name_key(re.sub(r"\s*\+", " plus", _folded(text))) - - -# The devices people type in the setup filter instead of the setup they run, -# beside the setups a first-party page says each one runs, spelled as -# _DEVICES spells them. Keys are platform ids or the system names of -# _EMBEDDED_RULES, and a device that runs several setups is under each. The -# handheld systems' lists are those of platforms/_guides.yml (handheld_guide, -# each with its devices_source), and a test holds the two equal. -_SETUP_DEVICES: dict[str, tuple[str, ...]] = { - "ArkOS": ("RG353M", "RG353V", "RG503", "RGB30", "RK2023", "RG351MP", "RG351V", "R35S", - "RGB10"), - "muOS": ("RG35XX H", "RG35XX Plus", "RG35XX SP", "RG35XX 2024", "RG34XX", "RG40XX H", - "RG40XX V", "RG28XX", "RG CubeXX", "TrimUI Brick", "TrimUI Smart Pro"), - "Onion": ("Miyoo Mini", "Miyoo Mini Plus"), - "spruceOS": ("Miyoo A30", "Miyoo Flip", "Miyoo Mini", "Miyoo Mini Plus", - "Miyoo Mini Flip", "TrimUI Smart Pro", "TrimUI Brick", - "RG35XX Plus", "RG40XX H", "RGB30"), - "Allium": ("Miyoo Mini", "Miyoo Mini Plus", "Miyoo Mini Flip"), - # The stock Linux these devices ship with runs /mnt/vendor/bin/dmenu.bin: - # GarlicOS/bootloader_anbernic_rg35xxplus 45b489b4, README.md:4. - "Anbernic stock firmware": ("RG35XX Plus", "RG35XX H", "RG35XX SP", "RG28XX"), - "ArchR": ("R36S", "R33S", "R36S Soysauce", "Odroid Go Advance", "Odroid Go Super", - "RG351V", "RG351M", "GameForce Chi", "MagicX XU10", "RGB10", "RGB10X", "K36"), - "CrossMix-OS": ("TrimUI Smart Pro",), - "dArkOS": ("RG353M", "RG353V", "RG503", "RGB30", "RGB20 Pro", "RK2023", "RG351MP", "RGB10", - "G350", "Odroid Go Advance", "A10 Mini", "Miniloong Pocket 1"), - # JELOS 7b2e116c, packages/hardware/quirks/devices: one folder per device - # it was built for, the handhelds here. - "JELOS": ("RG351M", "RG351V", "RG353M", "RG353P", "RG353V", "RG353VS", "RG503", "RG552", - "R33S", "R36S", "GameForce Ace", "GameForce Chi", "Odroid Go Advance", - "Odroid Go Super", "Odroid Go Ultra", "MagicX XU10", "RGB10", "RGB10 Max 3", - "RGB10 Max 3 Pro", "RGB20S", "RGB30", "RK2023", "X55", "AYANEO Air", - "AYANEO Air Plus", "AYANEO Air Pro", "AYANEO 2", "AYANEO 2S", "AYANEO 2021", - "AYANEO Geek", "AYANEO Next", "AYN Loki Max", "AYN Loki Mini Pro", - "AYN Loki Zero"), - "KOLOS": ("RG353P", "RG353M", "RG353V", "RG353VS", "RG503", "RK2023", "RGB30", - "RGB10 Max 3"), - "Koriki": ("Miyoo Mini",), - "MiyooCFW": ("BittBoy", "Pocket Go", "PowKiddy Q90", "PowKiddy V90", "PowKiddy Q20 Mini", - "Sup M3", "XYC Q8"), - "plumOS": ("MagicX XU20 V32",), - "RetroOZ": ("Odroid Go Super", "Odroid Go Advance", "RGB10 Max", "RGB10 Max 2"), - "UnofficialOS": ("R35S", "R36S", "RG351M", "RG351P", "RG351V", "RG353M", "RG353P", - "RG353V", "RG503", "RG552", "RGB30", "RGB20 Pro", "Odroid Go Advance", - "Odroid Go Super"), - # The Android tile of the handheld group (_guides.yml): goretroid.com - # "OS: Android 13" for the Retroid Pocket 5, ayntec.com "Android 15" for - # the AYN Odin 3. The guide runs RetroArch on Steam Deck (run: steamdeck) - # and on Windows, which the ROG Ally runs (rog.asus.com spec, - # "Windows 11 Home"). - "retroarch": ("Steam Deck", "ROG Ally", "Android", "Retroid Pocket", "Retroid Pocket 5", - "AYN Odin", "AYN Odin 3"), - "emudeck": ("Steam Deck", "ROG Ally"), - "retrodeck": ("Steam Deck",), - "retrobat": ("ROG Ally",), - "bizhawk": ("ROG Ally",), - # _guides.yml runs_on, each cited there. - "batocera": ("Steam Deck",), - "amberelec": ("RG351", "RG552"), - "emuelec": ("Odroid Go",), - # shauninman/MinUI dbf89435, README.md:65-90, Supported Devices. - "minui": ("RG28XX", "RG34XX", "RG34XX SP", "RG35XX", "RG35XX Plus", "RG35XX H", - "RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX", "GKD Pixel", "M17", - "MagicX XU Mini M", "MagicX Mini Zero 28", "Miyoo A30", "Miyoo Flip", - "Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus", "RGB30", "TrimUI Brick", - "TrimUI Smart", "TrimUI Smart Pro"), - "nextui": ("TrimUI Brick", "TrimUI Smart Pro"), - # Turro75/MyMinUI 72ed4f3d, README.md:11-35, List of working devices. - "myminui": ("RG35XX", "Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus", "Miyoo A30", - "SJGAM M21", "SJGAM M22 Pro", "R36S", "R36H", "R36S Plus", "R40XX Pro Max", - "XF40H", "RG351P", "RG353V", "RG353VS", "RG353P", "RG353PS", "RG353M", "V10", - "RGB30", "RG35XX SP"), - # rocknix.org/devices, read 2026-10-26. - "rocknix": ("RG351", "RG353", "RG503", "RG552", "RG 55G1", "RG ARC", "RG35XX 2024", - "RG35XX Plus", "RG35XX Pro", "RG35XX H", "RG35XX SP", "RG28XX", "RG40XX V", - "RG40XX H", "RG CubeXX", "RG34XX", "AYANEO Pocket", "AYN Odin 2", - "AYN Odin 3", "AYN Thor", "GameForce Ace", "Odroid Go Advance", - "Odroid Go Super", "Odroid Go Ultra", "MagicX XU Mini M", "Mangmi Air X", - "RGB10", "RGB10X", "RK2023", "RGB20SX", "RGB20 Pro", "RGB30", "X35S", "X35H", - "X55", "MagicX XU10", "Retroid Pocket 5", "Retroid Pocket 6", - "Retroid Pocket Flip 2", "Retroid Pocket Mini", "Retroid Pocket Nova", "R33S", - "R35S", "R36S", "K36"), - # knulli.org, read 2026-10-26. - "knulli": ("RG ARC-S", "RG28XX", "RG34XX", "RG35XX", "RG35XX Plus", "RG35XX H", - "RG35XX 2024", "RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX", - "Retroid Pocket 5", "Retroid Pocket Flip 2", "Retroid Pocket Mini", - "Miyoo Flip", "Orange Pi Zero 2w", "RGB30", "X55", "TrimUI Brick", - "TrimUI Smart Pro", "G350", "GKD Pixel 2"), -} - - -def _setup_devices(name: str, os_type: str = "") -> tuple[str, ...]: - """The devices a setup row names: an Android device only where this - installer runs on Android, RetroArch's row being this machine's.""" - devices = _SETUP_DEVICES.get(name, ()) - if name == "retroarch" and os_type != "android": - devices = tuple(device for device in devices if device not in _ANDROID_DEVICES) - return devices - - -def android_hint(needle: str, os_type: str) -> str: - """What a filter that names an Android device and finds nothing says: - RetroArch is the Android setup, and its row on a computer is that - computer's (_setup_devices). "android" matched nothing, with no word.""" - if os_type == "android" or not any(_device_found(device, needle) - for device in _ANDROID_DEVICES): - return "" - return "On Android, choose RetroArch: run RetroBIOS on the device itself." - - -def _device_needle(needle: str) -> str: - """The filter text with a model's short form spelled out: owners write - RP5 for the Retroid Pocket 5, as the store names it.""" - short = re.fullmatch(r"\s*rp\s*(\d+)\s*", needle, re.IGNORECASE) - if short: - return f"Retroid Pocket {short.group(1)}" - return needle - - -# A list that names a family stands for each of its models: ROCKNIX lists -# RG351 and RG353, and the RG353V typed from the box found every system but -# it. AmberELEC's RG351 is the series it was made for (amberelec.org). -_DEVICE_FAMILIES: dict[str, tuple[str, ...]] = { - "RG351": ("RG351P", "RG351M", "RG351V", "RG351MP"), - "RG353": ("RG353P", "RG353M", "RG353V", "RG353VS", "RG353PS"), -} - - -def _device_found(device: str, needle: str) -> bool: - """Whether typed text names device, by its model, with or without its - maker: Powkiddy RK2023 and RK2023 are one device. A family is found by - the name of any of its models.""" - key = _device_key(_device_needle(needle)) - if not key: - return False - maker = _device_key(_DEVICES.get(device, "")) - return any(key in _device_key(model) or key in maker + _device_key(model) - for model in (device, *_DEVICE_FAMILIES.get(device, ()))) - - -def _setup_matches(plat: str, systems: list[str], needle: str, - os_type: str = "") -> list[str] | None: - """What the filter names for plat: its devices and systems that match, - [] when plat's own name does, None when nothing does. A device counts - for each setup it runs.""" - if not needle or _name_found(f"{plat} {display_name(plat)}", needle): - return [] - devices = [device for device in _setup_devices(plat, os_type) - if _device_found(device, needle)] - named = [system for system in systems if _name_found(system, needle) or any( - _device_found(device, needle) for device in _SETUP_DEVICES.get(system, ()))] - return _computer_named(plat, needle) + devices + named or None - - -def _system_matches(name: str, needle: str) -> list[str] | None: - """What the filter names for a card system: [] when its name does, the - devices that run it that match, None when nothing does.""" - if not needle or _name_found(name, needle): - return [] - return [device for device in _SETUP_DEVICES.get(name, ()) - if _device_found(device, needle)] or None - - -def _name_found(name: str, needle: str) -> bool: - """Whether typed text names a setup, compared as a device is: spruce os, - unofficial os and cross mix found nothing on the screen, and line mode - took Unofficial OS.""" - key = _device_key(needle) - return _matches(name, needle) or bool(key) and key in _device_key(name) - - -def _comma_forms(names: list[str]) -> tuple: - """Shorter forms of a list for a narrow screen, each cut at a comma: - "Miyoo Mini, +2" where "Miyoo ...s" said nothing.""" - return tuple(", ".join(names[:keep]) + f", +{len(names) - keep}" - for keep in range(len(names) - 1, 0, -1)) - - -def _device_forms(names: list[str]) -> tuple: - """A setup row's devices cut for a narrow screen, the setup's name kept - whole: at 40 columns KNULLI and ROCKNIX lost every device, and - "CrossMix-OS, SD ca" was cut mid-word. The last form counts them, and a - row naming no device can leave its right column empty.""" - if not names: - return ("",) - if len(names) == 1: - # A count of one names nothing: the name is cut instead (TuiRow.cut). - return () - return (*_comma_forms(names), _plural(len(names), "device")) - - -def _device_setup(state: TuiState, plat: str, system: str) -> Path | None: - """The folder detection found for system on this machine itself, never - a card mounted in a reader: on a computer a card is looked for.""" - return _found_device(state.setups, state.mounted_setups, plat, system) - - -def _found_device(setups: list, mounted: set, plat: str, system: str) -> Path | None: - return next((path for name, path, _label in setups if name == plat - and (name, path) not in mounted - and detected_os(name, path) == system), None) - - -def setup_folder(os_type: str, setups: list, mounted: set, plat: str, - system: str) -> tuple[Path | None, str]: - """(folder, kind) offered for a setup taken from the setup list, on the - screen's Which folder? and at line mode's folder question. kind is - "found" (detected here), "share" (a system a computer reaches on its - SHARE drive, no folder of its own here) or "usual" (its built-in one). - - The folder detected here comes before the built-in one: line mode, by - o then RetroArch, offered ~/.config/retroarch/system and filled it, - when the retroarch.cfg found here names another folder. A card in a - reader is its own system's, never this computer's RetroArch, and a - system that runs from its card is found on the device itself only.""" - bound = card_bound(system, plat) - if bound: - found = _found_device(setups, mounted, plat, bound[0]) - return found, "found" if found else "usual" - found = next((path for name, path, _label in setups if name == plat - and (name, path) not in mounted), None) - if found is not None: - return found, "found" - if plat in _SHARE_FOLDERS: - # /userdata/bios exists on the Batocera machine alone: a computer - # sees its share drive or its network share. - return None, "share" - return _default_dest(os_type, plat), "usual" - - -def setup_list(setups: list, mounted: set, needle: str = "", - os_type: str = "", serves: frozenset = frozenset()) -> list[TuiRow]: - """The setup list, the screen's and the numbered one of line mode: each - platform, then each system that runs from its SD card, with what the - filter named. setups and mounted are what detection found here, as - TuiState holds them. - - Every card system is a row of its own that asks for its card, with or - without the filter, from card_setups(): RetroArch's row listed muOS, - JELOS and fourteen more, and A on it led an R36S owner to this - computer's RetroArch folder. RetroArch's row is this computer's. A card - row names the devices that run it, the name a handheld's owner knows: - "Onion, SD card" beside "RetroArch files" said nothing to a Miyoo Mini - owner. With nothing found here the card rows come right after RetroArch - (_cards_first). Line mode listed them in another order, and its 8 was - the screen's 19. serves, when not empty, keeps the setups that read - the file list given (LocalSources.serves). - """ - every_card = card_setups() - cards = {setup.name for setup in every_card} - cards_setups = [setup for setup in every_card if not serves or setup.plat in serves] - systems = _systems_reading() - desktop: list[TuiRow] = [] - handheld: list[tuple[str, TuiRow]] = [] - for plat in AVAILABLE_PLATFORMS: - if serves and plat not in serves: - continue - others = [name for name in systems.get(plat, []) if name not in cards] - named = _setup_matches(plat, others, needle, os_type) - if named is None: - continue - setup = card_setup(plat, plat) - label = display_name(plat) - if (setup and plat not in _DESK_CARDS - and _found_device(setups, mounted, plat, setup.name) is None): - label += ", SD card" - # The systems and devices the filter named, else a card's devices. - shown = named or (list(_setup_devices(plat, os_type)) if setup else []) - row = TuiRow("platform", label, ", ".join(shown), plat, narrow=_device_forms(shown), - cut=shown[0] if shown else "") - if setup and plat not in _DESK_CARDS: - handheld.append((label, row)) - else: - desktop.append(row) - for setup in cards_setups: - if setup.name == display_name(setup.plat): - continue - named = _system_matches(setup.name, needle) - if named is None: - continue - label = setup.name - if _found_device(setups, mounted, setup.plat, setup.name) is None: - label += ", SD card" - shown = named or list(_SETUP_DEVICES.get(setup.name, ())) - handheld.append((label, TuiRow("cardsystem", label, ", ".join(shown) - or f"{display_name(setup.plat)} files", - (setup.plat, setup.name), - narrow=_device_forms(shown), - cut=shown[0] if shown else ""))) - handheld.sort(key=lambda item: item[0].casefold()) - cards_rows = [row for _label, row in handheld] - if _cards_first(setups): - # The setups this computer runs lead, before the cards: RetroBat - # was row 27 of 34 on Windows, after 23 SD card rows. - here = _DESKTOP_LEAD.get(os_type, ("retroarch",)) - lead = sorted((row for row in desktop if row.value in here), - key=lambda row: here.index(row.value)) - rest = [row for row in desktop if row.value not in here] - return [*lead, *cards_rows, *rest] - return [*desktop, *cards_rows] - - -# The systems that run from an SD card on a board kept on a desk, not in -# the hand: their row stays among the platforms, and the handhelds' block, -# which leads when nothing is found here, keeps Onion four presses away. -_DESK_CARDS = frozenset({"misterfpga", "lakka"}) - -# The setups a computer runs, by its system, first in the setup list when -# nothing was found here. RetroBat runs on Windows alone (retrobat.org), and -# under WSL its folder is the Windows side's (_os_default_dests). EmuDeck has -# a Windows edition (emudeck-we). -_DESKTOP_LEAD: dict[str, tuple[str, ...]] = { - "windows": ("retroarch", "retrobat", "emudeck"), - "wsl": ("retroarch", "retrobat", "emudeck"), -} - -# The computer systems people type in the setup filter, with the setups each -# one runs: "windows" and "mac" matched nothing. RetroArch runs on the three -# (retroarch.com), RetroBat on Windows only, EmuDeck has a Windows edition -# and a Linux one (SteamOS), RetroDECK is a Linux Flatpak, BizHawk publishes -# Windows and Linux builds, RetroPie runs on Debian and Ubuntu. -_COMPUTER_SYSTEMS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = { - "Windows": (("windows", "pc"), ("retroarch", "retrobat", "emudeck", "bizhawk")), - "macOS": (("macos", "mac", "osx", "macbook"), ("retroarch",)), - "Linux": (("linux", "ubuntu", "debian", "steamos"), - ("retroarch", "emudeck", "retrodeck", "bizhawk", "retropie")), -} - - -def _computer_named(plat: str, needle: str) -> list[str]: - """The computer systems the filter names that run plat.""" - key = _device_key(needle) - # Two letters are a word on their way: "wi" said "No setup matches" - # between "w" and "win". "pc" is one of the words. - if len(key) < 2: - return [] - return [name for name, (words, plats) in _COMPUTER_SYSTEMS.items() - if plat in plats and any(word.startswith(key) for word in words)] - - -def _cards_first(setups: list) -> bool: - """Whether the card rows follow RetroArch: nothing was found here, so - this is a computer a handheld's card is prepared on, or a console the - detection does not know. A pad cannot type in the filter, and Onion was - row 30 of 34: 29 presses of Down. Right after RetroArch it is row 19, - in view after five presses of L1/R1 at 40x12, which page by the rows - drawn (_page_step). A row that opened a list of the - cards cost one more press than the list it opened.""" - return not setups - - -def _setup_label(plat: str, path: Path | None) -> str: - system = detected_shown(plat, path) if path is not None else "" - name = display_name(plat) - return f"{system} ({name} files)" if system and system != name else name - - -def _install_kind(path: Path) -> str: - """What sets one install of a frontend apart from another of the same.""" - # The config detection read it from says how it was installed: the - # Flatpak's system directory can be anywhere its config names. - found = _retroarch_config_at(path) - text = path.as_posix() + (" " + Path(found[0]).as_posix() if found else "") - for marker, word in (("/.var/app/", "Flatpak"), ("/steamapps/", "Steam"), - ("/snap/", "Snap")): - if marker in text: - return word - if _is_file(path.parent / "retroarch.cfg"): - return "portable" - return "" - - -def tell_apart(setups: list[tuple]) -> list[tuple]: - """Two setups that read alike get the word that separates them: the - Flatpak and the native RetroArch were both "RetroArch" at 40 columns. - The one no package names is "installed", and two of those keep the - end of their folder, the only thing that tells them apart.""" - labels = [label for _plat, _path, label in setups] - kinds = [_install_kind(path) or "installed" for _plat, path, _label in setups] - named = list(zip(labels, kinds)) - return [(plat, path, label if labels.count(label) == 1 - else f"{label} ({kind})" if named.count((label, kind)) == 1 - else f"{label} ({'/'.join(path.parts[-2:])})") - for (plat, path, label), kind in zip(setups, kinds)] - - -def _tui_passthrough(args: argparse.Namespace) -> list[tuple[str, str | None]]: - """Options the screens do not change, handed to every run unchanged.""" - flags: list[tuple[str, str | None]] = [] - if args.romm_firmware is not None: - flags.append(("--romm-firmware", str(args.romm_firmware))) - for flag in ("--save-dir", "--cores-dir"): - value = getattr(args, flag[2:].replace("-", "_")) - if value is not None: - flags.append((flag, str(Path(value).absolute()))) - flags.extend((flag, None) for flag in ("--standalone-copies", "--verbose") - if getattr(args, flag[2:].replace("-", "_"))) - return flags - - -def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]: - """(setups, mounted): what detection finds here, each with its label, - then each card mounted in a reader whose own files name its system, and - the (platform, folder) of those cards. The screen's "Found on this - machine" and line mode's "Found" read this one list: line mode looked - at this machine alone, and a mounted Onion card was never offered.""" - found = detect_platforms(os_type) - cards = [(card_system(mount), mount) for mount in _mounted_cards()] - setups = [(name, path, _setup_label(name, path)) for name, path in found] - mounted: set = set() - # On the device itself its own card is the system found, by its own - # path (muOS reads /run/muos/storage/bios, a bind of MUOS/bios). - here = {detected_os(name, path) for name, path in found} - taken = [] - for card, mount in cards: - if card is None: - # A drive whose files fit two systems is said, never guessed. - words = doubt_words(mount) - if words: - print(f" {words}") - continue - if (card[0], card[1]) not in found and card[2] not in here: - _DETECTED_OS.setdefault((card[0], card[1]), card[2]) - _FROM_CARD.add((card[0], card[1])) - mounted.add((card[0], card[1])) - taken.append((card, mount)) - systems = [card[2] for card, _mount in taken] - counts = {mount: _bios_count(card[1]) for card, mount in taken - if systems.count(card[2]) > 1} - # Two cards of one system read alike: each says what its BIOS folder - # holds, and the one with fewer files, the card being set up rather - # than the old one, comes first. - taken.sort(key=lambda item: (systems.index(item[0][2]), counts.get(item[1], -1))) - for card, mount in taken: - kind = _card_word(card) - held = counts.get(mount) - what = ("" if held is None else ", no BIOS folder" if held < 0 - else f", {_plural(held, 'BIOS file')}") - setups.append((card[0], card[1], - f"{card_title(card[2])} {kind} ({_mount_name(mount)}{what})")) - return tell_apart(setups), mounted - - -def _bios_count(folder: Path, cap: int = 99999) -> int: - """How many files a card's BIOS folder holds, -1 when it has none.""" - if not _is_dir(folder): - return -1 - count = 0 - for _top, _dirs, files in os.walk(folder): - count += len(files) - if count >= cap: - break - return count - - -# --- installer/platform_choice.py -------------------------------------------- - -def _row_name(row: TuiRow) -> str: - """The name a setup row is typed back with: a platform id, or the name - of a system that runs from its SD card.""" - value = row.value - if row.action == "cardsystem" and isinstance(value, tuple): - return str(value[1]) - return str(value) - - -def _row_platform(row: TuiRow) -> str: - """The platform of the system a cardsystem row stands for.""" - value = row.value - return str(value[0]) if isinstance(value, tuple) else "" - - -def _line_setups(setups: list | None = None, mounted: set | None = None, - os_type: str = "") -> list[tuple[str, str]]: - """(name typed back, label) of each choice of the line menus, the - screen's setup list (setup_list) in its order, numbered: Onion was - reachable only as RetroArch, whose folder on a computer is the - computer's, and the numbers followed another order than the rows.""" - def devices(names: list[str]) -> str: - # The devices that run it, three at most: the name its owner knows. - more = f", +{len(names) - 3}" if len(names) > 3 else "" - return ", ".join(names[:3]) + more - - choices = [] - for row in setup_list(setups or [], mounted or set(), "", os_type or detect_os(), - LOCAL.serves()): - name = _row_name(row) - if row.action == "cardsystem": - listed = list(_SETUP_DEVICES.get(name, ())) - shown = devices(listed) or f"{display_name(_row_platform(row))} files" - choices.append((name, f"{row.label} ({shown})")) - else: - listed = list(_setup_devices(name, os_type or detect_os())) \ - if card_setup(name, name) else [] - choices.append((name, row.label + (f" ({devices(listed)})" if listed else ""))) - return choices - - -def _line_matches(choices: list[tuple[str, str]], typed: str, setups: list | None = None, - mounted: set | None = None, os_type: str = "") -> list[tuple[int, str]]: - """(index, label) of the choices a typed device or system name finds, - with the screen filter's own matcher: "miyoo" was refused, the line - menu knowing only setup names. The label names what was matched first, - as the screen's row does on its right: "miyoo mini" listed MinUI with - RG28XX, RG34XX and RG34XX SP.""" - found = {_row_name(row): row for row in setup_list( - setups or [], mounted or set(), typed, os_type or detect_os(), LOCAL.serves())} - matched = [] - for index, (name, label) in enumerate(choices): - row = found.get(name) - if row is None: - continue - named = row.right.split(", ") if row.right else [] - more = f", +{len(named) - 3}" if len(named) > 3 else "" - matched.append((index, f"{row.label} ({', '.join(named[:3])}{more})" if named - else label)) - return matched - - -def _choose_platform(title: str, default: str = "", setups: list | None = None, - mounted: set | None = None) -> str: - """One setup from the numbered list, Enter taking the default: a - platform id, or the name of a system that runs from its SD card, which - normalize_platform turns into its list. - - A device several systems run lists them all, and Enter after that list - takes none of them: it took RetroArch, which none of them was. A number - out of range is said as one, never read as a device name. - """ - os_type = detect_os() - choices = _line_setups(setups, mounted, os_type) - if default and default not in {name for name, _label in choices}: - # A file list for another setup: Enter takes the first row, where - # the screen's focus falls (_platform_focus). - default = choices[0][0] if choices else "" - print(f"\n{title}") - # Wrapped at the width between words, its devices under its name: left - # to the terminal, "Miyoo Flip" was folded inside "Miy" and "oo" below - # 40 columns. - cols = terminal_size()[0] - 1 - width = len(str(len(choices))) - for i, (_name, label) in enumerate(choices, 1): - number = f" {i:>{width}}) " - pieces = _no_widow(_wrap(label, max(cols - len(number), 8), ""), - max(cols - len(number), 8)) - print(number + pieces[0]) - for piece in pieces[1:]: - print(" " * len(number) + piece) - print(" q) quit") - print("Type a number, a setup's name, or the device's name (Miyoo Mini, R36S).") - usage = (f" Type a number from 1 to {len(choices)}, a setup name or the " - "device's name, or q to quit.") - while True: - prompt = f"> [Enter for {display_name(default)}] " if default else "> " - choice = _ask(prompt) - if not choice: - if default: - return default - print(usage) - continue - if choice.lower() == "q": - _quit() - if choice.isdigit(): - if 1 <= int(choice) <= len(choices): - return choices[int(choice) - 1][0] - print(usage) - continue - key = _name_key(choice) - for name, _label in choices: - if key and key in (_name_key(name), _name_key(display_name(name))): - return name - found = _line_matches(choices, choice, setups, mounted, os_type) if key else [] - if len(found) == 1: - print(f" {found[0][1]}") - return choices[found[0][0]][0] - if found: - print(f" {len(found)} setups run on '{choice.strip()}':") - for index, label in found: - print(f" {index + 1}) {label}") - print(" Type the number of the right one.") - default = "" - continue - hint = android_hint(choice, os_type) - print(f" {hint}" if hint else usage) - - -def drive_example(os_type: str, label: str, below: str = "", plat: str = "") -> str: - """Where a drive mounted here is, as this system writes it, for the - example a refusal gives: macOS mounts it at /Volumes/