#!/usr/bin/env python3 # Generated by scripts/build_installer.py from the installer/ package. Edit # the modules there and run the script: a change made here is overwritten. """Universal BIOS installer for retrogaming platforms. Self-contained script using only Python stdlib. Downloads missing BIOS files from the retrobios repository and places them in the correct location for the detected emulator platform. Usage: python install.py python install.py --platform retroarch --dest ~/custom/bios python install.py --check python install.py --list-platforms python install.py --platform retroarch --system sony-playstation --region us """ from __future__ import annotations import argparse import bisect import codecs import concurrent.futures import contextlib import datetime import errno import functools import hashlib import http.client import io import json import os import platform import queue import re import shlex import shutil import signal import socket import stat import subprocess import sys import tarfile import tempfile import textwrap import threading import time import traceback import urllib.error import urllib.parse import urllib.request import weakref import xml.etree.ElementTree as ET import zipfile from collections.abc import Callable, Collection, Iterable, Iterator, Mapping from pathlib import Path, PurePosixPath, PureWindowsPath from typing import IO, Any, BinaryIO, ContextManager, NamedTuple, NoReturn, TextIO # Built as C extensions that a Python compiled without their libraries # lacks: the run stopped on a ModuleNotFoundError traceback. try: import unicodedata import zlib except ImportError as _missing: print(f"Error: this Python was built without its {_missing.name} module, which " "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr) sys.exit(1) # --- installer/detection_notes.py -------------------------------------------- # Each line detection said, in order, other than a folder it could not look # in (_DETECTION_REFUSED keeps those): a system found with no folder, a # configuration naming a folder nobody can type, an Android folder out of # reach, a card that fits two systems. DETECTION_NOTES: list[str] = [] # Set while the full screen runs detection: it shows the notes and the # refusals itself, and a line printed under it would tear the screen. _HELD = {"active": False} def echo_detection(line: str, stream: TextIO | None = None) -> None: """Print a line detection says, unless the screen shows it itself.""" if not _HELD["active"]: print(line, file=stream if stream is not None else sys.stderr) def note_detection(line: str, stream: TextIO | None = None) -> None: """Keep a line detection says, and print it in line mode.""" DETECTION_NOTES.append(line) echo_detection(line, stream) @contextlib.contextmanager def detection_held() -> Iterator[None]: """Detection that keeps its lines without printing them.""" outer = _HELD["active"] _HELD["active"] = True try: yield finally: _HELD["active"] = outer # --- installer/embedded.py --------------------------------------------------- # Frontends whose BIOS live on their SD card, installed from a computer the # 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) 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", ) # 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/model/region.py, which this file cannot import. # A test holds the two copies equal. WORLD_REGION = "world" REGION_TREE: dict[str, frozenset] = { "north-america": frozenset({"canada"}), "latin-america": frozenset({"brazil", "mexico", "argentina"}), "europe": frozenset({ "uk", "france", "germany", "italy", "spain", "netherlands", "portugal", "greece", "poland", "russia", "sweden", "norway", "denmark", "finland", }), "asia": frozenset({ "japan", "south-korea", "china", "taiwan", "hong-kong", "singapore", "india", "asia-ntsc", "asia-pal", }), "oceania": frozenset({"australia", "new-zealand"}), } REGION_ALIASES: dict[str, str] = { "jp": "japan", "ntsc-j": "japan", "us": "north-america", "usa": "north-america", "na": "north-america", "ntsc-u": "north-america", "eu": "europe", "pal": "europe", "kr": "south-korea", "korea": "south-korea", "auto": WORLD_REGION, "gb": "uk", "ca": "canada", "br": "brazil", "mx": "mexico", "ar": "argentina", "fr": "france", "de": "germany", "it": "italy", "es": "spain", "nl": "netherlands", "pt": "portugal", "gr": "greece", "pl": "poland", "ru": "russia", "se": "sweden", "no": "norway", "dk": "denmark", "fi": "finland", "cn": "china", "tw": "taiwan", "hk": "hong-kong", "sg": "singapore", "in": "india", "au": "australia", "nz": "new-zealand", } AREA_TERRITORIES: dict[str, frozenset] = { "asia-ntsc": frozenset({"taiwan"}), "asia-pal": frozenset({"china"}), } _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)) 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" def default_base_url(ref: str) -> str: """The project's own address for the file lists of ref.""" return ("https://raw.githubusercontent.com/Abdess/retrobios/" + urllib.parse.quote(ref, safe="")) _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, as ValueError. 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 raise ValueError(f"RETROBIOS_BASE_URL must use HTTPS, got {value!r}") # What --standalone reads, apart from the list every run downloads. STANDALONE_DIR = "standalone" class Remote(NamedTuple): """Where a run reads its lists and files: the revision, the base address, and whether RETROBIOS_BASE_URL chose that base.""" ref: str base: str overridden: bool @property def manifest_url(self) -> str: return f"{self.base}/install/{{platform}}.json" @property def targets_url(self) -> str: return f"{self.base}/install/targets/{{platform}}.json" @property def standalone_url(self) -> str: return f"{self.base}/install/{STANDALONE_DIR}/{{platform}}.json" @property def raw_file_url(self) -> str: return f"{self.base}/{{path}}" def remote_from_env() -> Remote: """The remote RETROBIOS_REF and RETROBIOS_BASE_URL name, ValueError for a base that is neither HTTPS nor loopback. A variable set but empty is unset, as every other reading of them takes it.""" ref = os.environ.get("RETROBIOS_REF") or DEFAULT_RELEASE_REF override = os.environ.get("RETROBIOS_BASE_URL") or "" if override: return Remote(ref, _checked_base_url(override), True) return Remote(ref, default_base_url(ref), False) # The remote main resolved, for the length of its run. _IN_USE: list[Remote] = [] @contextlib.contextmanager def remote_in_use(remote: Remote) -> Iterator[None]: """remote answers active_remote() until the block ends.""" _IN_USE.append(remote) try: yield finally: _IN_USE.pop() def active_remote() -> Remote: """The remote of this run: the one main resolved, else the one the environment names now, for a caller that did not come through main.""" return _IN_USE[-1] if _IN_USE else remote_from_env() 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 SITE_URL = "https://abdess.github.io/retrobios/" INSTALLER_PAGE = f"{SITE_URL}wiki/installer/" TROUBLESHOOTING_PAGE = f"{SITE_URL}wiki/troubleshooting/" # The one-line bootstraps the site serves: BOOTSTRAP_URL for sh, .ps1 after it # for PowerShell (scripts/sitebootstrap.py). BOOTSTRAP_URL = f"{SITE_URL}i" # 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 # --- installer/invocation.py ------------------------------------------------- # Options that take a value, as a hint gives them back. _VALUED_OPTIONS = ( "--system", "--core", "--emulator", "--region", "--target", "--cores-dir", "--save-dir", "--from-pack", "--from", "--manifest", ) # The options a choice at the questions sets, which replace the command's. _CHOICE_OPTIONS = ("--system", "--core", "--region", "--for-games", "--required-only") # The order every command given back writes its options in: the list, what # narrows it, where files are copied from, then how the run goes. The screen # wrote --manifest before --from and line mode after it, for one choice # An option not named here comes after them. _COMMAND_ORDER = ( "--manifest", "--from-pack", "--system", "--core", "--emulator", "--standalone", "--region", "--one-per-slot", "--source", "--find", "--for-games", "--required-only", "--all-files", "--target", "--no-game-data", "--installed-cores", "--cores-dir", "--every-board", "--declared-only", "--standalone-copies", "--save-dir", "--jobs", "--from", "--add-app", "--offline", "--check", "--dry-run", ) # The options that print a list and install nothing, in the order a run # names them. LISTING_FLAGS = (("--list-platforms", "list_platforms"), ("--list-targets", "list_targets"), ("--list-systems", "list_systems"), ("--list-cores", "list_cores"), ("--list-emulators", "list_emulators")) def listings_given(args: argparse.Namespace) -> list[str]: """The listing options of a run, as typed.""" return [flag for flag, attr in LISTING_FLAGS if getattr(args, attr)] def _command_rank(option: tuple[str, str | None]) -> int: flag = option[0] return _COMMAND_ORDER.index(flag) if flag in _COMMAND_ORDER else len(_COMMAND_ORDER) def package_command(prefix: str) -> str: """The command that ran the retrobios package, read from the environment it runs in. uvx runs it from uv's cache (~/.cache/uv/archive-v0/ with uv 0.12.9) and pipx run from pipx's (~/.cache/pipx/ with pipx 1.4.3), and neither leaves a retrobios command behind. pip, pipx install (pipx's venvs/) and uv tool install do.""" parts = re.split(r"[\\/]", prefix) if "archive-v0" in parts: return "uvx retrobios" if any(part in ("pipx", ".pipx") for part in parts) and "venvs" not in parts: return "pipx run retrobios" return "retrobios" class Invocation: """How this run was started, so that a hint gives the command back whole. A one-liner user has no install.py to run: install.sh and install.ps1 run a temporary copy and say so in RETROBIOS_BOOTSTRAP. And a hint that dropped --system turned a retry of 2 files into one of 8069. """ def __init__(self) -> None: self.os_type = "" self.options: list[tuple[str, str | None]] = [] # Per platform, what was chosen at the questions. self.chosen: dict[str, list[tuple[str, str | None]]] = {} def record(self, args: argparse.Namespace) -> None: """Keep every option that decides what a run installs or reports.""" options: list[tuple[str, str | None]] = [] for flag in _VALUED_OPTIONS: value = getattr(args, flag[2:].replace("-", "_"), None) values = value if isinstance(value, list) else [value] if value else [] options += [(flag, str(v)) for v in values] games = getattr(args, "for_games", None) if games is not None: options.append(("--for-games", None if games is True else str(games))) if getattr(args, "source", "full") != "full": options.append(("--source", args.source)) if getattr(args, "find", None): options.append(("--find", args.find)) for flag, on in ( ("--required-only", getattr(args, "required_only", False)), ("--all-files", getattr(args, "all_files", False)), ("--every-board", args.every_board), ("--installed-cores", args.installed_cores and not args.cores_dir), ("--no-game-data", args.no_game_data), ("--declared-only", args.declared_only), ("--one-per-slot", getattr(args, "one_per_slot", False)), ("--standalone", getattr(args, "standalone", False)), ("--standalone-copies", args.standalone_copies), ("--offline", offline_option(getattr(args, "offline", False))), ("--check", args.check), ("--dry-run", args.dry_run), ): if on: options.append((flag, None)) self.options = options def powershell(self) -> bool: """Whether the command is typed into PowerShell: its words and its line ends both read this (_continuation). The bootstrap names its shell, the system decides without one.""" bootstrap = os.environ.get("RETROBIOS_BOOTSTRAP") if bootstrap in ("ps1", "sh"): return bootstrap == "ps1" return (self.os_type or ("windows" if os.name == "nt" else "")) == "windows" def launcher(self, elevated: bool = False) -> str: """The command without its options, as the user typed it.""" bootstrap = os.environ.get("RETROBIOS_BOOTSTRAP", "") if bootstrap == "ps1": return f"&([scriptblock]::Create((irm {BOOTSTRAP_URL}.ps1)))" if bootstrap == "sh": return f"curl -fsSL {BOOTSTRAP_URL} | {'sudo ' if elevated else ''}sh -s --" if bootstrap == "pypi": return f"{'sudo ' if elevated else ''}{package_command(sys.prefix)}" python = "python" if self.os_type == "windows" else "python3" return f"{'sudo ' if elevated else ''}{python} install.py" def word(self, value: str) -> str: if self.powershell(): # A comma makes an array and @ a splat in PowerShell arguments. if re.fullmatch(r"[A-Za-z0-9_./:\\-]+", value): return value return "'" + value.replace("'", "''") + "'" return shlex.quote(value) def command( self, plat: str, dest: Path | str | None, elevated: bool = False, without: tuple[str, ...] = (), ) -> str: """The full command for plat and dest, a str dest being a placeholder.""" words = [self.launcher(elevated)] if plat: words += ["--platform", plat] if isinstance(dest, Path): words += ["--dest", self.word(str(dest.absolute()))] elif dest: words += ["--dest", dest] for flag, value in self.flags(plat): if flag in without: continue words += [flag] if value is None else [flag, self.word(value)] return " ".join(words) def flags(self, plat: str) -> list[tuple[str, str | None]]: """The options of the run for plat, in the command's order.""" options = self.options if plat in self.chosen: # A choice made at the questions replaces the narrowing the # command line gave: both were printed, and --system named # the systems of the first run and of the second. replaced = {*_CHOICE_OPTIONS, *(flag for flag, _value in self.chosen[plat])} options = [option for option in options if option[0] not in replaced] return sorted([*options, *self.chosen.get(plat, [])], key=_command_rank) _INVOCATION = Invocation() def installer_id() -> str: """The first twelve hex digits of this file's SHA-256, as the bootstraps pin it.""" try: return hashlib.sha256(Path(__file__).read_bytes()).hexdigest()[:12] except (OSError, NameError): return "unknown" # --offline, or this variable set to anything but 0, which every run the # full-screen interface starts inherits. RETROBIOS_OFFLINE stays the build # scripts' own: CI and the test suite set it for every process they start. OFFLINE_VARIABLE = "RETROBIOS_INSTALL_OFFLINE" def offline_option(given: bool) -> bool: """Whether a command given back to the user carries --offline: given, or RETROBIOS_INSTALL_OFFLINE set. sudo does not pass the variable on, and the command it was told to run fetched what the run had left out. Line mode and the screen build their commands with this one rule.""" return given or offline_requested() def offline_requested() -> bool: return os.environ.get(OFFLINE_VARIABLE, "") not in ("", "0") # --- 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") # 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 # 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 ------------------------------------------------------- def _plural(count: int, word: str) -> str: """Count and noun, so a run of one file does not read as machine output: 1 file, 2 files, 1 wrong copy, 2 wrong copies.""" if count == 1: return f"{count} {word}" if word.endswith("y") and word[-2:-1] not in tuple("aeiou"): return f"{count} {word[:-1]}ies" return f"{count} {word}s" def agree(count: int, one: str, many: str) -> str: """The verb a count takes: "1 needs", "2 need". Each count said with a verb reads it here: "1 need the internet" stood on the plan.""" return f"{count} {one if count == 1 else many}" def format_size(n: int) -> str: """Human-readable file size.""" if n < 1024: return f"{n} B" if n < 1024 * 1024: return f"{n / 1024:.1f} KB" if n < 1024 * 1024 * 1024: return f"{n / (1024 * 1024):.1f} MB" return f"{n / (1024 * 1024 * 1024):.1f} GB" # C0 and C1 controls, DEL and lone surrogates: a file, folder or core name # holding ESC would drive the terminal (clear it, or set the clipboard with # OSC 52) instead of being shown. _CONTROLS = re.compile("[\x00-\x1f\x7f-\x9f\ud800-\udfff]") def screen_text(text: str) -> str: """Text as a terminal shows it, every control character a "?".""" return _CONTROLS.sub("?", text) def _char_width(char: str) -> int: if unicodedata.combining(char) or unicodedata.category(char) in ("Mn", "Me", "Cf"): return 0 return 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1 def cell_width(text: str) -> int: """Terminal cells the text takes: a CJK character two, an accent none.""" return sum(_char_width(char) for char in text) def fit(text: str, width: int) -> str: """The text cut to width cells, never through a character.""" text = screen_text(text) kept: list[str] = [] used = 0 for char in text: size = _char_width(char) if used + size > width: break kept.append(char) used += size return "".join(kept) def _split_word(word: str, room: int) -> list[str]: """A word longer than room, cut after a slash where it can be: a path read /home/us and er/bios when cut anywhere.""" pieces = [] while cell_width(word) > room: head = fit(word, max(room, 1)) # After the last separator that fits, a Windows one too: cut where # a third of the room was left, a folder broke inside its name # ("Game Bo" / "y Advance"). cut = max(head.rfind("/"), head.rfind("\\")) + 1 if cut <= 1: cut = len(head) pieces.append(word[:cut]) word = word[cut:] return pieces + [word] if word else pieces def _is_path_word(word: str) -> bool: """A word that is a path: it breaks after a separator, never inside a name.""" return ("/" in word or "\\" in word) and not word.startswith(("http:", "https:")) _UNIT = re.compile(r"(B|KB|MB|GB)\b") def _glued_words(text: str) -> list[str]: """The words of text, a size kept with its unit: "5.1" / "KB" was broken across two lines of a 40-column headline.""" words: list[str] = [] for word in text.split(): if words and _UNIT.match(word) and re.fullmatch(r"\(?\d+(\.\d+)?", words[-1]): words[-1] += f" {word}" else: words.append(word) return words # A shell word: quoted parts kept with what they quote. _SHELL_WORD = re.compile(r"""(?:'[^']*'|"[^"]*"|[^\s'"]+|['"])+""") def _path_tail(text: str, width: int) -> str: """A path cut to its last folders that fit after ".../", as a person reads it on a narrow screen (".../retroarch/system"). Its last name is kept whole however long: cut in its middle, RetroArch_BIOS_Pack.zip read "Pack.zip".""" if cell_width(text) <= width: return text separator = "\\" if "\\" in text and "/" not in text else "/" parts = text.rstrip(separator).split(separator) tail = parts[-1] for part in reversed(parts[:-1]): longer = f"{part}{separator}{tail}" if cell_width(f"...{separator}{longer}") > width: break tail = longer return f"...{separator}{tail}" def _command_groups(text: str) -> list[str]: """A command's shell words as they stay together on a line: a long option with its value. "--platform" ended a line, its value on the next.""" groups: list[str] = [] for word in _SHELL_WORD.findall(text): last = groups[-1] if groups else "" if (last.startswith("--") and len(last) > 2 and " " not in last and "=" not in last and not word.startswith("-") and word != "|"): groups[-1] = f"{last} {word}" else: groups.append(word) return groups def _continuation(powershell: bool | None = None) -> str: """The character that ends a line of a command the shell reads on: a backtick in PowerShell, a backslash in sh. Asked as the command's words ask it: with RETROBIOS_OS=windows elsewhere one command had PowerShell's quotes and sh's line ends.""" return "`" if (_INVOCATION.powershell() if powershell is None else powershell) else "\\" def _command_wrap(text: str, width: int, indent: str = " ", powershell: bool | None = None) -> list[str]: """A command too wide for width, broken between its shell words, each line but the last ending with the continuation the shell accepts, so a copy of the lines runs as the command does. A line one group wide that fits only without the indent loses it. A path still wider keeps its last folders (_path_tail), said by TUI_SHORTENED: folded by the terminal, it read as broken inside a word. A web address is never cut.""" lead = text[:len(text) - len(text.lstrip(" "))] tail = " " + _continuation(powershell) groups = _command_groups(text) lines: list[str] = [] line = "" def close(done: str, last: bool) -> str: end = "" if last else tail prefix = lead + indent if lines else lead for fewer in (lead, ""): if cell_width(prefix + done + end) > width >= cell_width(fewer + done + end): prefix = fewer return prefix + done + end fitted: list[str] = [] for number, group in enumerate(groups): end = 0 if number == len(groups) - 1 else len(tail) room = width - cell_width(lead + indent) - end # A group is an option and its value: split at the first space, a # quoted value keeping its own. option, _space, value = (group.partition(" ") if group.startswith("--") and " " in group else ("", "", group)) if cell_width(group) > room and "://" not in value and _is_path_word(value.strip("'\"")): keep = cell_width(option) + 1 if option else 0 quote = value[0] if value[:1] in "'\"" and value[-1:] == value[:1] else "" bare = value[1:-1] if quote else value short = quote + _path_tail(bare, max(8, room - keep - 2 * len(quote))) + quote if option and cell_width(short) > room - keep: # The option and the name do not fit together: the value # on a line of its own, its name whole. fitted += [option, quote + _path_tail(bare, max(8, room - 2 * len(quote))) + quote] continue group = (f"{option} " if option else "") + short fitted.append(group) for number, group in enumerate(fitted): end = 0 if number == len(fitted) - 1 else len(tail) prefix = lead + indent if lines else lead longer = f"{line} {group}" if line else group if not line or cell_width(prefix + longer + (tail if end else "")) <= width: line = longer continue lines.append(close(line, False)) line = group lines.append(close(line, True)) return lines def _wrap(text: str, width: int, indent: str = " ", whole: str = "", powershell: bool | None = None) -> list[str]: """Lines of at most width cells, the ones after the first indented. whole keeps every word whole, a longer one alone on a line wider than width, which the terminal folds and a copy keeps in one piece: "text" for prose and paths, "command" for a command, whose words are shell words. A restore command was drawn split inside its URL and its folder, and a backup folder's dated name fell on a line of its own.""" if cell_width(text) <= width: return [text] if whole == "command": return _command_wrap(text, width, indent, powershell) lead = text[:len(text) - len(text.lstrip(" "))] lines: list[str] = [] line = "" words = _glued_words(text) if len(words) == 1 and _is_path_word(text.strip()): # A folder on a line of its own goes on at its own indent: the # rest of a save folder sat two cells under its start, the BIOS # folder's at its label's. indent = "" def close(done: str) -> str: # A line one word wide that fits without the indent loses it: one # cell too wide, a folder was folded by the terminal inside a word # ("syste" / "m"). The line's own lead too: a # pack path of 75 cells was folded at 80 columns under an indent # of 6. prefix = lead + indent if lines else lead if cell_width(prefix + done) > width >= cell_width(lead + done): prefix = lead elif cell_width(prefix + done) > width >= cell_width(done) and " " not in done: prefix = "" return prefix + done for word in words: # Kept whole, a path is still broken after a separator where it is # wider than the screen: the terminal folded it inside a name. A # command's words stay whole, copied as one. room = width - len(lead + indent) # A word that fits on a line of its own stays whole there (close). # A path only where it fits at the indent its line has: dropped to # fit, a folder stood at one indent and its neighbour at another. alone = lead + indent if (lines or line) and _is_path_word(word) else lead pieces = ([word] if whole == "command" or (whole and not _is_path_word(word)) or cell_width(alone + word) <= width else _split_word(word, room)) if len(pieces) > 1 and _is_path_word(word): # The path starts on the line it follows, broken at a separator # that fits there: "BIOS folder:" stood alone above its folder. prefix = lead + indent if lines else lead left = width - cell_width(prefix + line) - (1 if line else 0) head = _split_word(word, left)[0] if left >= 8 else "" if head.endswith(("/", "\\")) and head != word: pieces = [head, *_split_word(word[len(head):], room)] for index, piece in enumerate(pieces): prefix = lead + indent if lines else lead # The rest of a word broken at a slash joins it without a space: # a path was drawn "retroarch/ system", and copied wrong. longer = f"{line}{'' if index else ' '}{piece}" if line else piece # A path's pieces keep the indent, which they are cut to fit: # joined past it, the last piece of a folder lost its indent. if not line or cell_width(prefix + longer) <= width or ( lines and " " not in longer and cell_width(lead + longer) <= width and not _is_path_word(word)): line = longer else: lines.append(close(line)) line = piece lines.append(close(line)) 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, ...]] = { # mode: install, check, dry-run, list, remove (--remove, --delete-backup), # restore or pack (--pack, with --dry-run too). "start": ("schema", "installer", "mode"), # A folder detection could not look in, once each, before detect: the # probes under it counted as absent and the others went on. reason is # why in words (Permission denied). A kind of its own, since schema 1 # never adds a key to detect, and not an error: the run goes on. "unsearched": ("folder", "reason", "message"), # platforms: [{"platform", "name", "bios_dir"}], empty when none is found. "detect": ("os", "os_name", "platforms"), # stage: manifest (reason: network, not_found, invalid, clock for a # refused certificate under a clock set in the past, no_ca for no # trusted certificates on the machine, or no_ssl for a Python built # without ssl, unreadable for a --manifest file that cannot be read, # unavailable for the standalone layout --standalone needs) or detect # (reason: conflict, two # systems found on one machine, or not_found, the platform named with # --platform, or by a file list or a pack in a run without questions, # found nowhere and no folder to assume) or from (a folder named with --from, # reason: not_found, not_a_folder, unreadable, or system for the root # of the system and /proc, /sys, /dev) or dest (reason: unreadable, a # folder above it this user cannot open, not_a_folder, the BIOS folder # is a file or lies under one, or not_writable, the BIOS folder cannot # be created, a summary following) or option (reason: # unknown, a platform, target, system, core or emulator the run cannot # use, refused before any download, or not_recorded, the list does not # record what --system, --core, --region, --emulator or --standalone # reads) or cores (--installed-cores, reason: not_found, not_a_folder # or unreadable for the --cores-dir, none for no core installed) or # targets (the board list a run cannot go on without, reason: the # manifest's codes, http for a refused answer) or pack (--from-pack, # reason: invalid, other_platform for a pack of another platform, or # no_platform when none is named and the pack does not say) or space # (reason: drive_full, the drive cannot hold the download, after # no_space, before any file of the setup is written). "error": ("stage", "reason", "platform", "message"), # Right before the error of stage space: the BIOS folder, and the bytes # the run needs and the drive has free. A kind of its own, since schema # 1 never adds a key to error. "no_space": ("platform", "folder", "bytes_needed", "bytes_free"), # A folder named with --from, once read: the files it holds (counted # up to MAX_SCANNED_FILES, truncated past them), and the folders below # it on another drive, not entered. "scanned": ("folder", "files", "truncated", "other_drives"), # Before choices, once a list is read: the system here runs another # version than the one the list was built for (list_version, from the # manifest, installed_version, from the system's own version file). # message says it and what it means. Not written when either version # is unknown, and never a refusal. "version": ("platform", "list_version", "installed_version", "message"), # Before choices: the board the system or its card names, read with no # --target given. applied is whether the run keeps its cores' files # only, false for a board the platform's list does not name. message # says it. A kind of its own: the full-screen interface always gives # --dest, and the board was never applied there. "board": ("platform", "board", "applied", "message"), # --installed-cores, before choices, once per installed core the list # has no profile for: info is whether its .info was found, dests the # firmware paths it declares, kept whatever the narrowing drops. A # core with no .info keeps nothing it alone reads, and message says so. "unknown_core": ("platform", "core", "info", "dests", "message"), # Before the file events of a check: the systems the run's list lets # one choose among, --system aside, in id order (other for the files # no system names). What Choose systems lists, and what the plan counts # a --system out of: it said 12 where Choose systems listed 11. A kind # of its own, since schema 1 never adds a key to check. "choices": ("platform", "systems"), # Right after choices: the dests of the list's files the run sets aside # before any choice, those read from a save directory whose place is # not known among them, in list order. What Cores lists and counts is # the list without them: it listed 189 cores where --core accepted 181, # and an untick sent the 8 others to a run that refused them. A kind of # its own, since schema 1 never adds a key to choices. "set_aside": ("platform", "dests"), # state: present (hash verified), wrong_hash or missing. "file": ("platform", "dest", "systems", "size", "state"), "system": ("platform", "system", "name", "files", "present", "missing", "wrong_hash", "bytes_needed"), # The files in place being read, at most every half second, and the last. "checking": ("files_done", "files_total"), # --for-games: the games of the card being read (a cartridge hashed, a # disc's header read), at most every half second, and the last. "games_reading": ("files_done", "files_total"), # --for-games, once the games are read, before choices: the games # folder, the games found and those recognised by their content. # found: [{"system", "folder", "games", "recognised", "regions"}], # regions the ones kept where the games prove one, empty for every # region. fallback: [{"system", "folder", "name", "reason"}], each game # that got every BIOS of its system (reason: not_recognised, not_read, # region_unknown, unknown_set, no_parent). not_games: the other files # of the game folders. required_only: --required-only given. "games": ("platform", "folder", "games", "recognised", "found", "fallback", "not_games", "required_only"), # --for-games could not read what the games need (reason: offline, # network, invalid, stale, no_sets, no_folder): the run keeps every # file of the list, and message says why. "games_unavailable": ("platform", "reason", "message"), "check": ("platform", "name", "bios_dir", "files", "present", "missing", "wrong_hash", "bytes_needed", "data_missing", "not_installable"), # Right after check: the same counts over the files the platform's own # list declares (cores: null), and their dests in file-event order. A # kind of its own, since schema 1 never adds a key to the file event. "declared": ("platform", "files", "present", "missing", "wrong_hash", "bytes_needed", "dests"), # Right after declared: the files of the data trees to fetch (check's # data_missing) and the bytes they write. A kind of its own, since # schema 1 never adds a key to check. "data": ("platform", "files", "bytes"), # Right after data: the bytes the run writes on the drive of the BIOS # folder, the files missing or replaced and the data trees rebuilt # beside them. The number the run's refusal for space and both plans # hold against the free space. A kind of its own, since schema 1 never # adds a key to check. "space": ("platform", "bytes"), # A file to install that this machine already holds: misplaced in the # BIOS folder (folder is its bios_dir, reason says why in words) or in # a folder named with --from (reason empty). member names the ZIP member # when path is an archive, else "". Its copy is a downloaded event. "found": ("platform", "dest", "folder", "path", "member", "reason"), # What a folder named with --from holds that could not be read, of the # size of a file no copy was found for, or of no known size (a folder, # a ZIP that would not open). member as in found, reason in words. "unreadable": ("platform", "folder", "path", "member", "reason"), # The files of the list read from the frontend's save directory, and # where they go ( and stand for a folder per system or # per core), once that directory is known. Not written when it is not: # the summary's skipped then counts them (no_save_directory). "saves": ("platform", "files", "folder"), "download": ("platform", "files", "bytes"), "progress": ("files_done", "files_total", "bytes_done", "bytes_total"), # Right after each progress event, and once when the files of a # download event are done: bytes_done split into the bytes this machine # held (a copy found here, the pack, a resumed partial copy) and the # bytes the network brought. A speed is bytes_network over time. "transfer": ("bytes_local", "bytes_network"), "downloaded": ("dest", "ok", "reason", "size", "files_done", "files_total", "bytes_done", "bytes_total"), # failed: [{"dest", "reason"}]. skipped: [{"reason", "label", "files", # "required"}], the files the collection cannot supply. left_out: # [{"category", "label", "files", "dests"}], what --no-game-data left # out, empty without it. kept: [{"folder", "files", "bytes"}], the files # in place the run moved aside before replacing them (under --dry-run, # would move), one per backup folder, empty when none. "summary": ("mode", "installed", "up_to_date", "pending", "failed", "skipped", "left_out", "kept", "interrupted"), # --add-app, or yes to its question, after the summary: the RetroBIOS # app put on the handheld card (folder, its root) of system. dests are # the app's files below the root, written those this run wrote (none # when all were in place), kept the backup folders as in summary. # ok false with reason when it was refused or failed. "app": ("system", "folder", "ok", "reason", "dests", "written", "kept"), # The install record of the BIOS folder (path, beside it in # retrobios-backup). status: applied (before choices, its choice taken # as the run's because nothing on the command line chose), written # (before the summary, once the install placed files), unreadable (said # once and ignored) or not_written (the install itself unharmed). choice is # the recorded options as words, date when it was written, files the # files it holds for the platform. A kind of its own, since schema 1 # never adds a key to an existing kind. "record": ("platform", "folder", "path", "status", "choice", "date", "files", "message"), # --remove, before anything is removed (with --dry-run, all it writes): # the files that go (dests, in record order), their bytes, the systems # losing a file, kept [{"dest", "reason"}] for each file left (reason # one of REMOVAL_REASONS), gone the recorded files no longer there, # backup whether they are moved rather than deleted. message says it. # Written with files 0 when no record says what is the installer's. "removal_plan": ("platform", "folder", "files", "bytes", "systems", "dests", "kept", "gone", "backup", "message"), # Each file --remove took: ok false with reason when it stays, moved_to # the file's place in the backup with --backup, else "". "removed": ("platform", "dest", "size", "ok", "reason", "moved_to"), # Each file --restore put back from the backup folder to path. "restored": ("folder", "path", "size", "ok", "reason"), # A backup folder: listed by --backups, made by --remove --backup, or # deleted (not_deleted when a file stayed) by --delete-backup. date is # when it was made (local time), source remove for a removal's, install # for the files an install replaced. "backup": ("folder", "date", "files", "bytes", "source", "status", "message"), # --pack: planned (--dry-run), written or failed. files and bytes are # the pack's members, each stored once, size what it takes on disk, # parts each file written (the pack alone when it is one ZIP). "pack": ("platform", "path", "files", "bytes", "size", "parts", "status", "message"), "end": ("code",), } class EventStream: """The --events output: closed (nothing written) until opened.""" def __init__(self) -> None: self.stream: TextIO | None = None self._lock = threading.Lock() def open(self, stream: TextIO) -> None: self.stream = stream @property def on(self) -> bool: return self.stream is not None def emit(self, kind: str, **fields: object) -> None: if self.stream is None: return keys = EVENT_KEYS[kind] if set(fields) != set(keys): raise ValueError(f"event {kind}: keys {sorted(fields)} != {sorted(keys)}") # Every string a script reads goes through the terminal's filter, # a new line kept: a consumer printing a folder or a name obeyed # the control characters a card label or a list held. line = json.dumps({"event": kind, **{key: _clean_strings(fields[key], "\n") for key in keys}}) with self._lock: self.stream.write(line + "\n") self.stream.flush() EVENTS = EventStream() def _event_mode(args: argparse.Namespace) -> str: if getattr(args, "remove", False) or getattr(args, "delete_backup", None) is not None: return "remove" if getattr(args, "restore", None) is not None: return "restore" if getattr(args, "backups", False): return "list" if getattr(args, "pack", None) is not None: return "pack" if args.check: return "check" if args.dry_run: return "dry-run" if listings_given(args): return "list" return "install" def _event_exit_code(code: object) -> int: """The process status sys.exit(code) gives.""" if code is None: return 0 return code if isinstance(code, int) else 1 def _clean_strings(value: object, keep: str = "") -> object: """value with a "?" for each control character of its strings, keys included, those of keep left: the one filter between a list, a card or a config and the terminal, its paths refused before (_safe_relative_path).""" if isinstance(value, str): return _CONTROLS.sub(lambda found: found.group() if found.group() in keep else "?", value) if isinstance(value, dict): return _clean_mapping(value, keep) if isinstance(value, (list, tuple)): return [_clean_strings(item, keep) for item in value] return value def _clean_mapping(value: dict, keep: str = "") -> dict: """value with its keys and items through _clean_strings.""" return {_clean_strings(key, keep): _clean_strings(item, keep) for key, item in value.items()} # --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 # --- 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. """ 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) echo_detection(f" {screen_text(words)}") 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 _ready_to_place(written: Path, dest: Path, executable: bool) -> None: """Give verified bytes the mode a plain open() gives, executable where the repository file is, and clear the read-only attribute of the file they replace. The temporary file is private, and a folder written with sudo has to stay readable by the emulator's user.""" os.chmod(written, (0o777 if executable else 0o666) & ~_UMASK) _clear_read_only(dest) 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 read_local_json(path: Path, limit: int) -> object: """A JSON file of limit bytes at most. OSError when it cannot be read, ValueError saying why when it is too large or not JSON.""" with open(path, "rb") as handle: raw = handle.read(limit + 1) if len(raw) > limit: raise ValueError(f"it exceeds {limit} bytes") try: return json.loads(raw.decode("utf-8")) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise ValueError(f"not JSON ({exc})") from exc def write_atomically(path: Path, data: bytes) -> None: """Write data at path through a scratch file beside it, removed when the write fails. A scratch that cannot be removed is named in the error.""" fd, scratch = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".part") try: with os.fdopen(fd, "wb") as handle: handle.write(data) os.replace(scratch, path) except OSError as exc: if os.path.lexists(scratch): try: os.unlink(scratch) except OSError as left: exc.strerror = (f"{exc.strerror or exc}, and {scratch} stays " f"({left.strerror or left})") 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_value(cfg_path: Path, key: str) -> str | None: """The value of key in retroarch.cfg without its quotes, None when the config is unreadable, said like a closed folder, or does not set it.""" 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: name, sep, value = line.partition("=") if sep and name.strip() == key: return value.strip().strip('"').strip("'") return None 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. """ value = _retroarch_cfg_value(cfg_path, key) if value is None: return None if not value or value == "default": return app_dir / default return _expand_retroarch_path(value, app_dir, home) # 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]] = {} # Set by detection once it has read the configs: a lookup after it finds # nothing more by detecting again. _CONFIGS_READ: list[bool] = [] 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. A half-selected copy quotes one end only. """ text = raw.strip().strip("\"'").strip() # Under WSL, D: and D:\ are the Windows drive the screen calls D:. return _host_path(os.path.expanduser(os.path.expandvars(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") def _folder_answer(prompt: str, usage: str, default: bool, numbers: int = 0) -> str | None: """A folder question's answer: None for Enter on a default, else the text typed. q quits as at every other question, a folder named q being typed ./q: q was a folder created in the current one and filled. Enter with no default, or a number out of range that names no folder, says what to type: the question came back with no word.""" while True: raw = _ask(prompt) if not raw: if default: return None print(usage) continue if raw.lower() == "q": _quit() if raw.isdigit() and not 1 <= int(raw) <= numbers and not _is_dir(_typed_folder(raw)): print(usage) continue return raw def _numbers_hint(count: int) -> str: """" or 1 to N" after a question that takes a listed number, N rows.""" return "" if not count else " or 1" if count == 1 else f" or 1 to {count}" class ReadCounter: """Files read so far, as event_kind events and on the live line: the program driving the installer gets the count the terminal gets.""" def __init__(self, total: int, term: Terminal | None, event_kind: str, noun: str = "") -> None: self.total = total self.event_kind = event_kind self.noun = noun self.done = 0 self.evented = 0.0 self.drawn = 0.0 live = term is not None and term.live and not term.quiet self.stream = term.stream if live and term is not None else None def step(self, final: bool = False) -> None: now = time.monotonic() if EVENTS.on and (final or now - self.evented >= EVENT_PROGRESS_INTERVAL): self.evented = now EVENTS.emit(self.event_kind, files_done=self.done, files_total=self.total) if self.stream is not None and (final or now - self.drawn >= 0.1): self.drawn = now print(f"\r read {self.done}/{self.total}{self.noun}", end="", file=self.stream, flush=True) def end(self) -> None: if self.total: self.step(final=True) if self.stream is not None: print("\r\033[K", end="", file=self.stream, flush=True) # --- installer/paths.py ------------------------------------------------------ def _path_characters(value: object, field: str, colons: bool = True) -> str: """The character rules every manifest-controlled relative path meets. No backslash, control character, empty segment, trailing slash or drive prefix, and at most 1024 characters: on Windows a backslash or a C: segment leaves the folder the path is joined to. A segment that Windows reads as a drive (C:x, any segment of one letter and a colon in front) or that ends with a colon is refused wherever it stands, since a later segment is joined as a drive-relative path. ``colons`` keeps a colon inside a name: RetroDECK's ares reads bios/snes:st018.data.rom on Linux. A Windows host refuses it all the same, as an alternate data stream of the file before the colon. """ if not isinstance(value, str) or not value or len(value) > 1024: raise ValueError(f"invalid {field}") if ( "\\" in value or _CONTROLS.search(value) or "//" in value or value.endswith("/") or re.match(r"^[A-Za-z]:", value) ): # A control character is refused with NUL: a pack's member named # x]0;PWN.bin set the window title in the progress line, # and the file was written under that name. raise ValueError(f"unsafe {field}: {value!r}") for part in value.split("/"): if ":" not in part: continue if ( PureWindowsPath(part).drive or part.endswith(":") or not colons or os.name == "nt" ): raise ValueError(f"unsafe {field}: {value!r}") return value def _safe_relative_path(value: object, field: str, colons: bool = True) -> PurePosixPath: """Validate a manifest-controlled relative POSIX path.""" path = PurePosixPath(_path_characters(value, field, colons)) if path.is_absolute() or any(part in ("", ".", "..") for part in path.parts): raise ValueError(f"unsafe {field}: {value!r}") return path # The most folders a roms root climbs from the BIOS folder: two, as the rom # folders files of MinUI, NextUI, MyMinUI (../../Roms) and muOS (../../ROMS) # record it (platforms/romfolders/*.yml, roms_root.from_bios). MAX_ROMS_UPS = 2 def _roms_relation(value: object, field: str) -> tuple[int, PurePosixPath]: """A roms root relative to the BIOS folder: (folders up, names down). "." is the BIOS folder itself. Any other value climbs one to MAX_ROMS_UPS folders, then names plain folders: nothing climbs again once it went down, and nothing goes down without climbing first. """ if value == ".": return 0, PurePosixPath() path = PurePosixPath(_path_characters(value, field, colons=False)) parts = path.parts ups = next((i for i, part in enumerate(parts) if part != ".."), len(parts)) names = parts[ups:] if ( path.is_absolute() or not 1 <= ups <= MAX_ROMS_UPS or any(part in ("", ".", "..") for part in names) ): raise ValueError(f"unsafe {field}: {value!r}") return ups, PurePosixPath(*names) # The roots a list places files below by their place relative to the BIOS # folder: the roms root (ROCKNIX's /storage/roms) and the frontend's # configs folder (Batocera's /userdata/system/configs). RELATIVE_ROOTS = ("roms", "configs") def _relative_root(bios_path: Path, from_bios: str, root: str = "roms") -> Path | None: """A relative root of a BIOS folder, on the host's own path type. The BIOS folder's ancestor at the depth the relation climbs, then the named folders below it. None when the joined and normalized path is anything else. """ ups, names = _roms_relation(from_bios, f"{root}_directory.from_bios") if ups > len(bios_path.parents): return None ancestor = bios_path if not ups else bios_path.parents[ups - 1] expected = ancestor.joinpath(*names.parts) joined = Path(os.path.normpath(bios_path.joinpath(*PurePosixPath(from_bios).parts))) if joined != Path(os.path.normpath(expected)) or not _lexically_under(joined, ancestor): return None return expected def _lexically_under(candidate: Path, root: Path) -> bool: """Whether a path built from checked parts stays below *root*.""" try: Path(os.path.normpath(candidate)).relative_to(Path(os.path.normpath(root))) except ValueError: return False return True def _within(candidate: Path, root: Path) -> bool: """Whether *candidate* stays under *root* once both are resolved.""" try: (root / candidate.name).resolve().relative_to(root) except (OSError, ValueError): return False return True def _safe_target_dir(value: object, field: str) -> str: """Validate a manifest-controlled standalone-copy directory. These name emulator install directories, so unlike a BIOS destination they are legitimately absolute and outside the BIOS tree. What they must never do is climb: a '..' anywhere turns "copy next to the emulator" into "write wherever the manifest likes". """ if not isinstance(value, str) or not value or len(value) > 2048: raise ValueError(f"invalid {field}") if _CONTROLS.search(value): raise ValueError(f"unsafe {field}: {value!r}") parts = re.split(r"[\\/]", value) if any(part == ".." for part in parts): raise ValueError(f"unsafe {field}: {value!r}") return value # RetroDECK's settings folder below the home folder: retrodeck.json since the # cfg-to-json migration, which renames the old retrodeck.cfg to retrodeck.bak # (global.sh:149-153). RETRODECK_CONFIG = Path(".var") / "app" / "net.retrodeck.retrodeck" / "config" / "retrodeck" def _retrodeck_paths(retrodeck_json: Path) -> dict | None: """The paths table of retrodeck.json, None when it cannot be read.""" try: paths = json.loads(retrodeck_json.read_text(encoding="utf-8", errors="replace"))["paths"] except (OSError, ValueError, KeyError, TypeError): return None return paths if isinstance(paths, dict) else None def _moved_in(root: Path, paths: dict) -> dict[str, Path]: """Each RetroDECK folder that is no longer /.""" moved = {} for key, value in paths.items(): name = key[:-len("_path")] if key.endswith("_path") else "" if name and name != "rd_home" and isinstance(value, str) and value.strip(): place = Path(value.strip()) if place != root / name: moved[name] = place return moved class MovedFolders: """A platform whose folders move one by one: root -> {folder under the root: where it is now}. RetroDECK's per-folder move (RetroDECK 7786a849, functions/api_data_processing.sh:913-935) records each new place in retrodeck.json paths._path (config/retrodeck/retrodeck.json:3-23), and its manifest places files under bios/ and roms/ of the home folder. A root is looked up on first use, so a run given --dest that never detects places files where a detecting run does. Detection only fills the cache ahead. """ def __init__(self) -> None: self._lock = threading.Lock() self._by_root: dict[Path, dict[str, Path]] = {} def reset(self) -> None: with self._lock: self._by_root.clear() def record(self, root: Path, retrodeck_json: Path) -> None: """root's moved folders, as retrodeck_json lists them.""" paths = _retrodeck_paths(retrodeck_json) with self._lock: self._by_root[root] = _moved_in(root, paths) if paths is not None else {} def of(self, root: Path) -> dict[str, Path]: """root's moved folders: none unless root is RetroDECK's home folder.""" with self._lock: known = self._by_root.get(root) if known is not None: return known moved = self._look_up(root) with self._lock: return self._by_root.setdefault(root, moved) @staticmethod def _look_up(root: Path) -> dict[str, Path]: home = Path.home() paths = _retrodeck_paths(home / RETRODECK_CONFIG / "retrodeck.json") if paths is None: return {} rd_home = paths.get("rd_home_path") rd_root = Path(rd_home) if isinstance(rd_home, str) and rd_home else home / "retrodeck" if os.path.abspath(rd_root) != os.path.abspath(root): return {} return _moved_in(root, paths) MOVED = MovedFolders() # Resolved folder -> the same folder as the run names it: /sdcard is a link # to /storage/emulated/0 on Android, and one result named the BIOS folder # /sdcard/RetroArch/system and its backup in /storage/emulated/0/RetroArch. _SPELLED: dict[Path, Path] = {} def _note_spelling(root: Path) -> Path: """root resolved, its own spelling recorded for every path shown below the link it goes through (spelled).""" given, resolved = Path(os.path.abspath(root)), root.resolve() named, real = given, resolved while named.name == real.name and named != named.parent and real != real.parent: named, real = named.parent, real.parent if named != real: try: if Path(os.path.realpath(named)) == real: _SPELLED[real] = named except (OSError, ValueError): pass return resolved def spelled(path: Path | str) -> Path: """path in the form the run names its folders: below a link the BIOS folder was named through, the link's name (_note_spelling).""" path = Path(path) for real in sorted(_SPELLED, key=lambda each: len(each.parts), reverse=True): if path == real or real in path.parents: return _SPELLED[real] / path.relative_to(real) return path def _destination_path(root: Path, value: object) -> Path: """Place a manifest destination below *root*. The manifest cannot climb: _safe_relative_path refuses absolute paths, drive letters and '..'. Symbolic links met under the root are the user's own layout and are followed. EmuDeck links bios/shadps4/sys_modules into shadPS4's data directory, and the file has to land where the emulator reads it. """ relative = _safe_relative_path(value, "dest") moved = MOVED.of(root) if len(relative.parts) > 1 and relative.parts[0] in moved: return moved[relative.parts[0]].resolve() / Path(*relative.parts[1:]) return _note_spelling(root) / Path(*relative.parts) class SavePlace(NamedTuple): """The save directory a frontend's config names, whether it hands each core a folder of its own below it (RetroArch's sort_savefiles_enable, runloop.c runloop_path_set_redirect), and whether the file list's dests hold that folder (its save_directory.by_core).""" directory: Path by_core: bool listed_by_core: bool = True # BIOS folder -> where the files read below its frontend's save directory go, # set once the save directory is known (save_directory_for). _SAVE_DIRS: dict[Path, SavePlace] = {} # (BIOS folder, root) -> the platform's roms or configs folder, set by # place_relative_entries. _RELATIVE_DIRS: dict[tuple[Path, str], Path] = {} # (BIOS folder, emulator key) -> the emulator folder, set by # place_emulator_entries. _EMULATOR_DIRS: dict[tuple[Path, str], Path] = {} def _entry_place(root: Path, entry: dict) -> tuple[Path, object]: """The folder an entry's dest is relative to, and the dest. An entry with root: save is relative to the save directory the frontend hands the core, below the BIOS folder's frontend save directory and the core's own folder where the frontend sorts saves by core. Any other is relative to the BIOS folder. """ if entry.get("root") in RELATIVE_ROOTS: folder = _RELATIVE_DIRS.get((root, entry["root"])) if folder is None: raise ValueError(f"no {entry['root']} folder known for {entry.get('dest')}") return folder, entry.get("dest") if entry.get("root") == "emulators": key, _, rest = str(entry.get("dest")).partition("/") folder = _EMULATOR_DIRS.get((root, key)) if folder is None: raise ValueError(f"no emulator folder known for {entry.get('dest')}") return folder, rest if entry.get("root") != "save": return root, entry.get("dest") place = _SAVE_DIRS.get(root) if place is None: raise ValueError(f"no save directory known for {entry.get('dest')}") dest = entry.get("dest") folder = entry.get("core_folder") # No core_folder: the core reads the same place whether the frontend # sorts saves by core or not (an empty library_name, or Cemu adding its # own folder only where the directory is not named after it). if folder and isinstance(dest, str) and place.by_core != place.listed_by_core: if place.listed_by_core: dest = dest.split("/", 1)[1] if "/" in dest else dest else: dest = f"{folder}/{dest}" return place.directory, dest def _entry_path(root: Path, entry: dict) -> Path: """Where an entry is written, as _entry_place places it.""" return _destination_path(*_entry_place(root, entry)) def _entry_key(entry: dict) -> str: """What tells one entry of the list from another: its dest, below the BIOS folder, below the save directory or in an emulator's own folder. KNULLI lists its own fbneo/hiscore.dat in the BIOS tree and FB Alpha 2012's below the save directory, two files under one dest. NUL never appears in a dest.""" dest = str(entry.get("dest")) root = entry.get("root") if root == "emulator": # A path in one emulator's own folder: two emulators read two files. return f"emulator\0{','.join(entry.get('cores') or [])}\0{dest}" 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 read_mountinfo() -> str | None: """/proc/self/mountinfo, None where it cannot be read.""" try: return Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace") except OSError: return None def mount_point(field: str) -> str: """Field 5 of a mountinfo line, its space, tab, newline and backslash written as octal escapes (proc(5)).""" return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), field) 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 = mount_point(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 = read_mountinfo() except (OSError, subprocess.SubprocessError): return False return text is not None and fat_mounted(target, mountinfo_types(text)) # --- 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 entry_copies(entry: dict) -> list[dict]: """An entry and every copy another core reads at its place.""" return [entry, *(entry.get("alternatives") or []), *(entry.get("slot_choices") or [])] 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 folder name of a save entry.""" root = entry.get("root") if root not in (None, "save", "emulators", *RELATIVE_ROOTS) and not ( omitted and root == "emulator"): raise ValueError(f"invalid root for {dest}") if root == "emulators" and len(PurePosixPath(dest).parts) < 2: raise ValueError(f"an emulators entry names its folder first: {dest}") folder = entry.get("core_folder") if folder is None: return if root != "save": raise ValueError(f"core_folder outside root: save for {dest}") if len(_safe_relative_path(folder, f"core_folder of {dest}").parts) != 1: raise ValueError(f"core_folder must be one folder name for {dest}") def _check_relative_directories(data: dict) -> None: """The manifest's roms_directory and configs_directory, which every installable root: roms or root: configs entry needs.""" installable = [ entry for field in ("files", "case_variants") for entry in data.get(field) or [] if isinstance(entry, dict) ] for root in RELATIVE_ROOTS: field = f"{root}_directory" layout = data.get(field) if layout is None: if any(entry.get("root") == root for entry in installable): raise ValueError(f"entries below the {root} folder and no {field}") continue if ( not isinstance(layout, dict) or set(layout) != {"bios_folder", "from_bios"} or len(_safe_relative_path(layout["bios_folder"], f"{field}.bios_folder").parts) != 1 ): raise ValueError(f"invalid {field}") _roms_relation(layout["from_bios"], f"{field}.from_bios") def _check_emulators_directory(data: dict) -> None: """The manifest's emulators_directory, which every installable root: emulators entry needs.""" layout = data.get("emulators_directory") installable = [ entry for field in ("files", "case_variants") for entry in data.get(field) or [] if isinstance(entry, dict) ] if layout is None: if any(entry.get("root") == "emulators" for entry in installable): raise ValueError("entries in emulator folders and no emulators_directory") return if not isinstance(layout, dict) or set(layout) != {"bios_folder", "searched", "default", "config"}: raise ValueError("invalid emulators_directory") searched = layout["searched"] if ( not isinstance(searched, list) or not searched or layout["default"] not in searched or len(_safe_relative_path(layout["bios_folder"], "emulators_directory.bios_folder").parts) != 1 ): raise ValueError("invalid emulators_directory") for template in searched: if not isinstance(template, str) or template.count("{key}") != 1: raise ValueError("invalid emulators_directory.searched") _safe_relative_path( template.replace("{key}", "key"), "emulators_directory.searched", colons=False ) _safe_relative_path(layout["default"].replace("{key}", "key"), "emulators_directory.default", colons=False) _safe_relative_path(layout["config"], "emulators_directory.config", colons=False) def _check_save_directory(data: dict) -> None: """The manifest's save_directory, which every root: save entry needs.""" layout = data.get("save_directory") entries = [ entry for field in ("files", "case_variants", "omitted_files") for entry in data.get(field) or [] if isinstance(entry, dict) ] if layout is None: # An omission may name one: the list says the file exists and why # this platform cannot place it. installable = [ entry for field in ("files", "case_variants") for entry in data.get(field) or [] if isinstance(entry, dict) ] if any(entry.get("root") == "save" for entry in installable): raise ValueError("entries below the save directory and no save_directory") return if ( not isinstance(layout, dict) or set(layout) - {"by_system"} != {"folder", "by_core"} or not isinstance(layout["by_core"], bool) or layout.get("by_system", True) is not True or not _safe_relative_path(layout["folder"], "save_directory.folder").parts ): raise ValueError("invalid save_directory") if layout["by_core"]: # The core's folder heads each dest it names: dropped, never guessed, # where the frontend does not sort saves by core. for entry in entries: folder = entry.get("core_folder") dest = entry.get("dest") if folder and isinstance(dest, str) and dest.split("/", 1)[0] != folder: raise ValueError(f"{dest} does not start with its core_folder {folder}") def _check_tags(entry: dict, field: str, where: str) -> None: """A selection field is absent or a short list of short strings.""" value = entry.get(field) if value is None: return if ( not isinstance(value, list) or len(value) > MAX_SELECTION_TAGS or not all(isinstance(tag, str) and 0 < len(tag) <= 256 for tag in value) ): raise ValueError(f"invalid {field} for {where}") # What an alternative replaces on the entry it stands in for. _COPY_FIELDS = ( "sha1", "sha256", "size", "repo_path", "release_asset", "storage", "cores", "executable", ) def _check_omission(entry: dict, dest: str) -> None: """The fields of a file left out: an omitted entry, or the claim of a core with nothing held at a destination another core's copy serves.""" if not isinstance(entry.get("name"), str) or not entry["name"]: raise ValueError(f"invalid omitted file name for {dest}") if not isinstance(entry.get("system", ""), str): raise ValueError(f"invalid omitted system for {dest}") if not isinstance(entry.get("required"), bool): raise ValueError(f"invalid omitted required flag for {dest}") if entry.get("reason") not in OMISSION_REASONS: raise ValueError(f"invalid omission reason for {dest}") if "held" in entry and entry["held"] is not True: raise ValueError(f"invalid omitted held flag for {dest}") cores = entry.get("cores") if cores is not None and ( not isinstance(cores, list) or not all(isinstance(core, str) for core in cores) ): raise ValueError(f"invalid omitted cores list for {dest}") for field in SELECTION_FIELDS: _check_tags(entry, field, dest) def _check_download(entry: dict, where: str, dest: str) -> int: """The size, hashes, source and cores of one downloadable copy, and its size.""" size = entry.get("size") if isinstance(size, bool) or not isinstance(size, int) or not (0 <= size <= MAX_DOWNLOAD_SIZE): raise ValueError(f"invalid size for {dest}") sha1 = entry.get("sha1", "") sha256 = entry.get("sha256", "") if sha1 and (not isinstance(sha1, str) or not _SHA1_RE.fullmatch(sha1)): raise ValueError(f"invalid SHA1 for {dest}") if sha256 and ( not isinstance(sha256, str) or not _SHA256_RE.fullmatch(sha256) ): raise ValueError(f"invalid SHA256 for {dest}") if not sha1 and not sha256: raise ValueError(f"missing content hash for {dest}") release_asset = entry.get("release_asset") repo_path = entry.get("repo_path") if release_asset: asset = _safe_relative_path(release_asset, f"{where}.release_asset") if len(asset.parts) != 1: raise ValueError(f"release asset must be a basename: {release_asset}") elif repo_path: source = _safe_relative_path(repo_path, f"{where}.repo_path") if source.parts[0] != "bios": raise ValueError(f"repo_path outside bios/: {repo_path}") else: raise ValueError(f"no download source for {dest}") cores = entry.get("cores") if cores is not None and ( not isinstance(cores, list) or not all(isinstance(core, str) for core in cores) ): raise ValueError(f"invalid cores list for {dest}") if not isinstance(entry.get("executable", False), bool): raise ValueError(f"invalid executable flag for {dest}") return size def _check_slot(entry: dict, where: str, dest: str) -> int: """The copies a platform file takes as cores and systems drop, and the largest size.""" choices = entry.get("slot_choices", []) declared = entry.get("declared_choices") if declared is None and not choices: return 0 if ( entry.get("cores") is not None or not isinstance(choices, list) or not isinstance(declared, list) or not declared or len(choices) > MAX_SELECTION_TAGS or len(declared) > MAX_SELECTION_TAGS ): raise ValueError(f"invalid slot choices for {dest}") size = 0 for index, choice in enumerate(declared): systems = choice.get("systems") if isinstance(choice, dict) else None if ( not isinstance(systems, list) or not systems or not all(isinstance(s, str) for s in systems) or not set(choice) <= (set(_COPY_FIELDS) - {"cores"}) | {"systems"} ): raise ValueError(f"invalid declared choice for {dest}") size = max(size, _check_download(choice, f"{where}.declared_choices[{index}]", dest)) for index, choice in enumerate(choices): if ( not isinstance(choice, dict) or not choice.get("cores") or not set(choice) <= set(_COPY_FIELDS) ): raise ValueError(f"invalid slot choice for {dest}") # A choice naming only cores leaves the platform's own answer. if set(choice) != {"cores"}: size = max(size, _check_download( choice, f"{where}.slot_choices[{index}]", dest )) return size def _check_entry( entry: object, where: str, seen_destinations: set[str] ) -> tuple[int, int]: """Check one file entry, return its size and the largest copy it may fetch.""" if not isinstance(entry, dict): raise ValueError(f"{where} must be an object") # Below a roms or emulator folder a colon has no use: refused outright. dest = str(_safe_relative_path( entry.get("dest"), f"{where}.dest", colons=entry.get("root") not in ("emulators", *RELATIVE_ROOTS), )) key = _entry_key({**entry, "dest": dest}) if key in seen_destinations: raise ValueError(f"duplicate manifest destination: {dest}") seen_destinations.add(key) _check_root(entry, dest) size = _check_download(entry, where, dest) largest = size alternatives = entry.get("alternatives", []) if not isinstance(alternatives, list) or len(alternatives) > MAX_SELECTION_TAGS: raise ValueError(f"invalid alternatives for {dest}") for alt_index, alternative in enumerate(alternatives): if ( not isinstance(alternative, dict) or not alternative.get("cores") or not set(alternative) <= set(_COPY_FIELDS) ): raise ValueError(f"invalid alternative for {dest}") # Narrowing can swap in any copy: the cap holds for the largest. largest = max(largest, _check_download( alternative, f"{where}.alternatives[{alt_index}]", dest )) largest = max(largest, _check_slot(entry, where, dest)) absent = entry.get("absent_claims", []) if not isinstance(absent, list) or len(absent) > MAX_SELECTION_TAGS: raise ValueError(f"invalid absent claims for {dest}") for claim in absent: if not isinstance(claim, dict): raise ValueError(f"invalid absent claim for {dest}") _check_omission(claim, dest) for field in (*SELECTION_FIELDS, "declared_in"): _check_tags(entry, field, dest) _check_expert_fields(entry, dest) return size, largest def _check_expert_fields(entry: dict, dest: str) -> None: """`truth` and `slot`, what --source truth and --one-per-slot read.""" if "truth" in entry and entry["truth"] is not False: raise ValueError(f"invalid truth flag for {dest}") slot = entry.get("slot") if slot is None: return if not isinstance(slot, dict) or not {"groups", "keys"} <= set(slot) <= { "groups", "keys", "also"}: raise ValueError(f"invalid slot for {dest}") also = slot.get("also", []) if not isinstance(also, list) or len(also) > MAX_SELECTION_TAGS: raise ValueError(f"invalid slot for {dest}") for chain in [slot, *also]: if not isinstance(chain, dict) or not {"groups", "keys"} <= set(chain) or ( chain is not slot and set(chain) != {"groups", "keys"}): raise ValueError(f"invalid slot for {dest}") _check_slot_chain(chain, dest) def _check_slot_chain(chain: dict, dest: str) -> None: """One name's groups and the claims at each key its lookup tries.""" if not isinstance(chain.get("groups"), list): raise ValueError(f"invalid slot groups for {dest}") _check_tags(chain, "groups", dest) keys = chain["keys"] if not isinstance(keys, list) or len(keys) > MAX_SELECTION_TAGS: raise ValueError(f"invalid slot keys for {dest}") for claims in keys: if not isinstance(claims, dict) or not claims or len(claims) > MAX_SELECTION_TAGS: raise ValueError(f"invalid slot claims for {dest}") for name, claim in claims.items(): if not isinstance(claim, dict): raise ValueError(f"invalid slot claim for {dest}") ranks = claim.get("ranks") if (not isinstance(name, str) or not 0 < len(name) <= 256 or not set(claim) <= {"ranks", "regions", "sets"} or not isinstance(ranks, list) or not ranks or len(ranks) > MAX_SELECTION_TAGS or not all(rank is None or (isinstance(rank, int) and not isinstance(rank, bool)) for rank in ranks)): raise ValueError(f"invalid slot claim for {dest}") _check_tags(claim, "regions", dest) _check_tags(claim, "sets", dest) def _check_omitted_entry(entry: dict, dest: str) -> None: """An omission's fields, its cores' claims and its expert fields, the same for omitted_files and truth_omitted.""" _check_omission(entry, dest) _check_root(entry, dest, omitted=True) claims = entry.get("alternatives", []) if not isinstance(claims, list) or len(claims) > MAX_SELECTION_TAGS: raise ValueError(f"invalid omitted alternatives for {dest}") for claim in claims: claim_cores = claim.get("cores") if isinstance(claim, dict) else None if ( not isinstance(claim, dict) or set(claim) != {"cores"} or not isinstance(claim_cores, list) or not claim_cores or not all(isinstance(core, str) for core in claim_cores) ): raise ValueError(f"invalid omitted alternative for {dest}") for field in (*SELECTION_FIELDS, "declared_in"): _check_tags(entry, field, dest) _check_expert_fields(entry, dest) def _check_truth_lists(data: dict, seen_destinations: set[str]) -> int: """truth_files and truth_omitted, what --source truth adds to the list: each a valid entry, and the truth list it makes holds each destination once. Returns the largest size the truth files may fetch.""" files = data.get("truth_files") if files is None: if "truth_omitted" in data: raise ValueError("truth_omitted without truth_files") return 0 if not isinstance(files, list) or len(files) > MAX_MANIFEST_FILES: raise ValueError("invalid truth_files list") kept = {_entry_key(entry) for entry in data.get("files", []) if entry.get("truth", True)} seen: set[str] = set() largest = 0 for index, entry in enumerate(files): _size, most = _check_entry(entry, f"truth_files[{index}]", seen) largest += most if seen & kept: raise ValueError("truth_files repeats a destination the truth list keeps") omitted = data.get("truth_omitted", []) if not isinstance(omitted, list) or len(omitted) > MAX_MANIFEST_FILES: raise ValueError("invalid truth_omitted list") for index, entry in enumerate(omitted): if not isinstance(entry, dict): raise ValueError(f"truth_omitted[{index}] must be an object") dest = str(_safe_relative_path(entry.get("dest"), f"truth_omitted[{index}].dest")) _check_omitted_entry(entry, dest) return largest def _check_standalone_layouts(data: object, manifest: dict, plat: str) -> dict: """install/standalone/.json, checked as the list is: per emulator the list names, entries or [dest, sha1] pairs whose content the list carries. Returns the layouts.""" if not isinstance(data, dict) or data.get("schema") != 1 or data.get("platform") != plat: raise ValueError(f"it is no standalone layout of {plat}") layouts = data.get("standalone_layouts") if not isinstance(layouts, dict) or len(layouts) > MAX_SELECTION_TAGS: raise ValueError("invalid standalone_layouts") if sorted(layouts) != sorted(manifest.get("standalone_builds") or []): raise ValueError("its builds are not the ones the file list names") sizes = { copy["sha1"]: copy.get("size", 0) for entry in [*manifest.get("files", []), *(manifest.get("truth_files") or [])] for copy in entry_copies(entry) if isinstance(copy, dict) and copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset")) } for name, items in layouts.items(): if (not isinstance(name, str) or not 0 < len(name) <= 256 or not isinstance(items, list) or len(items) > MAX_MANIFEST_FILES): raise ValueError("invalid standalone_layouts entry") seen: set[str] = set() largest = 0 for index, item in enumerate(items): where = f"standalone_layouts[{name!r}][{index}]" if isinstance(item, list): if (len(item) != 2 or not isinstance(item[1], str) or item[1] not in sizes): raise ValueError(f"invalid {where}") key = _entry_key({"dest": str(_safe_relative_path(item[0], where))}) if key in seen: raise ValueError(f"duplicate destination in {where}") seen.add(key) largest += int(sizes[item[1]] or 0) else: largest += _check_entry(item, where, seen)[1] if largest > MAX_TOTAL_DOWNLOAD_SIZE: raise ValueError("standalone build size exceeds safety limit") return layouts def _check_data_directory_files(files: object, where: str) -> None: """A data directory's file list: relative paths, each with sha1 and size.""" if not isinstance(files, dict) or not files or len(files) > MAX_MANIFEST_FILES: raise ValueError(f"{where}.files is invalid") for rel, meta in files.items(): _safe_relative_path(rel, f"{where}.files") if ( not isinstance(meta, dict) or not isinstance(meta.get("sha1"), str) or not _SHA1_RE.fullmatch(meta["sha1"]) or not isinstance(meta.get("size"), int) or not 0 <= meta["size"] <= MAX_DOWNLOAD_SIZE ): raise ValueError(f"{where}.files[{rel!r}] is invalid") def _check_data_directory(entry: object, where: str) -> None: """A data directory: its source archive, its mapping, its file list.""" if not isinstance(entry, dict): raise ValueError(f"{where} must be an object") if not isinstance(entry.get("ref"), str) or not entry["ref"]: raise ValueError(f"{where}.ref is missing") if entry.get("dest", "") != "": _safe_relative_path(entry.get("dest"), f"{where}.dest") url = entry.get("url") parsed = urllib.parse.urlparse(url if isinstance(url, str) else "") if not (parsed.scheme == "https" or ( parsed.scheme == "http" and (parsed.hostname or "") in _LOOPBACK_HOSTS )): raise ValueError(f"{where}.url must use HTTPS") kind = entry.get("type") if kind not in ("zip", "tarball"): raise ValueError(f"{where}.type must be zip or tarball") strip = entry.get("strip_components", 0) if not isinstance(strip, int) or isinstance(strip, bool) or not 0 <= strip <= 16: raise ValueError(f"{where}.strip_components is invalid") size = entry.get("archive_size", 1) if not isinstance(size, int) or isinstance(size, bool) or size < 1: raise ValueError(f"{where}.archive_size is invalid") if kind == "tarball" and ( not isinstance(entry.get("source_path"), str) or not entry["source_path"] ): raise ValueError(f"{where}.source_path is missing") for field in ("exclude", "systems"): values = entry.get(field, []) if not isinstance(values, list) or not all(isinstance(v, str) for v in values): raise ValueError(f"{where}.{field} is invalid") for flag in ("optional", "rolling"): if entry.get(flag, True) is not True: raise ValueError(f"{where}.{flag} is invalid") cores = entry.get("cores", ["-"]) if not isinstance(cores, list) or not cores or not all(isinstance(c, str) and c for c in cores): raise ValueError(f"{where}.cores is invalid") _check_data_directory_files(entry.get("files"), where) def _check_manifest_entries(data: dict, files: list) -> tuple[set[str], int, int]: """The files and case_variants lists: their destinations, the declared total and the largest total a download can reach.""" seen_destinations: set[str] = set() total_size = 0 largest_total = 0 for index, entry in enumerate(files): size, largest = _check_entry(entry, f"files[{index}]", seen_destinations) total_size += size largest_total += largest if largest_total > MAX_TOTAL_DOWNLOAD_SIZE: raise ValueError("manifest total size exceeds safety limit") variants = data.get("case_variants", []) if not isinstance(variants, list) or len(variants) > MAX_MANIFEST_FILES: raise ValueError("invalid case_variants list") for index, entry in enumerate(variants): _size, largest = _check_entry( entry, f"case_variants[{index}]", seen_destinations ) largest_total += largest if largest_total > MAX_TOTAL_DOWNLOAD_SIZE: raise ValueError("manifest total size exceeds safety limit") return seen_destinations, total_size, largest_total def _check_manifest_directories(data: dict) -> None: """The data directories and the save, relative and emulators folders.""" data_dirs = data.get("data_directories", []) if not isinstance(data_dirs, list) or len(data_dirs) > MAX_SELECTION_TAGS: raise ValueError("invalid data_directories list") for index, entry in enumerate(data_dirs): _check_data_directory(entry, f"data_directories[{index}]") _check_save_directory(data) _check_relative_directories(data) _check_emulators_directory(data) def _check_omitted_list(omitted: list, seen_destinations: set[str]) -> None: """Each omitted file: an object at a destination no other entry holds.""" seen_omitted: set[str] = set() for index, entry in enumerate(omitted): if not isinstance(entry, dict): raise ValueError(f"omitted_files[{index}] must be an object") dest = str( _safe_relative_path( entry.get("dest"), f"omitted_files[{index}].dest" ) ) key = _entry_key({**entry, "dest": dest}) if key in seen_destinations or key in seen_omitted: raise ValueError(f"duplicate or conflicting omitted destination: {dest}") seen_omitted.add(key) _check_omitted_entry(entry, dest) def _check_manifest_mappings(data: dict) -> None: """The core and system mappings, the offered boards and the system titles.""" for field in ("core_names", "downloaded_cores", "system_cores", "system_names"): mapping = data.get(field) if mapping is None: continue if not isinstance(mapping, dict) or len(mapping) > MAX_MANIFEST_FILES: raise ValueError(f"invalid {field}") for key in mapping: if not isinstance(key, str) or not 0 < len(key) <= 256: raise ValueError(f"invalid {field} key") _check_tags(mapping, key, field) if mapping[key] is None: raise ValueError(f"invalid {field} for {key}") offered = data.get("offered_boards") if offered is not None: _check_offered_boards(offered) titles = data.get("system_titles") if titles is not None: _check_system_titles(titles) def _check_offered_boards(offered: object) -> None: """offered_boards: per name, the folders and boards it is offered on.""" if not isinstance(offered, dict) or len(offered) > MAX_MANIFEST_FILES: raise ValueError("invalid offered_boards") for key, places in offered.items(): if not isinstance(key, str) or not 0 < len(key) <= 256: raise ValueError("invalid offered_boards key") if not isinstance(places, list) or not all( isinstance(p, dict) and isinstance(p.get("folder"), str) and p.get("root") in ("roms", "install") and isinstance(p.get("boards"), list) and all(isinstance(b, str) for b in p["boards"]) for p in places ): raise ValueError(f"invalid offered_boards for {key}") def _check_system_titles(titles: object) -> None: """system_titles: a short title per system.""" if not isinstance(titles, dict) or len(titles) > MAX_MANIFEST_FILES: raise ValueError("invalid system_titles") for key, title in titles.items(): if not isinstance(key, str) or not 0 < len(key) <= 256: raise ValueError("invalid system_titles key") if not isinstance(title, str) or not 0 < len(title) <= 256: raise ValueError(f"invalid system_titles for {key}") def _check_copy_note(entry: dict, where: str) -> None: """A note of standalone_copies: its text and the detect lists.""" detect = entry.get("detect", {}) if not isinstance(entry["note"], str) or not isinstance(detect, dict): raise ValueError(f"invalid note entry at {where}") for values in detect.values(): if not isinstance(values, list) or not all( isinstance(value, str) for value in values ): raise ValueError(f"invalid note entry at {where}") def _check_copy_targets(entry: dict, index: int) -> None: """The target folders of a standalone copy.""" targets = entry.get("targets", {}) if targets and not isinstance(targets, dict): raise ValueError(f"invalid standalone copy targets at index {index}") for values in (targets or {}).values(): if not isinstance(values, list) or len(values) > 100: raise ValueError(f"invalid standalone copy targets at index {index}") for value in values: _safe_target_dir(value, f"standalone_copies[{index}].targets") def _check_standalone_copy(entry: object, index: int) -> None: """One entry of standalone_copies.""" if not isinstance(entry, dict): raise ValueError(f"standalone_copies[{index}] must be an object") # The shape do_standalone_copies reads, checked here: a note with a # list for detect, a copy naming neither file nor pattern, or a list # for emulator passed and crashed the copy step after the download. where = f"standalone_copies[{index}]" if "note" in entry: _check_copy_note(entry, where) return if "file" not in entry and "pattern" not in entry: raise ValueError(f"{where} names neither a file nor a pattern") if not isinstance(entry.get("emulator", ""), str): raise ValueError(f"invalid emulator at {where}") if "file" in entry: _safe_relative_path( entry["file"], f"standalone_copies[{index}].file" ) if "source" in entry: _safe_relative_path( entry["source"], f"standalone_copies[{index}].source" ) if "as" in entry and ( "file" not in entry or not isinstance(entry["as"], str) or PurePosixPath(_safe_relative_path( entry["as"], f"standalone_copies[{index}].as")).name != entry["as"] ): raise ValueError(f"invalid standalone copy name at {where}") if "pattern" in entry: pattern = entry["pattern"] if ( not isinstance(pattern, str) or not pattern or len(pattern) > 256 or "/" in pattern or "\\" in pattern or ".." in pattern ): raise ValueError(f"invalid standalone copy pattern: {pattern!r}") _check_copy_targets(entry, index) def _validate_manifest(data: object, plat: str) -> dict: """Validate the untrusted install-manifest boundary using stdlib only.""" if not isinstance(data, dict): raise ValueError("manifest root must be an object") if data.get("manifest_version") not in (1, 2): raise ValueError("unsupported manifest_version") if data.get("platform") != plat: raise ValueError("manifest platform does not match request") files = data.get("files") if not isinstance(files, list) or len(files) > MAX_MANIFEST_FILES: raise ValueError("invalid manifest files list") seen_destinations, total_size, largest_total = _check_manifest_entries(data, files) _check_manifest_directories(data) declared_total_files = data.get("total_files") if declared_total_files is not None and declared_total_files != len(files): raise ValueError("manifest total_files does not match files list") declared_total_size = data.get("total_size") if declared_total_size is not None and declared_total_size != total_size: raise ValueError("manifest total_size does not match file sizes") omitted = data.get("omitted_files", []) if not isinstance(omitted, list) or len(omitted) > MAX_MANIFEST_FILES: raise ValueError("invalid omitted_files list") _check_omitted_list(omitted, seen_destinations) if data.get("slot_fields", True) is not True: raise ValueError("invalid slot_fields") largest_total += _check_truth_lists(data, seen_destinations) if "standalone_builds" in data: _check_tags(data, "standalone_builds", "the file list") if largest_total > MAX_TOTAL_DOWNLOAD_SIZE: raise ValueError("manifest total size exceeds safety limit") declared_total_omitted = data.get("total_omitted") if ( declared_total_omitted is not None and declared_total_omitted != len(omitted) ): raise ValueError("manifest total_omitted does not match omitted_files") _check_manifest_mappings(data) copies = data.get("standalone_copies", []) if not isinstance(copies, list) or len(copies) > 10_000: raise ValueError("invalid standalone_copies") for index, entry in enumerate(copies): _check_standalone_copy(entry, index) # Its paths checked above, every other string (a system's title, a # core's name) is shown as the terminal shows text. return _clean_mapping(data) def _validate_targets(data: object) -> dict[str, dict]: """Validate and normalize legacy list-valued target manifests. A null core list means the target publishes no core inventory. That is a known target with no filter, not a broken manifest: rejecting it would discard every other target on the platform. """ if not isinstance(data, dict) or len(data) > 10_000: raise ValueError("invalid targets manifest") normalized: dict[str, dict] = {} for target, value in data.items(): if not isinstance(target, str) or not target or len(target) > 128: raise ValueError("invalid target name") if isinstance(value, dict): cores = value.get("cores") else: cores = value if cores is None: normalized[target] = {"cores": None} continue if not isinstance(cores, list) or len(cores) > 10_000 or not all( isinstance(core, str) and 0 < len(core) <= 256 for core in cores ): raise ValueError(f"invalid core list for target {target}") normalized[target] = {"cores": cores} images = value.get("images") if isinstance(value, dict) else None if images is None: continue if not isinstance(images, list) or len(images) > 10_000 or not all( isinstance(image, str) and 0 < len(image) <= 128 for image in images): raise ValueError(f"invalid image list for target {target}") normalized[target]["images"] = images return normalized # --- installer/refusal.py ---------------------------------------------------- class Refusal(SystemExit): """The run refused, with the error event a script reads and the lines a person reads. Each site printed its lines and chose on its own whether --events got the reason, and several did not: a script learned code 1 and nothing else. message is the event's, by default the lines joined without their leading "Error: ".""" def __init__(self, stage: str, reason: str, platform: str, *lines: str, code: int = 1, message: str | None = None) -> None: super().__init__(code) self.stage, self.reason, self.platform = stage, reason, platform self.lines = lines if message is None: message = " ".join(line.strip() for line in lines) if message.startswith("Error: "): message = message[len("Error: "):] self.message = message self.reported = False def report(self) -> None: """The error event, then the lines on stderr, once.""" if self.reported: return self.reported = True EVENTS.emit("error", stage=self.stage, reason=self.reason, platform=self.platform, message=self.message) for line in self.lines: print(line, file=sys.stderr) # --- 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", ) # 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: """A platform's name as the frontend writes it, the manifest's when it has one.""" named = (manifest or {}).get("display_name") if isinstance(named, str) and named.strip().isprintable() and 0 < len(named.strip()) <= 40: return named.strip() return PLATFORM_NAMES.get(plat, plat) def _name_key(name: str) -> str: """Letters and digits only: MiSTer FPGA, misterfpga and Mister-FPGA are one name.""" 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. """ raise Refusal("option", "unknown", platform, *lines, code=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. _SHARE_FOLDERS = { "batocera": "\\\\BATOCERA\\share\\bios", "recalbox": "\\\\RECALBOX\\share\\bios", } # What a handheld system writes on the games part a computer mounts, beside # its bios folder: a drive holding these is that card, and a data drive or # a stick with an emulation library holds none of them. # Each rule's values must all be there, with bios/, on a drive the system # does not call fixed (games_part). One system may have several rules: any # one of them is its proof. _GAMES_PART_RULES = ( # ArkOS and dArkOS mount EASYROMS as /roms. Every default tree ArkOS # ships for it holds bgmusic/, from the first one (christianhaitian/arkos # 9664c869, 2020-11-30, defaultromsfolderstructure.tar) through the # per-device trees of c14afbe5 (rg351p, rgb10, rk2020) to f41b9485, and # an RG351P card older than them gets it from the 11232020 update # (Update-RG351P.sh:238-242). launchimages/ is in every tree from # 495eb210 (2020-12-16) on. dArkOS daecf488 creates both # (game_systems.txt:23,54, finishing_touches.sh:288-290,420-430). # themes/ is no proof: the 12262020 update left it on the system part of # a card with under 1 GB free (Update-RGB10.sh:59-69), and 2020's trees # hold none. # Its list is RetroArch's, written in the bios folder of that part. _OsRule("retroarch", "ArkOS", "games_part", ("bgmusic",), "bios"), _OsRule("retroarch", "ArkOS", "games_part", ("launchimages",), "bios"), # AmberELEC 5a3882cb fills GAMES at every boot: homebrew/ from its ports # with gamelist.xml (packages/amberelec/sources/autostart.sh:93-94, # 110-113) and gamedata/ for RetroArch, PPSSPP, DOSBox and Hatari # (autostart.sh:123-145). Its list is written below that part's root. _OsRule(_STANDIN_MANIFESTS["AmberELEC"], "AmberELEC", "games_part", ("gamedata", "homebrew"), ""), # EmuELEC d4c7b2f1 copies its default bezels to EEROMS at every boot # (packages/sx05re/emuelec/bin/emuelec_autostart.sh:78-81). _OsRule(_STANDIN_MANIFESTS["EmuELEC"], "EmuELEC", "games_part", ("bezels/default.cfg",), ""), ) # GetDriveTypeW: DRIVE_FIXED, DRIVE_REMOTE, DRIVE_CDROM and DRIVE_RAMDISK, # none of them a card in a reader. _NOT_REMOVABLE_TYPES = (3, 4, 5, 6) def _drive_not_removable(mount: Path) -> bool: """Whether the system says mount is a drive no card sits in: a fixed disk, a network drive or a disc on Windows (GetDriveTypeW), a whole partition of a disk the kernel calls fixed elsewhere (_fixed_partition). False where it says nothing.""" if os.name == "nt": try: kind = _kernel32().GetDriveTypeW(str(mount)) except (AttributeError, OSError): return False return kind in _NOT_REMOVABLE_TYPES text = read_mountinfo() return text is not None and _fixed_partition(mount, text, Path("/sys")) def _fixed_partition(mount: Path, mountinfo: str, sys_root: Path) -> bool: """Whether mountinfo mounts a whole partition at mount whose disk sysfs calls fixed: removable at 0, neither on USB nor an MMC card. False for a folder bound in place, which is no whole drive, and for WSL's /mnt/d, a Windows drive Linux cannot classify.""" for line in mountinfo.splitlines(): fields = line.split(" ") if len(fields) < 5: continue point = mount_point(fields[4]) if point != str(mount): continue # Field 4 is the folder of the filesystem mounted there: "/" for a # whole partition, a folder for a bind mount (proc(5)). device = sys_root / "dev" / "block" / fields[2] if fields[3] != "/" or not _exists(device): return False try: real = device.resolve() disk = real.parent if _exists(real / "partition") else real if "/usb" in real.as_posix() or disk.name.startswith("mmcblk"): return False return (disk / "removable").read_text(encoding="ascii").strip() == "0" except OSError: return False return False def _games_part_matches(rule: _OsRule, root: Path) -> bool: """Whether root is the games part rule's system writes: its bios folder and every value of the rule on root's own drive, on a drive the system does not call fixed.""" return (_is_dir(root / "bios") and all(_exists(root / value) and _on_the_drive(root, value) for value in rule.values) and not _drive_not_removable(root)) def games_part(root: Path) -> _OsRule | None: """The rule naming the handheld system whose games part root is, by the files that system writes there, None for none (_GAMES_PART_RULES). The one reading of a games part, for the three systems alike: each is its system's own card everywhere (card_system, the first screen, the card routes, line mode). ArkOS's was a card "of a system that reads RetroArch's list", named nowhere and called a card RetroBIOS cannot tell on the ArkOS route.""" return next((rule for rule in _GAMES_PART_RULES if _games_part_matches(rule, root)), None) def card_platform(root: Path) -> str | None: """The frontend whose card ``root`` is, from the release name it wrote.""" for name, marker, prefix in _CARD_RULES: try: with open(root / marker, encoding="utf-8", errors="replace") as handle: first = handle.readline().strip() except OSError: continue if first.startswith(prefix): return name return None # A system that runs from its SD card names the card by where the device # mounts the part of it that holds the BIOS folder: on a computer that # part's root stands in for the mount point, and its device rule then reads # the same below the root. The specific mounts come before /mnt/, where # MiyooCFW mounts its MAIN part. The folders below them are the ones # _guides.yml handheld_guide gives each system, and a test holds the two # equal. _CARD_MOUNTS = ("/mnt/SDCARD/", "/mnt/plumos-user/", "/mnt/mmc/", "/storage/", "/roms/", "/mnt/") def _card_mount(path: str) -> str: """The card mount a device path lies under, "" for none.""" return next((mount for mount in _CARD_MOUNTS if path.startswith(mount)), "") # Systems whose card a computer sees as their data partition, by the file # their own build writes there, paths below that partition. KNULLI's is # /userdata, which S12populateshare fills from datainit (knulli-cfw # distribution ab3a6809, board/batocera/fsoverlay/etc/init.d/ # S12populateshare:93). The first rule is system/configs/emulationstation/ # about.info, which every board's datainit holds with the one line KNULLI # (board/batocera/*/fsoverlay/usr/share/batocera/datainit/system/configs/ # emulationstation/about.info), and which S12populateshare copies back at # each start when it is missing or older. EmulationStation reads it as the # system's name (knulli-cfw/batocera-emulationstation f7c5ae10, # es-app/src/ApiSystem.cpp:190-208) and no menu writes it. The second is # system.hostname=KNULLI in system/batocera.conf, which datainit sets # (datainit/system/batocera.conf:485) and the HOSTNAME row of the menu # rewrites (es-app/src/guis/GuiMenu.cpp:4092): a card renamed there was # read as a Batocera SHARE drive. ROCKNIX's is /storage: userconfig-setup:12 # copies /usr/config into /storage/.config, and its system.cfg sets # root.password=rocknix (ROCKNIX distribution 8b70f693, projects/ROCKNIX/ # packages/rocknix/config/system/configs/system.cfg:153). Nothing else there # names ROCKNIX: a password changed with setrootpass # (packages/rocknix/sources/scripts/setrootpass:25) leaves the card named # by nothing, never by another system. _SHARE_RULES: tuple[_OsRule, ...] = ( _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "file_matches", ("system/configs/emulationstation/about.info", r"\AKNULLI\s*$"), "bios"), _OsRule(_STANDIN_MANIFESTS["KNULLI"], "KNULLI", "file_matches", ("system/batocera.conf", r"^system\.hostname=KNULLI\s*$"), "bios"), _OsRule("rocknix", "ROCKNIX", "file_matches", (".config/system/configs/system.cfg", r"^root\.password=rocknix\s*$"), "roms/bios"), # Lakka's is /storage, its STORAGE partition (Lakka-LibreELEC v6.1, # packages/sysutils/busybox/scripts/fs-resize:31). RetroArch reads its # BIOS through /tmp/system, an overlay whose upper folder is # /storage/system (packages/lakka/retroarch_base/retroarch/system.d/ # tmp-system.mount:12). With HOME=/storage (config/retroarch-env.conf:1) # RetroArch writes .config/retroarch/retroarch.cfg from the /etc # skeleton at its first start (RetroArch 69a4f0ea, configuration.c: # 3650-3676), whose system_directory is that overlay (config/ # retroarch.cfg:3217): no other system we install for reads /tmp/system. _OsRule("lakka", "Lakka", "file_matches", (".config/retroarch/retroarch.cfg", r'^system_directory = "/tmp/system"\s*$'), "system"), # MiSTer's is its exFAT partition, /media/fat (Main_MiSTer e0a234f9, # file_io.cpp:1177), whose root holds the MiSTer binary and menu.rbf # (Distribution_MiSTer ce602319) and which reads each core's files # below games/ (GAMES_DIR, file_io.h:171). A card prepared on a # computer got RetroArch's list, or MiSTer's at its root. _OsRule("misterfpga", "MiSTer FPGA", "file_exists", ("MiSTer", "menu.rbf"), "games"), ) def _card_rules() -> list[_OsRule]: """The device rules that name a card, their paths below its root.""" rules = list(_SHARE_RULES) for rule in _EMBEDDED_RULES: if rule.method != "file_exists" or not rule.manifest or not rule.bios: continue # Only a file on the part its BIOS folder is on names the card: one # on its system part (/etc/main, /mnt/vendor) is not on it. mount = _card_mount(rule.bios) if mount and all(value.startswith(mount) for value in rule.values): rules.append(rule._replace( values=tuple(value[len(mount):] for value in rule.values), bios=rule.bios[len(mount):], configs=())) # The games part of a handheld system: the files it writes there name # the card as surely as Onion's .tmp_update (games_part), ArkOS's as # AmberELEC's. rules += list(_GAMES_PART_RULES) return rules def _card_rule_matches(rule: _OsRule, root: Path) -> bool: if rule.method == "games_part": return _games_part_matches(rule, root) if rule.method == "file_matches": path, pattern = rule.values try: text = (root / path).read_text(encoding="utf-8", errors="replace") except OSError: return False return (re.search(pattern, text, re.MULTILINE) is not None and _on_the_drive(root, path)) return (all(_exists(root / value) for value in rule.values) and all(_on_the_drive(root, value) for value in rule.values)) def _on_the_drive(root: Path, relative: str) -> bool: """Whether a marker below root is on root's own drive: /media/me holds the folder a card is mounted at as MUOS, and was read as a muOS card whose BIOS folder was the other card's MUOS/bios. A folder on the way that is a mount point is another drive (_card_boundary).""" points = _mount_points() folder = root for part in PurePosixPath(relative).parts: folder = folder / part if _card_boundary(folder, points): return False return True def card_system(root: Path) -> tuple[str, Path, str] | None: """(file list, BIOS folder, system name) of the card mounted at root. None when nothing on it names a system, or when two systems that would write to different folders both match: the card is then the user's to name, never a guess. """ plat = card_platform(root) if plat: return plat, root, display_name(plat) matched = _card_matches(root) if not matched: share = share_drive(root) return (share, root / "bios", display_name(share)) if share else None if len({(rule.manifest, rule.bios) for rule in matched}) != 1: return None rule = matched[0] return rule.manifest, root / (rule.bios or ""), rule.name # The SHARE drive of a system a computer reaches over the network, by the # file the system keeps on it, and both read bios/ beside it. Batocera's data # part (/userdata) holds system/batocera.conf, which S12populateshare copies # there (batocera.linux d1966272, board/batocera/fsoverlay/etc/init.d/ # S12populateshare:104) and which sets system.hostname=BATOCERA # (package/batocera/core/batocera-system/batocera.conf:103). Recalbox's # (/recalbox/share) holds system/recalbox.conf (recalbox 64b0fd40, # board/recalbox/fsoverlay/etc/init.d/S12populateshare:93), a name no menu # changes. KNULLI, built on Batocera, writes the same batocera.conf: its # rules (_SHARE_RULES) are read first, and a batocera.conf whose hostname # is neither system's own, on a drive no about.info names, is one of the # two renamed in its menu. That drive is said to be either (share_doubt), # never taken for one: a renamed KNULLI card was filled with Batocera's # list. Typed at the folder question, a drive was taken as the BIOS folder # and filled beside roms/ and system/, where neither reads. _SHARE_DRIVES: tuple[tuple[str, str], ...] = ( ("batocera", "system/batocera.conf"), ("recalbox", "system/recalbox.conf"), ) _HOSTNAME_LINE = re.compile(r"^system\.hostname=(.*?)\s*$", re.MULTILINE) def _share_markers(root: Path) -> list[str]: """The platforms whose SHARE drive file is on root's own drive.""" return [plat for plat, marker in _SHARE_DRIVES if _is_file(root / marker) and _on_the_drive(root, marker)] def _share_hostname(root: Path) -> str | None: """The hostname system/batocera.conf on root sets, "" when it sets none, None when the file cannot be read.""" try: text = (root / "system" / "batocera.conf").read_text(encoding="utf-8", errors="replace") except OSError: return None found = _HOSTNAME_LINE.findall(text) return found[-1] if found else "" def share_drive(root: Path) -> str | None: """The platform whose SHARE drive root is, by its own files, or None: for none, and for files that name two systems (share_doubt).""" markers = _share_markers(root) if len(markers) != 1: return None if markers == ["batocera"] and _share_hostname(root) not in ("", "BATOCERA"): return None return markers[0] def share_doubt(root: Path) -> tuple[tuple[str, ...], str]: """(platforms, why) for a drive whose files fit more than one system, ((), "") for any other: a batocera.conf renamed in its menu, with no file KNULLI alone writes, or the files of Batocera and Recalbox both.""" if card_platform(root) or _card_matches(root): return (), "" markers = _share_markers(root) if len(markers) > 1: return tuple(markers), "it holds system/batocera.conf and system/recalbox.conf" if markers == ["batocera"]: hostname = _share_hostname(root) if hostname not in ("", "BATOCERA"): return ((_STANDIN_MANIFESTS["KNULLI"], "batocera"), f"its system/batocera.conf names the host {screen_text(hostname or '?')}, " "which the menus of KNULLI and Batocera both set") return (), "" def _doubt_kinds(plats: tuple[str, ...]) -> str: """The systems a drive could be, in words: a KNULLI card or a Batocera SHARE drive.""" return " or ".join(f"{_a(display_name(plat))} " f"{'SHARE drive' if plat in _SHARE_FOLDERS else 'card'}" for plat in plats) def doubt_words(root: Path) -> str: """What is said of a mounted drive share_doubt cannot name, and how to name it: the same words on the first screen and in line mode.""" plats, why = share_doubt(root) if not plats: return "" shown = shown_path(root) kinds = _doubt_kinds(plats) names = " or ".join(f"--platform {plat} --dest {shown}" for plat in plats) return f"{shown} could be {kinds}: {why}. Name it: {names}." def drive_kind(system: tuple[str, Path, str]) -> str: """What a drive card_system read is, in words: an Onion card, a Batocera SHARE drive.""" return "SHARE drive" if system[0] in _SHARE_FOLDERS else "card" def _card_matches(root: Path, above: bool = False) -> list[_OsRule]: """The card rules root matches, a system another one is built on left out for it. above is for a folder above the one named: a rule that is one bare folder name (muOS's MUOS) then needs the system's BIOS folder too, a folder of backups holding a MUOS copy being no muOS card.""" matched = [rule for rule in _card_rules() if _card_rule_matches(rule, root) and not (above and _bare_marker(rule) and not _is_dir(root / (rule.bios or "")))] bases = {rule.base for rule in matched if rule.base} return [rule for rule in matched if rule.name not in bases] def _bare_marker(rule: _OsRule) -> bool: """Whether a card rule is only folder names any folder can hold.""" return rule.method == "file_exists" and all( "/" not in value and not value.startswith(".") for value in rule.values) class CardSetup(NamedTuple): """A system that runs from its SD card, as a computer sees that card.""" name: str plat: str # Its BIOS folder below the card's root, "" for the root itself. below: str # The rules that tell its card by the files on it: none when every file # that names the system is on another part of the card (/etc, /usr). rules: tuple = () # A card its rules do not match may still be its card: a share the # system fills when it first starts. fresh: bool = False def known(self) -> bool: """Whether the files on a card can say it is this system's.""" return self.plat in CARD_PLATFORMS or bool(self.rules) def card_setups() -> list[CardSetup]: """Every system that runs from its SD card, with the folder its device reads below the card's root. The MinUI family is told by its card's version.txt, KNULLI and ROCKNIX by the share they fill, and each system that gets RetroArch's list by its device rule, whose BIOS folder lies on one of _CARD_MOUNTS. The setup list, its filter, --platform, the line questions and every check of a card read this list: a second one kept by hand left UnofficialOS, ArkOS and MiyooCFW on this computer's RetroArch folder. """ rules = _card_rules() setups = [CardSetup(display_name(plat), plat, "") for plat in AVAILABLE_PLATFORMS if plat in CARD_PLATFORMS] # KNULLI is named by two files: one setup holding both rules. shares = {rule.name: tuple(each for each in _SHARE_RULES if each.name == rule.name) for rule in _SHARE_RULES} setups += [CardSetup(name, rules[0].manifest, rules[0].bios or "", rules, True) for name, rules in shares.items()] # AmberELEC and EmuELEC mount their card's games part as /storage/roms, # the folder their list is written below: AmberELEC 5a3882cb fs-resize # formats it exFAT as GAMES (packages/sysutils/busybox/scripts/ # fs-resize:64), autostart.sh:93 fills it as "the GAMES volume". EmuELEC # d4c7b2f1 makes EEROMS (fs-resize:127-140), mount_romfs.sh:10-14 mounts # it there. A computer sees that part's root, told by what each writes # there at every boot (_GAMES_PART_RULES): a card not started once # holds none of it yet, as a KNULLI card before its first start. setups += [CardSetup(name, plat, "", tuple(rule for rule in rules if rule.name == name), True) for name, plat in _STANDIN_MANIFESTS.items() if name in _GAMES_PART_CARDS] for name in _systems_reading().get("retroarch", []): below = next((rule.bios[len(_card_mount(rule.bios)):] for rule in _EMBEDDED_RULES if rule.name == name and rule.bios and _card_mount(rule.bios)), "") if below: own = tuple(rule for rule in rules if rule.name in (name, _built_on(name))) # Told by the games part alone, as AmberELEC's: a card that holds # none of it yet is taken as named, said so. setups.append(CardSetup(name, "retroarch", below, own, bool(own) and all(rule.method == "games_part" for rule in own))) return setups # The systems whose list is written below their card's games part, which a # computer sees as a drive of its own beside the system part (card_setups). _GAMES_PART_CARDS = ("AmberELEC", "EmuELEC") def setup_bios_folder(plat: str, path: Path) -> Path: """The BIOS folder a setup found is announced with, before its list is read: a MinUI card's Bios below its root, the folder found else. The first screen and line mode's Found named /media/me/MINUI, the plan then /media/me/MINUI/Bios. An AmberELEC or EmuELEC games part, whose list writes bios/ below its root (shown_bios_folder), is announced by that bios folder.""" if plat in CARD_PLATFORMS: return path / "Bios" rule = games_part(path) if plat in _STANDIN_MANIFESTS.values() else None return path / "bios" if rule is not None and rule.manifest == plat else path def setup_folders(setups: list) -> dict: """The BIOS folder each found setup announces, keyed by (platform, folder), read once for a screen that shows them on every frame.""" return {(plat, path): setup_bios_folder(plat, path) for plat, path, *_rest in setups} def card_setup(named: str, plat: str) -> CardSetup | None: """The card setup a name stands for with plat's list: a system by its own name, or a list that is one (MinUI). RetroArch names a list, not a card.""" key = _name_key(named) return next((setup for setup in card_setups() if setup.plat == plat and ( plat in CARD_PLATFORMS or (key and key == _name_key(setup.name)))), None) 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 from the same filesystem (a stick bound inside a muOS card's mount).""" text = read_mountinfo() if text is None: return frozenset() return frozenset(mount_point(fields[4]) for fields in (line.split(" ") for line in text.splitlines()) if len(fields) > 4) def _is_mount(folder: Path, points: frozenset | None = None) -> bool: """Whether a drive is mounted at folder, probed as detection probes.""" if str(folder) in (_mount_points() if points is None else points): return True return _probed(lambda: os.path.ismount(folder), folder) def _card_boundary(folder: Path, points: frozenset | None = None) -> bool: """Whether folder is where a drive is mounted: no folder above it is on the same card. /media/me holds a card mounted as MUOS, and is no muOS card for it.""" return _is_mount(folder, points) or folder in _mounted_cards() def card_bound(named: str, plat: str) -> tuple[str, str] | None: """(system name, BIOS folder below the card root) when what --platform named runs from an SD card, else None. `--platform onion` gets RetroArch's list, and on a computer that list's default folder is the computer's own RetroArch: the files went there, which Onion never reads. --platform retroarch names a list, not a card. """ setup = card_setup(named, plat) return (setup.name, setup.below) if setup else None def _mount_name(mount: Path) -> str: """How a person names a mounted card: E:\\ on Windows, its label elsewhere. Under WSL /mnt/d is the Windows D: drive, which "d" did not say.""" if (_WSL["active"] and mount.parent == Path(_WSL["root"]) and len(mount.name) == 1 and mount.name.isalpha()): return f"{mount.name.upper()}:" # The label is whoever formatted the card's: shown, never obeyed. return screen_text(mount.name or str(mount)) def _mounted_cards() -> list[Path]: """Mount points of removable media, where a card or a share appears. A handheld's card is most often prepared on a PC with a card reader: on Windows every drive but the system one may be that card. """ if os.name == "nt": system = os.environ.get("SYSTEMDRIVE", "C:").upper() return [Path(f"{letter}:\\") for letter in "DEFGHIJKLMNOPQRSTUVWXYZ" if f"{letter}:" != system and os.path.exists(f"{letter}:\\")] found: list[Path] = [] for root in (Path("/media"), Path("/run/media"), Path("/mnt"), Path("/Volumes")): try: children = sorted(root.iterdir()) except OSError: continue for child in children: # WSL's own mounts, and the Windows system drive, hold no card. if child.name in ("wsl", "wslg") or (root.name == "mnt" and child.name == "c"): continue if os.path.ismount(child): found.append(child) elif root.name in ("media", "run") or root == Path("/run/media"): # /media//