From e9f6fe43a0853faa78d0943d5b8c710156763bf8 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 01:37:28 +0100 Subject: [PATCH] refactor: split the installer into a package install.py held 31,575 lines and 1,370 definitions in one module. Its source is now installer/, 45 modules by concern, each importing from the others what it uses, so ruff and mypy read every module on its own. scripts/build_installer.py joins them back into install.py in import order, with one block of standard library imports and the zlib and unicodedata guard. It refuses an import from outside the standard library, a name two modules define, an import cycle, a renamed import and an import-time read of a name from a later module. install.py stays one stdlib-only file for the bootstraps, the launchers and PyPI. The split was written by a script, statement by statement: every top-level statement of the old file is in the new one with the same AST. Two tests that located code by its neighbour now read it by name. --- install.ps1 | 2 +- install.py | 29920 ++++++++++++++++---------------- install.sh | 2 +- install/launchers/index.json | 16 +- installer/__init__.py | 13 + installer/app.py | 401 + installer/arguments.py | 413 + installer/cards.py | 852 + installer/choices.py | 342 + installer/cli.py | 523 + installer/constants.py | 256 + installer/cores.py | 436 + installer/datadirs.py | 461 + installer/detect_frontends.py | 828 + installer/detect_os.py | 968 ++ installer/download.py | 567 + installer/embedded.py | 816 + installer/events.py | 253 + installer/from_folders.py | 1333 ++ installer/games.py | 1661 ++ installer/invocation.py | 188 + installer/line_ui.py | 1456 ++ installer/local_files.py | 595 + installer/manifest.py | 769 + installer/narrowing.py | 743 + installer/network.py | 480 + installer/offline.py | 114 + installer/outcome.py | 833 + installer/pack.py | 949 + installer/pack_source.py | 462 + installer/paths.py | 332 + installer/plan.py | 300 + installer/platform_choice.py | 154 + installer/probe.py | 174 + installer/prompt.py | 68 + installer/record.py | 1059 ++ installer/removal.py | 1011 ++ installer/run.py | 2159 +++ installer/setups.py | 629 + installer/standalone.py | 309 + installer/tally.py | 320 + installer/terminal.py | 508 + installer/text.py | 281 + installer/tui_actions.py | 1129 ++ installer/tui_results.py | 648 + installer/tui_rows.py | 1684 ++ installer/tui_session.py | 1320 ++ installer/tui_state.py | 929 + installer/tui_text.py | 451 + installer/tui_update.py | 745 + installer/tui_view.py | 2334 +++ scripts/build_installer.py | 373 + tests/test_build_installer.py | 164 + tests/test_install_tui.py | 7 +- tests/test_site_wiki.py | 8 +- 55 files changed, 48840 insertions(+), 14908 deletions(-) create mode 100644 installer/__init__.py create mode 100644 installer/app.py create mode 100644 installer/arguments.py create mode 100644 installer/cards.py create mode 100644 installer/choices.py create mode 100644 installer/cli.py create mode 100644 installer/constants.py create mode 100644 installer/cores.py create mode 100644 installer/datadirs.py create mode 100644 installer/detect_frontends.py create mode 100644 installer/detect_os.py create mode 100644 installer/download.py create mode 100644 installer/embedded.py create mode 100644 installer/events.py create mode 100644 installer/from_folders.py create mode 100644 installer/games.py create mode 100644 installer/invocation.py create mode 100644 installer/line_ui.py create mode 100644 installer/local_files.py create mode 100644 installer/manifest.py create mode 100644 installer/narrowing.py create mode 100644 installer/network.py create mode 100644 installer/offline.py create mode 100644 installer/outcome.py create mode 100644 installer/pack.py create mode 100644 installer/pack_source.py create mode 100644 installer/paths.py create mode 100644 installer/plan.py create mode 100644 installer/platform_choice.py create mode 100644 installer/probe.py create mode 100644 installer/prompt.py create mode 100644 installer/record.py create mode 100644 installer/removal.py create mode 100644 installer/run.py create mode 100644 installer/setups.py create mode 100644 installer/standalone.py create mode 100644 installer/tally.py create mode 100644 installer/terminal.py create mode 100644 installer/text.py create mode 100644 installer/tui_actions.py create mode 100644 installer/tui_results.py create mode 100644 installer/tui_rows.py create mode 100644 installer/tui_session.py create mode 100644 installer/tui_state.py create mode 100644 installer/tui_text.py create mode 100644 installer/tui_update.py create mode 100644 installer/tui_view.py create mode 100644 scripts/build_installer.py create mode 100644 tests/test_build_installer.py diff --git a/install.ps1 b/install.ps1 index 5cb32b8b1..62fb41c14 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "4a820bbfc7ed86b684a6fda8db0b19c3c021950b4ab3f1d9f861807afbf6ec7b" + $defaultInstallSha256 = "23d7586b7fac5e0e98e9f5e68cc389e2557cc448fc6e4329bd6ee322e8df32a6" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index 73ef7c0fc..b01d5549b 100644 --- a/install.py +++ b/install.py @@ -1,4 +1,6 @@ #!/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 @@ -63,6 +65,9 @@ except ImportError as _missing: "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr) sys.exit(1) + +# --- installer/constants.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. @@ -291,39 +296,6 @@ DEFAULT_DESTS = { "romm": Path("/romm/library/bios"), } - -def _os_default_dests(os_type: str) -> dict[str, Path]: - """Where a platform keeps its BIOS on this OS, when it is not detected. - - The same folders the platform's detection looks for: a platform named on - the command line but not found must not land in ~/bios, which none of - them reads. - """ - if os_type == "windows": - return { - # RetroArch's system directory defaults to \system - # (platform_win32.c), and its installer to C:\RetroArch-Win64. - "retroarch": _host_path("C:/RetroArch-Win64/system"), - # RetroBat's installer defaults to C:\RetroBat (installer.iss). - "retrobat": _host_path("C:/RetroBat/bios"), - # EmuDeck's Windows edition: C:\Emulation when its settings name - # no folder (emudeck-we functions/all.ps1:12-14). - "emudeck": _host_path("C:/Emulation/bios"), - } - if os_type == "wsl": - # RetroArch may be the Linux one inside the distribution, while RetroBat - # only exists on the Windows side, reached through /mnt/c. - return { - "retroarch": _unix_retroarch_base() / "system", - "retrobat": _host_path("C:/RetroBat/bios"), - } - if os_type == "darwin": - return {"retroarch": _macos_retroarch_base() / "system"} - return { - "retroarch": _unix_retroarch_base() / "system", - } - - # 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() @@ -344,6 +316,2109 @@ _UMASK = os.umask(0) os.umask(_UMASK) +# --- 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", +) + + +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/offline.py ---------------------------------------------------- + +class LocalSources: + """Where this run reads instead of the network: a file list, a pack, the + folders it copies BIOS files from.""" + + def __init__(self) -> None: + self.manifest: Path | None = None + self.pack: PackSource | None = None + # The folders named with --from, read once for every platform. + self.folders: list[FolderIndex] = [] + # The reads at once of the files in place (--jobs). + self.jobs: int = 8 + # Every folder index of the run still in use, closed at its end. + self.indexes: weakref.WeakSet[FolderIndex] = weakref.WeakSet() + self._serves: tuple = (None, None, frozenset()) + + def serves(self) -> frozenset: + """The platforms the file list or pack given to this run is for, + empty when none is given. The setup list offers those alone: after + o, Batocera was listed for a RetroArch list, and refused once its + folder was asked.""" + if self._serves[:2] != (self.manifest, self.pack): + named = (local_manifest_platform(self.manifest) if self.manifest is not None + else None) + found = ({named} if named else set()) if self.manifest is not None \ + else set(self.pack.platforms()) if self.pack is not None else set() + self._serves = (self.manifest, self.pack, frozenset(found)) + return self._serves[2] + + @property + def offline(self) -> bool: + """No network request in this run: a pack is read, or --offline.""" + return self.pack is not None or offline_requested() + + def reset(self) -> None: + if self.pack is not None: + self.pack.close() + self.close_indexes() + self.manifest = None + self.pack = None + self.folders = [] + self.jobs = 8 + + def close_indexes(self) -> None: + for index in list(self.indexes): + index.close() + self.indexes = weakref.WeakSet() + + +LOCAL = LocalSources() + + +class _Offline(OSError): + """A network request in a run told to make none.""" + + +OFFLINE_WORDS = "this run makes no network request" +# The value --offline gives the variable: the words then name the option, +# and the variable itself where it was set. +OFFLINE_FLAG_VALUE = "--offline" + + +def offline_named() -> str: + """What made this run offline, as the words name it.""" + value = os.environ.get(OFFLINE_VARIABLE, "") + return (f"{OFFLINE_VARIABLE}={value}" if value not in ("", "0", OFFLINE_FLAG_VALUE) + else "--offline") + + +def offline_undo() -> str: + """How a run gets the network back: without the option, or with the + variable unset. "without --offline" told a user who never typed it to + remove it.""" + return ("without --offline" if offline_named() == "--offline" + else f"with {OFFLINE_VARIABLE} unset") + + +def offline_words() -> str: + """This run makes no network request, and what said so.""" + return f"{OFFLINE_WORDS} ({offline_named()})" + + +def _network_allowed(what: str) -> None: + if LOCAL.pack is not None: + raise _Offline(f"{what}: this run reads a pack and makes no network request") + if offline_requested(): + raise _Offline(f"{what}: {offline_words()}") + + +def local_manifest_platform(path: Path) -> str | None: + """The platform a saved file list names, None when it names none.""" + try: + with open(path, "rb") as handle: + data = json.loads(handle.read(MAX_MANIFEST_BYTES).decode("utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return None + plat = data.get("platform") if isinstance(data, dict) else None + return plat if plat in AVAILABLE_PLATFORMS else None + + +# --- 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 + + +# --- 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) 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). + "error": ("stage", "reason", "platform", "message"), + # 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"), + # 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 (args.list_platforms or args.list_targets or args.list_systems + or args.list_cores or args.list_emulators): + 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()} + + +# --- installer/paths.py ------------------------------------------------------ + +def _read_limited_json( + response: http.client.HTTPResponse, limit: int, label: str, raw: bool = False +) -> object: + """Read a bounded UTF-8 JSON response, its bytes as they came with raw. + + A body shorter than its Content-Length is a dropped connection, raised + as one so the caller retries: parsed, the cut read as an invalid file + list and the run ended without the network advice. + """ + raw_length = response.headers.get("Content-Length") if response.headers else None + expected: int | None = None + if raw_length: + try: + expected = int(raw_length) + except ValueError: + expected = None + if expected is not None and expected > limit: + raise ValueError(f"{label} exceeds {limit} bytes") + try: + payload = response.read(limit + 1) + except http.client.IncompleteRead as exc: + raise ConnectionError( + f"{label} cut after {len(exc.partial)} bytes" + ) from exc + if len(payload) > limit: + raise ValueError(f"{label} exceeds {limit} bytes") + if expected is not None and len(payload) < expected: + raise ConnectionError(f"{label} cut after {len(payload)} of {expected} bytes") + if raw: + return payload + try: + return json.loads(payload.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as exc: + raise ValueError(f"invalid {label}: {exc}") from exc + + +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 + + +# 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. +_MOVED_FOLDERS: dict[Path, dict[str, Path]] = {} + + +def _record_moved_folders(root: Path, retrodeck_json: Path) -> None: + """Each RetroDECK folder that is no longer /.""" + try: + paths = json.loads(retrodeck_json.read_text(encoding="utf-8", errors="replace"))["paths"] + except (OSError, ValueError, KeyError, TypeError): + return + if not isinstance(paths, dict): + return + 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 + if moved: + _MOVED_FOLDERS[root] = moved + + +# 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_FOLDERS.get(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 + + +# --- installer/manifest.py --------------------------------------------------- + +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, *entry.get("alternatives", []), *entry.get("slot_choices", [])] + 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") + if entry.get("optional", True) is not True: + raise ValueError(f"{where}.optional 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 + + +def board_target(board: str, targets: dict[str, dict]) -> str | None: + """The target a board name stands for: the name itself, else the one + target whose images carry it. A card names its image (Batocera writes + anbernic-rg35xx-plus for the h700 target, x86-64-v3 for zen3).""" + if board in targets: + return board + owners = [name for name, info in targets.items() if board in info.get("images", ())] + return owners[0] if len(owners) == 1 else None + + +NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a " + "proxy, then run the same command again.\n" + f" More help: {TROUBLESHOOTING_PAGE}") + + +# --- installer/probe.py ------------------------------------------------------ + +# Set under WSL: a Windows path read from a config or a rule names a drive +# that Linux sees under /mnt (drvfs). C:\\RetroBat\\bios was used as a relative +# path and nothing Windows-side was ever found from WSL. +# unasked: why Windows could not be asked for its folders, said once by +# detection. +_WSL: dict[str, Any] = {"active": False, "root": "/mnt", "unasked": ""} + + +def _host_path(text: str) -> Path: + """A path as this machine opens it: under WSL, C:\\X is /mnt/c/X.""" + match = re.match(r"^([A-Za-z]):(?:[\\/]+(.*))?$", text) if _WSL["active"] else None + if match: + rest = [part for part in re.split(r"[\\/]", match.group(2) or "") if part] + return Path(_WSL["root"], match.group(1).lower(), *rest) + return Path(text) + + +# Set while detection runs on this thread: a probe this user may not make +# is then said once, and the probes of other threads (the files being +# hashed) stay silent. +_SETUP_SEARCH = threading.local() + +# (folder, why in words) for each folder detection could not look in. +_DETECTION_REFUSED: list[tuple[Path, str]] = [] +# Those of them that failed for another cause than a permission: a read +# error from a failing card, a link that loops. +_DETECTION_UNREADABLE: set[Path] = set() +# The errors that say a place is not there, as against one that is there +# and could not be read. +_ABSENT_ERRNOS = (errno.ENOENT, errno.ENOTDIR, errno.EINVAL, errno.ENAMETOOLONG) + + +def refused_words(folder: Path, why: str, shown: str = "") -> str: + """The line said for a folder detection could not look in. shown is + the folder as the screen writes it (~/.config/EmuDeck), the full path + by default.""" + if _WSL["active"] and why == _WSL["unasked"] and folder == Path(_WSL["root"]): + return (f"Could not look for setups on the Windows side: {why}. " + "Run it again once Windows answers, or name the BIOS folder with --dest.") + if folder in _DETECTION_UNREADABLE: + return (f"Could not look for setups: {shown or folder} could not be read ({why}). " + "A failing card or a link that loops gives this: check it, or name the " + "BIOS folder with --dest.") + return (f"Could not look for setups: this user cannot open {shown or folder} ({why}). " + "Run as its owner (su - or sudo -H), or name the BIOS folder " + "with --dest.") + + +def _note_refused(path: Path, exc: OSError) -> None: + """Say once that a folder detection looks in is closed to this user, + or could not be read. + + A probe refused there counts as absent and the others go on: a config + folder a sudo run left at 0700 (~/.config/EmuDeck) hid a RetroArch whose + retroarch.cfg was readable, and the run fell back to a folder it does + not read. + """ + if (not getattr(_SETUP_SEARCH, "active", False) or getattr(_SETUP_SEARCH, "quiet", False) + or exc.errno in _ABSENT_ERRNOS): + return + refused = closed_folder(path) or (path, exc.strerror or str(exc)) + if refused in _DETECTION_REFUSED: + return + _DETECTION_REFUSED.append(refused) + if not isinstance(exc, PermissionError): + # An EIO on retroarch.cfg counted as absent: the card about to be + # written to failed, and the run said nothing was detected. + _DETECTION_UNREADABLE.add(refused[0]) + words = refused_words(*refused) + EVENTS.emit("unsearched", folder=str(refused[0]), reason=refused[1], message=words) + print(f" {screen_text(words)}", file=sys.stderr) + + +def _held(path: Path) -> bool: + """Whether something may sit at path. A place that cannot be looked at + (a folder above it this user cannot enter, a card that answers a read + error) counts as held, so the file is reported unreadable and the run + goes on with the others: Path.exists() lets PermissionError through.""" + try: + return path.exists() + except OSError: + return True + + +def _probed(probe: Callable[[], bool], path: Path) -> bool: + """probe() for path, False where the place cannot be looked at. A + refusal met while looking for setups is said once (_note_refused).""" + try: + found = probe() + except OSError as exc: + _note_refused(path, exc) + return False + if not found: + # Python 3.14's Path.exists() answers False where earlier ones + # raised: a refusal is told from absence by the stat it hides. + try: + os.stat(path) + except OSError as exc: + _note_refused(path, exc) + return found + + +def _exists(path: Path) -> bool: + """Path.exists(), False where the place cannot be looked at.""" + return _probed(path.exists, path) + + +def _is_dir(path: Path) -> bool: + """Path.is_dir(), False where the place cannot be looked at.""" + return _probed(path.is_dir, path) + + +def _is_file(path: Path) -> bool: + """Path.is_file(), False where the place cannot be looked at.""" + return _probed(path.is_file, path) + + +def _closed_to_this_user(path: Path) -> OSError | None: + """The error that keeps path from being looked at, None when it can + be, there or not.""" + try: + os.stat(path) + except OSError as exc: + return None if exc.errno in _ABSENT_ERRNOS else exc + return None + + +def closed_folder(path: Path) -> tuple[Path, str] | None: + """The folder above path this user cannot open, and why in words, or + None when path can be looked at, there or not. + + A BIOS folder under /root run without sudo, or a card mounted at 0700 + for another user: Path.exists() raised PermissionError before the + first line said where. + """ + try: + os.stat(path) + return None + except OSError as exc: + failure = exc + probe = path.absolute() + for folder in (*reversed(probe.parents), probe): + try: + os.stat(folder) + except OSError as exc: + if exc.errno in (errno.ENOENT, errno.ENOTDIR): + return None + why = exc.strerror or str(exc) + if exc.errno == errno.ELOOP: + # The link that loops, not the open folder holding it. + return folder, why + real = Path(os.path.realpath(folder)) + if real != folder: + # ~/Emulation linked into a closed card: the closed folder + # is under the link's target, and naming the link's + # parent told the user they cannot open their own HOME. + return closed_folder(real) or (real.parent, why) + return folder.parent, why + return probe, failure.strerror or str(failure) + + +# --- installer/prompt.py ----------------------------------------------------- + +def _names_and(names: list[str]) -> str: + """Names in a sentence: A, A and B, A, B and C.""" + return " and ".join(names) if len(names) < 3 else f"{', '.join(names[:-1])} and {names[-1]}" + + +def _typed_folder(raw: str) -> Path: + """A folder typed at a question, read as a shell reads an argument. + + Explorer's "Copy as path" puts quotes around it, and users quote a path + with spaces: kept, they sent the files into a folder named `"` under + the current directory, and the run said Done. + """ + text = raw.strip() + if len(text) >= 2 and text[0] == text[-1] and text[0] in "'\"": + text = text[1:-1].strip() + # Under WSL, D: and D:\ are the Windows drive the screen calls D:. + return _host_path(os.path.expandvars(os.path.expanduser(text))) + + +def _ask(prompt: str) -> str: + """An answer, or a stop: Ctrl+D at a question is Ctrl+C. + + Both used to leave with 0, so `install.sh && retroarch` went on with no + BIOS. They now end where Ctrl+C ends everywhere else, on 130. + """ + try: + return input(prompt).strip() + except EOFError: + print() + raise KeyboardInterrupt from None + + +# A quit chosen at a question or on the screen: nothing was installed, as +# gh ends a prompt cancelled. 130 is 128 plus SIGINT, which shells read as a +# run killed by Ctrl-C, and 0 let `install.sh && retroarch` start RetroArch +# on no BIOS. Ctrl-C and Ctrl-D keep 130. +QUIT_CODE = 2 + + +def _quit() -> None: + """q at a question ends the run on QUIT_CODE.""" + sys.exit(QUIT_CODE) + + +def _no_widow(lines: list[str], room: int) -> list[str]: + """Wrapped lines whose last one is not a word alone: "shared" stood on a + line of its own under its size at 40 columns. The + word before it goes down with it where both fit.""" + if len(lines) < 2 or len(_glued_words(lines[-1])) > 1: + return lines + # A size goes down with its unit: "1.4" / "MB shared" split it. + words = _glued_words(lines[-2]) + lead = lines[-2][:len(lines[-2]) - len(lines[-2].lstrip(" "))] + moved = f"{words[-1]} {lines[-1].strip()}" + if len(words) < 2 or cell_width(moved) > room: + return lines + return [*lines[:-2], lead + " ".join(words[:-1]), moved] + + +# --- installer/terminal.py --------------------------------------------------- + def _kernel32() -> Any: """kernel32 from ctypes.windll, which typeshed declares for win32 only. AttributeError where the system has no windll.""" @@ -696,526 +2771,984 @@ class Progress: # 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 -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) 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). - "error": ("stage", "reason", "platform", "message"), - # 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"), - # 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",), -} + # Seconds between two progress events while bytes arrive. EVENT_PROGRESS_INTERVAL = 0.5 +# The files a FAILED line of the progress named in this run: the end of +# the run names the others. +SAID_FAILED: set[str] = set() -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() +# 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 -EVENTS = EventStream() +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 _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 (args.list_platforms or args.list_targets or args.list_systems - or args.list_cores or args.list_emulators): - return "list" - return "install" +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 _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 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 _os_name() -> str: - """The OS's own name, from os-release, else the kernel's.""" - release = _parse_os_release() - return release.get("PRETTY_NAME") or release.get("NAME") or platform.system() +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) - -class CheckTally(NamedTuple): - """What a check found, as _emit_check says it.""" - - files: list[dict] - up_to_date: list[dict] - mismatched: list[dict] - data_missing: int = 0 - not_installable: int = 0 - data_bytes: int = 0 - - -def _emit_check( - plat: str, manifest: dict, bios_path: Path, tally: CheckTally, - *, chosen: list[str] | None = None, -) -> None: - """One event per file, per system and per platform after a check, then - one for the files of the platform's own list. - - With systems chosen, only those are described: a file of SkyEmu's - carries four systems, and --system nintendo-gba described gb, gbc and - ds by the few files the choice kept of them. - """ - files, up_to_date, mismatched = tally.files, tally.up_to_date, tally.mismatched - present = {id(entry) for entry in up_to_date} - wrong = {id(entry) for entry in mismatched} - systems: dict[str, dict[str, int]] = {} - for entry in files: - state = ("present" if id(entry) in present - else "wrong_hash" if id(entry) in wrong else "missing") - size = entry.get("size", 0) - EVENTS.emit("file", platform=plat, dest=entry["dest"], - systems=entry_systems(entry), size=size, state=state) - for system in entry_systems(entry) or [OTHER_SYSTEMS]: - counts = systems.setdefault(system, { - "files": 0, "present": 0, "missing": 0, "wrong_hash": 0, - "bytes_needed": 0, - }) - counts["files"] += 1 - counts[state] += 1 - if state != "present": - counts["bytes_needed"] += size - names = manifest.get("system_names") or {} - for system in sorted(systems): - if chosen and system not in chosen: - continue - EVENTS.emit("system", platform=plat, system=system, - name=", ".join(names.get(system) or [system]), **systems[system]) - needed = [entry for entry in files if id(entry) not in present] - EVENTS.emit( - "check", platform=plat, name=display_name(plat, manifest), bios_dir=str(bios_path), - files=len(files), present=len(up_to_date), missing=len(needed) - len(mismatched), - wrong_hash=len(mismatched), - bytes_needed=sum(entry.get("size", 0) for entry in needed), - data_missing=tally.data_missing, not_installable=tally.not_installable, - ) - # The copy the platform itself checks at each of its slots, which is - # what --declared-only checks: a core's copy served in its place is - # judged against the platform's. - own_states = [] - for entry in files: - if entry.get("cores") is not None: - continue - copy = declared_copy(entry) - if copy is entry or copy.get("sha1") == entry.get("sha1"): - state = ("present" if id(entry) in present - else "wrong_hash" if id(entry) in wrong else "missing") - else: - state = _declared_state(copy, entry, bios_path) - own_states.append((entry["dest"], copy.get("size", 0), state)) - EVENTS.emit( - "declared", platform=plat, files=len(own_states), - present=sum(1 for _d, _s, state in own_states if state == "present"), - missing=sum(1 for _d, _s, state in own_states if state == "missing"), - wrong_hash=sum(1 for _d, _s, state in own_states if state == "wrong_hash"), - bytes_needed=sum(size for _d, size, state in own_states if state != "present"), - dests=[dest for dest, _s, _state in own_states], - ) - EVENTS.emit("data", platform=plat, files=tally.data_missing, bytes=tally.data_bytes) - - -def _declared_state(copy: dict, entry: dict, bios_path: Path) -> str: - """present, missing or wrong_hash: the file at entry's place against copy.""" - try: - path = _entry_path(bios_path, entry) - except ValueError: - return "missing" - try: - if not path.is_file(): - return "missing" if not path.exists() else "wrong_hash" - verdict = _classify_local(copy, path) - except OSError: - return "wrong_hash" - return "present" if verdict == "up_to_date" else "wrong_hash" - - -def leave_out_game_data( - files: list[dict], omitted: list[dict] -) -> tuple[list[dict], list[dict], list[dict]]: - """The files and omissions without game data, and what was left out. - - The same cut as a pack built with --no-game-data: the manifest marks - each file that is a game's data, not firmware. - """ - left_out = [e for e in files + omitted if e.get("category") == GAME_DATA] - return ( - [e for e in files if e.get("category") != GAME_DATA], - [e for e in omitted if e.get("category") != GAME_DATA], - left_out, - ) - - -class Tally(NamedTuple): - """Files and bytes of one list, BIOS files and game data apart. bios - and games add up to files, their bytes to size: every count a run - prints of a list comes from here.""" - - files: int - size: int - bios: int - bios_size: int - games: int - game_size: int - - -def tally(entries: Iterable[dict]) -> Tally: - """The counts of entries, each with its size and the category the list - gives it, anything not game data being a BIOS file. - - The run said 8069 files (6.5 GB) while its menu said 8348 (7.1 GB) and - 3259 BIOS files and 5089 game data files: three counts of three lists. - """ - bios = bios_size = games = game_size = 0 - for entry in entries: - size = int(entry.get("size") or 0) - if entry.get("category") == GAME_DATA: - games += 1 - game_size += size - else: - bios += 1 - bios_size += size - return Tally(bios + games, bios_size + game_size, bios, bios_size, games, game_size) - - -def sized_words(counts: Tally) -> str: - """The count and the size, as in 8358 files, 6.6 GB.""" - return f"{_plural(counts.files, 'file')}, {format_size(counts.size)}" - - -def installed_words(bios: int, games: int, data: int = 0) -> str: - """The kinds a run installed, those it installed none of left out: - "6 BIOS files" where the old card's result said no kind at all.""" - parts = [_plural(count, word) for count, word in ( - (bios, "BIOS file"), (games, "game data file"), (data, "data file")) if count] - if not parts: - return _plural(0, "file") - return f"{', '.join(parts[:-1])} and {parts[-1]}" if len(parts) > 1 else parts[0] - - -def parts_words(counts: Tally, data: int = 0, data_size: int | None = None, - left_out: int = 0) -> str: - """The files of a plan by kind, each with its size: BIOS files, game - data and the data files of the emulators' data folders, then the game - data left out. "" when one kind alone is counted and nothing is left - out. "8358 files and 2636 data files" sat above "3269 BIOS files and - 5089 game data files", which add up to 8358 only, and "No game data" - read as a list holding none.""" - parts = [] - if counts.bios or not (counts.games or data): - parts.append(f"{_plural(counts.bios, 'BIOS file')} ({format_size(counts.bios_size)})") - if counts.games: - parts.append(f"{_plural(counts.games, 'game data file')} " - f"({format_size(counts.game_size)})") - if data: - parts.append(_plural(data, "data file") - + (f" ({format_size(data_size)})" if data_size is not None else "")) - if len(parts) < 2 and not left_out: + 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 "" - text = f"{', '.join(parts[:-1])} and {parts[-1]}" if len(parts) > 1 else parts[0] - return text + (f". {_plural(left_out, 'game data file')} left out" if left_out else "") + 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 kinds_definition(games: bool, data: bool) -> str: - """What game data and data files are, one sentence each, for the kinds - a plan counts: said once, after the counts.""" - said = [words[0].upper() + words[1:] + "." for words, shown in ( - (GAME_DATA_WORDS, games), (DATA_FILES_WORDS, data)) if shown] - return " ".join(said) - - -def game_data_state(left_out: bool, games: Tally) -> str: - """The one label of the game data choice, its count after: the plan's - row and the line menu's g.""" - return (f"Game data: {'left out' if left_out else 'kept'} " - f"({_plural(games.games, 'file')}, {format_size(games.game_size)})") - - -def keep_declared(files: list[dict], omitted: list[dict]) -> tuple[list[dict], list[dict]]: - """The files and omissions the platform's own list declares (cores: null). - - A slot a core contradicts gets the platform's copy, and no core copy - stays behind as an alternative: narrowing by cores afterwards would - otherwise put a core's file back where a dropped system's was. Which of - the platform's declarations answers is left to that narrowing, as - without --declared-only: the first whose systems remain. - """ - def own(entries: list[dict]) -> list[dict]: - result = [] - for entry in entries: - if entry.get("cores") is not None: +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 - kept = {k: v for k, v in _settle_slot(entry, set()).items() - if k not in ("alternatives", "declared_copy")} - declared = entry.get("declared_choices") or [] - if len(declared) > 1: - kept["declared_choices"] = declared - result.append(kept) - return result - - return own(files), own(omitted) + return None -def declared_copy(entry: dict) -> dict: - """The copy the platform's own list checks at a platform file's slot. +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) - A narrowing that serves a core's copy there records the platform's - answer beside it, and an entry not yet settled answers by its first - declaration. Otherwise the entry is the platform's copy itself. + +def terminal_colours(term: str, env: Mapping[str, str]) -> int | None: + """The colours TERM's description here names, 0 when it names none + (vt100), None when no description is found or it cannot be read.""" + data = _terminfo_data(term, env) + if data is None: + return None + count = terminfo_number(data, _TERMINFO_COLORS) + return None if count is None else max(count, 0) + + +def terminal_few_colours(env: Mapping[str, str]) -> str: + """Why TERM's description here leaves colour off, "" when it does not: + no description is no refusal, as for the cursor.""" + if os.name == "nt": + return "" + term = env.get("TERM", "") + count = terminal_colours(term, env) + if count is not None and count < 8: + return f"TERM={term} names {count} colours, fewer than 8" + return "" + + +def terminal_without_ansi(env: Mapping[str, str]) -> str: + """Why TERM's description here says the ANSI sequences the screen and + the progress line write would print as text, "" when it does not.""" + if os.name == "nt": + return "" + term = env.get("TERM", "") + cup = terminal_cursor_address(term, env) + if cup == "": + return f"TERM={term} cannot move the cursor" + if cup is not None and not cup.startswith(("\x1b[", "\x9b")): + return f"TERM={term} does not take the escape sequences the screen is drawn with" + return "" + + +# --- installer/embedded.py --------------------------------------------------- + +def shown_path(path: Path | str) -> str: + """A path as the person names it: under WSL, /mnt/d/BIOS is D:\\BIOS, the + drive the card row calls D:.""" + text = str(spelled(path)) if os.path.isabs(str(path)) else str(path) + root = _WSL["root"].rstrip("/") + "/" + match = (re.match(rf"^{re.escape(root)}([a-z])(?:/(.*))?$", text) + if _WSL["active"] else None) + if match: + text = f"{match.group(1).upper()}:\\" + (match.group(2) or "").replace("/", "\\") + # A folder's name comes from whoever named it: a card's label, a + # retroarch.cfg, a pack. Printed raw, a control character in it is a + # terminal command. + return screen_text(text) + + +class _OsRule(NamedTuple): + """One piece of evidence that names an embedded system. + + manifest is the platform whose files it gets, "" for a system the + installer does not lay out. name is the system's own name. values are the + KEY=value pairs of os_release (any one), the files of file_exists (all), + or the file and the pattern of file_matches. bios is the folder used when + none of configs (retroarch.cfg files, read in order, `*` allowed) names a + system_directory. home is what `~` means to that system's RetroArch. + base is the system this one is built on: both match, this one is meant. """ - recorded = entry.get("declared_copy") - if recorded is not None: - return recorded - declared = entry.get("declared_choices") - if declared: - return declared[0] - return entry + + manifest: str + name: str + method: str + values: tuple[str, ...] + bios: str | None + configs: tuple[str, ...] = () + home: str = "" + base: str = "" -def _left_out_lines(left_out: list[dict], every: bool) -> list[str]: - """What --no-game-data left out, named per category, ten each unless every.""" - lines = [] - # The omitted ones apart: "leave out the 5089 game data files" was - # followed by "Left out as game data: 5099 files", the other ten being - # files the list cannot install anyway. - for group in _left_out_events(left_out): - dests = group["dests"] - shown = dests if every else dests[:10] - more = (f" ... and {len(dests) - len(shown)} more (--verbose lists them all)" - if len(shown) < len(dests) else "") - omitted = sum(1 for entry in left_out if entry.get("reason") - and entry.get("category", "") == group["category"]) - aside = f", {omitted} of them not installable" if omitted else "" - lines.append(f" {left_out_words(group)} (--no-game-data){aside}: " - f"{', '.join(shown)}{more}") - return lines +# 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 left_out_words(group: dict) -> str: - """A left_out group in the plan's words: 6 game data files left out.""" - return f"{_plural(group['files'], group['label'] + ' file')} left out" +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 _left_out_events(left_out: list[dict]) -> list[dict]: - """What --no-game-data left out, per category, every file named.""" - groups: dict[str, dict] = {} - for entry in left_out: - category = entry.get("category", "") - group = groups.setdefault(category, { - "category": category, "label": CATEGORY_LABELS.get(category, category), - "files": 0, "dests": [], - }) - group["files"] += 1 - group["dests"].append(entry["dest"]) - return [groups[category] for category in sorted(groups)] +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()) -def _skipped(omitted: list[dict]) -> list[dict]: - """The files the collection cannot supply, grouped by reason.""" - groups: dict[str, dict] = {} - for entry in omitted: - reason = entry.get("reason", "unknown") - group = groups.setdefault(reason, { - "reason": reason, "label": OMISSION_REASONS.get(reason, reason), - "files": 0, "required": 0, - }) - group["files"] += 1 - group["required"] += bool(entry.get("required", True)) - return [groups[reason] for reason in sorted(groups)] +# 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 + try: + text = Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace") + except OSError: + return False + return _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 = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), 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 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 _a(name: str) -> str: + """A name with its article: an Onion, a muOS.""" + return f"{'an' if name[:1].lower() in 'aeiou' else 'a'} {name}" + + +def _built_on(name: str) -> str: + """The system name is built on (dArkOS on ArkOS), "" for none.""" + return next((rule.base for rule in _EMBEDDED_RULES if rule.name == name and rule.base), "") + + +def _mount_points() -> frozenset: + """Every mount point this process sees, from /proc/self/mountinfo where + it exists: os.path.ismount compares devices, and misses a bind mount + from the same filesystem (a stick bound inside a muOS card's mount).""" + try: + text = Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace") + except OSError: + return frozenset() + # Field 5 is the mount point, with space, tab, newline and backslash + # written as octal escapes (proc(5)). + return frozenset(re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), 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//