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.
This commit is contained in:
Abdessamad Derraz committed 2026-11-18 01:37:28 +01:00
1 parent f75b87448e
commit e9f6fe43a0
55 files changed
+48840 -14908

No files matched your search

+1 -1
View File
@@ -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
+15026 -14894
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins
# curl or wget stop on a cut transfer before the hash is read: the site's
# build rewrites this line there (scripts/sitebootstrap.py).
MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that."
DEFAULT_INSTALL_SHA256="4a820bbfc7ed86b684a6fda8db0b19c3c021950b4ab3f1d9f861807afbf6ec7b"
DEFAULT_INSTALL_SHA256="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.
MAX_INSTALLER_BYTES=8388608
+8 -8
View File
@@ -27,8 +27,8 @@
{
"dest": "roms/ports/retrobios/install.py",
"repo_path": "install.py",
"size": 1440188,
"sha256": "4a820bbfc7ed86b684a6fda8db0b19c3c021950b4ab3f1d9f861807afbf6ec7b",
"size": 1444103,
"sha256": "23d7586b7fac5e0e98e9f5e68cc389e2557cc448fc6e4329bd6ee322e8df32a6",
"executable": false
},
{
@@ -71,8 +71,8 @@
"muos": {
"archive": {
"dest": "ARCHIVE/RetroBIOS.muxapp",
"size": 1493813,
"sha256": "95c30064eb47a7cc5d463f68b04479bab1bc6bc26d9d2f7bfbb54ea131490c22"
"size": 1497728,
"sha256": "25448461d9399ee307f2bbed3c48333eb16680e5663562004471b074f78c60e5"
},
"members": [
{
@@ -92,8 +92,8 @@
{
"name": "RetroBIOS/install.py",
"repo_path": "install.py",
"size": 1440188,
"sha256": "4a820bbfc7ed86b684a6fda8db0b19c3c021950b4ab3f1d9f861807afbf6ec7b",
"size": 1444103,
"sha256": "23d7586b7fac5e0e98e9f5e68cc389e2557cc448fc6e4329bd6ee322e8df32a6",
"executable": false
},
{
@@ -166,8 +166,8 @@
{
"dest": ".config/modules/retrobios/install.py",
"repo_path": "install.py",
"size": 1440188,
"sha256": "4a820bbfc7ed86b684a6fda8db0b19c3c021950b4ab3f1d9f861807afbf6ec7b",
"size": 1444103,
"sha256": "23d7586b7fac5e0e98e9f5e68cc389e2557cc448fc6e4329bd6ee322e8df32a6",
"executable": false
},
{
+13
View File
@@ -0,0 +1,13 @@
"""Universal BIOS installer for retrogaming platforms.
Self-contained script using only Python stdlib. Downloads missing BIOS files
from the retrobios repository and places them in the correct location for
the detected emulator platform.
Usage:
python install.py
python install.py --platform retroarch --dest ~/custom/bios
python install.py --check
python install.py --list-platforms
python install.py --platform retroarch --system sony-playstation --region us
"""
+401
View File
@@ -0,0 +1,401 @@
"""The installer copied onto a card as a launcher of the handheld."""
from __future__ import annotations
import argparse
import functools
import hashlib
import http.client
import io
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from pathlib import Path, PurePosixPath
from typing import NamedTuple
from installer.constants import MAX_RETRIES, RAW_FILE_URL
from installer.embedded import card_system
from installer.events import EVENTS
from installer.from_folders import APP_SCHEMA, LAUNCHERS_URL, MAX_APP_FILES, MAX_APP_FILE_SIZE, MAX_LAUNCHERS_BYTES
from installer.local_files import _sha256_file
from installer.network import _fetch_json, _retry_delay, network_words
from installer.offline import LOCAL, _Offline, _network_allowed
from installer.outcome import _transfer_failure
from installer.pack_source import NOT_WRITABLE, _write_refused, _write_verified
from installer.paths import _destination_path, _safe_relative_path
from installer.prompt import _ask
from installer.record import KEPT
from installer.text import _plural
class AppPlace(NamedTuple):
"""Where a system's launcher goes on its card, and what the player does next.
key names its entry in the launcher list, folder is below the card's
root, executable says whether the menu runs the launcher script itself.
"""
key: str
folder: str
executable: bool
then: str
APP_PLACES: dict[str, AppPlace] = {
# The Archive Manager lists the .muxapp files of ARCHIVE at the root of
# SD1, SD2 and a USB drive, and installs one into Applications
# (MustardOS/frontend 9c0fb5da, module/muxarchive.c:16,157-164,196-218,
# MUOS_ARCH_PATH "ARCHIVE" in common/base/options.h:180). The archive
# carries the modes of its members.
"muOS": AppPlace("muos", "ARCHIVE", False,
"Then open the Archive Manager on the console, install RetroBIOS, "
"and start it from Applications."),
# The card's root is the SHARE partition, /userdata on the console.
# Ports runs a .sh with /bin/bash (knulli-cfw distribution ab3a6809,
# configgen/generators/sh/shGenerator.py:19-35), and evmapy reads the
# .keys file beside it: no mode is needed on the card.
"KNULLI": AppPlace("knulli", "roms/ports", False,
"Then update the game list on the console, and start RetroBIOS "
"from Ports."),
# The card's root is the STORAGE partition, /storage on the console. Tools
# runs each file of /storage/.config/modules in foot or weston-terminal,
# which starts it as a program: the build installs them 0755 (ROCKNIX
# distribution 8b70f693, projects/ROCKNIX/packages/virtual/emulators/
# package.mk:118-122 and 1701-1707).
"ROCKNIX": AppPlace("rocknix", ".config/modules", True,
"Then start RetroBIOS from Tools on the console."),
}
# Card systems with no Python 3 to run the installer: Onion ships Python 2.7
# alone (OnionUI/Onion 07505ea5, static/build/.tmp_update/bin/parasyte/),
# MinUI (dbf89435), NextUI (5291344b) and Allium (ee0dda97) none, and
# MyMinUI is built from MinUI.
NO_PYTHON_CARDS = frozenset(("Onion", "Allium", "MinUI", "NextUI", "MyMinUI"))
def no_python_words(system: str) -> str:
"""Said where the card's system cannot run the installer. "This console"
read as the computer the person was at."""
return (f"{system} cannot run RetroBIOS: to update these files later, run it again "
"on this computer.")
APP_OFFER = "Put RetroBIOS on this card (update from the console later)"
APP_OFFER_SHORT = "Put RetroBIOS on this card"
class CardApp(NamedTuple):
"""A card a BIOS folder is on, and whether the RetroBIOS app can go there."""
root: Path
system: str
place: AppPlace | None
why: str
def card_app(bios_dir: Path) -> CardApp | None:
"""The card bios_dir is the BIOS folder of, None for a folder on no card
the installer recognises. why says, when place is None, why the app
cannot go on it."""
folder = Path(os.path.abspath(bios_dir))
for root in [folder, *list(folder.parents)[:3]]:
found = card_system(root)
if found is None or Path(os.path.abspath(found[1])) != folder:
continue
system = found[2]
place = APP_PLACES.get(system)
if place is not None:
return CardApp(root, system, place, "")
why = (f"{system} has no Python to run RetroBIOS" if system in NO_PYTHON_CARDS
else f"there is no RetroBIOS app for {system} yet")
return CardApp(root, system, None, why)
return None
def _app_entry(value: object, field: str, source: bool = True) -> dict:
"""One file of the launcher list, checked as a manifest entry is."""
if not isinstance(value, dict):
raise ValueError("an entry is not an object")
_safe_relative_path(value.get(field), field)
size = value.get("size")
if type(size) is not int or not 0 < size <= MAX_APP_FILE_SIZE:
raise ValueError(f"{value.get(field)}: invalid size")
digest = value.get("sha256")
if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
raise ValueError(f"{value.get(field)}: invalid sha256")
if not isinstance(value.get("executable", False), bool):
raise ValueError(f"{value.get(field)}: invalid executable")
if source:
repo, content = value.get("repo_path"), value.get("content")
if (repo is None) == (content is None):
raise ValueError(f"{value.get(field)}: needs repo_path or content")
if repo is not None:
_safe_relative_path(repo, "repo_path")
elif not isinstance(content, str):
raise ValueError(f"{value.get(field)}: invalid content")
return value
def app_targets(data: object, place: AppPlace) -> list[dict]:
"""The files the launcher list puts on a card for place, each under its
folder: an archive carries its members, the others their source.
The list comes from the same base as the file lists, and is held to
the folder its system reads: no entry writes elsewhere on the card.
"""
if not isinstance(data, dict) or data.get("schema") != APP_SCHEMA:
raise ValueError(f"not a launcher list of schema {APP_SCHEMA}")
launchers = data.get("launchers")
launcher = launchers.get(place.key) if isinstance(launchers, dict) else None
if not isinstance(launcher, dict):
raise ValueError(f"it holds no launcher for {place.key}")
if "archive" in launcher:
target = dict(_app_entry(launcher["archive"], "dest", source=False))
members = launcher.get("members")
if not isinstance(members, list) or not 0 < len(members) <= MAX_APP_FILES:
raise ValueError("invalid members")
target["members"] = [_app_entry(member, "name") for member in members]
if len({member["name"] for member in target["members"]}) != len(members):
raise ValueError("two members share a name")
targets = [target]
else:
files = launcher.get("files")
if not isinstance(files, list) or not 0 < len(files) <= MAX_APP_FILES:
raise ValueError("invalid files")
targets = [_app_entry(entry, "dest") for entry in files]
prefix = PurePosixPath(place.folder).parts
for target in targets:
parts = PurePosixPath(target["dest"]).parts
if len(parts) <= len(prefix) or parts[:len(prefix)] != prefix:
raise ValueError(f"{target['dest']} is outside {place.folder}")
if len({target["dest"].casefold() for target in targets}) != len(targets):
raise ValueError("two files share a destination")
return targets
def app_archive(members: list[tuple[dict, bytes]]) -> bytes:
"""A launcher archive from its members: stored, sorted, dated 1980-01-01,
only the executable bit kept, so the same members give the same bytes
on any machine and the list can record their hash."""
buffer = io.BytesIO()
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_STORED) as archive:
for entry, data in sorted(members, key=lambda member: member[0]["name"]):
info = zipfile.ZipInfo(entry["name"], date_time=(1980, 1, 1, 0, 0, 0))
info.compress_type = zipfile.ZIP_STORED
info.create_system = 3
mode = 0o755 if entry.get("executable") else 0o644
info.external_attr = (0o100000 | mode) << 16
archive.writestr(info, data)
return buffer.getvalue()
def _app_download(url: str, size: int) -> bytes:
"""The bytes at url, tried MAX_RETRIES times, never more than size + 1."""
_network_allowed("the RetroBIOS app")
for attempt in range(1, MAX_RETRIES + 1):
try:
with urllib.request.urlopen(url, timeout=60) as resp:
return resp.read(size + 1)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == MAX_RETRIES:
raise
except (urllib.error.URLError, OSError, http.client.HTTPException):
if attempt == MAX_RETRIES:
raise
time.sleep(_retry_delay(attempt, None))
raise AssertionError("unreachable")
def _app_bytes(entry: dict, name: str) -> bytes:
"""An entry's bytes, from the list itself or the repository, once they
have the size and the SHA-256 the list records."""
content = entry.get("content")
if content is not None:
data = content.encode("utf-8")
else:
url = RAW_FILE_URL.format(path=urllib.parse.quote(entry["repo_path"], safe="/"))
data = _app_download(url, entry["size"])
if len(data) != entry["size"]:
raise ValueError(f"{name} holds {len(data)} bytes, the list records {entry['size']}")
if hashlib.sha256(data).hexdigest() != entry["sha256"]:
raise ValueError(f"{name}: SHA-256 mismatch")
return data
def _target_bytes(target: dict) -> bytes:
"""What goes at a target's place: its file, or its archive built from
its members and checked against the hash the list records for it."""
members = target.get("members")
if members is None:
return _app_bytes(target, target["dest"])
data = app_archive([(member, _app_bytes(member, member["name"])) for member in members])
if len(data) != target["size"] or hashlib.sha256(data).hexdigest() != target["sha256"]:
raise ValueError(f"{target['dest']} built from its members is not the one the "
"list records")
return data
def _app_in_place(path: Path, target: dict) -> bool:
try:
return (path.is_file() and path.stat().st_size == target["size"]
and _sha256_file(path) == target["sha256"])
except OSError:
return False
def _app_failure(exc: BaseException) -> str:
if isinstance(exc, urllib.error.HTTPError):
return f"the server answered HTTP {exc.code}"
if isinstance(exc, ValueError):
return str(exc)
if isinstance(exc, _Offline) or _transfer_failure(exc):
return network_words(exc)[1]
return getattr(exc, "strerror", None) or str(exc)
def put_app(card: CardApp) -> dict:
"""Put the launcher of card's system on it: the fields of the app event.
Every file is fetched and verified before the first one is written, and
written as a BIOS file is, the one in place kept aside when it differs.
A file already in place with the recorded hash is left alone, so a
second run writes nothing.
"""
fields: dict = {"system": card.system, "folder": str(card.root), "ok": False,
"reason": card.why, "dests": [], "written": [], "kept": []}
if card.place is None:
return fields
try:
data = _fetch_json(LAUNCHERS_URL, MAX_LAUNCHERS_BYTES, "list of the app's files")
targets = app_targets(data, card.place)
except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc:
fields["reason"] = f"its list of files could not be read: {_app_failure(exc)}"
return fields
fields["dests"] = [target["dest"] for target in targets]
places = [(target, _destination_path(card.root, target["dest"])) for target in targets]
needed = [(target, path) for target, path in places if not _app_in_place(path, target)]
try:
payloads = [_target_bytes(target) for target, _path in needed]
except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc:
fields["reason"] = f"it could not be downloaded: {_app_failure(exc)}"
return fields
before = {item["folder"]: (item["files"], item["bytes"]) for item in KEPT.summary()}
for (target, path), payload in zip(needed, payloads):
try:
path.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
fields["reason"] = NOT_WRITABLE if _write_refused(exc) else _app_failure(exc)
break
_dest, ok, why = _write_verified(
target, card.root, path, functools.partial(io.BytesIO, payload), None,
"the RetroBIOS app")
if not ok:
fields["reason"] = f"{target['dest']}: {why}"
break
fields["written"].append(target["dest"])
else:
fields["ok"], fields["reason"] = True, ""
for item in KEPT.summary():
files, size = before.get(item["folder"], (0, 0))
if item["files"] > files:
fields["kept"].append({"folder": item["folder"], "files": item["files"] - files,
"bytes": item["bytes"] - size})
return fields
def app_lines(card: CardApp, fields: dict) -> list[str]:
"""What putting the app on the card did, in words."""
if not fields["ok"]:
return [f"RetroBIOS could not be put on the {card.system} card: {fields['reason']}."]
if fields["written"]:
lines = [f"RetroBIOS is on the {card.system} card: "
f"{_plural(len(fields['written']), 'file')} written in {card.root}."]
else:
lines = [f"RetroBIOS is already on the {card.system} card: nothing to write."]
lines += [f"The files it replaced are kept in {kept['folder']}" for kept in fields["kept"]]
if card.place is not None:
lines.append(card.place.then)
return lines
def app_refusal(args: argparse.Namespace, platforms: list[tuple[str, Path]]) -> list[CardApp]:
"""The cards --add-app puts the app on, one per folder. A folder that is
on no card the app can go on is refused with the reason, code 2, before
anything is written."""
cards: list[CardApp] = []
if not args.add_app:
return cards
for _plat, path in platforms:
card = card_app(path)
if card is None:
why = (f"{path} is not on a card this installer recognises (a muOS, "
"KNULLI or ROCKNIX card)")
else:
why = card.why
if card is None or why:
EVENTS.emit("app", system=card.system if card else "",
folder=str(card.root if card else path), ok=False, reason=why,
dests=[], written=[], kept=[])
print(f"Error: --add-app puts the RetroBIOS app on a handheld's SD card, and "
f"{why}.", file=sys.stderr)
if card is not None and card.system in NO_PYTHON_CARDS:
print(f" {no_python_words(card.system)}", file=sys.stderr)
else:
print(" Name the card's root or its BIOS folder with --dest.",
file=sys.stderr)
sys.exit(2)
if card not in cards:
cards.append(card)
_APP_PENDING[:] = cards
return cards
# The cards --add-app named, until the install finishes and the app is put.
_APP_PENDING: list[CardApp] = []
def app_not_added() -> None:
"""--add-app in a run that stopped before the app: said, never silent."""
cards, _APP_PENDING[:] = list(_APP_PENDING), []
for card in cards:
EVENTS.emit("app", system=card.system, folder=str(card.root), ok=False,
reason="the install did not finish", dests=[], written=[], kept=[])
print(f" RetroBIOS was not put on the {card.system} card: the install did "
"not finish.", file=sys.stderr)
def finish_app(
args: argparse.Namespace, platforms: list[tuple[str, Path]], cards: list[CardApp],
interactive: bool,
) -> None:
"""After an install that finished: the app on the cards --add-app named,
or on those the person says yes for at a terminal."""
_APP_PENDING[:] = []
chosen = list(cards)
if not args.add_app:
for card in dict.fromkeys(filter(None, (card_app(path) for _plat, path in platforms))):
if card.place is None:
if card.system in NO_PYTHON_CARDS:
print(f"\n{no_python_words(card.system)}")
continue
if not interactive or args.yes or LOCAL.offline:
continue
answer = _ask(f"\nPut RetroBIOS on this {card.system} card, to check and update "
"its BIOS files from the console later? [y/N] ")
if answer.lower() in ("y", "yes"):
chosen.append(card)
failed = False
for card in chosen:
print(f"\nPutting RetroBIOS on the {card.system} card...")
fields = put_app(card)
EVENTS.emit("app", **fields)
stream = sys.stdout if fields["ok"] else sys.stderr
for line in app_lines(card, fields):
print(f" {line}", file=stream)
failed = failed or not fields["ok"]
if failed:
sys.exit(1)
+413
View File
@@ -0,0 +1,413 @@
"""The command line: every option, its help and the epilog."""
from __future__ import annotations
import argparse
import re
from pathlib import Path
from installer.constants import INSTALLER_PAGE, RELEASE_REF
from installer.invocation import OFFLINE_VARIABLE, _INVOCATION, installer_id
from installer.local_files import BACKUP_DIR
from installer.text import format_size
# --pack writes the narrowed choice as a pack --from-pack reads: each file
# once by its SHA-1, at its destination (a file of another root under that
# root's name), each data tree at its place, and manifest.json carrying the
# list narrowed to the choice. For one zlib the bytes depend on the inputs
# alone: members in a fixed order, a fixed date and mode, one compression
# level set on each member. Another deflate gives other bytes for the same
# members (zlib-ng, which CPython 3.14 on Windows ships).
PACK_NAME_END = "_BIOS_Pack.zip"
MIN_PART_BYTES = 64 * 1024
def parse_part_size(text: str) -> int:
"""--split SIZE: bytes, or a number with K, M or G (powers of 1024)."""
match = re.fullmatch(r"\s*(\d+)\s*([KMG]?)(?:I?B)?\s*", text, re.IGNORECASE)
if match is None:
raise argparse.ArgumentTypeError(
f"{text!r} is not a size: give bytes, or a number with K, M or G (1900M)")
size = int(match[1]) * 1024 ** " KMG".index((match[2] or " ").upper())
if size < MIN_PART_BYTES:
raise argparse.ArgumentTypeError(
f"a part of {format_size(size)} is too small: give {format_size(MIN_PART_BYTES)} "
"or more")
return size
def _help_epilog() -> str:
"""Examples in the form the run was started with, and where the rest is."""
run = _INVOCATION.launcher()
card = "E:\\bios" if _INVOCATION.powershell() else "/media/SHARE/bios"
examples = (
("install for the platforms found here", run),
("prepare a card or a share for another device",
f"{run} --platform batocera --dest {card}"),
("only some systems (names: --list-systems)",
f"{run} --platform retroarch --system sony-playstation,nintendo-gba"),
("check what is installed, writing nothing", f"{run} --check"),
)
lines = ["examples:"]
for what, command in examples:
lines += [f" {what}", f" {command}"]
lines += ["", f"Every option, the environment variables and the exit codes: {INSTALLER_PAGE}"]
return "\n".join(lines)
def build_parser() -> argparse.ArgumentParser:
"""The options, in the order --help and wiki/installer.md list them
(scripts/generate_installer_doc.py writes its table from this parser)."""
parser = argparse.ArgumentParser(
# Never the file's own name: install.ps1 runs a copy named
# retrobios-install-<guid>.py, which usage and errors printed.
prog="install.py",
allow_abbrev=False,
description="Download missing BIOS files for retrogaming emulators. "
"For questions line by line, as a screen reader reads them, "
"add --plain.",
epilog=_help_epilog(),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--platform",
metavar="NAME",
help="target platform (retroarch, batocera, emudeck, ...)",
)
parser.add_argument(
"--dest",
metavar="PATH",
type=Path,
help="BIOS folder to install into. Without --platform, the file list is "
"the platform detected here, asked at a terminal, RetroArch's when "
"nothing is detected",
)
parser.add_argument(
"--target",
metavar="NAME",
help="hardware target for core filtering (switch, rpi4, ...). "
"On AmberELEC, EmuELEC, Batocera, Recalbox, ROCKNIX, Lakka, KNULLI and RetroPie "
"the board is read from the system",
)
parser.add_argument(
"--every-board",
action="store_true",
help="install the files of every board, not only the detected one",
)
parser.add_argument(
"--installed-cores",
action="store_true",
help="install only what the cores already installed read "
"(RetroArch, Lakka, RetroPie)",
)
parser.add_argument(
"--cores-dir",
type=Path,
metavar="PATH",
help="the folder RetroArch loads its cores from, when it is not found "
"(implies --installed-cores)",
)
parser.add_argument(
"--save-dir",
type=Path,
metavar="PATH",
help="the frontend's save directory (RetroArch: savefile_directory), "
"for the files some cores read there (Azahar's keys and system "
"data), when it is not found",
)
parser.add_argument(
"--system",
action="append",
metavar="NAMES",
help="install only these systems (repeat or comma-separate, see "
"--list-systems)",
)
parser.add_argument(
"--core",
action="append",
metavar="NAMES",
help="keep only the extra files these cores load (see --list-cores)",
)
parser.add_argument(
"--emulator",
action="append",
metavar="NAMES",
help="install what these emulators read on the platform, as a pack "
"built for them carries (names: --list-emulators)",
)
parser.add_argument(
"--region",
action="append",
metavar="LIST",
help="preferred regions, best first, e.g. us,eu,jp: keep one BIOS per "
"region where a system has several",
)
parser.add_argument(
"--for-games",
nargs="?",
const=True,
type=Path,
metavar="FOLDER",
help="install only what the games on the card need: the systems of its "
"game folders, one region where a game's content proves it, an "
"arcade set's BIOS sets. FOLDER names a games folder (on a computer, "
"one subfolder per system), else the card's own beside the BIOS folder",
)
parser.add_argument(
"--required-only",
action="store_true",
help="with --for-games, only the files the games cannot start without",
)
parser.add_argument(
"--all-files",
action="store_true",
help="install the whole list even when the card holds games. A run that "
"asks nothing (--yes, --no-input, --events) otherwise installs only "
"what the card's games need, the plan's first choice",
)
parser.add_argument(
"--no-game-data",
action="store_true",
help="leave out game data (files a game reads, not firmware) and "
"install the firmware only",
)
parser.add_argument(
"--declared-only",
action="store_true",
help="keep only the files the platform's own list names, not the extra "
"files cores load: --check then answers for the list the platform checks",
)
parser.add_argument(
"--one-per-slot",
action="store_true",
help="keep one BIOS per console and region, the one the emulators' own "
"search order ranks first (a slot no order decides keeps every file)",
)
parser.add_argument(
"--standalone",
action="store_true",
help="with --emulator: the files each emulator's standalone build reads, "
"where that build reads them",
)
parser.add_argument(
"--source",
choices=("full", "truth"),
default="full",
help="truth: only the files the emulator profiles prove a core reads "
"(default full: the platform's list and what its cores read)",
)
parser.add_argument(
"--find",
metavar="HASH",
help="install the file of the list with this sha1 or sha256, or md5 or "
"crc32 where the list records them",
)
parser.add_argument(
"--json",
action="store_true",
help="with --find: print the matching files as JSON and install nothing",
)
parser.add_argument(
"--list-systems",
action="store_true",
help="list a platform's systems with their file counts and exit",
)
parser.add_argument(
"--list-cores",
action="store_true",
help="list the cores whose extra files a platform installs and exit",
)
parser.add_argument(
"--list-emulators",
action="store_true",
help="list every name --emulator accepts for a platform and exit",
)
parser.add_argument(
"--romm-firmware",
metavar="TEMPLATE",
help="RomM: where each platform's firmware goes in the library, as "
"filesystem.structure.firmware in its config.yml (default: read "
"from config.yml, else bios/{platform})",
)
parser.add_argument(
"--no-input",
action="store_true",
help="never ask a question and fail where an answer is needed",
)
parser.add_argument(
"--check",
action="store_true",
help="check existing files without downloading",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="show what would be downloaded, and how much, without writing anything",
)
parser.add_argument(
"--yes", "-y",
action="store_true",
help="do not ask before a large download, nor anything else (implies --no-input)",
)
parser.add_argument(
"--quiet", "-q",
action="store_true",
help="print only errors and the final summary (implies --no-input)",
)
parser.add_argument(
"--events",
action="store_true",
help="write the run as JSON events on stdout, one per line, and the "
"usual text on stderr (implies --no-input)",
)
parser.add_argument(
"--from",
action="append",
type=Path,
metavar="FOLDER",
help="copy the BIOS files found in FOLDER (an old SD card, a backup, a "
"ZIP) instead of downloading them: every file recognised by its "
"hash, never moved. Repeat for several folders",
)
parser.add_argument(
"--from-pack",
action="append",
type=Path,
metavar="PATH",
help="install from a pack already downloaded: its ZIP, one of its parts "
"(the others are found beside it) or the folder holding them. "
"Makes no network request, and checks every file's hash",
)
parser.add_argument(
"--offline",
action="store_true",
help="make no network request: --check, --from, --from-pack and --manifest "
"work without one, and a file the run would download fails at once "
f"({OFFLINE_VARIABLE}=1 does the same)",
)
parser.add_argument(
"--manifest",
type=Path,
metavar="FILE",
help="read the file list from FILE (install/<platform>.json) instead "
"of downloading it",
)
parser.add_argument(
"--restore",
type=Path,
metavar="FOLDER",
help=f"put back the files an earlier run replaced and kept in FOLDER "
f"(a dated folder inside {BACKUP_DIR})",
)
parser.add_argument(
"--remove",
action="store_true",
help="remove what the installer placed in the BIOS folder, as its install "
"record proves it: every file, or those of --system, --core, --emulator "
"or --file. A file changed since, added by hand, still needed by "
"something kept, or that the collection cannot give again stays",
)
parser.add_argument(
"--file",
action="append",
type=Path,
metavar="PATH",
help="with --remove, one file of the BIOS folder (its path there, or the "
"full path). Repeat for several",
)
parser.add_argument(
"--misplaced",
action="store_true",
help="with --remove, delete instead the copies left in the wrong place of the "
"BIOS folder: each one whose bytes the installer placed where the cores "
"read them. A place a list reads, or a setup of the folder recorded, stays",
)
parser.add_argument(
"--backup",
action="store_true",
help=f"with --remove, move the files into a dated folder of {BACKUP_DIR} "
"instead of deleting them, for --restore to put back",
)
parser.add_argument(
"--backups",
action="store_true",
help="list the backups of the BIOS folder, newest first, and exit",
)
parser.add_argument(
"--delete-backup",
type=Path,
metavar="FOLDER",
help=f"delete one backup (a dated folder inside {BACKUP_DIR}) after one "
"question, to free its space",
)
parser.add_argument(
"--pack",
type=Path,
metavar="PATH",
help=f"download the choice into a pack ZIP at PATH instead of a BIOS folder, for "
f"another device or an install without the internet (--from-pack reads it). "
f"A folder takes <Platform>{PACK_NAME_END}. The narrowing options apply, and "
"--dry-run lists what the pack would hold",
)
parser.add_argument(
"--split",
type=parse_part_size,
metavar="SIZE",
help="with --pack, write parts of at most SIZE (1900M, 4G), each a whole ZIP. "
"A pack that would pass 4 GiB on a FAT32 drive is split by itself",
)
parser.add_argument(
"--tui",
action="store_true",
help="open the full-screen interface, which a keyboard or a controller "
"drives. It opens by itself for an install at a terminal of 40x12 "
"or more",
)
parser.add_argument(
"--plain",
action="store_true",
help="ask the questions line by line instead of the full-screen "
"interface, as a screen reader reads them (RETROBIOS_PLAIN=1 or "
"ACCESSIBLE=1 do the same)",
)
parser.add_argument(
"--version",
action="version",
version=f"retrobios installer {installer_id()} (ref {RELEASE_REF})",
help="print the installer version and exit",
)
parser.add_argument(
"--list-platforms",
action="store_true",
help="list detected platforms and exit",
)
parser.add_argument(
"--list-targets",
action="store_true",
help="list available targets for a platform and exit",
)
parser.add_argument(
"--jobs", "-j",
metavar="N",
type=int,
default=8,
help="parallel download threads (default: 8)",
)
parser.add_argument(
"--verbose", "-v",
action="store_true",
help="verbose output",
)
parser.add_argument(
"--standalone-copies",
action="store_true",
help="opt in to copies into detected standalone-emulator directories",
)
parser.add_argument(
"--add-app",
action="store_true",
help="after the install, put the RetroBIOS app on the handheld card the BIOS "
"folder is on (muOS, KNULLI, ROCKNIX), to check and update the BIOS "
"files from the console later",
)
return parser
+852
View File
@@ -0,0 +1,852 @@
"""Cards and folders chosen as the destination, and why one is refused."""
from __future__ import annotations
import os
import sys
from pathlib import Path, PurePosixPath
from typing import NamedTuple, NoReturn
from installer.constants import CARD_MARKER, CARD_PLATFORMS
from installer.cores import did_you_mean, info_dirs, info_firmware, normalize_platform, refuse_name, unknown_cores
from installer.detect_os import _DETECTED_OS, card_title, detect_os, os_conflict
from installer.embedded import (
_EMBEDDED_RULES,
_GAMES_PART_CARDS,
_SHARE_FOLDERS,
CardSetup,
_a,
_built_on,
_card_boundary,
_card_matches,
_doubt_kinds,
_mount_name,
_mount_points,
_mounted_cards,
_name_key,
card_bound,
card_platform,
card_setup,
card_system,
display_name,
drive_kind,
share_doubt,
share_drive,
shown_path,
)
from installer.events import EVENTS
from installer.from_folders import _read_from_folder, from_folder_problem, plan_local_copies
from installer.invocation import _INVOCATION
from installer.local_files import closed_folder_words
from installer.offline import LOCAL
from installer.platform_choice import _choose_platform, drive_example
from installer.probe import _exists, _is_dir, closed_folder
from installer.prompt import _ask, _names_and, _quit, _typed_folder
from installer.setups import _setup_label, found_setups
from installer.terminal import detail
from installer.text import _plural, screen_text
def _ask_from_folder(files: list[dict] | None = None, bios_path: Path | None = None) -> None:
"""A folder to copy from, asked at the menu: the screen offers it, the
line menu had no way to it. What it holds of files is counted, as the
screen's plan counts it: a folder holding none of them was kept, and
the menu offered to install what it held."""
# The drives mounted here, numbered as the screen's copy browser lists
# them, the card being installed to left out: line mode listed none, and
# took q for a folder named q.
drives = [mount for mount in _mounted_cards() if not copy_source_refusal(mount, bios_path)]
if drives:
print("\nCopy from:")
for number, mount in enumerate(drives, 1):
print(f" {number}) {card_line(mount)}")
numbers = "" if not drives else " or 1" if len(drives) == 1 else f" or 1 to {len(drives)}"
while True:
raw = _ask(f"Folder, old card or ZIP to copy from{numbers} (Enter to go back, "
"q to quit): ").strip()
if not raw:
return
if raw.lower() == "q":
_quit()
if raw.isdigit() and 1 <= int(raw) <= len(drives):
label = str(drives[int(raw) - 1])
elif raw.isdigit() and drives and not _is_dir(_typed_folder(raw)):
# A number out of range, said as one: "2" was read as the folder
# ./2.
count = "1" if len(drives) == 1 else f"a number from 1 to {len(drives)}"
print(f" Type {count}, a folder, or Enter.")
continue
else:
label = os.path.normpath(str(_typed_folder(raw).absolute()))
refused = copy_source_refusal(Path(label), bios_path)
if refused:
print(f" {refused}")
continue
problem = from_folder_problem(label)
if problem is not None:
print(f" {screen_text(shown_path(label))} {problem[1]}.")
continue
index = _read_from_folder(label)
name = _last_name(label)
held = len(plan_local_copies(files, bios_path, None, [index])) \
if files and bios_path is not None else -1
if held == 0:
LOCAL.folders.remove(index)
print(f" {name} holds none of these files.")
return
if files and held > 0:
print(f" {held} of {len(files)} found in {name}.")
_INVOCATION.options.append(("--from", label))
return
def _refuse_closed(dest: Path, named: str) -> None:
"""End the run, with its name, on a folder above dest this user cannot
open."""
closed = closed_folder(dest)
if closed is None:
return
message = closed_folder_words(dest, closed)
EVENTS.emit("error", stage="dest", reason="unreadable", platform="", message=message)
print(f"Error: {screen_text(message)}. Give this user access to it, run as "
f"its owner, or choose another folder than the one {named}.",
file=sys.stderr)
sys.exit(1)
def _refuse_file(dest: Path, named: str) -> None:
"""End the run on a BIOS folder that is a file, or lies under one.
mkdir then failed on EEXIST or ENOTDIR, and the run blamed permissions
and offered sudo, which fails the same way.
"""
for folder in (dest, *dest.parents):
if _exists(folder):
break
else:
return
if _is_dir(folder):
return
where = (f"{shown_path(dest)} is a file, not a folder" if folder == dest
else f"{shown_path(dest)} cannot be a folder: {shown_path(folder)} is a file")
EVENTS.emit("error", stage="dest", reason="not_a_folder", platform="", message=where)
print(f"Error: {screen_text(where)}. Name the folder the BIOS files go in, not "
f"the file {named}.", file=sys.stderr)
sys.exit(1)
def _missing_dest(dest: Path, ask: bool, named: str = "named with --dest",
again: bool = False) -> bool:
"""Say that a --dest folder does not exist before anything goes there.
A typo (~/.config/retroarh/system) was created with every missing
parent, filled, and reported done in a folder no platform reads, and
--check said only "0/7 present". One missing level is a BIOS folder not
made yet and is created. Several make a path that may be mistyped:
at a terminal the run asks first, and the answer defaults to no. A
folder above it this user cannot open ends the run with its name.
With again, no returns False, for the folder to be asked again: no to
a card's folder ended the run where it meant "not that card".
"""
_refuse_closed(dest, named)
_refuse_file(dest, named)
if dest.exists():
return True
nearest = dest.absolute()
while not nearest.exists() and nearest.parent != nearest:
nearest = nearest.parent
missing = len(dest.absolute().relative_to(nearest).parts)
# Said where it comes before a question: elsewhere the folder is made.
(print if missing > 1 and ask else detail)(
f" {shown_path(dest)} does not exist. The nearest folder that does: "
f"{shown_path(nearest)}")
if missing > 1 and ask:
answer = _ask(f" Create {_plural(missing, 'folder')} under {shown_path(nearest)}? [y/N] ")
if not answer.strip().lower().startswith("y"):
if again:
print(" Not created.")
return False
print(f" Nothing installed. Check the folder {named}, then run "
"the command again.")
sys.exit(2)
return True
def _check_cores_dir(folder: Path) -> None:
"""Refuse a --cores-dir that cannot be listed, saying why: a typo
(core/ for cores/) or a closed folder read as an empty one, and the
run said "none in" and asked for the --cores-dir it was given."""
try:
with os.scandir(folder):
return
except FileNotFoundError:
why = "does not exist"
except NotADirectoryError:
why = "is not a folder"
except PermissionError as exc:
closed = closed_folder(folder)
why = (f"cannot be opened by this user ({exc.strerror or exc})"
if closed is None or closed[0] == folder
else f"cannot be opened: {closed_folder_words(folder, closed)}")
except OSError as exc:
why = f"could not be read ({exc.strerror or exc})"
print(f"Error: --cores-dir {screen_text(str(folder))} {why}.", file=sys.stderr)
print(" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default).", file=sys.stderr)
sys.exit(1)
def _unprofiled_cores_firmware(
plat: str, bios_path: Path, manifest: dict, found: list[str], searched: list[Path],
) -> list[str]:
"""What the installed cores the list has no profile for declare, each said.
Such a core reads systems the list cannot name, and narrowing to the
installed cores dropped its BIOS without a word (issue 87, parallel_dc
before its profile). Its .info is what RetroArch itself checks, so the
files it declares are kept. A core without one is named.
"""
unknown = unknown_cores(manifest, found)
if not unknown:
return []
dirs = info_dirs(plat, bios_path, searched)
dests: list[str] = []
for core in unknown:
declared = info_firmware(dirs, core)
if declared is None:
message = (f"{core}: a core this list does not know, with no .info to read: "
"its files may be missing. Run without --installed-cores "
"to install every file.")
else:
message = (f"{core}: a core this list does not know, "
f"{_plural(len(declared), 'file')} its .info declares kept")
print(f" {message}")
EVENTS.emit("unknown_core", platform=plat, core=core,
info=declared is not None, dests=declared or [], message=message)
dests.extend(declared or [])
return dests
def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None:
"""Refuse --installed-cores with no core, and say how to point at them.
With no retroarch.cfg naming the folder as its system_directory, and
none beside it, nothing names the cores folder: the run stopped on "no
known directory" with no way forward.
"""
where = (f"none in {', '.join(map(str, searched))}" if searched
else f"no retroarch.cfg was found for {bios_path} to name their folder")
print(f"Error: no installed core found for {display_name(plat)}: {where}.",
file=sys.stderr)
print(" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default):", file=sys.stderr)
command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir"))
print(f" {command} --cores-dir <cores folder>", file=sys.stderr)
print(" Or run it without --installed-cores to install every file.", file=sys.stderr)
sys.exit(1)
def doubt_cards(plat: str) -> list[Path]:
"""The mounted drives whose files fit plat and another system."""
return [mount for mount in _mounted_cards() if plat in share_doubt(mount)[0]]
def _ends_with(path: Path, relative: str) -> bool:
"""Whether path's last folders are relative's, compared folder by folder
and without case: NOTMUOS/bios does not end with MUOS/bios."""
tail = [part.casefold() for part in PurePosixPath(relative).parts]
parts = [part.casefold() for part in path.parts]
return len(parts) >= len(tail) and parts[len(parts) - len(tail):] == tail
class CardChoice(NamedTuple):
"""Where the files of a folder named for a card go, and what is said: a
note, or why the folder is not the card of the system named."""
plat: str
folder: Path
note: str = ""
# Why the folder is not the card, with its path, and what was looked
# for on it. short says it without the path, for a 40-column screen.
refused: str = ""
detail: str = ""
short: str = ""
# The system's folder below its card.
below: str = ""
# The card's root, when the folder refused lies inside it.
root: Path | None = None
# The card found and where its files go, said where nothing else names
# the folder (line mode): the screen's plan names it.
found: str = ""
# The system whose card the folder refused is, when one is.
other: str = ""
def card_where(name: str, below: str) -> str:
"""Where on its card a system keeps its BIOS files, in words."""
if below:
return f"on its SD card, in its {below} folder"
if name in _GAMES_PART_CARDS:
# Its card shows two drives on a computer: "the root of its SD
# card" named neither.
return "on the games part of its SD card"
return "at the root of its SD card"
def shown_bios_folder(bios_path: Path, files: list[dict]) -> Path:
"""The BIOS folder a plan names: the bios folder nearly every file of
the list goes below (AmberELEC writes bios/ on its games part, and two
Neo Geo archives beside it), the folder given else. The plan named the
card's games part, then listed files under bios/."""
tops = [PurePosixPath(str(entry.get("dest", ""))).parts[:1] for entry in files
if entry.get("root") != "save"]
under = [top[0] for top in tops if top and top[0].casefold() == "bios"]
if len(tops) > 1 and len(under) * 10 >= len(tops) * 9:
return bios_path / under[0]
return bios_path
def _card_is(setup: CardSetup, card: Path, above: bool = False) -> tuple[str, str]:
"""("own", name) when the files on card say it runs setup's system,
("other", names) when they name another one, ("unknown", "") when they
name none. A MinUI card for NextUI's list is its own: one layout. above
is for a folder above the one named (_card_matches)."""
family = card_platform(card)
if family:
return ("own" if setup.plat in CARD_PLATFORMS else "other"), display_name(family)
names = sorted({rule.name for rule in _card_matches(card, above)})
if setup.name in names or _built_on(setup.name) in names:
# dArkOS writes ArkOS's games part: an ArkOS card is its own.
return "own", setup.name
share = share_drive(card)
if not names and share and not (share == "batocera" and setup.name == "KNULLI"):
# A Recalbox share is no KNULLI card not started yet. A Batocera
# one may be: KNULLI writes the same batocera.conf, and a card
# older than its about.info has nothing else (_unknown_card_note).
return "other", display_name(share)
return ("other", " and ".join(names)) if names else ("unknown", "")
def _not_the_card(setup: CardSetup, folder: Path, card: Path, other: str) -> CardChoice:
"""folder refused for setup: card, its root, is another system's card
(other names it) or names no system at all. The detail names what is
looked for on the card: the help's "says more" said the refusal again."""
name, shown = setup.name, shown_path(card)
marker = (CARD_MARKER if setup.plat in CARD_PLATFORMS
else setup.rules[0].values[0].split("/")[0] if setup.rules else "")
detail = f"{name} keeps {marker} at the root of its card" if marker else ""
games = [rule for rule in setup.rules if rule.method == "games_part"]
if games:
# The file the rule reads, never its first folder: AmberELEC's card
# holds a bezels folder too, and EmuELEC's refusal named it as the
# mark of an EmuELEC card.
held = " or ".join(dict.fromkeys(_names_and(list(rule.values)) for rule in games))
where = ("on the games part of its card" if setup.name in _GAMES_PART_CARDS
else "on its card")
detail = f"{name} keeps {held} beside bios {where}"
if " and " in other:
return CardChoice(setup.plat, folder, refused=f"{shown} holds the files of {other}, "
f"not of {name}", detail=detail,
short=f"That card holds {other} files.", below=setup.below)
if other:
kind = "SHARE drive" if share_drive(card) else "card"
return CardChoice(setup.plat, folder, refused=f"{shown} is {_a(other)} {kind}, not "
f"{_a(name)} card", detail=detail, short=f"That is {_a(other)} {kind}, "
f"not {_a(name)} card.", below=setup.below, other=other)
return CardChoice(setup.plat, folder, refused=f"{shown} is not {_a(name)} SD card: no "
f"{name} files on it", detail=detail,
short=f"Not {_a(name)} SD card: no {name} files on it.",
below=setup.below)
def _refusal_words(choice: CardChoice, setup: CardSetup) -> str:
"""Why a card typed or numbered in line mode is refused, and what to do:
another system's card is the top folder of a card, only not this one."""
detail = f" {choice.detail}." if choice.detail else ""
if choice.other:
return (f"{choice.refused}.{detail} Insert the {setup.name} card, or choose "
f"{choice.other} for that one.")
if choice.root is not None:
return f"{choice.refused}.{detail} Type its root: {shown_path(choice.root)}"
return f"{choice.refused}.{detail} Type the top folder of the {setup.name} card."
def _dest_refusal_words(choice: CardChoice, setup: CardSetup | None) -> str:
"""Why a --dest is not the card of the system named, and the one remedy
that works: "<card>/bios" was offered for a ROCKNIX card named for
KNULLI, and for a blank stick named for Onion, both refused the same."""
detail = f" {choice.detail}." if choice.detail else ""
name = setup.name if setup else display_name(choice.plat)
if choice.other and choice.plat in _SHARE_FOLDERS and setup is None:
return (f"{choice.refused}.{detail} Connect the {name} SHARE drive, or name that "
f"drive's own system: --platform {_name_key(choice.other)}")
if choice.other:
return (f"{choice.refused}.{detail} Insert the {name} card, or name that "
f"card's own system: --platform {_name_key(choice.other)}")
if choice.root is not None:
return f"{choice.refused}.{detail} Name the card's root: --dest {shown_path(choice.root)}"
if choice.plat in _SHARE_FOLDERS and setup is None:
return (f"{choice.refused}.{detail} Connect the {name} SHARE drive and name its "
"root with --dest")
return f"{choice.refused}.{detail} Name the top folder of the {name} card with --dest"
def _unknown_card_note(setup: CardSetup, card: Path, folder: Path) -> str:
"""Said when a card nothing names is taken for setup's."""
if setup.name in _GAMES_PART_CARDS:
# Its list writes bios/ below the games part: the plan names that.
folder = folder / "bios"
plats, why = share_doubt(card)
if setup.name == "KNULLI" and share_drive(card) == "batocera":
plats, why = ((setup.plat,), "it holds the system/batocera.conf Batocera and KNULLI "
"both write, and no about.info naming KNULLI")
if setup.plat in plats:
return (f"{shown_path(card)} could be another system's: {why}. Taken as "
f"{setup.name}'s, as named: the files go to {shown_path(folder)}")
if setup.fresh:
return (f"Nothing on {shown_path(card)} says it is {_a(setup.name)} card yet (not started "
f"once?): the files go to {shown_path(folder)}")
return (f"RetroBIOS cannot tell {_a(setup.name)} card by its files: the files go "
f"to {shown_path(folder)}")
def _card_and_below(setup: CardSetup, path: Path) -> tuple[Path, bool]:
"""(card root, whether path is the BIOS folder below it) for a folder
named for setup: its BIOS folder named outright stands for its card.
A folder whose own files name a system is that card, whatever its
name: an Onion card mounted as BIOS was read as a BIOS folder, its
parent checked as the card and refused."""
below = setup.below
if (not below and setup.name in _GAMES_PART_CARDS and path.name.casefold() == "bios"
and not _is_dir(path / "bios") and _card_is(setup, path)[0] == "unknown"
and not _card_boundary(path)):
# Its list writes bios/ below the games part's root: its BIOS
# folder named got bios/bios, or was refused as inside the card.
return path.parent, True
depth = len(PurePosixPath(below).parts)
if (below and _ends_with(path, below) and _card_is(setup, path)[0] == "unknown"
and not any(_card_boundary(folder)
for folder in [path, *list(path.parents)[:depth - 1]])):
return path.parents[depth - 1], True
return path, False
def _card_above(setup: CardSetup, card: Path) -> tuple[str, str, Path] | None:
"""(kind, name, root) of the card a folder nothing names lies inside,
when one of the folders above it, up to the drive's mount point, is a
card: ROCKNIX's roms/bios named for KNULLI read as a KNULLI card not
started once. Every folder up to that mount point is read: three at
most took MUOS/a/b/c/d for a KNULLI card."""
folder = card.absolute()
points = _mount_points()
for parent in folder.parents:
if _card_boundary(folder, points):
return None
kind, what = _card_is(setup, parent, above=True)
if kind != "unknown":
return kind, what, parent
folder = parent
return None
def _list_card_choice(plat: str, dest: Path) -> CardChoice:
"""card_choice for a list named, not a card: a card's root it recognises
is read as that card, with the list's own system, and another system's
card is said, the user having named both."""
found = card_system(dest)
if found and (not plat or found[0] == plat) and found[1] != dest:
if drive_kind(found) != "card":
# Its root typed, the drive itself: the files go to its bios.
return CardChoice(found[0], found[1],
found=f"{found[2]} SHARE drive: its BIOS folder is "
f"{shown_path(found[1])}")
return CardChoice(found[0], found[1],
found=f"{card_title(found[2])} card: {display_name(found[0])} files, "
f"in {shown_path(found[1])}")
if found and plat in _SHARE_FOLDERS and found[0] != plat and drive_kind(found) != "card":
# Another system's drive, never filled beside its own files.
shown = shown_path(dest)
kind = drive_kind(found)
return CardChoice(plat, dest, refused=f"{shown} is {_a(found[2])} {kind}, not "
f"{_a(display_name(plat))} SHARE drive",
short=f"That is {_a(found[2])} {kind}.", other=found[2])
if found and plat and found[0] != plat:
shown = shown_path(dest)
return CardChoice(plat, dest, f"Note: {shown} is {_a(card_title(found[2]))} "
f"{drive_kind(found)}, "
"which reads "
f"the {display_name(found[0])} file list in {shown_path(found[1])}: "
f"--platform {_name_key(found[2])} --dest {shown}. The "
f"{display_name(plat)} list goes into it as named.")
doubt, why = ((), "") if found else share_doubt(dest)
if plat in doubt:
# Named by the user, a drive its files cannot name is taken for the
# system named, and the doubt is said.
folder = dest / "bios"
return CardChoice(plat, folder, f"Note: {shown_path(dest)} could be another system's: "
f"{why}. Taken as {display_name(plat)}'s, as named: the files go "
f"to {shown_path(folder)}")
if doubt and plat in _SHARE_FOLDERS:
name = display_name(plat)
return CardChoice(plat, dest, refused=f"{shown_path(dest)} could be "
f"{_doubt_kinds(doubt)}, not {_a(name)} SHARE drive", detail=why,
short=f"That could be {_doubt_kinds(doubt)}.")
matched = [] if found else _card_matches(dest)
if len({(match.manifest, match.bios) for match in matched}) > 1:
names = " and ".join(sorted({match.name for match in matched}))
return CardChoice(plat, dest, f"{screen_text(str(dest))} holds the files of "
f"{names}: installing into it as named. Name the card's BIOS "
"folder with --dest to write there.")
if plat == "retrodeck" and dest.name.lower() == "bios" and not _is_dir(dest / "bios"):
# RetroDECK's list writes bios/, roms/ and the rest below its own
# folder: its BIOS folder, which --help asks for, got bios/bios.
return CardChoice(plat, dest.parent, f"{shown_path(dest)} is RetroDECK's BIOS "
f"folder: the files go below {shown_path(dest.parent)}, the "
"RetroDECK folder holding it")
return CardChoice(plat, dest)
def card_choice(named: str, plat: str, root: Path) -> CardChoice:
"""The file list and BIOS folder for a folder named for what --platform
or a row of the setup list names, or why it is not that system's card.
The one reading of a card's root, wherever it is named: --dest, the
setup list with --dest, a card listed, browsed or typed on the folder
screen, a card numbered or typed in line mode. Two readings gave a blank
stick named for KNULLI two folders, the root with --dest and bios below
it typed. The card's root is where the user points, its BIOS folder is
below it: `--platform muos --dest /media/me/SD1` wrote to the root,
which muOS never reads. A card of another system is refused for every
card system: KNULLI took a muOS card and wrote its layout into it. A
folder nothing names is refused for a system whose card always carries
its files (the MinUI family among them), and gets the system's folder
and a note for one that fills its card on first start or leaves no
file there that names it. A folder that does not exist is refused: a
typo four folders deep was created and filled.
"""
setup = card_setup(named, plat)
if setup is None:
return _list_card_choice(plat, root)
# A folder its device reads (/run/muos/storage/bios): on the device.
if root.as_posix() in {rule.bios for rule in _EMBEDDED_RULES if rule.name == setup.name}:
return CardChoice(plat, root)
card, inside = _card_and_below(setup, root)
if not _is_dir(card):
return CardChoice(plat, root, refused=f"{shown_path(card)} does not exist, or is not "
"a folder", short="That folder does not exist.", below=setup.below)
if plat in CARD_PLATFORMS:
above = card_root_above(root)
if above:
name = _a(display_name(above[0]))
return CardChoice(plat, root, refused=f"{shown_path(root)} is inside {name} card, "
f"whose root is {shown_path(above[1])}",
short=f"That is inside {name} card.", root=above[1])
kind, what = _card_is(setup, card)
if kind == "unknown":
holder = _card_above(setup, card)
if holder and holder[0] == "other":
return _not_the_card(setup, root, holder[2], holder[1])
if holder:
return CardChoice(plat, root, refused=f"{shown_path(root)} is inside the "
f"{setup.name} card, whose root is {shown_path(holder[2])}",
short=f"That is inside {_a(setup.name)} card.",
below=setup.below, root=holder[2])
folder = (card if inside and not setup.below
else root if inside or not setup.below else card / setup.below)
if kind == "other":
return _not_the_card(setup, root, card, what)
if kind == "own":
note = ("" if what == setup.name else f"Note: this card holds {what} "
f"({CARD_MARKER}), and the {display_name(plat)} file list was asked for.")
found = (f"{setup.name} card: {display_name(plat)} files, in {shown_path(folder)}"
if folder != root else "")
return CardChoice(plat, folder, note, below=setup.below, found=found)
if not setup.fresh and setup.known():
return _not_the_card(setup, root, card, "")
return CardChoice(plat, folder, _unknown_card_note(setup, card, folder),
below=setup.below)
def card_dest(named: str, plat: str, dest: Path) -> tuple[str, Path]:
"""The file list and folder for a --dest that names a handheld's card,
the run ended on a folder that is not the card of the system named."""
choice = card_choice(named, plat, dest)
if choice.refused:
message = _dest_refusal_words(choice, card_setup(named, plat))
# A script reading the stream learned code 1 and no reason.
EVENTS.emit("error", stage="detect", reason="not_found", platform=choice.plat,
message=message)
print(f"Error: {message}", file=sys.stderr)
sys.exit(1)
for line in (choice.found, choice.note):
if line:
print(f" {line}")
system = card_bound(named, plat)
if system is not None:
_DETECTED_OS.setdefault((choice.plat, choice.folder), system[0])
return choice.plat, choice.folder
def card_root_above(dest: Path) -> tuple[str, Path] | None:
"""(platform, root) of the MinUI-family card dest is inside, when dest is
a folder below its root and not the root."""
if card_platform(dest) is not None:
return None
for parent in list(dest.absolute().parents)[:2]:
holder = card_platform(parent)
if holder:
return holder, parent
return None
def mounted_cards_of(system: str, plat: str) -> list[Path]:
"""The mounted drives offered as system's card: those whose own files
say they run it, or, for a system no file on its card names, those no
other system claims."""
setup = card_setup(system, plat)
if setup is None:
return []
if plat in CARD_PLATFORMS:
return [mount for mount in _mounted_cards() if card_platform(mount) == plat]
wanted = "own" if setup.known() else "unknown"
return [mount for mount in _mounted_cards() if _card_is(setup, mount)[0] == wanted]
def blank_cards_of(system: str, plat: str) -> list[Path]:
"""The mounted drives no system claims, offered too for a system that
fills its card when it first starts (KNULLI, ROCKNIX): such a card is
blank until then. Listed after its own cards, never taken by itself.
The screen's browser listed a blank stick for KNULLI, line mode none."""
setup = card_setup(system, plat)
if setup is None or not setup.fresh or not setup.known():
return []
return [mount for mount in _mounted_cards() if _card_is(setup, mount)[0] == "unknown"]
def card_line(mount: Path) -> str:
"""A mounted drive in the line questions, named as the screen names it,
its path after unless the name is the path: ONION (Onion card,
/media/me/ONION), D: (Onion card) under WSL, where /mnt/d was printed."""
name, shown = _mount_name(mount), shown_path(mount)
if shown.rstrip("\\") == name:
return f"{name} ({_card_what(mount)})"
return f"{name} ({_card_what(mount)}, {shown})"
def card_install_dest(named: str, plat: str, interactive: bool, ask: bool = True) -> Path:
"""The folder for a card-bound system named without --dest, on a machine
that is not the device.
One mounted card that runs it is taken. At a terminal the card's root is
asked for, never this machine's own folder, and asked again until it is
that card. Only that system's cards are listed, as on the screen: a muOS
card listed for Onion was taken, and the run became a muOS install.
Without questions the run stops on the --dest that names the card. ask
is whether creating several missing folders is asked first, as it is
for --dest, and no to it asks for the card again.
"""
setup = card_setup(named, plat) or CardSetup(display_name(plat), plat, "")
system = setup.name
cards = mounted_cards_of(system, plat)
if setup.known() and len(cards) == 1:
dest = cards[0] / setup.below if setup.below else cards[0]
print(f" {system} card found at {_mount_name(cards[0])}, BIOS folder "
f"{shown_path(dest)}")
_DETECTED_OS.setdefault((plat, dest), system)
return dest
# Pasted, the name of a system in words is two arguments: its key is one.
word = named.strip() if _name_key(named) == named.strip().lower() else _name_key(named)
example = f"--platform {word or plat} --dest {drive_example(detect_os(), '<card>')}"
blank = [mount for mount in blank_cards_of(system, plat) if mount not in cards]
if setup.known() and len(cards) > 1:
print(f" {len(cards)} {system} cards are mounted: "
+ ", ".join(_mount_name(card) for card in cards) + ".", file=sys.stderr)
if not interactive:
EVENTS.emit("error", stage="detect", reason="not_found", platform=plat,
message=f"{system} keeps its BIOS files on its SD card, and no "
"card was named with --dest")
print(f" {system} keeps its BIOS files on its SD card, not on this machine. "
f"Mount it and give its root with --dest: {example}", file=sys.stderr)
sys.exit(1)
print(f" {system} keeps its BIOS files {card_where(system, setup.below)}, not on "
"this machine. "
+ ("" if setup.known() else
f"RetroBIOS cannot tell {_a(system)} card by its files. ")
+ ("Type its number or its top folder:" if cards
else _blank_offer(system, len(blank)) if blank
else "Mount the card, then type its top folder."))
listed = _list_cards(cards, blank)
while True:
numbers = ("" if not listed else " or 1" if len(listed) == 1
else f" or 1 to {len(listed)}")
# Enter looks again, as the screen's Look again does: a card
# inserted after the question was never found.
raw = _ask(f"Card root{numbers}, Enter to look again, q to quit: ")
if not raw:
listed = _list_cards(mounted_cards_of(system, plat), blank_cards_of(system, plat),
f"Still no {system} card is mounted.")
continue
if raw.lower() == "q":
_quit()
chosen = raw.isdigit() and 1 <= int(raw) <= len(listed)
if raw.isdigit() and not chosen and not _is_dir(_typed_folder(raw)):
print(f" Type a number from 1 to {len(listed)}, a folder, Enter to look "
"again, or q to quit." if listed else
" Type the card's top folder, Enter to look again, or q to quit.")
continue
root = listed[int(raw) - 1] if chosen else _typed_folder(raw).absolute()
choice = card_choice(system, plat, root)
if choice.refused:
print(f" {_refusal_words(choice, setup)}")
continue
# The card picked, echoed: the run went on to "RetroArch: 23 files"
# with no word of which card. A card nothing names has its note,
# which names the folder: said once.
print(f" {choice.note}" if choice.note else
f" {system} card {_mount_name(root)}, BIOS folder {shown_path(choice.folder)}")
_DETECTED_OS.setdefault((choice.plat, choice.folder), system)
if _missing_dest(choice.folder, ask, "typed", again=True):
return choice.folder
def _blank_offer(system: str, count: int) -> str:
"""What line mode says above drives no file names, numbered for a
system whose card they may be: "Mount the card" was said of a card in
the reader."""
if count == 1:
return f"Type 1 if it is the {system} card, or type its top folder."
return f"Type its number if one is the {system} card, or type its top folder."
def _list_cards(cards: list[Path], blank: list[Path], none: str = "") -> list[Path]:
"""Number a system's cards, then the blank drives it may take (the
screen's rows), and return them in that order. none is said when
there is none."""
listed = cards + [mount for mount in blank if mount not in cards]
for index, mount in enumerate(listed, 1):
print(f" {index}) {card_line(mount)}")
if not listed and none:
print(f" {none}")
return listed
def dest_default(setups: list) -> str:
"""The setup a folder named without a system is offered for, on the
screen and in line mode: the one found here, else RetroArch."""
found = list(dict.fromkeys(setup[0] for setup in setups))
return found[0] if len(found) == 1 else "retroarch"
def _platform_for_dest(os_type: str, dest: Path, interactive: bool) -> tuple[str, Path]:
"""The file list for a --dest given without --platform.
A folder says where, not for whom, and a card is often prepared on a PC
for a console: --dest alone installed RetroArch's names and layout into
a Batocera share. The platforms detected here are the evidence. At a
terminal the user picks, Enter taking the one found. Otherwise the one
found is used, RetroArch when none is, and several found are refused.
"""
card = card_platform(dest)
if card:
print(f" File list: {display_name(card)} (the card's {CARD_MARKER}). "
f"Same choice without detection: --platform {card}")
return card, dest
print("Looking for setups here...")
if interactive:
# The screen's list for --dest: the setups found here first, in its
# order and with its default. Without them the cards came after
# RetroArch, and Onion was 19 here and 29 on the screen.
setups, mounted = found_setups(os_type)
default = dest_default(setups)
while interactive:
named = _choose_platform(f"Which platform's files go to {shown_path(dest)}?",
default, setups, mounted)
plat = normalize_platform(named, say=False)
# A system that runs from its card checks dest as --platform does.
choice = card_choice(named, plat, dest)
if choice.refused:
detail = f" {choice.detail}." if choice.detail else ""
print(f" {choice.refused}.{detail} Choose another.")
continue
if choice.note:
print(f" {choice.note}")
print(f" File list: {display_name(plat)}. Same choice without questions: "
f"--platform {_name_key(named) if named != plat else plat}")
return plat, choice.folder
# The setups the screen and line mode find, cards mounted here included.
found = list(dict.fromkeys(name for name, _path, _label in found_setups(os_type)[0]))
default = found[0] if len(found) == 1 else "" if found else "retroarch"
if not default:
print(f"Error: {' and '.join(display_name(n) for n in found)} found here. "
f"Name the platform {dest} is for with --platform.", file=sys.stderr)
sys.exit(1)
why = "the platform found here" if found else "nothing was detected here"
print(f" File list: {display_name(default)} ({why}). For another platform's "
"list, add --platform (--list-platforms names them).")
return default, dest
def _several_found(platforms: list[tuple[str, Path]], setups: list) -> None:
"""Stop a run without questions that found more than one setup, each
named with the options that choose it."""
labels = {(name, path): label for name, path, label in setups}
shown = [(labels.get((name, path)) or _setup_label(name, path), name, path)
for name, path in platforms]
conflict = os_conflict(platforms)
lead = (f"{' and '.join(conflict)} are both detected here, and a machine runs one"
if conflict else f"{len(shown)} setups were found here")
message = (f"{lead}, and a run without questions installs for one: "
+ ", ".join(label for label, _n, _p in shown))
EVENTS.emit("error", stage="detect", reason="conflict", platform="", message=message)
print(f"Error: {message}. Name the one to install for:", file=sys.stderr)
for label, name, path in shown:
print(f" {label}: --platform {name} --dest {shown_path(path)}", file=sys.stderr)
sys.exit(1)
def _unknown_target(target: str, plat: str, targets: dict, *after: str) -> NoReturn:
if not targets:
# No value can work: "unknown target" read as a typo of the board.
refuse_name(plat, f"Error: {display_name(plat)} has no hardware targets: run again "
"without --target.", *after)
refuse_name(plat, f"Error: unknown target '{target}' for {display_name(plat)}.",
" " + did_you_mean([target], sorted(targets), "--list-targets"), *after)
def _card_what(mount: Path) -> str:
"""What a mounted card is, as its own files say."""
system = card_system(mount)
return f"{card_title(system[2])} {drive_kind(system)}" if system else "card or drive"
def dest_drive(dest: Path | None) -> Path | None:
"""The mounted card or drive dest is on, None for none."""
if dest is None:
return None
place = dest.absolute()
return next((mount for mount in _mounted_cards()
if mount == place or mount in place.parents), None)
def copy_source_refusal(chosen: Path | None, dest: Path | None) -> str:
"""Why a folder cannot be copied from, "" when it can: the card being
installed to, or the BIOS folder itself. The copy browser focused that
card, and choosing it was taken without a word."""
if chosen is None or dest is None:
return ""
place = chosen.absolute()
if place == dest.absolute():
return "That is the BIOS folder being installed to: choose the old card or a backup."
if place == dest_drive(dest):
return "That is the card being installed to: choose the old card or a backup."
return ""
def _last_name(folder: str) -> str:
"""A folder or ZIP by its last name, a drive by itself (E:\\), a WSL
path by the name Windows gives it (E:\\old is old, /mnt/e is E:\\)."""
shown = shown_path(folder)
if shown != str(folder):
return shown.rstrip("\\").rsplit("\\", 1)[-1] + ("\\" if shown.endswith(":\\")
else "")
return Path(folder).name or folder
+342
View File
@@ -0,0 +1,342 @@
"""RomM firmware layout and the narrowing a command or a record asks for."""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from installer.constants import DEFAULT_RELEASE_REF, RELEASE_REF
from installer.cores import entry_systems, key_file_holders, refuse_name
from installer.embedded import display_name
from installer.line_ui import emulator_names, system_aliases
from installer.narrowing import (
available_choices,
designated_cores,
narrow_to_cores,
recorded_axes,
resolve_choices,
resolve_regions,
standalone_layout,
)
from installer.network import _pack_alone, fetch_standalone
from installer.offline import LOCAL
from installer.probe import _is_dir
from installer.record import drop_recorded
from installer.terminal import detail
# RomM 5.4 places each platform's firmware by `filesystem.structure.firmware`
# in config.yml, "bios/{platform}" by default, relative to the library
# (rommapp/romm 5.4.0 68f71259, backend/config/config_manager.py:58,101-109,
# 205-225,564-568). The library and config.yml both sit under the RomM base
# folder (config/__init__.py:46-48, config_manager.py:264-265). A library
# laid out as {platform}/roms makes RomM stop until config.yml declares its
# templates, and RomM suggests firmware: "{platform}/bios" there
# (config_manager.py:1105-1124).
def parse_romm_firmware(template: str) -> tuple[tuple[str, ...], tuple[str, ...]]:
"""The literal folders before and after {platform}, as RomM parses them."""
sections = [section for section in template.strip().split("/") if section]
if not sections:
raise ValueError("the RomM firmware template is empty")
def macro(section: str) -> str | None:
if section.startswith("{") and section.endswith("}"):
return section[1:-1].strip()
return None
if any(section in (".", "..") for section in sections):
raise ValueError(f"the RomM firmware template {template!r} climbs out of the library")
platform_at = [i for i, section in enumerate(sections) if macro(section) == "platform"]
if len(platform_at) != 1:
raise ValueError(f"the RomM firmware template {template!r} needs one '{{platform}}'")
before, after = sections[:platform_at[0]], sections[platform_at[0] + 1:]
if any(macro(section) is not None for section in before + after):
raise ValueError(f"the RomM firmware template {template!r} takes literal folder "
"names around '{platform}'")
return tuple(before), tuple(after)
def _romm_configured_firmware(config: Path) -> str | None:
"""filesystem.structure.firmware from RomM's config.yml, read without a
YAML library: only that nested scalar is needed."""
try:
lines = config.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
return None
path: list[tuple[int, str]] = []
for line in lines:
stripped = line.split(" #", 1)[0].rstrip()
if not stripped.strip() or stripped.lstrip().startswith(("#", "-")):
continue
indent = len(stripped) - len(stripped.lstrip())
key, sep, value = stripped.strip().partition(":")
if not sep:
continue
while path and path[-1][0] >= indent:
path.pop()
keys = [name for _indent, name in path] + [key.strip().strip("'\"")]
if keys == ["filesystem", "structure", "firmware"] and value.strip():
return value.strip().strip("'\"")
path.append((indent, key.strip().strip("'\"")))
return None
def romm_firmware_layout(
bios_path: Path, template: str | None
) -> tuple[tuple[str, ...], tuple[str, ...]] | None:
"""Where RomM reads each platform's firmware, relative to its library.
bios_path is the folder the default template names, so its parent is the
library. The template comes from --romm-firmware, else from config.yml
beside the library. None keeps the pack's own bios/<platform> layout.
"""
library = bios_path.parent
if template is None:
template = _romm_configured_firmware(library.parent / "config" / "config.yml")
if template is not None:
return parse_romm_firmware(template)
platform_first = not _is_dir(library / "roms") and any(
_is_dir(path) for path in library.glob("*/roms")
)
if platform_first:
raise ValueError(
f"{library} keeps its roms inside each platform folder, and RomM then "
"reads firmware where filesystem.structure.firmware in its config.yml "
"says, which was not found here. RomM suggests \"{platform}/bios\" for "
"this layout: run again with --romm-firmware \"{platform}/bios\", or "
"with the value config.yml holds."
)
return None
def romm_relayout(
files: list[dict], bios_path: Path,
before: tuple[str, ...], after: tuple[str, ...],
) -> tuple[list[dict], Path]:
"""The manifest's bios/<platform>/<file> entries under RomM's template,
with the library as the root they are relative to."""
if (before, after) == (("bios",), ()):
return files, bios_path
moved = []
for entry in files:
slug, _, rest = str(entry["dest"]).partition("/")
if not rest:
# Firmware of no platform: RomM lists none, the default place stays.
moved.append({**entry, "dest": f"bios/{slug}"})
continue
moved.append({**entry, "dest": "/".join((*before, slug, *after, rest))})
return moved, bios_path.parent
def _older_list_advice(plat: str = "") -> str:
"""How to reach a file list that records what an option needs.
A list without the fields comes from an older release. Pinned with
RETROBIOS_REF, as the docs suggest for reproducibility, "a newer one"
meant unsetting the variable, and nothing said so. A pack's own list is
the pack's: the one-line installer does not change it, and a current
pack was said to come from an older release.
"""
if _pack_alone(plat) and LOCAL.pack is not None:
return (f" The list in {LOCAL.pack.name} does not record it: add --manifest FILE, "
f"a copy of install/{plat or '<platform>'}.json, or run without the option.")
if RELEASE_REF != DEFAULT_RELEASE_REF:
return (f" RETROBIOS_REF={RELEASE_REF} selects file lists published before "
"this option existed: unset RETROBIOS_REF to use the current ones, "
"or run without the option.")
return (" The file list comes from an older release: run the one-line "
"installer again to fetch the current one.")
def _narrowing_advice(plat: str, axis: str, flag: str, recorded: frozenset,
pack_alone: bool) -> str:
"""What to do when a list or a pack records no axis: only a remedy
that changes the outcome. The pack's remedy named install/minui.json,
refused the same way, and the list's fetched the same list again."""
works = [name for name, field in (("--system", "systems"), ("--core", "cores"),
("--region", "regions")) if field in recorded]
rest = f"Run it without {flag}" + (f", or narrow with {' and '.join(works)}"
if works else "") + "."
if pack_alone:
listed = LOCAL.pack.list_records if LOCAL.pack is not None else None
if listed is not None and axis not in listed:
# The pack says its platform's own list lacks the axis too.
return f" {display_name(plat)}'s own file list records no {axis} either. {rest}"
when = "which records them" if listed is not None else f"when that list records {axis}"
return f" Add --manifest FILE, a copy of install/{plat}.json, {when}. {rest}"
if recorded:
# A current list: the platform has no such axis.
return f" {rest}"
return _older_list_advice(plat)
def _narrow_to_emulators(
names: list[str], manifest: dict, plat: str,
files: list[dict], omitted: list[dict],
) -> tuple[list[dict], list[dict]]:
"""Keep what the named emulators read, as the pack built for them.
An emulator page offers this as one command, so a name the platform
does not run is refused rather than read as nothing to install.
"""
if "system_cores" not in manifest:
print(f"Error: the {plat} file list does not say which emulators read "
"which systems, which --emulator needs.", file=sys.stderr)
print(_older_list_advice(plat), file=sys.stderr)
sys.exit(1)
known = sorted(emulator_names(manifest, files, omitted))
try:
chosen = resolve_choices(names, known, "emulator")
except ValueError as exc:
refuse_name(plat, f"Error: {plat}: {exc}")
before = len(files)
files, omitted = narrow_to_cores(manifest, chosen, files, omitted)
# A whole-platform install keeps the platform's files of a system no
# core is mapped to. Here only the named emulators' systems are wanted.
cores = designated_cores(manifest, chosen)
reached = {
system for system, readers in (manifest.get("system_cores") or {}).items()
if cores.intersection(readers)
}
def theirs(entry: dict) -> bool:
return entry.get("cores") is not None or bool(reached.intersection(entry_systems(entry)))
files = [entry for entry in files if theirs(entry)]
omitted = [entry for entry in omitted if theirs(entry)]
print(f" Narrowed {before} to {len(files)} files to {', '.join(chosen)}")
return files, omitted
def _standalone_builds(
values: list[str], names: dict[str, str], manifest: dict, plat: str,
files: list[dict], omitted: list[dict],
) -> tuple[list[dict], list[dict]]:
"""--emulator with --standalone: each emulator's standalone build in
place of the files its core reads. An emulator with no standalone
build is refused, as `generate_pack.py --standalone` refuses it."""
if "standalone_builds" not in manifest:
print(f"Error: the {plat} file list does not say which emulators have a "
"standalone build, which --standalone needs.", file=sys.stderr)
print(_older_list_advice(plat), file=sys.stderr)
sys.exit(1)
profiles = sorted({names[name] for name in resolve_choices(values, sorted(names),
"emulator")})
lacking = [p for p in profiles if p not in manifest["standalone_builds"]]
if lacking:
refuse_name(plat, f"Error: {', '.join(lacking)} has no standalone build: run "
"again without --standalone.")
before = len(files)
files, omitted = standalone_layout(manifest, fetch_standalone(plat, manifest), profiles,
files, omitted)
detail(f" The standalone {'builds' if len(profiles) > 1 else 'build'}: "
f"{before} to {len(files)} files")
return files, omitted
def _known_names(values: list[str] | None, known: list[str], label: str,
aliases: dict[str, str] | None = None) -> list[str]:
"""The names of values that resolve against known, the others left out."""
kept = []
for value in values or []:
try:
resolve_choices([value], known, label, aliases)
except ValueError:
continue
kept.append(value)
return kept
def _recorded_names(args: argparse.Namespace, plat: str, flag: str, known: list[str],
aliases: dict[str, str] | None = None) -> None:
"""A recorded --system, --core or --emulator kept to the names the list
still holds, the others left out in one line."""
name = flag[2:].replace("-", "_")
values = list(getattr(args, name) or [])
kept = _known_names(values, known, flag[2:], aliases)
if kept != values:
gone = ", ".join(value for value in values if value not in kept)
drop_recorded(args, plat, flag, f"{gone} no longer on the list", kept)
def _recorded_emulators(args: argparse.Namespace, plat: str, manifest: dict,
files: list[dict], omitted: list[dict]) -> None:
"""A recorded --emulator that cannot narrow this list, left out."""
if "system_cores" not in manifest:
drop_recorded(args, plat, "--emulator", "the list does not say which emulators "
"read which systems")
return
_recorded_names(args, plat, "--emulator", sorted(emulator_names(manifest, files, omitted)))
def _recorded_regions(args: argparse.Namespace, plat: str) -> None:
"""A recorded --region kept to the regions this installer knows."""
values = list(args.region or [])
kept = []
for value in values:
try:
resolve_regions([value])
except ValueError:
continue
kept.append(value)
if kept != values:
drop_recorded(args, plat, "--region", "a region this installer does not know", kept)
def _requested_narrowing(
args: argparse.Namespace, plat: str, files: list[dict], omitted: list[dict],
manifest: dict | None = None,
) -> tuple[list[str], list[str], list[str]] | None:
"""The systems, cores and regions named on the command line, checked."""
if not (args.system or args.core or args.region):
return None
pack_alone = _pack_alone(plat)
recorded = recorded_axes(files, omitted)
if pack_alone:
# A pack records the systems of its files, not their cores or
# regions: either filter would keep everything, and is refused.
recorded = recorded & {"systems"}
asked = [(flag, axis) for flag, given, axis in (
("--system", args.system, "systems"), ("--core", args.core, "cores"),
("--region", args.region, "regions")) if given]
if getattr(args, "from_record", False):
# A recorded option that cannot narrow this list is left out: nobody
# typed it, and every run without options would stop on it.
for flag, axis in asked:
if axis not in recorded:
drop_recorded(args, plat, flag, f"the list records no {axis}")
asked = [(flag, axis) for flag, axis in asked if axis in recorded]
_recorded_regions(args, plat)
choices = available_choices(files, omitted)
if args.system:
_recorded_names(args, plat, "--system", choices["systems"],
system_aliases(manifest))
if args.core:
_recorded_names(args, plat, "--core", choices["cores"])
if not (args.system or args.core or args.region):
return None
for flag, axis in asked:
if axis in recorded:
continue
# Without the field, a filter would match nothing and install
# everything: refused rather than ignored, by the axis the list
# lacks, with what works on it.
source = (LOCAL.pack.name if pack_alone and LOCAL.pack is not None
else f"the {plat} file list")
print(f"Error: {source} records no {axis}, so {flag} cannot narrow it.",
file=sys.stderr)
print(_narrowing_advice(plat, axis, flag, recorded, pack_alone), file=sys.stderr)
sys.exit(1)
choices = available_choices(files, omitted)
try:
systems = resolve_choices(
args.system or [], choices["systems"], "system", system_aliases(manifest),
key_file_holders(files, omitted),
)
cores = resolve_choices(args.core or [], choices["cores"], "core")
regions = resolve_regions(args.region or [])
except ValueError as exc:
refuse_name(plat, f"Error: {plat}: {exc}")
return systems, cores, regions
+523
View File
@@ -0,0 +1,523 @@
"""main: the options read, the action chosen and the run started."""
from __future__ import annotations
import argparse
import io
import os
import re
import sys
from collections.abc import Callable
from pathlib import Path
from typing import NoReturn
from installer.app import app_not_added
from installer.arguments import PACK_NAME_END, build_parser
from installer.constants import AVAILABLE_PLATFORMS, TARGET_PLATFORMS, _writing
from installer.cores import refuse_name
from installer.detect_os import detect_os
from installer.embedded import _name_key, display_name
from installer.events import EVENTS, _event_exit_code, _event_mode
from installer.from_folders import _open_local_sources
from installer.invocation import OFFLINE_VARIABLE, _INVOCATION, installer_id, offline_requested
from installer.line_ui import fold_line
from installer.narrowing import FIND_KINDS, resolve_regions
from installer.network import _RAW_ERRORS, install_bounded_opener
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE, offline_named
from installer.probe import _is_dir
from installer.record import restore_kept
from installer.removal import run_backups, run_delete_backup, run_removal
from installer.run import TUI_LIST_ENV, TUI_RECORD_ENV, _install
from installer.terminal import EVENT_SCHEMA, OUTPUT
from installer.tui_session import run_tui
from installer.tui_state import line_mode_reason, plain_requested, tui_blocker
def _check_expert(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""--one-per-slot, --standalone, --source truth and --find, applied or
refused, never ignored. Each is held equal to the pack builder's own
option, so a choice the builder refuses beside it is refused here."""
listing = (args.list_platforms or args.list_targets or args.list_systems
or args.list_cores or args.list_emulators)
truth = args.source == "truth"
refusals = (
(args.json and not args.find, "--json applies to --find"),
(args.standalone and not args.emulator,
"--standalone applies to --emulator: it picks that emulator's standalone build"),
(args.standalone and (args.region or args.one_per_slot or args.core or args.system),
"--standalone installs each emulator's standalone build whole, which "
"--region, --one-per-slot, --core and --system do not narrow"),
(args.one_per_slot and (args.system or args.emulator or args.for_games is not None),
"--one-per-slot decides each slot over the whole list, which --system, "
"--emulator and --for-games narrow first"),
(args.one_per_slot and args.declared_only,
"--one-per-slot ranks the files cores load too, which --declared-only leaves out"),
(truth and (args.system or args.core or args.emulator or args.region
or args.one_per_slot or args.for_games is not None
or args.declared_only or args.target or args.installed_cores
or args.no_game_data),
"--source truth installs what the emulator profiles prove is read, over "
"the whole list: run it without other choices"),
(truth and args.tui, "the full-screen interface has no choice for --source truth"),
(bool(args.find) and (args.system or args.core or args.emulator or args.region
or args.one_per_slot or truth or args.for_games is not None
or args.declared_only or args.no_game_data or args.target
or args.installed_cores or args.all_files or args.standalone),
"--find picks one file by its hash: run it without other choices"),
(bool(args.find) and (listing or args.check or args.tui),
"--find installs or names one file, not a listing, a check or the full screen"),
(args.json and args.events, "--json and --events each write JSON on stdout"),
(listing and (args.one_per_slot or args.standalone or truth),
"a listing prints the whole list, which --one-per-slot, --standalone and "
"--source do not narrow"),
)
for given, reason in refusals:
if given:
parser.error(reason)
if args.find:
# Each would be skipped by a run that installs one file or prints it.
for flag, given in (("--pack", getattr(args, "pack", None) is not None),
("--add-app", args.add_app),
("--standalone-copies", args.standalone_copies),
("--romm-firmware", args.romm_firmware is not None),
("--from", bool(getattr(args, "from")))):
if given:
parser.error(f"--find picks one file by its hash, which {flag} does not apply to")
if args.find is not None:
value = args.find.strip()
if len(value) not in FIND_KINDS or not re.fullmatch(r"[0-9a-fA-F]+", value):
kinds = ", ".join(f"{kind} ({length} digits)" for length, kind in FIND_KINDS.items())
parser.error(f"--find takes a hash in hexadecimal: {kinds}")
def say_raw_errors(verbose: bool) -> None:
"""Each run says errors from its own options: a run with --verbose before
it in the same process left every later message with its raw cause."""
if verbose:
_RAW_ERRORS.set()
else:
_RAW_ERRORS.clear()
def _main_settle(args: argparse.Namespace) -> None:
"""Options that set others, and the record of the command."""
say_raw_errors(args.verbose)
if args.cores_dir:
args.installed_cores = True
if args.yes:
# Asked at a terminal, --yes still waited at Install for: and at
# the menu. Yes to every question is no question.
args.no_input = True
_INVOCATION.record(args)
if os.environ.get(TUI_RECORD_ENV):
args.from_record = True
if os.environ.get(TUI_LIST_ENV):
# The full screen's own copy of the list, deleted when it closes: a
# command naming it fails once the screen is gone.
_INVOCATION.options = [option for option in _INVOCATION.options
if option[0] != "--manifest"]
def _main_check_values(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse values out of range and options that ask for two things."""
if not 1 <= args.jobs <= 32:
parser.error("--jobs must be between 1 and 32")
if args.region:
try:
resolve_regions(args.region)
except ValueError as exc:
parser.error(str(exc))
for option, values in (("--system", args.system), ("--core", args.core)):
if values is not None and not any(
token.strip() for value in values for token in value.split(",")
):
parser.error(f"{option} needs at least one name")
if args.quiet and (
args.check or args.dry_run or args.list_platforms or args.list_targets
or args.list_systems or args.list_cores or args.list_emulators
):
parser.error("--quiet applies to an install, not to --check, --dry-run or a listing")
if args.tui and args.plain:
parser.error("--tui and --plain ask for two different interfaces")
if args.all_files and args.for_games is not None:
parser.error("--all-files and --for-games ask for two different lists")
if args.required_only and args.for_games is None:
parser.error("--required-only applies to --for-games: the list alone does not "
"say which files a game cannot start without")
if args.for_games is not None and (
args.list_platforms or args.list_targets or args.list_systems
or args.list_cores or args.list_emulators):
parser.error("--for-games narrows an install, not a listing")
def _main_check_listings(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse two listings, or a listing with an option it does not read."""
# Applied or refused, never ignored: a run prints one list, and the
# narrowing options apply to --list-systems and --list-cores only, past
# --target and --installed-cores, which --list-emulators also reads.
listings = [flag for flag, given in (
("--list-platforms", args.list_platforms), ("--list-targets", args.list_targets),
("--list-systems", args.list_systems), ("--list-cores", args.list_cores),
("--list-emulators", args.list_emulators)) if given]
if len(listings) > 1:
parser.error(f"{listings[0]} and {listings[1]} each print a list: run them "
"one at a time")
if listings and listings[0] in ("--list-platforms", "--list-targets",
"--list-emulators"):
unread: tuple[tuple[str, object], ...] = (
("--system", args.system), ("--core", args.core),
("--region", args.region), ("--emulator", args.emulator))
if listings[0] != "--list-emulators":
unread += (("--target", args.target), ("--every-board", args.every_board),
("--installed-cores", args.installed_cores))
if listings[0] == "--list-platforms":
unread += (("--platform", args.platform),)
given = next((flag for flag, value in unread if value), "")
if given:
parser.error(f"{listings[0]} prints the whole list, which {given} "
"does not narrow")
def _main_check_declared_only(parser: argparse.ArgumentParser,
args: argparse.Namespace) -> None:
"""Refuse --declared-only with an option it leaves without effect."""
if args.declared_only:
# Applied or refused, never ignored.
for given, reason in (
(args.tui, "the full-screen interface has no choice for --declared-only"),
(args.list_platforms or args.list_targets,
"--declared-only narrows a file list, not --list-platforms or --list-targets"),
(args.core or args.list_cores,
"--declared-only leaves out the files cores load, which --core and "
"--list-cores choose among"),
(args.list_emulators,
"--list-emulators names emulators, and --declared-only narrows files"),
(args.standalone_copies,
"--standalone-copies copies into standalone emulators' folders, outside "
"the platform's own list that --declared-only keeps"),
):
if given:
parser.error(reason)
def _main_check_add_app(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse --add-app where the run writes or downloads nothing."""
if args.add_app:
# Applied or refused, never ignored.
for given, reason in (
(args.check or args.dry_run,
"--add-app writes the RetroBIOS app on the card, which --check and "
"--dry-run do not"),
(args.list_platforms or args.list_targets or args.list_systems
or args.list_cores or args.list_emulators,
"--add-app writes the RetroBIOS app on the card, which a listing does not"),
(args.from_pack, "--add-app downloads the RetroBIOS app, and --from-pack "
"makes no network request"),
(args.offline or offline_requested(), "--add-app downloads the RetroBIOS "
"app, which --offline does not"),
):
if given:
parser.error(reason)
def _main_check_offline(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Record --offline, and refuse --target where no core list can be read."""
if args.offline:
# The runs the full-screen interface starts read it from here, and
# the words name the option given.
os.environ[OFFLINE_VARIABLE] = OFFLINE_FLAG_VALUE
named = next((plat for plat in AVAILABLE_PLATFORMS if args.platform and _name_key(
args.platform) in (_name_key(plat), _name_key(display_name(plat)))), "")
if offline_requested() and args.target and named and named not in TARGET_PLATFORMS:
refuse_name(named, f"Error: {display_name(named)} has no hardware targets: run "
"again without --target.")
if (offline_requested() and (args.target or args.list_targets)
and not (args.manifest or args.from_pack)
and not (named and named not in TARGET_PLATFORMS)):
# No list can be at hand: a pack carries one, and so can the folder
# of a --manifest (targets/<platform>.json).
parser.error(f"--target needs a core list, which {offline_named()} does not fetch: "
"give --from-pack, or --manifest with targets/<platform>.json beside it")
def _main_check_sources(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse a source of files given with a listing that reads none."""
if getattr(args, "from") and (
args.list_platforms or args.list_targets or args.list_systems
or args.list_cores or args.list_emulators
):
parser.error("--from copies files into the BIOS folder, which a listing "
"does not write")
if (args.from_pack or args.manifest) and args.list_platforms:
# --list-targets reads its boards from them, where --target does.
parser.error("--from-pack and --manifest give a file list, which --list-platforms "
"does not read")
if args.no_game_data and (args.list_platforms or args.list_targets):
parser.error("--no-game-data narrows a file list, not --list-platforms "
"or --list-targets")
def _main_run_events(args: argparse.Namespace) -> None:
"""Run with --events, the run framed by start and end."""
# The events own stdout. The text a person reads goes to stderr, so a
# program never has to tell one from the other.
args.no_input = True
EVENTS.open(sys.stdout)
sys.stdout = sys.stderr
EVENTS.emit("start", schema=EVENT_SCHEMA, installer=installer_id(),
mode=_event_mode(args))
try:
_run(args)
except SystemExit as exc:
EVENTS.emit("end", code=_event_exit_code(exc.code))
raise
except KeyboardInterrupt:
EVENTS.emit("end", code=130)
raise
EVENTS.emit("end", code=0)
def _main_dispatch(args: argparse.Namespace) -> None:
"""Open the full screen, or run line by line, with events or JSON."""
# The screens have no choice for --declared-only: the questions ask the
# rest, and the run keeps the platform's own list.
# Nor for --source truth and --find, which choose the files themselves.
lined = args.declared_only or args.source == "truth" or bool(args.find)
blocker = "" if args.tui else tui_blocker(args)
if args.tui or not (plain_requested(args) or lined or blocker):
sys.exit(run_tui(args))
if not (plain_requested(args) or lined):
# The questions came line by line with no word of why: the page
# says a smaller window says so, and a TERM
# unset or dumb said nothing.
said = line_mode_reason(blocker)
if said:
print(fold_line(said))
if args.events:
_main_run_events(args)
return
if args.json:
# The matches own stdout, the text a person reads goes to stderr.
args.no_input = True
args.json_out = sys.stdout
sys.stdout = sys.stderr
try:
_run(args)
finally:
sys.stdout = args.json_out
return
_run(args)
def main() -> None:
"""Entry point."""
_INVOCATION.os_type = detect_os()
parser = build_parser()
args = parser.parse_args()
_main_settle(args)
_main_check_values(parser, args)
_main_check_listings(parser, args)
_main_check_declared_only(parser, args)
_check_expert(parser, args)
if args.tui:
reason = tui_blocker(args)
if reason:
# The reason alone: fourteen lines of usage hid it.
print(f"{parser.prog}: error: --tui cannot open the full-screen interface "
f"here: {reason}", file=sys.stderr)
sys.exit(2)
_check_actions(parser, args)
_check_pack(parser, args)
if args.restore is not None:
_run_action(args, lambda given: restore_kept(given.restore, given.dry_run))
if args.delete_backup is not None:
_run_action(args, run_delete_backup)
if args.every_board and args.target:
parser.error("--every-board installs every board, and --target names one")
_main_check_add_app(parser, args)
_main_check_offline(parser, args)
install_bounded_opener()
if args.remove or args.backups:
_open_local_sources(args)
_run_action(args, run_removal if args.remove else run_backups)
_main_check_sources(parser, args)
_main_dispatch(args)
# What each action reads beside its own option: anything else given with
# it is refused, never ignored. dest and platform name the BIOS folder.
_ACTION_TAKES = {
"restore": ("dry_run", "events", "yes", "no_input", "verbose"),
"delete_backup": ("dry_run", "events", "yes", "no_input", "verbose"),
"backups": ("platform", "dest", "events", "no_input", "verbose"),
"remove": ("platform", "dest", "system", "core", "emulator", "file", "backup",
"misplaced", "dry_run", "events", "yes", "no_input", "verbose", "manifest", "from_pack",
"offline"),
}
# Options that are a choice of their own, never refused for being given.
_ACTION_FREE = ("jobs", "plain", "from_record")
def _check_actions(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse an action given with an option it does not read, two actions,
or --file, --backup and --misplaced without --remove."""
actions = [name for name in _ACTION_TAKES if getattr(args, name)]
if len(actions) > 1:
parser.error(f"--{actions[0].replace('_', '-')} and --{actions[1].replace('_', '-')} "
"are two actions: run them one at a time")
if not actions:
for name in ("file", "backup", "misplaced"):
if getattr(args, name):
parser.error(f"--{name} applies to --remove")
return
action = actions[0]
defaults = build_parser().parse_args([])
given = [name for name, value in vars(args).items()
if name != action and name not in _ACTION_TAKES[action]
and name not in _ACTION_FREE and value != getattr(defaults, name, value)]
if given:
parser.error(f"--{action.replace('_', '-')} takes no "
f"--{given[0].replace('_', '-')}")
if action == "remove":
narrowed = [flag for flag, value in (("--system", args.system), ("--core", args.core),
("--emulator", args.emulator),
("--file", args.file)) if value]
if len(narrowed) > 1:
parser.error(f"--remove takes one of --system, --core, --emulator or --file, "
f"not {narrowed[0]} and {narrowed[1]}")
if args.misplaced and (narrowed or args.backup):
# The copies are the user's, so no backup note can give them
# back to a setup, and no system or core names them.
parser.error(f"--remove --misplaced takes no {(narrowed or ['--backup'])[0]}")
def _check_pack(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None:
"""Refuse --split without --pack, and --pack with an option that reads
or writes a BIOS folder: applied or refused, never ignored."""
pack = getattr(args, "pack", None)
if getattr(args, "split", None) is not None and pack is None:
parser.error("--split applies to --pack")
if pack is None:
return
for flag, given in (
("--check", args.check), ("--dest", args.dest),
("--installed-cores", args.installed_cores), ("--cores-dir", args.cores_dir),
("--save-dir", args.save_dir), ("--standalone-copies", args.standalone_copies),
("--add-app", args.add_app), ("--romm-firmware", args.romm_firmware is not None),
("--tui", args.tui), ("--list-platforms", args.list_platforms),
("--list-targets", args.list_targets), ("--list-systems", args.list_systems),
("--list-cores", args.list_cores), ("--list-emulators", args.list_emulators),
):
if given:
parser.error(f"--pack writes a pack ZIP, and {flag} reads or writes the "
"BIOS folder of this machine")
if args.for_games is True:
parser.error("--for-games with --pack needs its FOLDER: no card is read for a pack")
name = Path(os.path.expanduser(str(pack))).name
if not (_is_dir(Path(os.path.expanduser(str(pack))))
or str(pack).endswith(("/", os.sep)) or name.endswith(PACK_NAME_END)):
parser.error(f"--pack names a folder, or a file whose name ends with "
f"{PACK_NAME_END} (--from-pack and the parts of a pack read that "
f"name): {name}")
def _run_action(args: argparse.Namespace,
action: Callable[[argparse.Namespace], int]) -> NoReturn:
"""Run an action and exit with its code, its events framed by start and
end with --events."""
if not args.events:
sys.exit(action(args))
args.no_input = True
EVENTS.open(sys.stdout)
sys.stdout = sys.stderr
EVENTS.emit("start", schema=EVENT_SCHEMA, installer=installer_id(),
mode=_event_mode(args))
try:
code = action(args)
except SystemExit as exc:
EVENTS.emit("end", code=_event_exit_code(exc.code))
raise
except KeyboardInterrupt:
EVENTS.emit("end", code=130)
raise
EVENTS.emit("end", code=code)
sys.exit(code)
def _run(args: argparse.Namespace) -> None:
"""The run, its text quiet or not, the archives it read closed after."""
try:
_run_text(args)
except SystemExit as exc:
if exc.code not in (0, None):
app_not_added()
raise
except KeyboardInterrupt:
app_not_added()
raise
finally:
LOCAL.close_indexes()
# A caller running the installer in its own process gets the next
# run's text as quiet as any first run.
OUTPUT.verbose = OUTPUT.where_said = False
def _run_text(args: argparse.Namespace) -> None:
if not args.quiet:
_install(args, sys.stdout)
return
# Quiet: what a run prints is kept, and shown on stderr if the run fails,
# so an error printed on stdout is never lost.
captured = io.StringIO()
real_stdout = sys.stdout
sys.stdout = captured
try:
_install(args, real_stdout)
except SystemExit as exc:
if sys.stdout is captured:
sys.stdout = real_stdout
if exc.code not in (0, None):
sys.stderr.write(captured.getvalue())
raise
finally:
if sys.stdout is captured:
sys.stdout = real_stdout
def _line_buffered_stdout() -> None:
"""Flush stdout line by line, as stderr is.
Piped to a log (`| tee install.log`), stdout was block-buffered while
errors went out at once: the log opened on "Could not fetch the file
list" before the banner and the step that produced it.
"""
reconfigure = getattr(sys.stdout, "reconfigure", None)
if reconfigure is not None:
try:
reconfigure(line_buffering=True)
except (ValueError, OSError):
# A stream that cannot be reconfigured keeps its own buffering:
# the order of a log is cosmetic, the run goes on.
return
if __name__ == "__main__":
_line_buffered_stdout()
# A reader that stops early (`install.py --list | head`) ends the run
# quietly instead of on a BrokenPipeError traceback.
try:
main()
sys.stdout.flush()
except BrokenPipeError:
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
sys.exit(141)
except KeyboardInterrupt:
# Outside the download phase (fetching the file list, checking the
# files present, rebuilding data directories): nothing is half
# written there, and a socket traceback read as a crash. Stopped at
# a question, nothing has started, and there is nothing to carry on.
if _writing.is_set():
print("\nStopped. Run the same command again to carry on from here. "
"Nothing is lost.")
else:
print("\nStopped. Nothing was installed.")
sys.exit(130)
+256
View File
@@ -0,0 +1,256 @@
"""Where the file lists and files come from, their limits, and the vocabulary every part shares."""
from __future__ import annotations
import os
import re
import sys
import threading
import urllib.parse
from pathlib import Path
# File lists are read from main, the newest ones, whichever commit the
# installer came from. RETROBIOS_REF pins them to a tag or a commit when
# reproducibility matters.
DEFAULT_RELEASE_REF = "main"
RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF)
DEFAULT_BASE_URL = (
"https://raw.githubusercontent.com/Abdess/retrobios/"
+ urllib.parse.quote(RELEASE_REF, safe="")
)
_LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1")
def _checked_base_url(value: str) -> str:
"""Refuse a base URL that is neither HTTPS nor loopback.
This base serves the manifest and the files it declares, so whoever
controls it controls the expected hashes too and verification stops
proving anything. install.sh and install.ps1 make the same check on the
URL they fetch the installer from.
Plain HTTP to loopback stays allowed: nothing sits between the two ends
to intercept it, and it is how the installer is exercised end to end.
"""
parsed = urllib.parse.urlparse(value)
if parsed.scheme == "https":
return value
host = (parsed.hostname or "").lower()
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
return value
print(
f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}",
file=sys.stderr,
)
sys.exit(1)
BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL))
MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json"
TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json"
# What --standalone reads, apart from the list every run downloads.
STANDALONE_DIR = "standalone"
STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json"
# The platforms that publish a core list per board, install/targets/ in the
# repository: a test holds the two equal. Offline, a platform outside it
# has no hardware targets, where the run sent the user after a list that
# exists nowhere.
TARGET_PLATFORMS = frozenset({
"amberelec", "batocera", "emudeck", "emuelec", "knulli", "lakka", "recalbox", "retroarch",
"retrobat", "retrodeck", "retropie", "rocknix", "romm",
})
RAW_FILE_URL = f"{BASE_URL}/{{path}}"
RELEASE_URL = (
"https://github.com/Abdess/retrobios/releases/download/large-files/{asset}"
)
MAX_RETRIES = 3
# Seconds a connection has to open. A dropped network cost three tries of a
# 30-second timeout, 93 s, before the error: a connection that does not open
# now fails in this time, and once open a read waits as long as before, so
# a slow line is not cut.
CONNECT_TIMEOUT = 4.0
MAX_MANIFEST_BYTES = 16 * 1024 * 1024
MAX_TARGETS_BYTES = 4 * 1024 * 1024
MAX_STANDALONE_BYTES = 16 * 1024 * 1024
MAX_MANIFEST_FILES = 100_000
MAX_DOWNLOAD_SIZE = 1024 * 1024 * 1024
# A data directory's source archive: PCSX2's source tarball is the largest.
MAX_DATA_ARCHIVE_SIZE = 4 * 1024 * 1024 * 1024
MAX_TOTAL_DOWNLOAD_SIZE = 64 * 1024 * 1024 * 1024
# Why a manifest leaves a file out, as the installer words it. The manifest
# schema and the generator are held to this list by the tests.
OMISSION_REASONS = {
"hash_mismatch": "hash mismatch",
"not_found": "not found",
"external": "external",
"user_provided": "user provided",
"no_platform_slug": "no platform folder",
"below_platform_folder": "below the platform folder",
"no_save_directory": "no save directory",
"no_core_folder": "no core folder",
"no_save_system": "no system runs the core",
"outside_bios_folder": "read outside the BIOS folder",
"no_roms_directory": "no roms folder",
"no_configs_directory": "no configs folder",
"no_emulators_directory": "no emulator folder",
}
# What a file is when it is not firmware, as the manifest's category field
# says, and as the installer words it. Firmware carries no category.
GAME_DATA = "game_data"
CATEGORY_LABELS = {GAME_DATA: "game data"}
# The manifest writes its digests in lowercase, as hashlib gives them, and
# every comparison reads them as written.
_SHA1_RE = re.compile(r"^[0-9a-f]{40}$")
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
# The region vocabulary of scripts/region.py, which this file cannot import.
# A test holds the two copies equal.
WORLD_REGION = "world"
REGION_TREE: dict[str, frozenset] = {
"north-america": frozenset({"canada"}),
"latin-america": frozenset({"brazil", "mexico", "argentina"}),
"europe": frozenset({
"uk", "france", "germany", "italy", "spain", "netherlands", "portugal",
"greece", "poland", "russia", "sweden", "norway", "denmark", "finland",
}),
"asia": frozenset({
"japan", "south-korea", "china", "taiwan", "hong-kong", "singapore",
"india", "asia-ntsc", "asia-pal",
}),
"oceania": frozenset({"australia", "new-zealand"}),
}
REGION_ALIASES: dict[str, str] = {
"jp": "japan",
"ntsc-j": "japan",
"us": "north-america",
"usa": "north-america",
"na": "north-america",
"ntsc-u": "north-america",
"eu": "europe",
"pal": "europe",
"kr": "south-korea",
"korea": "south-korea",
"auto": WORLD_REGION,
"gb": "uk",
"ca": "canada",
"br": "brazil",
"mx": "mexico",
"ar": "argentina",
"fr": "france",
"de": "germany",
"it": "italy",
"es": "spain",
"nl": "netherlands",
"pt": "portugal",
"gr": "greece",
"pl": "poland",
"ru": "russia",
"se": "sweden",
"no": "norway",
"dk": "denmark",
"fi": "finland",
"cn": "china",
"tw": "taiwan",
"hk": "hong-kong",
"sg": "singapore",
"in": "india",
"au": "australia",
"nz": "new-zealand",
}
AREA_TERRITORIES: dict[str, frozenset] = {
"asia-ntsc": frozenset({"taiwan"}),
"asia-pal": frozenset({"china"}),
}
_REGION_PARENT = {
member: parent for parent, members in REGION_TREE.items() for member in members
}
REGIONS = frozenset({WORLD_REGION} | set(REGION_TREE) | set(_REGION_PARENT))
# Marks a region group named after one file that no system names.
FILE_GROUP = ":file:"
MAX_SELECTION_TAGS = 1000
SELECTION_FIELDS = ("systems", "regions", "region_groups", "region_system_groups")
# The files cores load for systems the platform does not list (game engines,
# computers): no system of the platform owns them, and choosing systems
# leaves them out unless this name is chosen too.
OTHER_SYSTEMS = "other"
# Platforms with a manifest in install/. Manifest URLs are case sensitive,
# so user input is normalized against this list before any fetch.
AVAILABLE_PLATFORMS = (
"retroarch", "batocera", "recalbox", "retrobat", "emudeck",
"lakka", "retrodeck", "rocknix", "romm", "bizhawk", "misterfpga",
"retropie", "amberelec", "emuelec", "knulli",
"minui", "nextui", "myminui",
)
# The names the frontends give themselves, as each manifest's display_name
# spells them (a test holds the two equal). Detection and the platform menu
# come before any manifest is fetched, and str.capitalize() wrote Retroarch,
# Retrodeck and Misterfpga.
PLATFORM_NAMES = {
"retroarch": "RetroArch", "batocera": "Batocera", "recalbox": "Recalbox",
"retrobat": "RetroBat", "emudeck": "EmuDeck", "lakka": "Lakka",
"retrodeck": "RetroDECK", "rocknix": "ROCKNIX", "romm": "RomM",
"bizhawk": "BizHawk", "misterfpga": "MiSTer FPGA", "retropie": "RetroPie",
"amberelec": "AmberELEC", "emuelec": "EmuELEC", "knulli": "KNULLI",
"minui": "MinUI", "nextui": "NextUI", "myminui": "MyMinUI",
}
# Frontends whose BIOS live on their SD card, installed from a computer the
# card is mounted on. Each release unpacks as .system/ at the card root and
# writes its release name as the first line of .system/version.txt (MinUI
# makefile:22-24 and 152-157, NextUI makefile:33-35 and 249, MyMinUI
# makefile:16-19 and 124). The registry publishes the same rules as each
# manifest's `detect` (card_marker), and a test holds the two equal.
CARD_MARKER = ".system/version.txt"
_CARD_RULES: tuple[tuple[str, str, str], ...] = (
("minui", CARD_MARKER, "MinUI-"),
("nextui", CARD_MARKER, "NextUI-"),
("myminui", CARD_MARKER, "MyMinUI-"),
)
CARD_PLATFORMS = frozenset(name for name, _file, _prefix in _CARD_RULES)
SITE_URL = "https://abdess.github.io/retrobios/"
INSTALLER_PAGE = f"{SITE_URL}wiki/installer/"
TROUBLESHOOTING_PAGE = f"{SITE_URL}wiki/troubleshooting/"
# The one-line bootstraps the site serves: BOOTSTRAP_URL for sh, .ps1 after it
# for PowerShell (scripts/sitebootstrap.py).
BOOTSTRAP_URL = f"{SITE_URL}i"
# Fallback BIOS destination per platform when --platform is forced
# but auto-detection finds nothing on the machine.
DEFAULT_DESTS = {
"batocera": Path("/userdata/bios"),
"recalbox": Path("/recalbox/share/bios"),
"lakka": Path("/storage/system"),
"retrodeck": Path.home() / "retrodeck",
"emudeck": Path.home() / "Emulation" / "bios",
"rocknix": Path("/storage/roms/bios"),
# Their BIOS lists name files under /storage/roms beside bios/.
"amberelec": Path("/storage/roms"),
"emuelec": Path("/storage/roms"),
"knulli": Path("/userdata/bios"),
"misterfpga": Path("/media/fat/games"),
"retropie": Path.home() / "RetroPie" / "BIOS",
"romm": Path("/romm/library/bios"),
}
# Set when the run is interrupted, so queued downloads end instead of draining
# the pool: every future is submitted before the first one completes.
_stop = threading.Event()
# Set once a run starts writing: Ctrl+C before that has nothing to carry on.
_writing = threading.Event()
class _Interrupted(Exception):
"""Raised inside a worker once the run has been stopped."""
# A file this size or larger keeps its partial download when a transfer
# stops, and the next run asks the server for the rest: the release assets
# run to hundreds of megabytes. Smaller files simply start over.
RESUME_FROM_SIZE = 16 * 1024 * 1024
# Read once, before any download thread runs: reading the umask sets it.
_UMASK = os.umask(0)
os.umask(_UMASK)
+436
View File
@@ -0,0 +1,436 @@
"""Libretro cores installed, their info files, and the names people type for platforms and systems."""
from __future__ import annotations
import errno
import os
import re
import sys
import tempfile
from pathlib import Path, PurePosixPath
from typing import NoReturn
from installer.constants import AVAILABLE_PLATFORMS
from installer.detect_os import _NO_FOLDER, _retroarch_cfg_dir
from installer.embedded import _EMBEDDED_RULES, _name_key, display_name, shown_path
from installer.events import EVENTS
from installer.local_files import _retroarch_config_for
from installer.probe import _exists, _is_dir, _is_file
# A libretro core as RetroArch loads it: <name>_libretro.so|dll|dylib, and
# <name>_libretro_android.so on Android.
_CORE_FILE_RE = re.compile(
r"^(?P<name>.+?)_libretro(?:_android)?\.(?:so|dll|dylib)$", re.IGNORECASE
)
CORE_PLATFORMS = ("retroarch", "lakka", "retropie")
# Where these systems install cores whatever retroarch.cfg says: RetroPie
# gives each package its own folder, Lakka keeps the image's cores and the
# ones the online updater fetches apart.
_FIXED_CORE_DIRS = {
"retropie": (Path("/opt/retropie/libretrocores"),),
"lakka": (Path("/usr/lib/libretro"), Path("/storage/cores"), Path("/tmp/cores")),
}
def core_dirs(plat: str, bios_path: Path) -> list[Path]:
"""The directories the RetroArch writing to bios_path loads cores from.
The config detection read for this system directory names them in
libretro_directory, read here when the run was given --dest, as the
interface's runs all are. Without one, a retroarch.cfg beside the system
directory is the portable layout. Unset, the setting is cores/ under
RetroArch's own directory.
"""
found = _retroarch_config_for(bios_path)
if found is None and _is_file(bios_path.parent / "retroarch.cfg"):
found = (bios_path.parent / "retroarch.cfg", bios_path.parent)
dirs: list[Path] = []
if found is not None:
cfg, app_dir = found
dirs.append(
_retroarch_cfg_dir(cfg, "libretro_directory", app_dir, "cores")
or app_dir / "cores"
)
dirs.extend(_FIXED_CORE_DIRS.get(plat, ()))
return list(dict.fromkeys(dirs))
def keeps_case(directory: Path) -> bool:
"""Whether names differing only by case are distinct files there.
Probed on the nearest existing directory, since the filesystem decides,
not the operating system: an ext4 drive mounted on macOS keeps case and
a casefolded ext4 directory folds it. Unprobeable: the system's default.
"""
probe_dir = directory
while not _is_dir(probe_dir) and probe_dir != probe_dir.parent:
probe_dir = probe_dir.parent
try:
handle, name = tempfile.mkstemp(prefix=".retrobios-case-", dir=str(probe_dir))
except OSError:
return sys.platform not in ("win32", "darwin")
os.close(handle)
try:
twin = os.path.join(os.path.dirname(name), os.path.basename(name).upper())
return not os.path.exists(twin)
finally:
os.unlink(name)
def fold_case_twins(files: list[dict]) -> tuple[list[dict], list[str]]:
"""One file per name where the directory folds case, the others named.
The first in manifest order stays, as the pack's own order places it.
"""
kept: list[dict] = []
seen: set[str] = set()
folded: list[str] = []
for entry in files:
key = str(entry.get("dest", "")).casefold()
if key in seen:
folded.append(str(entry.get("dest", "")))
continue
seen.add(key)
kept.append(entry)
return kept, folded
# The characters FAT and exFAT refuse in a name, as Windows does on any drive
# (Linux 7475ea8b, fs/fat/namei_vfat.c:201-207 and fs/exfat/nls.c:396-403;
# "Naming Files, Paths, and Namespaces" in the Win32 documentation). The
# slash, the backslash and the controls never reach a destination
# (_safe_relative_path). RetroDECK names three files zxs:48.rom,
# zxs:if1-2.rom and snes:st018.data.rom (its retroarch component manifest):
# on an exFAT card each write failed, on every run.
FAT_REFUSED = re.compile(r'[<>:"|?*]')
FAT_REFUSED_SHOWN = '< > : " | ? *'
def holds_fat_refused_names(directory: Path) -> bool:
"""Whether a name holding a colon can be created there.
Probed on the nearest existing directory, as keeps_case is: an ext4
card on a Steam Deck holds one, an exFAT card refuses it with EINVAL.
Windows refuses it on every drive. A probe refused for another cause
(a folder this user cannot write) decides nothing.
"""
if os.name == "nt":
return False
probe_dir = directory
while not _is_dir(probe_dir) and probe_dir != probe_dir.parent:
probe_dir = probe_dir.parent
try:
handle, name = tempfile.mkstemp(prefix=".retrobios-name-", suffix=":",
dir=str(probe_dir))
except OSError as exc:
return exc.errno != errno.EINVAL
os.close(handle)
os.unlink(name)
return True
def split_fat_refused(files: list[dict]) -> tuple[list[dict], list[str]]:
"""The entries whose destination a FAT, exFAT or Windows folder can
hold, and the destinations it cannot."""
kept = [entry for entry in files if not FAT_REFUSED.search(str(entry.get("dest", "")))]
refused = [str(entry.get("dest", "")) for entry in files
if FAT_REFUSED.search(str(entry.get("dest", "")))]
return kept, refused
# Android's media scanner marks a folder holding a .nomedia file hidden, and
# every folder below it (MediaProvider a183e2b9, FileUtils.java:1587-1629
# isDirectoryHidden, ModernMediaScanner.java:845-846 and 1017-1020). Without
# one, the samples, overlays and videos of a BIOS folder in shared storage
# showed in the phone's gallery and music apps. RetroArch writes none
# (libretro-common/file/file_path_io.c:194 only skips one).
NOMEDIA = ".nomedia"
def hide_from_media_scanner(folder: Path) -> bool:
"""Leave an empty .nomedia in folder, True when this call wrote it."""
marker = folder / NOMEDIA
if not _is_dir(folder) or _exists(marker):
return False
try:
marker.touch()
except OSError as exc:
print(f" {NOMEDIA} not written in {shown_path(folder)}: {exc.strerror}",
file=sys.stderr)
return False
return True
def installed_cores(dirs: list[Path]) -> list[str]:
"""The cores present in these directories, by the name the buildbot uses.
A folder inside is looked into once, which is how RetroPie installs
each package. An unreadable directory holds nothing that can be seen.
"""
names: set[str] = set()
for directory in dirs:
try:
children = list(directory.iterdir())
except OSError:
continue
for child in children:
candidates = [child]
if child.is_dir():
try:
candidates = list(child.iterdir())
except OSError:
continue
for path in candidates:
match = _CORE_FILE_RE.match(path.name)
if match and path.is_file():
names.add(match.group("name"))
return sorted(names)
def info_dirs(plat: str, bios_path: Path, searched: list[Path]) -> list[Path]:
"""The directories RetroArch reads core .info files from.
libretro_info_path in retroarch.cfg, info/ beside RetroArch by default,
then the cores folders: Linux builds and Lakka keep each .info beside
its core.
"""
found = _retroarch_config_for(bios_path)
if found is None and _is_file(bios_path.parent / "retroarch.cfg"):
found = (bios_path.parent / "retroarch.cfg", bios_path.parent)
dirs: list[Path] = []
if found is not None:
cfg, app_dir = found
dirs.append(_retroarch_cfg_dir(cfg, "libretro_info_path", app_dir, "info")
or app_dir / "info")
dirs.extend(searched)
return list(dict.fromkeys(dirs))
_INFO_FIRMWARE_RE = re.compile(r'^\s*firmware\d+_path\s*=\s*"?([^"\r\n]*?)"?\s*$')
def info_firmware(dirs: list[Path], core: str) -> list[str] | None:
"""The firmware paths a core's .info declares, None without a .info.
RetroArch reads firmware<N>_path, relative to the system directory
(core_info.c), and so does this.
"""
for directory in dirs:
info = directory / f"{core}_libretro.info"
try:
text = info.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
paths = (m.group(1).strip().replace("\\", "/")
for m in map(_INFO_FIRMWARE_RE.match, text.splitlines()) if m)
return list(dict.fromkeys(p for p in paths if p))
return None
def known_core_names(manifest: dict) -> set[str]:
"""Every core name a file list answers for: profiles and their other names."""
names: set[str] = set()
for profile, aliases in (manifest.get("core_names") or {}).items():
names.add(profile)
names.update(aliases)
for cores in (manifest.get("system_cores") or {}).values():
names.update(cores)
for entry in [*manifest.get("files", []), *manifest.get("omitted_files", [])]:
names.update(entry.get("cores") or [])
for alternative in entry.get("alternatives", []):
names.update(alternative.get("cores") or [])
return names
def unknown_cores(manifest: dict, names: list[str]) -> list[str]:
"""The installed cores the file list has no profile for, in name order."""
known = known_core_names(manifest)
return sorted(name for name in names if name not in known)
# A list this short is printed whole rather than pointed at.
SHORT_LIST = 12
# Names people type for a system, each with its id. Only ever suggested:
# --system gba, psx and ps1 were refused with no hint on RetroArch, whose
# list names no system that way, and taking one in silence could install
# another console than the one meant.
SYSTEM_SHORT_NAMES = {
**dict.fromkeys(("psx", "ps1", "ps", "playstation1"), "sony-playstation"),
"ps2": "sony-playstation-2", "ps3": "sony-playstation-3", "psp": "sony-psp",
**dict.fromkeys(("vita", "psvita"), "sony-playstation-vita"),
"gb": "nintendo-gb", "gbc": "nintendo-gbc", "gba": "nintendo-gba",
**dict.fromkeys(("nes", "famicom", "fc"), "nintendo-nes"), "fds": "nintendo-fds",
**dict.fromkeys(("snes", "sfc", "superfamicom"), "nintendo-snes"),
"n64": "nintendo-64", "n64dd": "nintendo-64dd", "sgb": "nintendo-sgb",
**dict.fromkeys(("nds", "ds"), "nintendo-ds"), "dsi": "nintendo-dsi",
"3ds": "nintendo-3ds", "wiiu": "nintendo-wii-u", "switch": "nintendo-switch",
**dict.fromkeys(("gc", "ngc", "gcn", "gamecube"), "nintendo-gamecube"),
"pokemini": "nintendo-pokemon-mini",
**dict.fromkeys(("md", "gen", "genesis", "megadrive"), "sega-mega-drive"),
**dict.fromkeys(("scd", "segacd", "megacd"), "sega-mega-cd"),
"32x": "sega-32x", **dict.fromkeys(("sms", "mastersystem"), "sega-master-system"),
**dict.fromkeys(("gg", "gamegear"), "sega-game-gear"),
**dict.fromkeys(("ss", "saturn"), "sega-saturn"),
**dict.fromkeys(("dc", "dreamcast"), "sega-dreamcast"),
**dict.fromkeys(("naomi", "atomiswave"), "sega-dreamcast-arcade"),
**dict.fromkeys(("pce", "tg16", "turbografx", "turbografx16", "pcengine",
"supergrafx"), "nec-pc-engine"),
**dict.fromkeys(("pcecd", "tgcd", "turbografxcd"), "nec-pc-engine-cd"),
"pcfx": "nec-pc-fx",
**dict.fromkeys(("neogeo", "mvs", "aes"), "snk-neogeo"),
**dict.fromkeys(("neocd", "neogeocd"), "snk-neogeo-cd"),
**dict.fromkeys(("msx", "msx2"), "microsoft-msx"),
"c64": "commodore-c64", "c128": "commodore-c128",
**dict.fromkeys(("amiga", "cd32"), "commodore-amiga"),
"x68k": "sharp-x68000", **dict.fromkeys(("jag", "jaguar"), "atari-jaguar"),
**dict.fromkeys(("st", "atarist"), "atari-st"), "a800": "atari-400-800",
**dict.fromkeys(("coleco", "colecovision"), "coleco-colecovision"),
**dict.fromkeys(("intv", "intellivision"), "mattel-intellivision"),
"o2": "magnavox-odyssey2", "channelf": "fairchild-channel-f",
**dict.fromkeys(("zx", "spectrum", "zxspectrum"), "sinclair-zx-spectrum"),
"cpc": "amstrad-cpc", "bbc": "acorn-bbc-micro", "apple2": "apple-ii",
}
# A system some lists file under another id, by the file that stands for it.
# The Neo Geo card offers --system snk-neogeo, and RetroArch's list keeps
# neogeo.zip under arcade: the run suggests arcade, never takes it.
SYSTEM_KEY_FILES = {"snk-neogeo": "neogeo.zip"}
def key_file_holders(files: list[dict], omitted: list[dict]) -> dict[str, list[str]]:
"""The systems a list files each SYSTEM_KEY_FILES file under, for the
systems the list does not name itself."""
entries = files + omitted
known = {system for entry in entries for system in entry_systems(entry)}
holders: dict[str, list[str]] = {}
for system, name in SYSTEM_KEY_FILES.items():
if system in known:
continue
held = sorted({
holder for entry in entries
if PurePosixPath(str(entry.get("dest", ""))).name.lower() == name
for holder in entry_systems(entry)
})
if held:
holders[system] = held
return holders
def did_you_mean(
typed: list[str], known: list[str], listing: str,
aliases: dict[str, str] | None = None, inside_from: int = 4,
meant: dict[str, list[str]] | None = None,
) -> str:
"""The closest known names to what was typed, and the option listing them all.
A typo was answered with every name the platform has, up to 400 on one
line, with no hint that playstation is sony-playstation. An alias close
to what was typed suggests the name it stands for. A name holding what
was typed, inside_from letters or more, is suggested too. meant gives,
by the letters and digits of a typed name, the names it stands for
here, suggested instead of the close ones.
"""
import difflib
by_key: dict[str, str] = {}
for name in known:
by_key.setdefault(_name_key(name), name)
for alias, name in (aliases or {}).items():
by_key.setdefault(_name_key(alias), name)
close: list[str] = []
for word in typed:
key = _name_key(word)
if not key:
continue
if meant and key in meant:
close += [name for name in meant[key] if name not in close]
continue
matches = difflib.get_close_matches(key, list(by_key), n=3, cutoff=0.6)
if len(key) >= inside_from:
matches += sorted(k for k in by_key if key in k and k not in matches)
for k in matches:
# Two aliases of one system (psx, ps1) name it once.
if by_key[k] not in close:
close.append(by_key[k])
if close:
return f"Close matches: {', '.join(close[:3])}. {listing} lists all {len(known)}."
if len(known) <= SHORT_LIST:
return f"Known: {', '.join(known)}."
return f"{listing} lists all {len(known)}."
def refuse_name(platform: str, *lines: str) -> NoReturn:
"""End the run on a name it cannot use (a platform, target, system, core
or emulator), refused before any download.
The reason went to stderr only: a reader of --events got start, then
end with code 1, and could not tell a typo from a failed download. Code
2, as for an option argparse refuses: 1 also means --check found files
to fetch, and a script reading it reran the install on a typo forever.
"""
message = " ".join(line.strip() for line in lines)
if message.startswith("Error: "):
message = message[len("Error: "):]
EVENTS.emit("error", stage="option", reason="unknown", platform=platform,
message=message)
for line in lines:
print(line, file=sys.stderr)
sys.exit(2)
# Frontends and systems that keep no BIOS folder of their own: each
# emulator they start reads its own, which a run without --platform finds.
# --platform es-de was "Unknown platform", the answer left unsaid.
_NO_BIOS_FOLDER = ("ES-DE", "LaunchBox", "Android")
def normalize_platform(name: str, say: bool = True) -> str:
"""Return the canonical platform id for user-supplied input.
The site writes MiSTer FPGA and RetroArch: letters and digits decide,
as they do for verify.py and generate_pack.py. say is False where the
name is read again later, which says it once.
"""
key = _name_key(name)
for plat in AVAILABLE_PLATFORMS:
if key and key in (_name_key(plat), _name_key(display_name(plat))):
return plat
# --list-platforms prints `muOS: retroarch`, and --platform muos was
# refused: a system named there stands for the list it gets.
for rule in _EMBEDDED_RULES:
if key and rule.manifest and key == _name_key(rule.name):
if say:
print(f" {rule.name} gets the {display_name(rule.manifest)} file list: "
f"--platform {rule.manifest}.")
return rule.manifest
for frontend in _NO_BIOS_FOLDER:
if key and key == _name_key(frontend):
refuse_name(name.strip(), f"{frontend} has no BIOS folder of its own: run again "
"without --platform, and the installer fills the folder of each "
"emulator it finds here.")
# --list-platforms prints TrimUI with why it gets no folder, and naming
# it answered "Unknown platform".
for rule in _EMBEDDED_RULES:
if key and not rule.manifest and key == _name_key(rule.name):
refuse_name(name.strip(), f"{rule.name} is not installed to: "
f"{_NO_FOLDER.get(rule.name, 'no source names its BIOS folder')}.",
" Name that folder: --platform retroarch "
"--dest FOLDER")
# Every name --list-platforms prints, so that spruce suggests spruceOS
# and the count is the one the listing shows.
known = list(AVAILABLE_PLATFORMS) + list(dict.fromkeys(
rule.name for rule in _EMBEDDED_RULES
if _name_key(rule.name) not in {_name_key(plat) for plat in AVAILABLE_PLATFORMS}
)) + list(_NO_BIOS_FOLDER)
refuse_name(name.strip(), f"Unknown platform '{name.strip()}'. "
+ did_you_mean([name], known, "--list-platforms"))
def entry_systems(entry: dict) -> list[str]:
"""The platform systems a file or an omission belongs to.
An omission's `system` is spelled the way its profile spells it. Only
`systems` names the platform's own, the ones --system accepts.
"""
return list(entry.get("systems") or [])
+461
View File
@@ -0,0 +1,461 @@
"""Data directories rebuilt from their source archive, each file checked."""
from __future__ import annotations
import functools
import hashlib
import http.client
import os
import tarfile
import tempfile
import time
import urllib.error
import urllib.request
import zipfile
from collections.abc import Callable, Iterable, Iterator, Mapping
from pathlib import Path, PurePosixPath
from typing import IO, TYPE_CHECKING, BinaryIO, ContextManager
from installer.constants import MAX_DATA_ARCHIVE_SIZE, MAX_RETRIES, OTHER_SYSTEMS, _Interrupted, _stop, _writing
from installer.cores import entry_systems
from installer.download import _claim_partial, _drive_full, _release_claim
from installer.local_files import _read_digests
from installer.network import _retry_delay
from installer.offline import LOCAL, _Offline, _network_allowed
from installer.outcome import DRIVE_FULL, OfflineReason, _offline_only
from installer.pack_source import NOT_WRITABLE, _MEMBER_ERRORS, _folder_writable, _write_refused, unreadable_words
from installer.paths import _destination_path
from installer.record import KEPT, _NotKept, _kept_slot
from installer.terminal import Progress
if TYPE_CHECKING:
from installer.games import GamesPlan
def _archive_validator(headers: http.client.HTTPMessage | Mapping[str, str] | None) -> str:
"""What names this revision of an archive to its server: an If-Range
with it gets the rest of the same bytes, or the whole new archive."""
if not headers:
return ""
etag = headers.get("ETag", "") or ""
# A weak tag never answers a range (RFC 9110 13.1.5).
return etag if etag and not etag.startswith("W/") else headers.get("Last-Modified", "") or ""
class _ArchiveCount:
"""The bytes one attempt at an archive drew on the progress."""
def __init__(self, progress: Progress | None) -> None:
self.progress = progress
self.received = 0
self.resumed = 0
def take_back(self) -> None:
"""Take a failed attempt's bytes off the progress."""
if self.progress is not None:
if self.received:
self.progress.add(-self.received)
if self.resumed:
self.progress.add(-self.resumed)
self.progress.forget_resumed(self.resumed)
def _archive_resume_point(url: str, keep: Path | None, note: Path | None) -> tuple[int, str]:
"""(bytes the kept archive holds, its validator) when its note names
url, else (0, "")."""
if keep is None or note is None:
return 0, ""
try:
recorded = note.read_text(encoding="utf-8").split("\n")
if recorded[0] == url and len(recorded) > 1 and recorded[1]:
return keep.stat().st_size, recorded[1]
except (OSError, UnicodeError):
return 0, ""
return 0, ""
def _archive_file(keep: Path | None, offset: int, directory: Path) -> IO[bytes]:
"""The file an attempt writes: the kept archive, or a scratch file in directory."""
if keep is not None:
return open(keep, "r+b" if offset else "wb")
return tempfile.NamedTemporaryFile(dir=directory, suffix=".archive", delete=False)
def _receive_archive(
resp: http.client.HTTPResponse, handle: IO[bytes], offset: int, url: str,
note: Path | None, count: _ArchiveCount,
) -> None:
"""Write the response into handle, past offset when the server sent the rest."""
headers: http.client.HTTPMessage | Mapping[str, str] = resp.headers or {}
ranged = (offset and getattr(resp, "status", 200) == 206 and str(
headers.get("Content-Range", "")).startswith(f"bytes {offset}-"))
if not ranged:
offset = 0
handle.seek(offset)
handle.truncate()
if note is not None and not offset:
# Written before the first byte: a cut transfer is then
# resumed only against the revision it holds.
note.write_text(f"{url}\n{_archive_validator(headers)}\n",
encoding="utf-8")
progress = count.progress
if progress is not None:
length = headers.get("Content-Length", "")
if length.isdigit():
progress.expect(offset + int(length))
if offset:
progress.add(offset, resumed=True)
count.resumed = offset
total = offset
while True:
if _stop.is_set():
raise _Interrupted()
chunk = resp.read(1024 * 1024)
if not chunk:
break
count.received += len(chunk)
total += len(chunk)
if total > MAX_DATA_ARCHIVE_SIZE:
raise ValueError("archive exceeds the size limit")
handle.write(chunk)
if progress is not None:
progress.add(len(chunk))
def _fetch_archive(url: str, directory: Path, progress: Progress | None = None,
keep: Path | None = None) -> Path:
"""A data directory's source archive, in *directory*, retried like files.
progress draws its bytes as they come, an attempt that failed taken back.
With keep, the archive is written there and kept when the transfer is
cut, beside a note of its address and the validator its server sent:
the next attempt, or the next run, asks for the rest with Range and
If-Range, and a server that changed the archive sends it whole. A cut
50 MB archive started again from zero, and a link that drops more often
than one archive takes never installed the tree.
"""
_network_allowed(url)
note = keep.with_name(keep.name + ".source") if keep is not None else None
reason: Exception | None = None
for attempt in range(1, MAX_RETRIES + 1):
offset, validator = _archive_resume_point(url, keep, note)
request = urllib.request.Request(url)
if offset:
request.add_header("Range", f"bytes={offset}-")
request.add_header("If-Range", validator)
handle = _archive_file(keep, offset, directory)
count = _ArchiveCount(progress)
try:
with handle, urllib.request.urlopen(request, timeout=60) as resp:
_receive_archive(resp, handle, offset, url, note, count)
return keep if keep is not None else Path(handle.name)
except urllib.error.HTTPError as exc:
if keep is None or exc.code == 416 or exc.code < 500 and exc.code != 429:
# Refused, or a range past an archive that shrank: no
# attempt resumes it.
_drop_archive(Path(handle.name), note)
if exc.code < 500 and exc.code not in (416, 429):
raise
reason = exc
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
if keep is None:
Path(handle.name).unlink(missing_ok=True)
reason = exc if isinstance(exc, OSError) else ConnectionError(repr(exc))
except ValueError:
_drop_archive(Path(handle.name), note)
raise
except BaseException:
# Stopped: a kept archive waits for the next run.
if keep is None:
Path(handle.name).unlink(missing_ok=True)
raise
count.take_back()
if attempt < MAX_RETRIES:
time.sleep(_retry_delay(attempt, None))
raise reason if reason else OSError("download failed")
def _drop_archive(path: Path, note: Path | None) -> None:
"""Remove an archive and the note of where it came from."""
path.unlink(missing_ok=True)
if note is not None:
note.unlink(missing_ok=True)
def _tar_member(tf: tarfile.TarFile, member: tarfile.TarInfo) -> IO[bytes]:
"""The bytes of a regular file of a tarball, which extractfile always opens."""
handle = tf.extractfile(member)
assert handle is not None
return handle
def _archive_members(
archive: Path, entry: dict
) -> Iterator[tuple[str, int, Callable[[], IO[bytes]]]]:
"""(path in the tree, declared size, opener) for each file the archive
maps into it.
The rules refresh_data_dirs applies to build the cache: a ZIP drops
strip_components leading parts, a tarball keeps what sits under
source_path, and a first part named in exclude is left out.
"""
exclude = set(entry.get("exclude") or [])
if entry["type"] == "zip":
strip = entry.get("strip_components", 0)
with zipfile.ZipFile(archive) as zf:
for info in zf.infolist():
if info.is_dir():
continue
parts = info.filename.split("/")
if ".." in parts or info.filename.startswith("/"):
continue
if strip:
if len(parts) <= strip:
continue
parts = parts[strip:]
if parts[0] in exclude:
continue
yield "/".join(parts), info.file_size, functools.partial(zf.open, info)
return
prefix = entry["source_path"].rstrip("/") + "/"
with tarfile.open(archive, "r:gz") as tf:
for member in tf:
if not member.isfile() or not member.name.startswith(prefix):
continue
rel = member.name[len(prefix):]
if not rel or ".." in rel.split("/") or rel.split("/")[0] in exclude:
continue
yield rel, member.size, functools.partial(_tar_member, tf, member)
def data_directory_state(entry: dict, bios_path: Path,
remember: bool = False) -> tuple[Path, dict[str, dict], int]:
"""(tree root, files missing or wrong, files already right). remember
keeps what was read for the check after the line menu (_HEAD_READS)."""
root = _destination_path(bios_path, entry["dest"]) if entry.get("dest") else bios_path.resolve()
needed: dict[str, dict] = {}
present = 0
for rel, meta in entry["files"].items():
target = _destination_path(root, rel)
try:
held = (target.is_file() and target.stat().st_size == meta["size"]
and _read_digests(target, ("sha1",), remember)["sha1"] == meta["sha1"])
except OSError:
held = False
if held:
present += 1
else:
needed[rel] = meta
return root, needed, present
def data_space_bytes(data_states: list[tuple[dict, tuple[Path, dict[str, dict], int]]]) -> int:
"""What the data trees take on the drive while they are rebuilt: every
file they lack, plus the largest source archive, which sits in its tree
until that tree is read. Only the BIOS files were held against the free
space: 18.8 KB passed on a card with 20 MB left, and 81.8 MB followed.
Nothing is written for them offline without a pack."""
if LOCAL.pack is None and _offline_only():
return 0
files = sum(meta.get("size", 0) for _entry, (_root, needed, _present) in data_states
for meta in needed.values())
if LOCAL.pack is not None:
return files
return files + max((data_fetch_bytes(entry, state[1]) for entry, state in data_states
if state[1]), default=0)
def data_fetch_bytes(entry: dict, needed: dict[str, dict]) -> int:
"""What getting a tree's missing files costs: its source archive, which
comes whole for one file, or from a pack the files themselves. A list
that records no archive size gives the files' own sizes: a tarball whose
tree is 10 KB was announced as 10 KB and was a download of 21 MB."""
if not needed:
return 0
size = entry.get("archive_size")
if LOCAL.pack is None and isinstance(size, int) and size > 0:
return size
return sum(meta.get("size", 0) for meta in needed.values())
def install_data_directory(entry: dict, bios_path: Path,
state: tuple[Path, dict[str, dict], int] | None = None,
progress: Progress | None = None) -> dict:
"""Rebuild one data tree from its source archive, file by file verified.
state is the tree's data_directory_state when the run already read it:
each read hashes every file in place.
Returns counts: present, installed, changed (the source no longer holds
the recorded bytes), absent (not in the archive), error, the reason
the archive could not be read, not_kept, the (path, reason) of each
file in place that differs and could not be moved aside, left as it is,
and written, each file written (dest below the BIOS folder, sha1, size).
"""
root, needed, present = state or data_directory_state(entry, bios_path)
needed = dict(needed)
written: list[dict] = []
not_kept: list[tuple[str, str]] = []
tallies = {"installed": 0, "changed": 0}
counts: dict[str, object] = {
"present": present, "installed": 0, "changed": 0, "absent": 0, "error": "",
"not_kept": not_kept, "written": written}
if not needed:
return counts
_writing.set()
fetched: Path | None = None
lock: BinaryIO | None = None
lock_path = root / f".{entry['ref']}.archive.lock"
members: Iterable[tuple[str, int, Callable[[], IO[bytes]]]]
try:
root.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=root) as scratch:
if LOCAL.pack is not None:
# The pack holds the tree where it extracts, already mapped.
members = LOCAL.pack.tree(entry.get("dest", ""))
else:
# Beside the tree, outside the scratch folder: a transfer
# cut short is resumed by the next attempt or the next run.
# Two runs into one folder truncated or deleted the archive
# the other was still writing or reading: the run that finds
# it locked downloads into its scratch folder instead.
lock = _claim_partial(lock_path)
kept = root / f".{entry['ref']}.archive.part" if lock is not None else None
archive = _fetch_archive(entry["url"], Path(scratch), progress, kept)
fetched = archive
members = _archive_members(archive, entry)
for rel, declared, opener in members:
meta = needed.pop(rel, None)
if meta is None:
continue
# Read no more than the list records: the archive's own size
# field is checked first, and the stream is cut at the
# expected size whatever the member claims, so a member that
# inflates without end costs one byte past it.
if declared != meta["size"]:
tallies["changed"] += 1
continue
target = _destination_path(root, rel)
target.parent.mkdir(parents=True, exist_ok=True)
slot = f"{entry['dest']}/{rel}" if entry.get("dest") else rel
outcome = _install_data_member(
opener, meta, target, bios_path, slot, rel, not_kept)
if outcome:
tallies[outcome] += 1
if outcome == "installed":
written.append({"dest": slot, "sha1": meta["sha1"], "size": meta["size"]})
except _Offline as exc:
# Kept apart, so the advice is the offline one, not the network's.
counts["error"] = OfflineReason(str(exc))
except (urllib.error.URLError, OSError, ValueError, tarfile.TarError) as exc:
# The tree's folder refused, not the source: said as the BIOS files
# say it, never as an archive that could not be read.
# A full drive is said as one too: "could not read <url>: [Errno
# 28]" put the cause on the source, and the end said to run again.
counts["error"] = (NOT_WRITABLE if isinstance(exc, OSError)
and not isinstance(exc, urllib.error.URLError)
and _write_refused(exc) and not _folder_writable(root)
else DRIVE_FULL if _drive_full(exc)
else str(getattr(exc, "reason", None) or exc))
except _MEMBER_ERRORS as exc:
# A damaged, encrypted or unsupported member, in words.
counts["error"] = unreadable_words(exc)
finally:
if fetched is not None:
# Read whole: the next run fetches the archive afresh.
_drop_archive(fetched, fetched.with_name(fetched.name + ".source"))
if lock is not None:
_release_claim(lock, lock_path)
counts["installed"] = tallies["installed"]
counts["changed"] = tallies["changed"]
counts["absent"] = len(needed)
return counts
def _install_data_member(
opener: Callable[[], ContextManager[IO[bytes]]], meta: dict, target: Path,
bios_path: Path, slot: str, rel: str, not_kept: list[tuple[str, str]],
) -> str:
"""Write one member of a data tree's archive at target once its bytes
are the recorded ones: "installed", "changed" when they are not, or ""
when the file in place could not be moved aside (named in not_kept).
A read or write error is raised, and leaves no .part behind."""
scratch: Path | None = None
try:
digest = hashlib.sha1()
size = 0
with opener() as src, tempfile.NamedTemporaryFile(
dir=target.parent, prefix=f".{target.name}.", suffix=".part", delete=False,
) as out:
scratch = Path(out.name)
while size <= meta["size"]:
chunk = src.read(min(1024 * 1024, meta["size"] + 1 - size))
if not chunk:
break
digest.update(chunk)
size += len(chunk)
out.write(chunk)
if digest.hexdigest() != meta["sha1"] or size != meta["size"]:
return "changed"
try:
KEPT.keep(*_kept_slot(bios_path, slot), target, {"sha1": meta["sha1"]})
except _NotKept as exc:
not_kept.append((rel, str(exc)))
return ""
os.replace(scratch, target)
scratch = None
return "installed"
finally:
if scratch is not None:
scratch.unlink(missing_ok=True)
def select_data_directories(manifest: dict, files: list[dict], narrowed: bool,
required_only: bool = False,
games: GamesPlan | None = None,
systems: list[str] | None = None) -> list[dict]:
"""The data trees this install keeps: all, or those of a kept system.
systems, the systems chosen by name, decide when given: a file several
systems share named them all, and the arcade choice took blueMSX's
machines through FBNeo's msx.zip, which the pack built with --system
arcade leaves out.
--required-only leaves out a tree every core reading it runs without
(`optional`): a GBA and a SNES game took FBNeo's cheats and samples,
3,472 files no game opened. For the games of a card, a tree only cores
read (`cores`) is kept when the plan runs one of them, or runs a system
of the tree on a core no setup names."""
entries = [e for e in manifest.get("data_directories") or []
if not (required_only and e.get("optional"))]
if games is not None:
entries = [e for e in entries if not e.get("cores")
or set(e["cores"]) & games.profiles
or set(e.get("systems") or []) & games.any_core]
if not narrowed:
return entries
kept = (set(systems) if systems else
{system for f in files for system in entry_systems(f)})
# A tree no platform system serves goes with the files of none, as the
# pack built with --system puts it in the part of its own.
other = (OTHER_SYSTEMS in kept if systems else
any(not entry_systems(f) for f in files))
return [e for e in entries if kept & set(e.get("systems") or [])
or (other and not e.get("systems"))]
def _copy_targets(
entry: dict, os_type: str, extra_dirs: dict[str, Path] | None = None,
) -> list[Path]:
"""The emulator folders a standalone copy entry names on this OS.
WSL falls back to the Linux ones, and extra_dirs adds the folder a
frontend such as LaunchBox keeps the emulator in.
"""
targets = entry.get("targets", {}).get(os_type, [])
if not targets and os_type == "wsl":
targets = entry.get("targets", {}).get("linux", [])
target_dirs = [Path(os.path.expandvars(os.path.expanduser(t))) for t in targets]
extra_root = (extra_dirs or {}).get(entry.get("emulator", ""))
if extra_root is not None:
subdir = PurePosixPath(entry.get("file", "")).parent
extra = extra_root if str(subdir) == "." else extra_root / subdir
if extra not in target_dirs:
target_dirs.append(extra)
return target_dirs
+828
View File
@@ -0,0 +1,828 @@
"""Frontends and emulators found on this machine, Android included."""
from __future__ import annotations
import contextlib
import functools
import os
import re
import sys
import xml.etree.ElementTree as ET
from collections.abc import Callable, Iterator
from pathlib import Path
from installer.detect_os import (
ANDROID_APP_DATA,
ANDROID_RETROARCH_PACKAGES,
_detect_embedded,
_macos_retroarch_base,
_note_windows_unasked,
_parse_bash_var,
_parse_json_path,
_parse_ps1_var,
_parse_retroarch_system_dir,
_read_registry,
_retroarch_appimage_dirs,
_retroarch_cfg_dir,
_steam_libraries,
_unix_retroarch_base,
_windows_retroarch_dirs,
)
from installer.embedded import display_name, shown_path
from installer.paths import _record_moved_folders
from installer.probe import _SETUP_SEARCH, _exists, _host_path, _is_dir, _is_file, _note_refused
from installer.text import _CONTROLS
def _android_storage_root() -> Path:
"""Shared storage root, the parent RetroArch builds its defaults from."""
value = os.environ.get("EXTERNAL_STORAGE", "").strip()
return Path(value) if value else Path("/storage/emulated/0")
# Where each RetroArch package keeps its folders, RetroArch v1.22.2
# (pkg/android/phoenix/build.gradle:46-95). com.retroarch and
# com.retroarch.aarch64 are each published twice under one id: by
# retroarch.com (normal, aarch64) and on Google Play (playStoreNormal,
# playStorePlus). com.retroarch.ra32 has no Google Play flavor. The Google
# Play build hands RetroArch Android/data/<package>/files as the storage its
# defaults are built from, the other builds the shared storage root
# (MainMenuActivity.java:182-183).
_ANDROID_RETROARCH_PLAY_IDS = ("com.retroarch", "com.retroarch.aarch64")
# A Google Play versionCode is the manifest's 1597175267 (AndroidManifest.xml:5)
# plus one per half week since 1609632000 (build.gradle:76, 87, 168-175), so
# it stays below that start time. The other flavors use the build time in
# seconds (build.gradle:42), above it for every build since 2021. The launcher
# writes the code to retroarch.cfg (UserPreferences.java:150), which
# RetroArch keeps (configuration.c:2623).
_ANDROID_PLAY_VERSION_CEILING = 1609632000
def _android_cfg_value(cfg: Path, key: str) -> str | None:
"""A value of an Android retroarch.cfg, None when unreadable or unset."""
try:
lines = cfg.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError:
return None
for line in lines:
name, sep, value = line.partition("=")
if sep and name.strip() == key:
return value.strip().strip('"').strip("'")
return None
@contextlib.contextmanager
def _refusals_expected() -> Iterator[None]:
"""Probes whose refusal is the answer, not a folder to report: another
app's private data on Android, which any app may test for existence and
none may enter, has a line of its own (android_unreachable_folders)."""
outer = getattr(_SETUP_SEARCH, "active", False)
_SETUP_SEARCH.active = False
try:
yield
finally:
_SETUP_SEARCH.active = outer
def _android_play_build(package: str, storage: Path, cfgs: tuple[Path, ...]) -> bool | None:
"""True for the Google Play build of this package, False for the
retroarch.com one, None when nothing it wrote tells them apart.
The version code in its config decides. Without a readable config, the
folder each build writes does: the Google Play build never asks for
shared storage (MainMenuActivity.java:199-202), and only it builds its
defaults under Android/data/<package>/files/RetroArch.
"""
if package not in _ANDROID_RETROARCH_PLAY_IDS:
return False
for cfg in cfgs:
code = _android_cfg_value(cfg, "bundle_assets_extract_version_current")
if code and code.isdigit() and int(code) > 0:
return int(code) < _ANDROID_PLAY_VERSION_CEILING
if _is_dir(storage / "Android" / "data" / package / "files" / "RetroArch"):
return True
if _is_dir(storage / "RetroArch"):
return False
return None
def _android_writable(folder: Path) -> bool:
"""Whether this shell can create folder: its nearest existing parent is
writable. Android 11 and later keep Android/data/<package> of other apps
from Termux."""
for parent in (folder, *folder.parents):
if _exists(parent):
return _is_dir(parent) and os.access(parent, os.W_OK)
return False
def _android_out_of_reach(name: str, folder: Path, what: str) -> str:
"""The line said for an emulator whose BIOS folder this shell cannot write."""
return (f"{name} is installed, but this shell cannot write its BIOS folder "
f"{folder} without root: {what} are not copied there.")
@_refusals_expected()
def _android_retroarch_builds() -> list[tuple[Path | None, str]]:
"""Each installed RetroArch build: its system folder when this shell can
write it, else None and the line that says why.
RetroArch v1.22.2: the launcher picks retroarch.cfg in the app external
files directory, else in the internal one
(pkg/android/phoenix-common/src/com/retroarch/browser/preferences/util/
UserPreferences.java:36-89), and passes it as CONFIGFILE
(MainMenuActivity.java:178, read at frontend/drivers/platform_unix.c:
1428-1444). A system_directory left at default resolves against
<storage>/RetroArch/system (platform_unix.c:1670-1697), storage being
what the launcher passes as SDCARD: Android/data/<package>/files for the
Google Play build, the shared storage root for the others.
"""
storage = _android_storage_root()
builds: list[tuple[Path | None, str]] = []
for package in ANDROID_RETROARCH_PACKAGES:
external = storage / "Android" / "data" / package / "files"
if not _exists(ANDROID_APP_DATA / package) and not _exists(external):
continue
cfgs = (external / "retroarch.cfg",
ANDROID_APP_DATA / package / "files" / "retroarch.cfg")
play = _android_play_build(package, storage, cfgs)
play_root, shared_root = external / "RetroArch", storage / "RetroArch"
named = next(filter(None, (_android_cfg_value(cfg, "system_directory")
for cfg in cfgs)), "default")
if play is None and named == "default":
builds.append((None,
f"RetroArch ({package}) is installed, but nothing it has written tells "
f"which build it is: the Google Play build reads {play_root / 'system'}, "
f"the retroarch.com build reads {shared_root / 'system'}. "
"Name the folder with --dest."))
continue
root = play_root if play else shared_root
folder = next(filter(None, (_parse_retroarch_system_dir(cfg, root) for cfg in cfgs)),
root / "system")
private = (storage / "Android" / "data", ANDROID_APP_DATA)
if any(folder == base or base in folder.parents for base in private) \
and not _android_writable(folder):
build = "Google Play build" if play else "retroarch.com build"
builds.append((None, _android_out_of_reach(
f"RetroArch ({build}, {package})", folder, "BIOS files")))
continue
builds.append((folder, ""))
return builds
def _detect_android() -> list[tuple[str, Path]]:
"""Find the RetroArch system directory of each installed build on
Android, as _android_retroarch_builds() resolves it (RetroArch v1.22.2,
platform_unix.c:1670-1697).
With no package seen, <shared storage>/RetroArch is the folder of a
retroarch.com build whose private data this shell cannot see.
"""
found: list[tuple[str, Path]] = []
builds = _android_retroarch_builds()
for folder, _line in builds:
if folder is not None and ("retroarch", folder) not in found:
found.append(("retroarch", folder))
default_root = _android_storage_root() / "RetroArch"
if not builds and _exists(default_root):
found.append(("retroarch", default_root / "system"))
return found
# Android emulators that keep their BIOS outside RetroArch's folder:
# (name, package, folder, files read there). DraStic keeps it in its private
# data (GammaOS Next 14 bb28e71d, gammaos/setup.sh:345-363 extracts it to
# /data/data/com.dsemu.drastic/files/DraStic/system), which no other app
# writes without root. Flycast reads <home>/data/ (flycast a9bd1c74,
# shell/android-studio/flycast/src/main/jni/src/Android.cpp:143-159), its
# home being Android/data/com.flycast.emulator/files, which Android 11 and
# later keep from other apps.
_ANDROID_APP_FOLDERS = (
("DraStic", "com.dsemu.drastic", "/data/data/com.dsemu.drastic/files/DraStic/system",
("nds_bios_arm7.bin", "nds_bios_arm9.bin", "nds_firmware.bin")),
("Flycast", "com.flycast.emulator",
"$STORAGE/Android/data/com.flycast.emulator/files/data",
("dc_boot.bin", "dc_nvmem.bin")),
)
@_refusals_expected()
def android_unreachable_folders() -> list[str]:
"""A line for each Android emulator installed here whose BIOS folder
this shell cannot write, said instead of skipping it in silence. A
RetroArch build whose folder is out of reach, or whose build cannot be
told, is among them.
An app's private folder can be tested for existence by any app, so the
emulator is known to be installed even where its folder is out of reach.
"""
lines = [line for folder, line in _android_retroarch_builds() if folder is None]
storage = str(_android_storage_root())
for name, package, folder, files in _ANDROID_APP_FOLDERS:
target = Path(folder.replace("$STORAGE", storage, 1))
if folder.startswith("/data/data/"):
target = ANDROID_APP_DATA / Path(folder).relative_to("/data/data")
if not _exists(ANDROID_APP_DATA / package) and not _exists(target):
continue
if _is_dir(target) and os.access(target, os.W_OK):
continue
lines.append(_android_out_of_reach(name, target, ", ".join(files)))
return lines
def _lnk_target(lnk_path: Path, exe_name: str) -> Path | None:
"""Read the target path of a Windows shortcut.
Shortcuts embed the target as a plain local path. Scanning for it avoids
parsing the whole .lnk structure for the one field that matters here.
"""
try:
if lnk_path.stat().st_size > 64 * 1024:
return None
blob = lnk_path.read_bytes()
except OSError:
return None
pattern = re.compile(
rb"[A-Za-z]:\\[ -~]{0,260}?" + re.escape(exe_name.encode()), re.IGNORECASE
)
match = pattern.search(blob)
if not match:
return None
return Path(match.group().decode("ascii", "replace").replace("\\", "/"))
def launchbox_root(os_type: str) -> Path | None:
"""Locate the LaunchBox installation directory.
LaunchBox installs wherever the user points its installer and writes no
uninstall registry key, so the Start menu shortcut is the only record of
that choice. Everything else falls back to the default location.
"""
if os_type not in ("windows", "wsl"):
return None
candidates: list[Path] = []
appdata = os.environ.get("APPDATA", "")
if appdata:
lnk = (
Path(appdata)
/ "Microsoft"
/ "Windows"
/ "Start Menu"
/ "Programs"
/ "LaunchBox"
/ "LaunchBox.lnk"
)
if _exists(lnk):
target = _lnk_target(lnk, "LaunchBox.exe")
if target:
# The shortcut points at Core/LaunchBox.exe
candidates.append(target.parent.parent)
candidates.append(target.parent)
userprofile = os.environ.get("USERPROFILE", "")
if userprofile:
candidates.append(Path(userprofile) / "LaunchBox")
for root in candidates:
if _exists(root / "Data" / "Emulators.xml"):
return root
return None
def launchbox_emulators(emulators_xml: Path) -> dict[str, Path]:
"""Map each emulator LaunchBox knows about to its installation directory.
LaunchBox stores its emulator list in Data/Emulators.xml. ApplicationPath
is either absolute or relative to the LaunchBox root directory. Keys are
the lowercase executable names.
"""
found: dict[str, Path] = {}
if not _exists(emulators_xml):
return found
try:
if emulators_xml.stat().st_size > 10 * 1024 * 1024:
return found
raw = emulators_xml.read_text(encoding="utf-8", errors="replace")
# ElementTree expands internal entities, and LaunchBox writes no doctype
if "<!DOCTYPE" in raw.upper():
return found
root = ET.fromstring(raw)
except (ET.ParseError, OSError):
return found
lb_root = emulators_xml.parent.parent
for emu in root.iter("Emulator"):
app_path = (emu.findtext("ApplicationPath") or "").replace("\\", "/")
if not app_path:
continue
exe = Path(app_path)
if not exe.is_absolute():
exe = lb_root / exe
if _is_dir(exe.parent):
found.setdefault(exe.name.lower(), exe.parent)
return found
def _launchbox_retroarch_system_dir(emulators_xml: Path) -> Path | None:
"""Resolve the system dir of a RetroArch referenced by LaunchBox.
Mirrors the plugin's UpdateSystemPath: read system_directory from the
retroarch.cfg sitting next to the executable, else assume system/.
"""
emu_dir = launchbox_emulators(emulators_xml).get("retroarch.exe")
if emu_dir is None:
return None
system_dir = _parse_retroarch_system_dir(emu_dir / "retroarch.cfg", emu_dir)
return system_dir or emu_dir / "system"
def _pcsx2_bios_dir(emu_dir: Path) -> Path:
"""Resolve the BIOS folder of a PCSX2 installed under LaunchBox.
EmuFolders (pcsx2/Pcsx2Config.cpp) enters portable mode when portable.ini
or portable.txt sits next to the executable, and then takes the data root
from the contents of portable.txt, relative to the executable. Otherwise
the data root is Documents/PCSX2. Bios defaults to "bios" below it and the
Bios key of PCSX2.ini overrides that.
"""
documents = Path(os.environ.get("USERPROFILE", str(Path.home()))) / "Documents"
portable_txt = emu_dir / "portable.txt"
portable = _exists(emu_dir / "portable.ini") or _exists(portable_txt)
if portable:
subpath = ""
with contextlib.suppress(OSError):
subpath = portable_txt.read_text(
encoding="utf-8", errors="replace"
).strip()
data_root = emu_dir / subpath if subpath else emu_dir
else:
data_root = documents / "PCSX2"
ini = data_root / "inis" / "PCSX2.ini"
try:
for line in ini.read_text(encoding="utf-8", errors="replace").splitlines():
if line.startswith("Bios = "):
value = line[len("Bios = "):].strip()
candidate = Path(value)
return candidate if candidate.is_absolute() else data_root / value
except OSError:
pass
return data_root / "bios"
def _xemu_bios_dir(emu_dir: Path) -> Path:
"""Resolve the BIOS folder of a xemu managed by LaunchBox.
Follows the plugin: xemu.toml next to the executable else the roaming
copy, with bootrom_path and flashrom_path naming a file whose directory
holds the images. Both default to bios/ under the executable.
"""
appdata = os.environ.get("APPDATA", "")
toml = emu_dir / "xemu.toml"
if not _exists(toml) and appdata:
toml = Path(appdata) / "xemu" / "xemu" / "xemu.toml"
if _exists(toml):
try:
for line in toml.read_text(encoding="utf-8", errors="replace").splitlines():
if line.startswith(("bootrom_path", "flashrom_path")):
parts = line.split("'")
if len(parts) > 1 and _exists(Path(parts[1])):
return Path(parts[1]).parent
except OSError:
pass
return emu_dir / "bios"
def launchbox_bios_dirs(root: Path) -> dict[str, Path]:
"""Map emulator ids to the BIOS directory LaunchBox expects for them.
Only emulators whose destination LaunchBox itself computes are listed.
The rest keep the default locations declared in the manifest.
"""
emulators = launchbox_emulators(root / "Data" / "Emulators.xml")
dirs: dict[str, Path] = {}
emu_dir = emulators.get("pcsx2.exe")
if emu_dir:
dirs["pcsx2"] = _pcsx2_bios_dir(emu_dir)
emu_dir = emulators.get("xemu.exe")
if emu_dir:
dirs["xemu"] = _xemu_bios_dir(emu_dir)
emu_dir = emulators.get("dolphin.exe")
if emu_dir and _exists(emu_dir / "portable.txt"):
# portable.txt beside the executable moves the user directory to
# User (SetUserDirectory in Source/Core/UICommon/UICommon.cpp,
# PORTABLE_USER_DIR in Source/Core/Common/CommonPaths.h)
dirs["dolphin"] = emu_dir / "User"
return dirs
# The platforms whose configuration names a folder with a control character.
_UNNAMEABLE: list[str] = []
def _detection_guarded(detect: Callable[..., list]) -> Callable[..., list]:
"""Detection whose probes treat a folder this user cannot open as
absent, and say so once.
Each probe goes through _exists, _is_dir or _is_file, which records the
refusal. A probe that still raises PermissionError (a glob on a Python
whose pathlib lets it through) is the last net: the call finds nothing
and says why, where HOME kept across `su` without `-` once ended the
run on a traceback.
"""
@functools.wraps(detect)
def guarded(*args: object, **kwargs: object) -> list:
outer = getattr(_SETUP_SEARCH, "active", False)
_SETUP_SEARCH.active = True
try:
return detect(*args, **kwargs)
except PermissionError as exc:
_note_refused(Path(str(exc.filename or "")), exc)
return []
finally:
_SETUP_SEARCH.active = outer
return guarded
@_detection_guarded
def detect_frontends(os_type: str, home: Path | None = None) -> list[str]:
"""Detect frontends that reference emulators without owning a BIOS dir.
ES-DE resolves its application data directory to $ESDE_APPDATA_DIR or
<home>/ES-DE (es-core FileSystemUtil.cpp getAppDataDirectory).
"""
home = home or Path.home()
frontends: list[str] = []
esde_env = os.environ.get("ESDE_APPDATA_DIR", "")
if (esde_env and _is_dir(Path(esde_env))) or _is_dir(home / "ES-DE"):
frontends.append("esde")
if launchbox_root(os_type) is not None:
frontends.append("launchbox")
return frontends
# The registry's path_exists rules (platforms/_registry.yml install.detect),
# one row each: (os, platform, path, BIOS directory when it is not the path).
# The manifests publish them too, but detection runs before any manifest is
# fetched. A test holds this table equal to the registry. Without it a Linux
# home holding RetroPie/BIOS or .config/BizHawk/Firmware detected nothing.
_PATH_RULES: tuple[tuple[str, str, str, str | None], ...] = (
("windows", "retrobat", "C:\\RetroBat\\bios", None),
("windows", "retrobat", "%USERPROFILE%\\RetroBat\\bios", None),
("linux", "emudeck", "$HOME/Emulation/bios", None),
("darwin", "emudeck", "$HOME/Emulation/bios", None),
("linux", "retrodeck", "$HOME/.var/app/net.retrodeck.retrodeck", "$HOME/retrodeck"),
("linux", "romm", "/romm/library/bios", None),
# A library laid out as {platform}/bios has no library/bios: RomM's
# config folder is the evidence (config_manager.py:264-265).
("linux", "romm", "/romm/config/config.yml", "/romm/library/bios"),
("linux", "retropie", "$HOME/RetroPie/BIOS", None),
("windows", "bizhawk", "%USERPROFILE%\\BizHawk\\Firmware", None),
("linux", "misterfpga", "/media/fat/MiSTer", "/media/fat/games"),
)
def _rule_path(template: str) -> Path:
"""A rule's path on this machine: $HOME or %USERPROFILE%, then the rest."""
bases = (
("$HOME", Path.home()),
("%USERPROFILE%", Path(os.environ.get("USERPROFILE") or Path.home())),
)
for variable, base in bases:
if template.startswith(variable):
rest = [part for part in re.split(r"[\\/]", template[len(variable):]) if part]
return base.joinpath(*rest)
return _host_path(template)
# The registry's executable rules: (os, platform, glob under $HOME or
# %USERPROFILE%, folder beside the executable that holds the BIOS). BizHawk is
# a portable archive reading <EmuHawk folder>/Firmware (PathExtensions.cs
# DataDirectoryPath), wherever it was extracted. ~/.config/BizHawk/Firmware,
# the old guess, is a folder no build reads.
_EXE_RULES: tuple[tuple[str, str, tuple[str, ...], str], ...] = (
("linux", "bizhawk", ("$HOME/BizHawk*/EmuHawkMono.sh", "$HOME/*/BizHawk*/EmuHawkMono.sh"),
"Firmware"),
("windows", "bizhawk", ("%USERPROFILE%\\BizHawk*\\EmuHawk.exe",
"%USERPROFILE%\\*\\BizHawk*\\EmuHawk.exe"), "Firmware"),
)
def _detect_by_executable(os_type: str, found: list[tuple[str, Path]]) -> None:
"""Add a portable install found by its executable, the newest first."""
systems = ("linux", "windows") if os_type == "wsl" else (os_type,)
for rule_os, platform_name, patterns, subdir in _EXE_RULES:
if rule_os not in systems or any(name == platform_name for name, _ in found):
continue
hits: list[Path] = []
for pattern in patterns:
base, _, rest = pattern.partition("/" if "/" in pattern else "\\")
glob = "/".join(part for part in re.split(r"[\\/]", rest) if part)
try:
hits.extend(path for path in _rule_path(base).glob(glob) if _is_file(path))
except OSError:
continue
if hits:
newest = max(hits, key=lambda path: path.stat().st_mtime)
found.append((platform_name, newest.parent / subdir))
# The registry's registry rules: (os, platform, key, value, BIOS folder under
# the folder the value names). RetroBat.exe writes its own folder there on
# every start (retrobat-executable 702da66a, RetroBat/RetroBat/Program.cs:57
# and 99, RegistryTools.cs:15-50), wherever it was installed. The path rules
# only knew C:\RetroBat and the profile folder.
_REGISTRY_RULES: tuple[tuple[str, str, str, str, str], ...] = (
("windows", "retrobat", "HKCU\\SOFTWARE\\RetroBat", "LatestKnownInstallPath", "bios"),
)
def _detect_by_registry(os_type: str, found: list[tuple[str, Path]]) -> None:
"""Add a platform whose own program names its folder in the registry.
A folder since moved or removed is passed over, so the path rules still
get their turn.
"""
systems = ("windows",) if os_type in ("windows", "wsl") else ()
for rule_os, platform_name, key, value, subdir in _REGISTRY_RULES:
if rule_os not in systems or any(name == platform_name for name, _ in found):
continue
folder = _read_registry(key, value)
if not folder:
continue
base = _host_path(folder.rstrip("\\/") or folder)
if _is_dir(base):
found.append((platform_name, base / subdir))
def _detect_by_path(os_type: str, found: list[tuple[str, Path]]) -> None:
"""Add what a registry path rule finds, for a platform not found yet."""
systems = ("linux", "windows") if os_type == "wsl" else (os_type,)
for rule_os, platform_name, path, bios in _PATH_RULES:
if rule_os not in systems or any(name == platform_name for name, _ in found):
continue
if _exists(_rule_path(path)):
found.append((platform_name, _rule_path(bios or path)))
def _detect_emudeck_unix(found: list[tuple[str, Path]]) -> None:
"""Add EmuDeck on Linux or macOS."""
# EmuDeck on Linux and macOS: functions/all.sh:3-4 and 24 (EmuDeck
# dddb3022) reads $emudeckFolder/settings.sh on both, and vars.sh:2
# sets emudeckFolder to $HOME/.config/EmuDeck.
emudeck_settings = Path.home() / ".config" / "EmuDeck" / "settings.sh"
if _exists(emudeck_settings):
emu_path = _parse_bash_var(emudeck_settings, "emulationPath")
if emu_path:
found.append(("emudeck", Path(emu_path) / "bios"))
def _detect_retrodeck(home: Path, found: list[tuple[str, Path]]) -> None:
"""Add RetroDECK's home folder."""
# RetroDECK: retrodeck.json since the cfg-to-json migration, which
# renames the old retrodeck.cfg to retrodeck.bak (global.sh:149-153)
retrodeck_conf_dir = home / ".var" / "app" / "net.retrodeck.retrodeck" / "config" / "retrodeck"
retrodeck_json = retrodeck_conf_dir / "retrodeck.json"
retrodeck_cfg = retrodeck_conf_dir / "retrodeck.cfg"
if _exists(retrodeck_json):
rd_home = _parse_json_path(retrodeck_json, "paths", "rd_home_path")
if not rd_home:
# A home moved to an SD card lives only in this file: the
# default is a guess, and the user is told so.
print(
f"Warning: could not read paths.rd_home_path from "
f"{retrodeck_json}: assuming {home / 'retrodeck'}",
file=sys.stderr,
)
rd_root = Path(rd_home) if rd_home else home / "retrodeck"
_record_moved_folders(rd_root, retrodeck_json)
found.append(("retrodeck", rd_root))
elif _exists(retrodeck_cfg):
rd_home = _parse_bash_var(retrodeck_cfg, "rdhome")
found.append(("retrodeck", Path(rd_home) if rd_home else home / "retrodeck"))
def _detect_linux_retroarch(home: Path, found: list[tuple[str, Path]]) -> None:
"""Add RetroArch's Linux builds: Flatpak, Snap, native and AppImage."""
# RetroArch Flatpak
flatpak_cfg = home / ".var" / "app" / "org.libretro.RetroArch" / "config" / "retroarch" / "retroarch.cfg"
ra_dir = _parse_retroarch_system_dir(flatpak_cfg)
if ra_dir:
found.append(("retroarch", ra_dir))
# RetroArch Snap
snap_cfg = home / "snap" / "retroarch" / "current" / ".config" / "retroarch" / "retroarch.cfg"
ra_dir = _parse_retroarch_system_dir(snap_cfg)
if ra_dir:
found.append(("retroarch", ra_dir))
# RetroArch native: the config under its base folder, then
# ~/.retroarch.cfg when that one is missing (open_default_config_file
# in configuration.c). Either way the system folder defaults to the
# base folder's.
native_base = _unix_retroarch_base()
for native_cfg in (native_base / "retroarch.cfg", home / ".retroarch.cfg"):
ra_dir = _parse_retroarch_system_dir(native_cfg, native_base)
if ra_dir:
found.append(("retroarch", ra_dir))
break
found.extend(("retroarch", ra_dir) for ra_dir in _retroarch_appimage_dirs(home))
def _detect_darwin_retroarch(found: list[tuple[str, Path]]) -> None:
"""Add RetroArch on macOS."""
# open_default_config_file reads <Application Support>/RetroArch/config
# (configuration.c). A value left at default is the documents folder,
# or Application Support itself for a portable install
# (platform_darwin.m). The config beside it is where older builds
# kept it.
support = Path.home() / "Library" / "Application Support" / "RetroArch"
for mac_cfg in (support / "config" / "retroarch.cfg", support / "retroarch.cfg"):
ra_dir = _parse_retroarch_system_dir(mac_cfg, _macos_retroarch_base())
if ra_dir:
found.append(("retroarch", ra_dir))
break
def _detect_windows_retroarch(found: list[tuple[str, Path]]) -> None:
"""Add EmuDeck and RetroArch on Windows: installed, Steam, then UWP."""
emudeck = _emudeck_windows_bios()
if emudeck is not None:
found.append(("emudeck", emudeck))
# RetroArch Windows: open_default_config_file reads retroarch.cfg
# beside the exe, then under %APPDATA%\RetroArch, and a value left at
# default is <exe folder>\system (configuration.c, platform_win32.c).
appdata = os.environ.get("APPDATA", "")
appdata_cfg = Path(appdata) / "RetroArch" / "retroarch.cfg" if appdata else None
exe_dirs = _windows_retroarch_dirs()
for exe_dir in exe_dirs:
ra_dir = _parse_retroarch_system_dir(exe_dir / "retroarch.cfg", exe_dir)
if ra_dir is None and appdata_cfg is not None:
ra_dir = _parse_retroarch_system_dir(appdata_cfg, exe_dir)
found.append(("retroarch", ra_dir or exe_dir / "system"))
break
if not exe_dirs and appdata_cfg is not None:
ra_dir = _parse_retroarch_system_dir(appdata_cfg)
if ra_dir:
found.append(("retroarch", ra_dir))
# RetroArch from Steam: a portable install in a Steam library
for library in _steam_libraries():
steam_cfg = library / "steamapps" / "common" / "RetroArch" / "retroarch.cfg"
ra_dir = _parse_retroarch_system_dir(steam_cfg)
if ra_dir and not any(name == "retroarch" for name, _ in found):
found.append(("retroarch", ra_dir))
break
# The UWP/MSIX package (sideloaded, or Xbox in dev mode)
if not any(name == "retroarch" for name, _ in found):
uwp = _retroarch_uwp_system_dir()
if uwp is not None:
found.append(("retroarch", uwp))
def _detect_windows_launchbox(os_type: str, found: list[tuple[str, Path]]) -> None:
"""Add RetroArch and BizHawk as LaunchBox references them."""
# Portable RetroArch referenced by LaunchBox
lb_root = launchbox_root(os_type)
if lb_root and not any(name == "retroarch" for name, _ in found):
system_dir = _launchbox_retroarch_system_dir(
lb_root / "Data" / "Emulators.xml"
)
if system_dir:
found.append(("retroarch", system_dir))
# BizHawk is a portable archive reading <EmuHawk folder>\Firmware
# (PathExtensions.cs DataDirectoryPath, PathEntryCollection "Firmware").
if lb_root and not any(name == "bizhawk" for name, _ in found):
emu_dir = launchbox_emulators(lb_root / "Data" / "Emulators.xml").get("emuhawk.exe")
if emu_dir is not None:
found.append(("bizhawk", emu_dir / "Firmware"))
def _without_unnameable(found: list[tuple[str, Path]]) -> list[tuple[str, Path]]:
"""found once each, less a folder named with a control character."""
# An embedded system's config read again as the home folder's one (HOME is
# /storage on the ELEC family) is the same folder.
kept = []
for name, path in dict.fromkeys(found):
if _CONTROLS.search(str(path)):
# A config naming a folder with a control character: printed,
# the name is a terminal command, and the folder one nobody can
# type. Its default is then no answer: the
# setup reads the folder named.
if name not in _UNNAMEABLE:
_UNNAMEABLE.append(name)
print(f" {display_name(name)}: the folder its configuration names holds a "
f"control character ({shown_path(path)}). Name its BIOS folder with "
"--dest.", file=sys.stderr)
continue
kept.append((name, path))
return kept
@_detection_guarded
def detect_platforms(os_type: str) -> list[tuple[str, Path]]:
"""Detect installed emulator platforms and their BIOS directories."""
found: list[tuple[str, Path]] = []
if os_type == "wsl":
_note_windows_unasked()
if os_type == "android":
found.extend(_detect_android())
for line in android_unreachable_folders():
print(line, file=sys.stderr)
if os_type in ("linux", "wsl"):
found.extend(_detect_embedded())
if os_type in ("linux", "wsl", "darwin"):
_detect_emudeck_unix(found)
if os_type in ("linux", "wsl"):
home = Path.home()
_detect_retrodeck(home, found)
_detect_linux_retroarch(home, found)
if os_type == "darwin":
_detect_darwin_retroarch(found)
if os_type in ("windows", "wsl"):
_detect_windows_retroarch(found)
_detect_windows_launchbox(os_type, found)
if os_type in ("linux", "wsl", "darwin"):
bizhawk = _bizhawk_unix_firmware()
if bizhawk is not None and not any(name == "bizhawk" for name, _ in found):
found.append(("bizhawk", bizhawk))
_detect_by_executable(os_type, found)
_detect_by_registry(os_type, found)
_detect_by_path(os_type, found)
return _without_unnameable(found)
def _emudeck_windows_bios() -> Path | None:
"""The BIOS folder of EmuDeck's Windows edition, as its scripts find it.
functions/all.ps1:4-14 (emudeck-we 037460ef) loads
%APPDATA%\\EmuDeck\\settings.ps1, else %USERPROFILE%\\EmuDeck\\settings.ps1,
and takes C:\\Emulation when neither sets $emulationPath. A network
install sets it through a drive mapped to $VolName in that session
(JSONtoPS1.ps1:166-172), which is the share itself here.
"""
candidates = [Path(os.environ[var]) / "EmuDeck" / "settings.ps1"
for var in ("APPDATA", "USERPROFILE") if os.environ.get(var)]
settings = next((path for path in candidates if _is_file(path)), None)
if settings is None:
return None
emu_path = _parse_ps1_var(settings, "$emulationPath")
if emu_path and ("$" in emu_path or "+" in emu_path):
share = _parse_ps1_var(settings, "$VolName")
emu_path = f"{share.rstrip(chr(92))}\\Emulation" if share else None
return _host_path(emu_path or "C:\\Emulation") / "bios"
# Identity Name in pkg/msvc-uwp/RetroArch-msvcUWP/Package.appxmanifest.
RETROARCH_UWP_ID = "1e4cf179-f3c2-404f-b9f3-cb2070a5aad8"
def _retroarch_uwp_system_dir() -> Path | None:
"""System directory of the RetroArch UWP package, if one is installed.
The package writes into its LocalState folder: uwp_main.cpp makes it the
home directory, configuration.c reads retroarch.cfg there, and
platform_uwp.c defaults the system directory to ~\\system. A `~` in the
config is therefore LocalState, not the user's profile.
"""
local = os.environ.get("LOCALAPPDATA", "").strip()
if not local:
return None
states = sorted(Path(local, "Packages").glob(f"{RETROARCH_UWP_ID}_*/LocalState"))
if not states:
return None
state = states[0]
cfg = state / "retroarch.cfg"
try:
for line in cfg.read_text(encoding="utf-8", errors="replace").splitlines():
name, sep, value = line.strip().partition("=")
if sep and name.strip() == "system_directory":
value = value.strip().strip('"').strip("'")
if value.startswith("~"):
return state / value[1:].lstrip("\\/")
break
except OSError:
return state / "system"
return _retroarch_cfg_dir(cfg, "system_directory", state, "system") or state / "system"
def _bizhawk_unix_firmware() -> Path | None:
"""BizHawk's Firmware folder on Unix, where its data home says.
PathExtensions.cs reads $BIZHAWK_DATA_HOME before the executable's
folder, and the Nix package sets it to
$XDG_DATA_HOME/emuhawk-monort-<version> (Dist/launch-scripts.nix).
"""
data_home = os.environ.get("BIZHAWK_DATA_HOME", "").strip()
if data_home and _is_dir(Path(data_home)):
return Path(data_home) / "Firmware"
xdg = os.environ.get("XDG_DATA_HOME", "").strip() or str(Path.home() / ".local" / "share")
homes = sorted((home for home in Path(xdg).glob("emuhawk-monort-*") if _is_dir(home)),
key=lambda home: home.stat().st_mtime)
return homes[-1] / "Firmware" if homes else None
+968
View File
@@ -0,0 +1,968 @@
"""The operating system, the board and the RetroArch folders it keeps."""
from __future__ import annotations
import argparse
import json
import os
import platform
import re
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
from typing import NamedTuple
from installer.constants import CARD_MARKER
from installer.embedded import (
_EMBEDDED_RULES,
_OsRule,
_mounted_cards,
card_platform,
display_name,
setup_bios_folder,
shown_path,
)
from installer.events import EVENTS
from installer.paths import _MOVED_FOLDERS
from installer.probe import (
_DETECTION_REFUSED,
_SETUP_SEARCH,
_WSL,
_exists,
_host_path,
_is_dir,
_is_file,
_note_refused,
refused_words,
)
from installer.text import _CONTROLS, screen_text
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 <exe folder>\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",
}
# The three RetroArch packages published for Android, newest ABI first.
ANDROID_RETROARCH_PACKAGES = (
"com.retroarch.aarch64",
"com.retroarch",
"com.retroarch.ra32",
)
# Where Android keeps each app's private data.
ANDROID_APP_DATA = Path("/data/data")
def _is_android() -> bool:
"""Android reports itself as Linux, so the runtime is named instead.
Termux inherits the two variables the Android runtime exports, and
/system/build.prop covers a shell that was started without them.
"""
if os.environ.get("ANDROID_ROOT") and os.environ.get("ANDROID_DATA"):
return True
return Path("/system/build.prop").exists()
def detect_os() -> str:
"""Return normalized OS identifier.
RETROBIOS_OS names the platform outright (linux, wsl, windows, darwin,
android), for a run that has to behave like another host: the PowerShell
wrapper tests drive a Windows layout on a Linux runner.
"""
forced = os.environ.get("RETROBIOS_OS", "").strip().lower()
if forced in ("linux", "wsl", "windows", "darwin", "android"):
return forced
system = platform.system().lower()
if system == "linux":
if _is_android():
return "android"
proc_version = Path("/proc/version")
if _exists(proc_version):
try:
content = proc_version.read_text(encoding="utf-8", errors="replace")
if "microsoft" in content.lower():
return "wsl"
except OSError:
pass
return "linux"
if system == "darwin":
return "darwin"
if system == "windows":
return "windows"
return system
def _parse_os_release() -> dict[str, str]:
"""Parse /etc/os-release KEY=value format."""
result: dict[str, str] = {}
path = _on_device("/etc/os-release")
if not _exists(path):
return result
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
line = line.strip()
if "=" not in line or line.startswith("#"):
continue
key, _, value = line.partition("=")
value = value.strip('"').strip("'")
result[key] = value
except OSError:
pass
return result
_WINDOWS_VARIABLES = ("USERPROFILE", "APPDATA", "LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)")
def _wsl_dest(args: argparse.Namespace) -> None:
"""Every path option as WSL opens it: the screen names a card D:, and
D:\\ given to --dest was refused as a folder that does not exist, then
E:\\ given to --from once --dest took it."""
for name in ("dest", "save_dir", "cores_dir"):
if getattr(args, name, None) is not None:
setattr(args, name, _host_path(str(getattr(args, name))))
for name in ("from", "from_pack"):
if getattr(args, name, None):
setattr(args, name, [_host_path(str(path)) for path in getattr(args, name)])
def _enter_wsl() -> None:
"""Read Windows paths through drvfs, and the Windows variables detection
needs, which WSL does not pass to Linux (only those named in WSLENV)."""
_WSL["active"] = True
for variable in _WINDOWS_VARIABLES:
if os.environ.get(variable):
continue
try:
# No stdin: cmd.exe inherited the terminal and swallowed the
# answer typed at the first prompt.
result = subprocess.run(
["cmd.exe", "/c", f"echo %{variable}%"],
capture_output=True, text=True, timeout=10, stdin=subprocess.DEVNULL,
cwd="/mnt/c" if Path("/mnt/c").is_dir() else None, check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
# The others would wait as long: detection is told the Windows
# side was not searched, never that nothing is there.
_windows_unasked("cmd.exe", exc)
return
value = result.stdout.strip()
if value and not value.startswith("%"):
os.environ[variable] = str(_host_path(value))
def _windows_unasked(tool: str, exc: Exception) -> None:
"""Keep why a Windows program run from WSL gave no answer: an interop
slow to start or turned off hid every Windows setup, and the run said
none was installed."""
if isinstance(exc, subprocess.TimeoutExpired):
why = f"{tool} did not answer in {exc.timeout:g} s"
else:
why = f"{tool} could not run: {getattr(exc, 'strerror', None) or exc}"
_WSL["unasked"] = _WSL["unasked"] or why
def _expand_retroarch_path(value: str, app_dir: Path, home: Path | None = None) -> Path:
"""Expand the notations RetroArch writes into its config values.
fill_pathname_expand_special (libretro-common/file/file_path.c) maps a
leading '~' to the home directory and a leading ':' to the application
directory, dropping the two leading characters in both cases.
"""
if value[:1] == "~":
return (home or Path(str(Path.home()))) / value[2:]
if value[:1] == ":":
return app_dir / value[2:]
return _host_path(os.path.expandvars(os.path.expanduser(value)))
def _retroarch_cfg_dir(
cfg_path: Path, key: str, app_dir: Path, default: str, home: Path | None = None
) -> Path | None:
"""A directory setting of retroarch.cfg, as RetroArch expands it.
A value left empty or at `default` is the directory RetroArch falls back
on, `default` under app_dir. None when the config is unreadable or does
not set the key. A config this user cannot read is said once, like a
closed folder: a retroarch.cfg a `sudo retroarch` left to root hid the
setup without a word.
"""
try:
lines = cfg_path.read_text(encoding="utf-8", errors="replace").splitlines()
except OSError as exc:
_note_refused(cfg_path, exc)
return None
for line in lines:
line = line.strip()
name, sep, value = line.partition("=")
if sep and name.strip() == key:
value = value.strip().strip('"').strip("'")
if not value or value == "default":
return app_dir / default
return _expand_retroarch_path(value, app_dir, home)
return None
def _steam_libraries() -> list[Path]:
"""Every Steam library, the default one first.
Steam lists the others in steamapps/libraryfolders.vdf, each as a
"path" line. A RetroArch installed on D:/SteamLibrary was not found
when only Program Files was searched. The client's own folder is the
SteamPath value it writes under HKCU\\Software\\Valve\\Steam, read the
same way by Playnite (PlayniteExtensions 886468f6,
source/Libraries/SteamLibrary/Steam.cs:34-38): a client installed in
D:\\Steam hid every library.
"""
roots: list[Path] = []
steam_path = _read_registry("HKCU\\Software\\Valve\\Steam", "SteamPath")
candidates = [_host_path(steam_path.replace("/", "\\"))] if steam_path else []
for var in ("ProgramFiles(x86)", "ProgramFiles"):
base = os.environ.get(var, "")
if base:
candidates.append(Path(base) / "Steam")
for candidate in candidates:
if candidate not in roots and _is_dir(candidate):
roots.append(candidate)
libraries = list(roots)
for root in roots:
vdf = root / "steamapps" / "libraryfolders.vdf"
try:
text = vdf.read_text(encoding="utf-8", errors="replace")
except OSError:
continue
for raw in re.findall(r'"path"\s+"([^"]+)"', text):
library = Path(raw.replace("\\\\", "\\"))
if library not in libraries:
libraries.append(library)
return libraries
def _scoop_root(variable: str, parent: str) -> str:
"""%variable%, else %parent%\\scoop, else nothing."""
folder = os.environ.get(parent)
return os.environ.get(variable) or (str(Path(folder) / "scoop") if folder else "")
def _windows_retroarch_dirs() -> list[Path]:
"""Folders holding retroarch.exe where its installers put it.
C:/RetroArch-Win64 by default, C:/RetroArch for 32-bit builds, the same
names under Program Files, every Steam library, the Emulators folder of
an installed ES-DE (es_find_rules.xml lists all of them), and a Scoop
install, user or global.
"""
candidates = [_host_path("C:/RetroArch-Win64"), _host_path("C:/RetroArch")]
for var in ("ProgramFiles", "ProgramFiles(x86)"):
root = os.environ.get(var, "")
if root:
candidates += [Path(root) / "RetroArch-Win64", Path(root) / "RetroArch"]
candidates += [
Path(root) / "ES-DE" / "Emulators" / name
for name in ("RetroArch-Win64", "RetroArch")
]
candidates += [
library / "steamapps" / "common" / "RetroArch" for library in _steam_libraries()
]
# Scoop's Extras bucket: <root>\apps\retroarch\current, the root being
# %SCOOP% or ~\scoop for a user install, %SCOOP_GLOBAL% or
# %ProgramData%\scoop for a global one. Its system folder is persisted
# through a junction, so the folder beside retroarch.exe is the real one.
scoop_roots = [_scoop_root("SCOOP", "USERPROFILE"), _scoop_root("SCOOP_GLOBAL", "ProgramData")]
candidates += [
Path(root) / "apps" / "retroarch" / "current" for root in scoop_roots if root
]
return [folder for folder in candidates if _is_file(folder / "retroarch.exe")]
def _macos_retroarch_base() -> Path:
"""Where RetroArch on macOS keeps its system folder by default:
~/Documents/RetroArch, or Application Support/RetroArch for a portable
install. The Steam build is always portable (platform_darwin.m, `#if
HAVE_STEAM portable = YES`), with no portable.txt to say so: its
bundle under Steam's library, and no other RetroArch.app, mark it."""
support = Path.home() / "Library" / "Application Support" / "RetroArch"
if _is_file(support / "portable.txt"):
return support
steam = (
Path.home() / "Library" / "Application Support" / "Steam" / "steamapps"
/ "common" / "RetroArch" / "RetroArch.app"
)
if _is_dir(steam) and not _is_dir(Path("/Applications/RetroArch.app")):
return support
return Path.home() / "Documents" / "RetroArch"
def _retroarch_appimage_dirs(home: Path) -> list[Path]:
"""The system folder of each RetroArch AppImage kept with a portable
folder, up to two folders below home.
The buildbot's Linux build unpacks RetroArch-Linux-x86_64.AppImage beside
RetroArch-Linux-x86_64.AppImage.home/.config/retroarch. The AppImage
runtime sets HOME to <AppImage>.home and XDG_CONFIG_HOME to
<AppImage>.config when those folders exist (type2-runtime fedfad51,
src/runtime/runtime.c:1449-1462), so this RetroArch never reads
~/.config/retroarch. The archive holds no retroarch.cfg: until the first
run writes one, the system folder is the base folder's (frontend_unix_get_env
in platform_unix.c).
"""
images: list[Path] = []
for depth in ("", "*/", "*/*/"):
for suffix in (".home", ".config"):
try:
hits = sorted(home.glob(f"{depth}*.AppImage{suffix}"))
except OSError:
continue
for hit in hits:
image = hit.with_name(hit.name[:-len(suffix)])
if image not in images and _is_file(image):
images.append(image)
dirs: list[Path] = []
for image in images:
portable_home = image.with_name(image.name + ".home")
portable_config = image.with_name(image.name + ".config")
if _is_dir(portable_config):
base = portable_config / "retroarch"
elif _is_dir(portable_home) and "XDG_CONFIG_HOME" not in os.environ:
base = portable_home / ".config" / "retroarch"
else:
continue
tilde = portable_home if _is_dir(portable_home) else home
system = _parse_retroarch_system_dir(base / "retroarch.cfg", base, tilde)
if system is None and _is_dir(base):
system = base / "system"
if system is not None and system not in dirs:
dirs.append(system)
return dirs
def _unix_retroarch_base() -> Path:
"""RetroArch's base folder on Linux: $XDG_CONFIG_HOME/retroarch when the
variable is set, else ~/.config/retroarch (fill_pathname_application_data
in file_path_special.c, frontend_unix_get_env in platform_unix.c). The
code tests only that the variable exists, so an empty one counts."""
xdg = os.environ.get("XDG_CONFIG_HOME")
if xdg is not None:
return Path(xdg) / "retroarch"
return Path.home() / ".config" / "retroarch"
# System directory -> the retroarch.cfg it was read from and the directory
# ':' expands to there, for finding the cores of the same installation.
_RETROARCH_CONFIGS: dict[Path, tuple[Path, Path]] = {}
def _parse_retroarch_system_dir(
cfg_path: Path, app_dir: Path | None = None, home: Path | None = None
) -> Path | None:
"""Parse system_directory from retroarch.cfg.
app_dir is RetroArch's application directory, used to expand ':' values.
It defaults to the directory holding the config, which is where a portable
install keeps both. home is what '~' means to that RetroArch, the user's
home when not given.
"""
if not _exists(cfg_path):
return None
app_dir = app_dir or cfg_path.parent
system_dir = _retroarch_cfg_dir(cfg_path, "system_directory", app_dir, "system", home)
if system_dir is not None:
_RETROARCH_CONFIGS.setdefault(system_dir, (cfg_path, app_dir))
return system_dir
def _shell_unquote(value: str) -> str:
"""Resolve a shell right-hand side into its effective string value.
Handles concatenated quoted/unquoted segments the way bash does
(e.g. "/run/media/deck/EmuSD"/Emulation), expands variables in
double-quoted and unquoted segments, and stops at unquoted
whitespace or a comment.
"""
parts: list[str] = []
i = 0
n = len(value)
while i < n:
c = value[i]
if c == '"':
end = value.find('"', i + 1)
if end == -1:
parts.append(os.path.expandvars(value[i + 1:]))
break
parts.append(os.path.expandvars(value[i + 1:end]))
i = end + 1
elif c == "'":
end = value.find("'", i + 1)
if end == -1:
parts.append(value[i + 1:])
break
parts.append(value[i + 1:end])
i = end + 1
elif c.isspace() or c == "#":
break
else:
end = i
while end < n and value[end] not in "\"'#" and not value[end].isspace():
end += 1
parts.append(os.path.expandvars(value[i:end]))
i = end
return os.path.expanduser("".join(parts))
def _parse_bash_var(path: Path, key: str) -> str | None:
"""Extract the effective value of key= from a bash/shell file."""
if not _exists(path):
return None
try:
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
line = line.strip()
if line.startswith(f"{key}="):
_, _, value = line.partition("=")
return _shell_unquote(value)
except OSError as exc:
# A settings.sh a sudo EmuDeck run left to root hid the setup.
_note_refused(path, exc)
return None
# Where an embedded system names the board it was built for, in the words
# of our target lists: batocera-system.mk writes BATOCERA_SYSTEM_ARCH,
# recalbox-system.mk RECALBOX_SYSTEM_PLATFORM, ROCKNIX's scripts/image puts
# HW_DEVICE in os-release (RK3326, our rk3326). Lakka's scripts/image writes
# LIBREELEC_DEVICE when the image is built for a device (RPi4) and always
# LIBREELEC_PROJECT (Generic): the first one set is the board. KNULLI moves
# /usr/share/batocera to /usr/share/knulli (knulli-linux 57afa662,
# board/scripts/post-build-script.sh:264-278) and writes KNULLI_SYSTEM_ARCH
# to knulli.arch (package/system/knulli-system/knulli-system.mk:98-99).
# AmberELEC's scripts/image writes COREELEC_DEVICE (a21975bf, line 168), the
# DEVICE its Makefile builds (RG351P). EmuELEC's writes the same line (v4.8,
# line 189), the DEVICE of the release image (OdroidGoAdvance).
_BOARD_SOURCES: dict[str, tuple[str, str]] = {
"amberelec": ("os_release", "COREELEC_DEVICE"),
"emuelec": ("os_release", "COREELEC_DEVICE"),
"batocera": ("file", "/usr/share/batocera/batocera.arch"),
"recalbox": ("file", "/recalbox/recalbox.arch"),
"rocknix": ("os_release", "HW_DEVICE"),
"lakka": ("os_release", "LIBREELEC_DEVICE|LIBREELEC_PROJECT"),
"knulli": ("file", "/usr/share/knulli/knulli.arch"),
"retropie": ("retropie", ""),
}
# The board a system's own name stands for, where the two differ: the
# target lists are named for the board files (configs/knulli-rk3566.board),
# and the arch file for the TARGET flag the board sets. knulli-rk3566.board
# sets BR2_PACKAGE_BATOCERA_TARGET_RK3568, which knulli-system.mk:22-23
# (20260511) writes as rk3568. batocera-zen3.board sets TARGET_ZEN3, which
# batocera-system.mk:56-57 (batocera-43.1) writes as x86-64-v3.
_BOARD_NAMES: dict[str, dict[str, str]] = {
"batocera": {"x86-64-v3": "zen3"},
"knulli": {"rk3568": "rk3566"},
}
# The board a card names on a partition a computer reads. Batocera writes
# its image's board to boot/batocera.board on the BATOCERA boot partition,
# the FAT one beside SHARE (batocera-43.1, board/batocera/scripts/
# post-image-script.sh:60), and reads it there itself (package/batocera/
# core/batocera-scripts/scripts/batocera-info). batocera.arch is inside the
# image, out of a computer's reach. KNULLI writes boot/knulli.board the same
# way (knulli-linux 20260511, board/scripts/post-image-script.sh:66). Both
# write the image's name, which the target list maps to its board.
_CARD_BOARD_FILES: dict[str, str] = {"batocera": "boot/batocera.board",
"knulli": "boot/knulli.board"}
def card_board(platform: str) -> str | None:
"""The board the card mounted here names, None where no card or two
cards of different boards do: a card is most often prepared on a
computer, where the system's own board file does not exist."""
where = _CARD_BOARD_FILES.get(platform)
if where is None:
return None
boards: set[str] = set()
for mount in _mounted_cards():
try:
value = (mount / where).read_text(encoding="utf-8", errors="replace")
except OSError:
continue
if value.strip() and not _CONTROLS.search(value.strip()):
boards.add(value.strip().lower())
return boards.pop() if len(boards) == 1 else None
def detect_board(platform: str) -> str | None:
"""The board this system was built for, or None where it names none."""
kind, where = _BOARD_SOURCES.get(platform, ("", ""))
if kind == "file":
try:
value = Path(where).read_text(encoding="utf-8", errors="replace")
except OSError:
return None
elif kind == "os_release":
release = _parse_os_release()
value = next((release[key] for key in where.split("|") if release.get(key)), "")
elif kind == "retropie":
value = _retropie_board() or ""
else:
return None
board = value.strip().lower()
# A board no TARGET line names is written "unknown" (KNULLI's r16).
if board == "unknown":
return None
return _BOARD_NAMES.get(platform, {}).get(board, board) or None
# RetroPie names its board as get_platform does (RetroPie-Setup f5ebfba6,
# scriptmodules/system.sh:396-424 and 425-513): a Pi by the BCM Hardware
# line of /proc/cpuinfo or raspberrypi in its device tree, its model by the
# CPU field (bits 12-15) of a revision code with bit 23 set, rpi1 without
# it. With neither a Hardware line nor a device tree, the machine: x86_64.
# Read only where RetroPie is installed (rootdir /opt/retropie,
# retropie_packages.sh:17): a computer preparing a Pi's card is no Pi.
_RPI_MODELS = {0: "rpi1", 1: "rpi2", 2: "rpi3", 3: "rpi4", 4: "rpi5"}
def _retropie_board() -> str | None:
"""The target RetroPie's own reading of this machine names, or None."""
if not _is_dir(_on_device("/opt/retropie")):
return None
try:
cpuinfo = _on_device("/proc/cpuinfo").read_text(encoding="utf-8", errors="replace")
except OSError:
cpuinfo = ""
fields = {key.strip(): value.strip() for key, sep, value in
(line.partition(":") for line in cpuinfo.splitlines()) if sep}
tree = _on_device("/proc/device-tree/compatible")
try:
compatible = tree.read_bytes().decode("ascii", errors="replace")
except OSError:
compatible = None
hardware = fields.get("Hardware", "")
if hardware.startswith("BCM") or (not hardware and compatible is not None
and "raspberrypi" in compatible):
try:
revision = int(fields.get("Revision", ""), 16)
except ValueError:
return None
if not (revision >> 23) & 1:
return "rpi1"
return _RPI_MODELS.get((revision >> 12) & 15)
if hardware or compatible is not None:
return None
return "x86_64" if platform.machine() == "x86_64" else None
def _parse_json_path(path: Path, *keys: str) -> str | None:
"""Extract a nested string value from a JSON file."""
if not _exists(path):
return None
try:
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
for key in keys:
data = data[key]
return data if isinstance(data, str) and data else None
except (OSError, json.JSONDecodeError, KeyError, TypeError):
return None
def _parse_ps1_var(path: Path, key: str) -> str | None:
"""Extract value of $key= or key= from a PowerShell file."""
if not _exists(path):
return None
normalized = key.lstrip("$")
try:
raw = path.read_bytes()
# Windows PowerShell's Out-File writes UTF-16, Set-Content -Encoding
# UTF8 a byte order mark: EmuDeck's settings.ps1 passes through both.
encoding = "utf-16" if raw[:2] in (b"\xff\xfe", b"\xfe\xff") else "utf-8-sig"
for line in raw.decode(encoding, errors="replace").splitlines():
line = line.strip()
check = line.lstrip("$")
if check.startswith(f"{normalized}="):
_, _, value = check.partition("=")
return value.strip('"').strip("'")
except OSError as exc:
_note_refused(path, exc)
return None
# The root the embedded rules read under: "/" on a device, a folder holding a
# copy of one in the tests.
_SYSTEM_ROOT = Path("/")
def _on_device(path: str) -> Path:
"""A path of the running system, read under _SYSTEM_ROOT."""
if _SYSTEM_ROOT == Path("/"):
return Path(path)
return _SYSTEM_ROOT / path.lstrip("/")
# Why a system found here gets no folder: said once per run.
_NO_FOLDER = {
"TrimUI": "its firmware publishes no source naming the folder its RetroArch reads",
"MinUI": f"its card names no release in {CARD_MARKER}, which tells MinUI, NextUI "
"and MyMinUI apart. Name the card's root and the one it runs: "
"--platform minui (or nextui, myminui) --dest /mnt/SDCARD",
}
# A system found by its card, with the end of the path that proves it: the
# card root is what comes before.
_CARD_SYSTEMS = {"MinUI": "/.system/res"}
# (platform, BIOS folder) -> the name the system found there gives itself.
_DETECTED_OS: dict[tuple[str, Path], str] = {}
# A version as a list or a system writes it: v1.22.2, 43.1, 8.3.1.1.
_VERSION_TEXT = re.compile(r"[0-9A-Za-z][0-9A-Za-z._+-]{0,39}")
# What generate_pack.py wrote as every list's version until it recorded the
# platform's own: not a version, so a list holding it names none.
_NO_LIST_VERSION = "1.0"
# What the platform's own check does, not a verdict on it: it compares the
# files with the list of its own version, and no run proved them working.
_MD5_CHECK = ("{name}'s own BIOS check reads the list of the version it runs, and "
"may show some files as not matching it.")
def _version_line(path: Path) -> str:
"""The first line of a small version file, "" when it cannot be read."""
if not _is_file(path):
return ""
try:
with path.open("rb") as fh:
head = fh.read(4096)
except OSError:
return ""
lines = head.decode("utf-8", errors="replace").strip().splitlines()
return lines[0].strip() if lines else ""
def _batocera_version(_bios_path: Path) -> str:
# batocera-system.mk:9,100-102 (batocera-43.1): the version, then the
# date and time of the build.
words = _version_line(_on_device("/usr/share/batocera/batocera.version")).split()
return words[0] if words else ""
def _recalbox_version(_bios_path: Path) -> str:
# Dockerfile:31 (recalbox 10.1.1) writes RECALBOX_VERSION, which
# .gitlab-ci.yml:723 sets to the release tag, or for a build of a branch
# to its date and name. A build from a working tree says "development"
# (projects/configgen/configgen/challenge/RuleScript.py:64). Only a
# release is a version a list is built for.
text = _version_line(_on_device("/recalbox/recalbox.version"))
return text if re.fullmatch(r"\d+(?:\.\d+)+", text) else ""
def _retrobat_version(bios_path: Path) -> str:
# <RetroBat>/system/version.info, which es-update writes and es-checkversion
# reads (emulatorlauncher 48cdc616, es-update/RetrobatVersion.cs:66-92).
# The 8.3.1 installer holds "8.3.1.1-stable-win64".
text = _version_line(bios_path.parent / "system" / "version.info")
head = text.split("-", 1)[0]
return head if re.fullmatch(r"\d+(?:\.\d+)+", head) else ""
def _os_release_version(key: str, value: str) -> Callable[[Path], str]:
"""VERSION_ID from os-release, on the system that names itself so."""
def read(_bios_path: Path) -> str:
release = _parse_os_release()
if release.get(key, "").lower() != value:
return ""
return release.get("VERSION_ID", "")
return read
def _same_release(installed: str, listed: str) -> bool:
return installed == listed
def _retrobat_release(installed: str, listed: str) -> bool:
# The release tagged 8.3.1 ships 8.3.1.1: a fourth number is a build of
# the tagged version.
return installed == listed or installed.startswith(listed + ".")
class _VersionSource(NamedTuple):
"""Where a system states the version it runs, and what a different one means."""
read: Callable[[Path], str]
meaning: str
same: Callable[[str, str], bool] = _same_release
# Written by the list (v6.1) and not by the system (6.1).
prefix: str = ""
# The systems whose version a file states, read without running anything.
# RetroArch writes its version in no file: its lists come from core info
# files the online updater replaces, so its version is not compared. KNULLI
# writes its codename (knulli-system.mk:9,100-102, "scarab") and ROCKNIX the
# date of the build (scripts/image:82), not the release their lists name.
# AmberELEC's list names a prerelease tag, and how that tag maps to the
# VERSION its image writes is not established.
_VERSION_SOURCES: dict[str, _VersionSource] = {
"batocera": _VersionSource(_batocera_version, _MD5_CHECK),
"recalbox": _VersionSource(_recalbox_version, _MD5_CHECK),
"retrobat": _VersionSource(_retrobat_version, _MD5_CHECK, _retrobat_release),
# scripts/image:159-164 (Lakka-LibreELEC v6.1) writes VERSION_ID from
# OS_VERSION, "6.1" in distributions/Lakka/version, and ID=lakka.
"lakka": _VersionSource(
_os_release_version("ID", "lakka"),
"Lakka checks only that a file is there, so this matters only where a core "
"of the version it runs reads a file this list does not name.", prefix="v"),
# scripts/image:172-177 (EmuELEC v4.8): VERSION_ID from OS_VERSION, 4.8 in
# distributions/EmuELEC/version, and NAME=EmuELEC.
"emuelec": _VersionSource(_os_release_version("NAME", "emuelec"), _MD5_CHECK),
}
def version_note(plat: str, bios_path: Path, manifest: dict) -> tuple[str, str, str] | None:
"""(list version, installed version, sentence) when the system here runs
another version than the one the list was built for, else None: an
unknown version on either side says nothing."""
source = _VERSION_SOURCES.get(plat)
listed = manifest.get("version")
if (source is None or not isinstance(listed, str) or listed == _NO_LIST_VERSION
or not _VERSION_TEXT.fullmatch(listed)):
return None
installed = source.read(bios_path)
if not _VERSION_TEXT.fullmatch(installed):
return None
compared = listed[len(source.prefix):] if listed.startswith(source.prefix) else listed
if source.same(installed, compared):
return None
name = display_name(plat, manifest)
return listed, installed, (
f"This list was built for {name} {listed}, this machine runs {installed}. "
+ source.meaning.format(name=name))
def _rule_matches(rule: _OsRule, release: dict[str, str]) -> bool:
if rule.method == "os_release":
# Any of the KEY=value pairs, the value compared without case.
return any(
release.get(key) == value.lower()
for key, _, value in (pair.partition("=") for pair in rule.values)
)
if rule.method == "file_matches":
path, pattern = rule.values
try:
text = _on_device(path).read_text(encoding="utf-8", errors="replace")
except OSError:
return False
return re.search(pattern, text, re.IGNORECASE | re.MULTILINE) is not None
return all(_exists(_on_device(value)) for value in rule.values)
def _config_files(pattern: str) -> list[tuple[Path, Path]]:
"""(file to read, its folder as the system sees it) for a config rule."""
device = pattern.replace("$HOME", str(Path.home()), 1)
folder, _, name = device.rpartition("/")
if "*" not in name:
return [(_on_device(device), Path(folder))]
try:
return [(path, Path(folder)) for path in sorted(_on_device(folder).glob(name))
if _is_file(path)]
except OSError:
return []
def _os_system_dir(rules: list[_OsRule]) -> Path | None:
"""The folder a system's RetroArch reads: the system_directory of its
first config that sets one, else the folder its build defaults to.
The config also records where the cores of that installation are.
"""
for rule in rules:
home = Path(rule.home) if rule.home else None
for pattern in rule.configs:
for path, folder in _config_files(pattern):
system_dir = _parse_retroarch_system_dir(path, folder, home)
if system_dir is not None:
seen = _on_device(str(system_dir))
_RETROARCH_CONFIGS.setdefault(seen, _RETROARCH_CONFIGS[system_dir])
return seen
bios = next((rule.bios for rule in rules if rule.bios), None)
return _on_device(bios) if bios else None
def _detect_embedded() -> list[tuple[str, Path]]:
"""The embedded system this is, by what its own build writes.
A system built on another matches both: the derivative is meant. Two
unrelated systems matching are both returned, and os_conflict() names
them, so that no folder is chosen between them in silence.
"""
release = {k: v.lower() for k, v in _parse_os_release().items()}
matched = [rule for rule in _EMBEDDED_RULES if _rule_matches(rule, release)]
bases = {rule.base for rule in matched if rule.base}
found: list[tuple[str, Path]] = []
for name in dict.fromkeys(rule.name for rule in matched):
if name in bases:
continue
rules = [rule for rule in matched if rule.name == name]
plat = rules[0].manifest
folder = _os_system_dir(rules) if plat else None
if name in _CARD_SYSTEMS:
marker = next(value for rule in rules for value in rule.values
if value.endswith(_CARD_SYSTEMS[name]))
root = _on_device(marker[:-len(_CARD_SYSTEMS[name])])
plat = card_platform(root) or ""
if plat:
folder, name = root, display_name(plat)
if folder is None:
reason = _NO_FOLDER.get(
name, "nothing on it names the folder its RetroArch reads")
closing = "" if name in _CARD_SYSTEMS else " Name the folder with --dest."
print(f"{name} found here, but {reason}.{closing}", file=sys.stderr)
continue
_DETECTED_OS[(plat, folder)] = name
found.append((plat, folder))
return found
def detected_os(plat: str, path: Path) -> str:
"""The name of the system detection found this folder on, or ""."""
return _DETECTED_OS.get((plat, path), "")
# A card read from a computer can name a system it cannot tell from
# another: dArkOS writes ArkOS's EASYROMS tree (finishing_touches.sh:420-
# 481, daecf488) and replaced it on 30 December 2025, so an EASYROMS card is
# either one. The detection keeps ArkOS's name, as its rules and lists are
# keyed. On the device itself the boot splash title tells them apart.
_CARD_TITLES = {"ArkOS": "dArkOS or ArkOS"}
# The folders whose system was named from a card read on a computer.
_FROM_CARD: set[tuple[str, Path]] = set()
def card_title(name: str) -> str:
"""The system a card's own files name, as a computer reading it can tell."""
return _CARD_TITLES.get(name, name)
def detected_shown(plat: str, path: Path) -> str:
"""detected_os as the screen says it: a card read on a computer by the
name its files allow."""
name = detected_os(plat, path)
return card_title(name) if (plat, path) in _FROM_CARD else name
def os_conflict(platforms: list[tuple[str, Path]]) -> list[str]:
"""The systems among these when there are two or more: a machine runs one."""
names = list(dict.fromkeys(filter(None, (detected_os(n, p) for n, p in platforms))))
return names if len(names) > 1 else []
def _system_lines() -> list[str]:
"""Each embedded system detection knows, with the files it gets."""
lines = []
for name in dict.fromkeys(rule.name for rule in _EMBEDDED_RULES):
plat = next(rule.manifest for rule in _EMBEDDED_RULES if rule.name == name)
if name in _CARD_SYSTEMS:
lines.append(f"{name}: minui, nextui or myminui, as the card's {CARD_MARKER} "
"names it (from a computer: --dest <card root>)")
elif plat:
lines.append(f"{name}: {plat}")
else:
lines.append(f"{name}: not installed to, {_NO_FOLDER[name]} (use --dest)")
return lines
def found_label(plat: str, path: Path) -> str:
"""How a detected folder is announced: the system's own name, and the
platform whose files it gets when that is another name."""
name = detected_shown(plat, path)
shown = display_name(plat)
moved = "".join(f", {folder}/ at {place}"
for folder, place in sorted(_MOVED_FOLDERS.get(path, {}).items())
if folder in ("bios", "roms"))
folder = shown_path(setup_bios_folder(plat, path))
if not name or name == shown:
return f"{shown} at {folder}{moved}"
return f"{name} at {folder} ({shown} files){moved}"
def _note_windows_unasked() -> None:
"""Say once, as a folder detection could not look in, that Windows did
not answer: its drives are then searched without its folders."""
why = _WSL["unasked"]
if (not why or not getattr(_SETUP_SEARCH, "active", False)
or getattr(_SETUP_SEARCH, "quiet", False)):
return
refused = (Path(_WSL["root"]), why)
if refused in _DETECTION_REFUSED:
return
_DETECTION_REFUSED.append(refused)
words = refused_words(*refused)
EVENTS.emit("unsearched", folder=str(refused[0]), reason=why, message=words)
print(f" {screen_text(words)}", file=sys.stderr)
def _winreg_value(key: str, value: str) -> str | None:
"""A string value of the Windows registry, read natively."""
if sys.platform != "win32":
return None
import winreg
hive, _, subkey = key.partition("\\")
roots = {"HKCU": winreg.HKEY_CURRENT_USER, "HKLM": winreg.HKEY_LOCAL_MACHINE}
try:
with winreg.OpenKey(roots[hive], subkey) as handle:
data, _kind = winreg.QueryValueEx(handle, value)
except (OSError, KeyError):
return None
return data.strip() if isinstance(data, str) and data.strip() else None
def _read_registry(key: str, value: str) -> str | None:
"""A string value of the Windows registry, read natively or, under WSL,
through reg.exe. None when the key, the value or the means is missing."""
if os.name == "nt":
return _winreg_value(key, value)
if not _WSL["active"]:
return None
try:
result = subprocess.run(
["reg.exe", "query", key, "/v", value],
capture_output=True, text=True, errors="replace", timeout=10,
stdin=subprocess.DEVNULL, cwd="/mnt/c" if Path("/mnt/c").is_dir() else None,
check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
_windows_unasked("reg.exe", exc)
_note_windows_unasked()
return None
match = re.search(
rf"^\s*{re.escape(value)}\s+REG_(?:EXPAND_)?SZ\s+(.+?)\s*$", result.stdout, re.M
)
return match.group(1) if match else None
+567
View File
@@ -0,0 +1,567 @@
"""Downloading a file: resume, retries, partial copies and write errors."""
from __future__ import annotations
import contextlib
import errno
import http.client
import os
import stat
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from collections.abc import Callable
from pathlib import Path
from typing import BinaryIO
from installer.constants import (
MAX_DOWNLOAD_SIZE,
MAX_RETRIES,
RAW_FILE_URL,
RELEASE_URL,
RESUME_FROM_SIZE,
_UMASK,
_Interrupted,
_stop,
)
from installer.from_folders import FOLDER_IN_PLACE, LocalCopy, _copy_local
from installer.invocation import offline_requested
from installer.local_files import _digest_file, _digest_handle, unreachable_words
from installer.network import _retry_delay, network_words
from installer.offline import LOCAL, offline_words
from installer.outcome import DRIVE_FULL, HttpReason, NetworkReason, OfflineReason, _transfer_failure
from installer.pack_source import (
NOT_IN_PACK,
NOT_KEPT,
NOT_WRITABLE,
READ_ONLY,
_SHARING_VIOLATIONS,
_extract_from_pack,
_read_only_file,
_write_refused,
)
from installer.paths import _entry_path, _entry_place
from installer.probe import _is_file
from installer.record import KEPT, _NotKept, _clear_read_only, _kept_slot
from installer.terminal import Progress
def _folder_failure(exc: OSError) -> str:
"""Why the folder a file goes in could not be made."""
if _write_refused(exc):
return NOT_WRITABLE
if _drive_full(exc):
return DRIVE_FULL
return exc.strerror or str(exc)
def _download_dest(
f: dict, bios_path: Path, copy: LocalCopy | None,
) -> Path | tuple[str, bool, str]:
"""Where f goes, its folder made, or the result of a file that cannot go there."""
if _stop.is_set():
return str(f.get("dest", "?")), False, "stopped"
try:
dest = _entry_path(bios_path, f)
except ValueError:
return str(f.get("dest", "?")), False, "unsafe destination"
# Nothing to write, no folder made: a pack lacking the list's files
# left 405 empty folders in the BIOS folder.
if copy is None and LOCAL.pack is not None and LOCAL.pack.find(f) is None:
return f["dest"], False, NOT_IN_PACK
if copy is None and LOCAL.pack is None and offline_requested():
return f["dest"], False, OfflineReason(f"not fetched: {offline_words()}")
try:
dest.parent.mkdir(parents=True, exist_ok=True)
except OSError as exc:
return f["dest"], False, _folder_failure(exc)
try:
in_place_folder = dest.is_dir()
except OSError as exc:
return f["dest"], False, unreachable_words(exc)
if in_place_folder:
# Fetched, it failed only at the rename, on an errno and two paths.
return f["dest"], False, FOLDER_IN_PLACE
return dest
def _download_copied(
f: dict, bios_path: Path, dest: Path, copy: LocalCopy, verbose: bool,
progress: Progress | None,
) -> tuple[str, bool, str]:
"""Copy f from where copy found it on this machine, fetched when the copy fails."""
result = _copy_local(f, bios_path, dest, copy, progress)
if result[1]:
copy.index.count_copy(copy.misplaced)
return result
if result[2] in ("stopped", NOT_WRITABLE, READ_ONLY) or result[2].startswith(NOT_KEPT):
return result
# The copy went or changed since it was read (a card pulled out, a
# file another run replaced): the file is fetched as if never found,
# and a fetch that fails too names both reasons.
if verbose:
print(f" {f['dest']}: {result[2]}, fetching it instead", file=sys.stderr)
fetched = _download_one(f, bios_path, verbose, progress)
why = fetched[2]
if (fetched[1] or why in ("stopped", NOT_WRITABLE, READ_ONLY)
or why.startswith(NOT_KEPT)):
return fetched
both = f"{result[2]}, and {why}"
# The fetch's kind of failure stays, so the advice is the right one.
kind = type(why) if isinstance(why, (NetworkReason, OfflineReason)) else str
return fetched[0], False, kind(both)
def _download_one(
f: dict, bios_path: Path, verbose: bool = False,
progress: Progress | None = None, copy: LocalCopy | None = None,
) -> tuple[str, bool, str]:
"""Download a single file, or copy it from where copy found it on this
machine. Returns (dest, success, reason it failed)."""
dest = _download_dest(f, bios_path, copy)
if not isinstance(dest, Path):
return dest
if copy is not None:
return _download_copied(f, bios_path, dest, copy, verbose, progress)
if LOCAL.pack is not None:
return _extract_from_pack(f, bios_path, dest, progress)
if offline_requested():
return f["dest"], False, OfflineReason(f"not fetched: {offline_words()}")
if f.get("release_asset"):
url = RELEASE_URL.format(asset=urllib.parse.quote(f["release_asset"], safe=""))
else:
url = RAW_FILE_URL.format(path=urllib.parse.quote(f["repo_path"], safe="/"))
return _fetch_file(_FileFetch(f, bios_path, dest, url, verbose, progress))
class _FileFetch:
"""One file's download: where it goes, and what the current attempt holds."""
def __init__(self, f: dict, bios_path: Path, dest: Path, url: str, verbose: bool,
progress: Progress | None) -> None:
self.f = f
self.bios_path = bios_path
self.dest = dest
self.url = url
self.verbose = verbose
self.progress = progress
self.expected_size: int = f["size"]
# A large file keeps a fixed partial name so the next attempt, or the
# next run, asks only for what is missing.
self.resumable = self.expected_size >= RESUME_FROM_SIZE
self.full_partial = False
self.mismatch = ""
self.tmp_path: Path | None = None
self.partial: BinaryIO | None = None
self.counted = 0
self.resumed_count = 0
def begin(self) -> None:
"""Start an attempt holding nothing."""
self.tmp_path = None
self.counted = 0
self.resumed_count = 0
self.partial = None
def drop_private(self) -> None:
"""Remove the private copy of this attempt, never the locked partial."""
if self.tmp_path is not None and self.partial is None and self.tmp_path.exists():
self.tmp_path.unlink()
def take_back(self) -> None:
"""Take the bytes a failed attempt drew off the progress."""
if self.progress is not None and self.counted:
self.progress.add(-self.counted)
if self.resumed_count:
self.progress.forget_resumed(self.resumed_count)
def _fetch_file(job: _FileFetch) -> tuple[str, bool, str]:
"""Fetch job's file, retried, verified and moved into place."""
f = job.f
reason: str = "download failed"
refused = False
for attempt in range(1, MAX_RETRIES + 1):
job.begin()
try:
_fetch_attempt(job)
return f["dest"], True, ""
except _Interrupted:
# Stopped mid-transfer: a large file keeps its partial copy for
# the next run, and a small one is dropped rather than left beside
# the destination.
job.drop_private()
return f["dest"], False, "stopped"
except _NotKept as exc:
# No attempt changes it, and the file in place stays as it is.
job.drop_private()
return f["dest"], False, f"{NOT_KEPT} ({exc})"
except _Corrupt:
reason = job.mismatch
if job.verbose:
print(f" {reason} on attempt {attempt}", file=sys.stderr)
# Closed before the delete: Windows refuses to remove a file
# still open (WinError 32), and the error ended the run.
if job.partial is not None:
job.partial.close()
if job.tmp_path is not None and job.tmp_path.exists():
job.tmp_path.unlink()
delay = 0.0
except urllib.error.HTTPError as exc:
reason = _http_attempt_failure(job, exc, attempt)
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
# http.client raises IncompleteRead (an HTTPException, not an
# OSError) when a chunked transfer is cut, as a proxy re-encoding
# the stream does: it is a dropped connection like any other.
except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc:
reason, refused = _attempt_failure_reason(job.dest, exc)
if job.verbose:
print(f" Attempt {attempt} failed: {exc}", file=sys.stderr)
if not refused:
job.drop_private()
delay = _retry_delay(attempt, None)
finally:
if job.partial is not None:
job.partial.close()
job.take_back()
if refused or reason == DRIVE_FULL:
return f["dest"], False, reason
if attempt < MAX_RETRIES and delay and _stop.wait(delay):
return f["dest"], False, "stopped"
return f["dest"], False, reason
def _http_attempt_failure(job: _FileFetch, exc: urllib.error.HTTPError, attempt: int) -> str:
"""The reason an attempt the server refused gives, its copy dropped."""
words = f"HTTP {exc.code}"
if exc.code in (403, 429):
words += " (GitHub rate limit or access refused)"
reason = (NetworkReason if exc.code >= 500 or exc.code == 429
else HttpReason)(words)
reason.url = job.url
if job.verbose:
print(f" Attempt {attempt} failed: {exc}", file=sys.stderr)
job.drop_private()
if exc.code == 416 and job.tmp_path is not None and job.tmp_path.exists():
if job.partial is not None:
job.partial.close()
job.tmp_path.unlink() # the partial copy no longer fits the file
return reason
def _attempt_failure_reason(dest: Path, exc: Exception) -> tuple[str, bool]:
"""The reason a failed attempt gives, and whether no attempt can change it."""
if (isinstance(exc, OSError) and not isinstance(exc, urllib.error.URLError)
and _write_refused(exc)):
# No attempt can change a refused write. A read-only file in
# place is not a folder this user cannot write.
return (READ_ONLY if _read_only_file(dest) else NOT_WRITABLE), True
if _drive_full(exc):
# No attempt frees space either. A private copy is still
# removed below: it holds the space the next file needs.
return DRIVE_FULL, False
if _transfer_failure(exc):
return NetworkReason(network_words(exc)[1]), False
return str(getattr(exc, "reason", "") or exc), False
def _fetch_attempt(job: _FileFetch) -> None:
"""One attempt: the bytes received, checked and moved into place."""
offset = _resume_offset(job)
request = urllib.request.Request(job.url)
if offset:
request.add_header("Range", f"bytes={offset}-")
with urllib.request.urlopen(request, timeout=60) as resp:
if job.partial is not None and offset and getattr(resp, "status", 200) != 206:
offset = 0 # the server sent the whole file again
job.partial.truncate(0)
raw_length = resp.headers.get("Content-Length") if resp.headers else None
if raw_length and int(raw_length) != job.expected_size - offset:
raise ValueError(
f"Content-Length {raw_length} != expected {job.expected_size - offset}"
)
written = _receive_file(job, resp, offset)
_place_fetched(job, written)
def _resume_offset(job: _FileFetch) -> int:
"""Where the transfer starts: past the bytes the locked partial copy holds."""
if not job.resumable:
return 0
tmp_path = job.dest.parent / f".{job.dest.name}.part"
job.tmp_path = tmp_path
_partial_size(tmp_path)
# Two runs into one BIOS folder used to append to the same
# partial copy: the one that finds it locked downloads into
# a private file instead.
partial = _claim_partial(tmp_path)
job.partial = partial
if partial is None:
job.tmp_path = None
return 0
offset = os.fstat(partial.fileno()).st_size
if offset >= job.expected_size and _NO_RENAME_WHILE_OPEN:
# The run that verified this copy releases its lock
# to rename it: truncating it there destroyed that
# copy and failed the rename. It is left alone and
# this run writes a private file.
partial.close()
job.partial = None
job.tmp_path = None
job.full_partial = True
return 0
if offset >= job.expected_size:
partial.truncate(0)
return 0
return offset
def _receive_file(job: _FileFetch, resp: http.client.HTTPResponse, offset: int) -> Path:
"""Write the response into the partial copy or a private file, and
return the path written."""
partial, tmp_path = job.partial, job.tmp_path
if partial is not None and tmp_path is not None:
partial.seek(offset)
out = _Unclosed(partial)
with out:
downloaded = _stream_response(job, resp, out.write, offset)
written = tmp_path
else:
with tempfile.NamedTemporaryFile(
mode="wb", dir=job.dest.parent, prefix=f".{job.dest.name}.",
suffix=".part", delete=False,
) as temp:
written = job.tmp_path = Path(temp.name)
downloaded = _stream_response(job, resp, temp.write, offset)
if downloaded != job.expected_size:
raise ValueError(
f"downloaded {downloaded} bytes, expected {job.expected_size}"
)
return written
def _stream_response(job: _FileFetch, resp: http.client.HTTPResponse,
write: Callable[[bytes], object], offset: int) -> int:
"""Copy the response through write, counted on the progress. Returns
the bytes the file holds."""
progress = job.progress
downloaded = offset
if progress is not None and offset:
progress.add(offset, resumed=True)
job.counted += offset
job.resumed_count = offset
while True:
if _stop.is_set():
raise _Interrupted()
chunk = resp.read(1024 * 1024)
if not chunk:
break
downloaded += len(chunk)
if downloaded > job.expected_size or downloaded > MAX_DOWNLOAD_SIZE:
raise ValueError("download exceeded declared size")
write(chunk)
if progress is not None:
progress.add(len(chunk))
job.counted += len(chunk)
return downloaded
def _place_fetched(job: _FileFetch, written: Path) -> None:
"""Check the bytes written against the list, then give them the file's name."""
f, dest = job.f, job.dest
expected = {
name: f[name].lower() for name in ("sha256", "sha1") if f.get(name)
}
# A large file is hashed through the handle that holds its lock.
# On Windows that lock is mandatory: reopening the path to read
# it failed with a sharing violation, which read as an unwritable
# folder for every file of 16 MB or more (issue 82).
if job.partial is not None:
actual = _digest_handle(job.partial, tuple(expected))
else:
actual = _digest_file(written, tuple(expected))
if "sha256" in expected and actual["sha256"] != expected["sha256"]:
job.mismatch = "SHA-256 mismatch"
raise _Corrupt()
if "sha1" in expected and actual["sha1"] != expected["sha1"]:
job.mismatch = "SHA-1 mismatch"
raise _Corrupt()
# The mode a plain open() gives, executable where the repository
# file is: the temporary file is private, and a BIOS folder
# written with sudo has to stay readable by the emulator's user.
os.chmod(written, (0o777 if f.get("executable") else 0o666) & ~_UMASK)
_clear_read_only(dest)
# The file in place, a personal dump or another revision, is
# moved aside first: replaced, it was gone for good.
KEPT.keep(*_kept_slot(*_entry_place(job.bios_path, f)), dest, expected, written)
if job.partial is not None and _NO_RENAME_WHILE_OPEN:
# Windows renames no open file. Elsewhere the lock is held
# until the copy has its final name.
job.partial.close()
_replace_released(written, dest, expected)
else:
os.replace(written, dest)
if job.full_partial:
_drop_full_partial(dest, job.expected_size)
# Windows renames no file another handle holds open, and Python opens files
# without FILE_SHARE_DELETE: a locked partial copy is closed before its rename.
_NO_RENAME_WHILE_OPEN = os.name == "nt"
# Seconds a closed partial copy waits for a sharing violation to clear: a
# second run closing it again, or a scanner reading the new file.
RELEASE_WAIT = 30.0
def _replace_released(source: Path, dest: Path, expected: dict[str, str]) -> None:
"""Rename a verified copy whose lock was just released.
Another run may open the copy in that moment, which refuses the rename
with a sharing violation until it lets go. When the copy is gone, that
run placed the same file and removed it: the destination is checked
against the manifest's hashes before it counts as installed.
"""
deadline = time.monotonic() + RELEASE_WAIT
while True:
try:
os.replace(source, dest)
return
except FileNotFoundError:
if expected and _is_file(dest) and _digest_file(dest, tuple(expected)) == expected:
return
raise
except PermissionError as exc:
if (getattr(exc, "winerror", None) not in _SHARING_VIOLATIONS
or time.monotonic() >= deadline):
raise
time.sleep(0.2)
def _drop_full_partial(dest: Path, expected_size: int) -> None:
"""Remove a complete partial copy this run left alone.
A copy at full size that nothing holds is what a run stopped between its
check and its rename leaves behind. The destination now holds the
verified file, so the copy is only clutter. One another run holds is
left to it.
"""
path = dest.parent / f".{dest.name}.part"
if not _is_file(path):
return
try:
handle = _claim_partial(path)
except OSError:
return
if handle is None:
return
with handle:
complete = os.fstat(handle.fileno()).st_size >= expected_size
if complete:
# another run opened it meanwhile and finishes with it
with contextlib.suppress(OSError):
path.unlink()
else:
# created by the claim and taken since by another run
with contextlib.suppress(OSError):
if path.stat().st_size == 0:
path.unlink()
def _partial_size(path: Path) -> int:
"""Bytes already held by a partial copy. Anything but a plain file is dropped."""
try:
info = path.lstat()
except FileNotFoundError:
return 0
if stat.S_ISREG(info.st_mode):
return info.st_size
path.unlink()
return 0
def _claim_partial(path: Path) -> BinaryIO | None:
"""The partial copy, opened and locked for this run, or None when
another run holds it. A link planted at its name is not followed."""
flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
handle = os.fdopen(os.open(path, flags, 0o644), "r+b")
try:
if os.name == "nt":
import importlib
# typeshed declares msvcrt for win32 only: the module is read
# as the runtime holds it.
msvcrt = importlib.import_module("msvcrt")
locking: Callable[[int, int, int], None] = msvcrt.locking
locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
handle.close()
return None
# Opened and locked are two steps: in between, the run that held the
# partial may have renamed it into place and released it. The lock then
# sits on the installed BIOS, which looks like a finished partial and
# would be truncated. Only the file still under the partial's name is ours.
try:
ours = os.path.samestat(os.fstat(handle.fileno()), os.lstat(path))
except OSError:
ours = False
if not ours:
handle.close()
return None
return handle
def _release_claim(handle: BinaryIO, path: Path) -> None:
"""Free a file taken with _claim_partial and remove it. Removed while
still held where the system allows it, so no other run takes the name
in between. Windows refuses to remove an open file: there it is closed
first, and one another run opened meanwhile is left to that run."""
if not _NO_RENAME_WHILE_OPEN:
path.unlink(missing_ok=True)
handle.close()
if _NO_RENAME_WHILE_OPEN:
# another run holds it now and removes it when done
with contextlib.suppress(OSError):
path.unlink(missing_ok=True)
class _Unclosed:
"""The locked partial copy, written through without closing it."""
def __init__(self, handle: BinaryIO) -> None:
self._handle = handle
def __enter__(self) -> BinaryIO:
return self._handle
def __exit__(self, *_exc: object) -> None:
self._handle.flush()
def write(self, data: bytes) -> int:
return self._handle.write(data)
class _Corrupt(Exception):
"""The bytes arrived but are not the file the manifest names."""
_FULL_ERRNOS = (errno.ENOSPC, getattr(errno, "EDQUOT", errno.ENOSPC))
def _drive_full(exc: BaseException) -> bool:
return isinstance(exc, OSError) and exc.errno in _FULL_ERRNOS
+816
View File
@@ -0,0 +1,816 @@
"""Embedded systems, their cards and their network shares, named by the files they write."""
from __future__ import annotations
import os
import re
from pathlib import Path, PurePosixPath
from typing import NamedTuple
from installer.constants import AVAILABLE_PLATFORMS, CARD_PLATFORMS, PLATFORM_NAMES, _CARD_RULES
from installer.paths import spelled
from installer.probe import _WSL, _exists, _is_dir, _is_file, _probed
from installer.terminal import _kernel32
from installer.text import screen_text
def shown_path(path: Path | str) -> str:
"""A path as the person names it: under WSL, /mnt/d/BIOS is D:\\BIOS, the
drive the card row calls D:."""
text = str(spelled(path)) if os.path.isabs(str(path)) else str(path)
root = _WSL["root"].rstrip("/") + "/"
match = (re.match(rf"^{re.escape(root)}([a-z])(?:/(.*))?$", text)
if _WSL["active"] else None)
if match:
text = f"{match.group(1).upper()}:\\" + (match.group(2) or "").replace("/", "\\")
# A folder's name comes from whoever named it: a card's label, a
# retroarch.cfg, a pack. Printed raw, a control character in it is a
# terminal command.
return screen_text(text)
class _OsRule(NamedTuple):
"""One piece of evidence that names an embedded system.
manifest is the platform whose files it gets, "" for a system the
installer does not lay out. name is the system's own name. values are the
KEY=value pairs of os_release (any one), the files of file_exists (all),
or the file and the pattern of file_matches. bios is the folder used when
none of configs (retroarch.cfg files, read in order, `*` allowed) names a
system_directory. home is what `~` means to that system's RetroArch.
base is the system this one is built on: both match, this one is meant.
"""
manifest: str
name: str
method: str
values: tuple[str, ...]
bios: str | None
configs: tuple[str, ...] = ()
home: str = ""
base: str = ""
# The platform whose files each of these systems gets. They publish their own
# BIOS list, and these platforms transcribe it.
_STANDIN_MANIFESTS = {
"AmberELEC": "amberelec",
"EmuELEC": "emuelec",
"KNULLI": "knulli",
}
# Where the ELEC family keeps RetroArch: the config runemu writes and copies
# back on every launch, and HOME=/storage for the services that start it.
_ELEC_CONFIGS = ("/storage/.config/retroarch/retroarch.cfg",)
# ArkOS and dArkOS: the 64-bit and the 32-bit RetroArch. "Switch to SD2 for
# Roms" rewrites /roms/ to /roms2/ in both (darkos daecf488,
# scripts/Switch to SD2 for Roms.sh:91-92), so a second card is read here.
_ARK_CONFIGS = ("/home/ark/.config/retroarch/retroarch.cfg",
"/home/ark/.config/retroarch32/retroarch.cfg")
_PLYMOUTH_TITLE = "/usr/share/plymouth/themes/text.plymouth"
# muOS runs RetroArch on the config it copies from its default on first launch
# (internal f41f4a89, script/control/retroarch.sh:8-20). The default names
# /run/muos/storage/bios, a bind mount of MUOS/bios on the second card when
# that card holds one, else on the first (script/device/bind.sh:4,116-150),
# and loads cores from /opt/muos/share/core (retroarch.default.cfg:2806,3151).
MUOS_RETROARCH_CONFIGS = (
"/opt/muos/share/info/config/retroarch.cfg",
"/opt/muos/share/emulator/retroarch/retroarch.default.cfg",
)
# 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
# (<date>)", 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-<platform>.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 <card>/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/<tag>/ (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 display_name(plat: str, manifest: dict | None = None) -> str:
"""A platform's name as the frontend writes it, the manifest's when it has one."""
named = (manifest or {}).get("display_name")
if isinstance(named, str) and named.strip().isprintable() and 0 < len(named.strip()) <= 40:
return named.strip()
return PLATFORM_NAMES.get(plat, plat)
def _name_key(name: str) -> str:
"""Letters and digits only: MiSTer FPGA, misterfpga and Mister-FPGA are one name."""
return re.sub(r"[^a-z0-9]", "", name.lower())
# 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/<user>/<label> and /run/media/<user>/<label>.
try:
found += [g for g in sorted(child.iterdir()) if os.path.ismount(g)]
except OSError:
continue
return found
def _systems_reading() -> dict[str, list[str]]:
"""The device systems that get each platform's files, as detection knows
them: someone on muOS or ArkOS looks for that name, not RetroArch."""
names: dict[str, list[str]] = {}
for rule in _EMBEDDED_RULES:
if (rule.manifest and rule.name != display_name(rule.manifest)
and rule.name not in names.setdefault(rule.manifest, [])):
names[rule.manifest].append(rule.name)
return names
+253
View File
@@ -0,0 +1,253 @@
"""The JSON event stream of --events: schema 1, new kinds only, never a new key."""
from __future__ import annotations
import argparse
import json
import threading
from typing import TextIO
from installer.text import _CONTROLS
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 (<system> and <core> 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()}
File diff suppressed because it is too large. Load diff
+1661
View File
File diff suppressed because it is too large. Load diff
+188
View File
@@ -0,0 +1,188 @@
"""How the installer was started, and the command it gives back to run it again."""
from __future__ import annotations
import argparse
import hashlib
import os
import re
import shlex
import sys
from pathlib import Path
from installer.constants import BOOTSTRAP_URL
# 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/<id>
with uv 0.12.9) and pipx run from pipx's (~/.cache/pipx/<id> 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")
+1456
View File
File diff suppressed because it is too large. Load diff
+595
View File
@@ -0,0 +1,595 @@
"""Digests of the files in place, the RetroArch configuration and where saves go."""
from __future__ import annotations
import concurrent.futures
import contextlib
import errno
import hashlib
import io
import os
import re
import stat
import sys
import time
from pathlib import Path, PurePosixPath
from typing import IO
from installer.detect_frontends import _android_cfg_value, detect_platforms
from installer.detect_os import _RETROARCH_CONFIGS, _retroarch_cfg_dir, detect_os
from installer.embedded import shown_path
from installer.events import EVENTS
from installer.invocation import _INVOCATION
from installer.paths import (
RELATIVE_ROOTS,
_EMULATOR_DIRS,
_RELATIVE_DIRS,
_SAVE_DIRS,
SavePlace,
_entry_path,
_lexically_under,
_note_spelling,
_relative_root,
_safe_relative_path,
spelled,
)
from installer.probe import _SETUP_SEARCH, _held, _is_dir
from installer.terminal import EVENT_PROGRESS_INTERVAL, Terminal, detail
from installer.text import _plural
def _digest_file(path: Path, algorithms: tuple[str, ...]) -> dict[str, str]:
"""Compute several digests of a file in a single read.
Checking a 3 GB collection against both a SHA-1 and a SHA-256 used to walk
every file twice, single threaded. Hashing is cheap next to the I/O, so
the read is what has to happen once.
"""
with open(path, "rb") as fh:
return _digest_handle(fh, algorithms)
def _digest_handle(fh: IO[bytes], algorithms: tuple[str, ...]) -> dict[str, str]:
"""Digests of an open file, read from its start."""
hashers = {name: hashlib.new(name) for name in algorithms}
fh.seek(0)
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
for hasher in hashers.values():
hasher.update(chunk)
return {name: hasher.hexdigest() for name, hasher in hashers.items()}
def _sha1_file(path: Path) -> str:
"""Compute SHA1 of a file."""
return _digest_file(path, ("sha1",))["sha1"]
def _sha256_file(path: Path) -> str:
"""Compute SHA256 of a file."""
return _digest_file(path, ("sha256",))["sha256"]
def _cfg_true(value: str | None) -> bool:
return (value or "").strip().lower() == "true"
_CONFIGS_READ: list[bool] = []
def _retroarch_config_for(bios_path: Path) -> tuple[Path, Path] | None:
"""The retroarch.cfg whose system_directory is bios_path, and the
folder ':' expands to there.
A run given --dest detects nothing, so the configs are read here, once
and silently, the first time a save directory or the cores folder is
asked for: the interface names every folder with --dest, and its runs
sent Azahar's keys.txt to a guessed folder where line mode read
savefile_directory, and found no core where line mode found them.
"""
found = _retroarch_config_at(bios_path)
if found is not None or _CONFIGS_READ:
return found
_CONFIGS_READ.append(True)
# Silent, the unsearched event too: this run searched for no setup, and
# the event came after detect, the line it stands for never shown.
_SETUP_SEARCH.quiet = True
try:
with contextlib.redirect_stdout(io.StringIO()), \
contextlib.redirect_stderr(io.StringIO()):
detect_platforms(_INVOCATION.os_type or detect_os())
finally:
_SETUP_SEARCH.quiet = False
return _retroarch_config_at(bios_path)
def _folder_key(path: Path) -> str:
"""The folder as the system names it: absolute, links followed, and
case folded where the system's default filesystem folds it."""
real = os.path.realpath(path)
return real.casefold() if sys.platform in ("win32", "darwin") else real
def _retroarch_config_at(bios_path: Path) -> tuple[Path, Path] | None:
"""The config detection read for bios_path, however the folder is
written: --dest relative, through a link, or in another case. The
configs are keyed by the folder as each retroarch.cfg writes it."""
found = _RETROARCH_CONFIGS.get(bios_path)
if found is not None or not _RETROARCH_CONFIGS:
return found
wanted = _folder_key(bios_path)
for system_dir, config in _RETROARCH_CONFIGS.items():
if _folder_key(system_dir) == wanted:
return config
# A drive whose filesystem folds case where the system's default does
# not (or the reverse): the filesystem answers for folders that exist.
for system_dir, config in _RETROARCH_CONFIGS.items():
try:
if os.path.samefile(system_dir, bios_path):
return config
except (OSError, ValueError):
continue
return None
def save_directory_for(
bios_path: Path, manifest: dict, override: Path | None = None,
) -> SavePlace | str:
"""The save directory the platform's frontend hands its cores, or why
this run cannot tell.
A RetroArch found by its retroarch.cfg answers from it: savefile_directory
as RetroArch expands it, a value left at default or naming no folder
being saves/ beside the config (configuration.c config_load_file keeps
the default unless path_is_directory), and sort_savefiles_enable, true by
default (config.def.h:1099). savefiles_in_content_dir and
sort_savefiles_by_content_enable put the directory beside each game: no
single place then. Without a config, the BIOS folder standing at its
default name puts the save directory beside it, as the pack lays them out,
and a list whose dests start above the BIOS folder (RetroDECK) puts it
in the folder the run installs to. ``override`` (--save-dir) names the directory itself. A launcher that
writes the save directory at each launch, one folder per system
(by_system: Batocera, RetroBat), is not read from any retroarch.cfg:
the one on disk holds the last launch's system.
"""
layout = manifest.get("save_directory")
if not layout:
return "the file list names no save directory for this platform"
folder = layout["folder"]
listed = bool(layout["by_core"])
by_core = listed
found = None if layout.get("by_system") else _retroarch_config_for(bios_path)
if found is not None:
cfg_path, app_dir = found
for key in ("savefiles_in_content_dir", "sort_savefiles_by_content_enable"):
if _cfg_true(_android_cfg_value(cfg_path, key)):
return (f"RetroArch keeps saves beside each game ({key} in {cfg_path}): "
"name the folder with --save-dir")
sort = _android_cfg_value(cfg_path, "sort_savefiles_enable")
if sort is not None:
by_core = _cfg_true(sort)
if override is not None:
return SavePlace(override, by_core, listed)
directory = _retroarch_cfg_dir(cfg_path, "savefile_directory", app_dir, folder)
if directory is None or not _is_dir(directory):
directory = app_dir / folder
return SavePlace(directory, by_core, listed)
if override is not None:
return SavePlace(override, by_core, listed)
base = manifest.get("base_destination") or ""
if base and bios_path.name == base:
return SavePlace(bios_path.parent / folder, by_core, listed)
if not base:
# The dests start below the folder holding the BIOS folder
# (RetroDECK's ~/retrodeck holds bios/ and saves/).
return SavePlace(bios_path / folder, by_core, listed)
# The wording of the run's end, said before the menu too: two wordings
# of one fact in one run, the first printing /mnt/e under WSL.
return "its place is not known. Name it with --save-dir"
def place_save_entries(
files: list[dict], bios_path: Path, manifest: dict, override: Path | None,
display: str, say: bool = True,
) -> tuple[list[dict], list[dict]]:
"""Find the save directory for the entries read below it.
Returns the files to install and, when the save directory is unknown,
the entries left out as omissions, said once with the reason. Without
say nothing is printed or sent: the run says it (say_saves) once a
choice of systems has kept the files it counts.
"""
saved = [entry for entry in files if entry.get("root") == "save"]
if not saved:
return files, []
place = save_directory_for(bios_path, manifest, override)
if isinstance(place, SavePlace):
_SAVE_DIRS[bios_path] = place
# Named through the link the BIOS folder was named through.
_note_spelling(bios_path)
where = str(spelled(place.directory))
if (manifest.get("save_directory") or {}).get("by_system"):
where += f"{os.sep}<system>"
if place.by_core:
where += f"{os.sep}<core>"
_SAVE_WHERE[bios_path] = where
if say:
print(f" {saves_line(display, len(saved), where)}")
EVENTS.emit("saves", platform=str(manifest.get("platform", "")),
files=len(saved), folder=where)
return files, []
_SAVE_WHY[bios_path] = place
if say:
print(f" {_plural(len(saved), 'file')} read from {display}'s save directory "
f"left out: {place}.")
kept = [entry for entry in files if entry.get("root") != "save"]
unplaced = [
{"dest": entry["dest"], "name": PurePosixPath(entry["dest"]).name,
"system": "", "systems": list(entry.get("systems") or []), "required": False,
"reason": "no_save_directory", "frontend": display,
"cores": entry.get("cores"), "root": "save",
**({"core_folder": entry["core_folder"]} if entry.get("core_folder") else {})}
for entry in saved
]
return kept, unplaced
def place_relative_entries(
files: list[dict], bios_path: Path, manifest: dict, display: str, say: bool = True,
) -> tuple[list[dict], list[dict]]:
"""Find the roms and configs folders for the entries read below them.
The list gives each root relative to the BIOS folder, as the OS's own
source places them (ROCKNIX's /storage/roms holds bios/, Batocera's
configs folder is ../system/configs): a BIOS folder of the platform's
name puts the root there. Any other is a folder this run cannot relate
to the root, and the entries are left out with the reason.
"""
unplaced: list[dict] = []
for root in RELATIVE_ROOTS:
below = [entry for entry in files if entry.get("root") == root]
if not below:
continue
layout = manifest.get(f"{root}_directory") or {}
folder = (
_relative_root(bios_path, layout["from_bios"], root)
if layout and bios_path.name == layout.get("bios_folder") else None
)
if folder is not None:
_RELATIVE_DIRS[(bios_path, root)] = folder
continue
if say:
print(f" {_plural(len(below), 'file')} read from {display}'s {root} folder left "
f"out: {bios_path} is not its {layout.get('bios_folder') or 'BIOS'} folder.")
files = [entry for entry in files if entry.get("root") != root]
unplaced += [
{"dest": entry["dest"], "name": PurePosixPath(entry["dest"]).name,
"system": "", "systems": list(entry.get("systems") or []), "required": False,
"reason": f"no_{root}_directory", "cores": entry.get("cores"), "root": root}
for entry in below
]
return files, unplaced
def _config_keys(path: Path) -> set[str]:
"""The keys an emulatorLauncher-style key=value file sets, lowercased."""
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return set()
return {
line.split("=", 1)[0].strip().lower()
for line in text.splitlines() if "=" in line and line.split("=", 1)[1].strip()
}
def place_emulator_entries(
files: list[dict], bios_path: Path, manifest: dict, display: str, say: bool = True,
) -> tuple[list[dict], list[dict]]:
"""Find the emulator folder each entry a launcher runs from one goes to.
The platform keeps its BIOS folder beside its own folder holding the
launcher config (RetroBat's bios beside emulationstation): a BIOS
folder of that name whose parent holds the config is the platform's.
A key the config sets moves the folder somewhere this run does not
follow, so its files are left out. Otherwise the folder is the first of
the searched places that exists, the default one when none does, as the
launcher searches them.
"""
inside = [entry for entry in files if entry.get("root") == "emulators"]
if not inside:
return files, []
layout = manifest.get("emulators_directory") or {}
home = bios_path.parent
config = (
home.joinpath(*_safe_relative_path(
layout["config"], "emulators_directory.config", colons=False).parts)
if layout else None
)
if config is not None and bios_path.name == layout.get("bios_folder") and config.is_file():
moved = _config_keys(config)
matches = True
else:
moved, matches = set(), False
kept: list[dict] = []
unplaced: list[dict] = []
for entry in files:
if entry.get("root") != "emulators":
kept.append(entry)
continue
key = _safe_relative_path(str(entry["dest"]), "emulators dest", colons=False).parts[0]
places = [
home.joinpath(*_safe_relative_path(
t.replace("{key}", key), "emulators place", colons=False).parts)
for t in layout.get("searched") or []
]
default = home.joinpath(
*_safe_relative_path(layout.get("default", "").replace("{key}", key),
"emulators default", colons=False).parts
) if matches else None
if (matches and key.lower() not in moved and default is not None
and all(_lexically_under(place, home) for place in [*places, default])):
found = next((place for place in places if _is_dir(place)), None)
_EMULATOR_DIRS[(bios_path, key)] = found or default
kept.append(entry)
continue
unplaced.append({
"dest": entry["dest"], "name": PurePosixPath(entry["dest"]).name,
"system": "", "systems": list(entry.get("systems") or []), "required": False,
"reason": "no_emulators_directory", "cores": entry.get("cores"),
"root": "emulators",
})
if unplaced and say:
why = (f"{config} sets their folder" if matches
else f"{bios_path} is not the {layout.get('bios_folder') or 'BIOS'} folder "
f"beside {layout.get('config') or 'its config'}")
print(f" {_plural(len(unplaced), 'file')} read from {display}'s emulator folders "
f"left out: {why}.")
return kept, unplaced
# Per BIOS folder, where its save files go in words, or why that is not
# known: read by the lines that count them once a choice is made.
_SAVE_WHERE: dict[Path, str] = {}
_SAVE_WHY: dict[Path, str] = {}
def say_saves(plat: str, files: list[dict], omitted: list[dict], bios_path: Path,
display: str, printed: bool) -> None:
"""The save directory lines and the saves event, over the files the
run installs once narrowed: --system sony-playstation said 106 files
went to the save directory, none of them a PlayStation file. printed
is the menu having said them already."""
saved = sum(1 for entry in files if entry.get("root") == "save")
where = _SAVE_WHERE.get(bios_path)
if saved and where is not None:
if not printed:
print(f" {saves_line(display, saved, where)}")
EVENTS.emit("saves", platform=plat, files=saved, folder=where)
if printed:
return
for line in save_lines([], omitted, bios_path, display):
detail(f" {line}")
# The digests the line menu's head read of the files in place, by path and
# by what stat says of the file, kept for the check that follows Enter: the
# head named a wrong copy of the right size in place,
# and a card read twice is read at the speed of its reader. Emptied once
# that check has read them (head_reads_done).
_HEAD_READS: dict[tuple, dict[str, str]] = {}
def _stat_key(path: Path) -> tuple | None:
"""What tells a file apart from the same path rewritten: None for none."""
try:
info = path.stat()
except OSError:
return None
return (str(path), info.st_size, info.st_mtime_ns, info.st_ctime_ns, info.st_ino)
def _read_digests(path: Path, algorithms: tuple[str, ...], remember: bool = False) -> dict:
"""_digest_file, answered from what the head read when the file is the
same one, and remembered for the check when remember is set."""
key = _stat_key(path)
known = _HEAD_READS.get((key, algorithms)) if key is not None else None
if known is not None:
return known
digests = _digest_file(path, algorithms)
if remember and key is not None:
_HEAD_READS[(key, algorithms)] = digests
return digests
def head_reads_done() -> None:
"""The check after the head has read what it holds: nothing more is
answered from it, a file the run writes being read again."""
_HEAD_READS.clear()
def _classify_local(entry: dict, dest: Path, remember: bool = False) -> str:
"""Return 'up_to_date' or 'mismatched' for a file already on disk.
remember keeps what was read for the check after the line menu."""
expected = {
name: entry.get(name, "").lower()
for name in ("sha256", "sha1")
if entry.get(name)
}
try:
is_file = dest.is_file()
except OSError:
# A folder above it this user cannot enter: what sits there is not
# known to be the right file.
return "mismatched"
if not is_file:
# A folder at the file's place: --check says so, an install fails
# on that file alone.
return "mismatched"
if not expected:
return "up_to_date"
try:
actual = _read_digests(dest, tuple(expected), remember)
except OSError:
# Unreadable (no permission, a read error on a failing card): its
# contents are not known to be the right ones.
return "mismatched"
if all(actual[name] == value for name, value in expected.items()):
return "up_to_date"
return "mismatched"
def closed_folder_words(dest: Path, closed: tuple[Path, str]) -> str:
folder, why = closed
return f"this user cannot open {folder} ({why}), which holds {dest}"
def unreachable_words(exc: OSError) -> str:
"""Why the place of a file could not be looked at, in words."""
return (f"could not be read ({exc.strerror or exc}): this user may not "
f"have access to its folder")
def check_local(
files: list[dict], bios_path: Path, jobs: int = 8,
term: "Terminal | None" = None,
) -> tuple[list[dict], list[dict], list[dict]]:
"""Check which files exist locally and have correct hashes.
Returns (to_download, up_to_date, mismatched). With a terminal, a count
moves while the files are read: 3.9 GB on an SD card went by in minutes
of silence, read as a hung run and stopped with Ctrl+C.
"""
to_download: list[dict] = []
present: list[tuple[dict, Path]] = []
for f in files:
dest = _entry_path(bios_path, f)
if _held(dest):
present.append((f, dest))
else:
to_download.append(f)
up_to_date: list[dict] = []
mismatched: list[dict] = []
if present:
with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool:
verdicts = pool.map(
lambda item: (item[0], _classify_local(item[0], item[1])), present
)
shown = term if term is not None and term.live and not term.quiet else None
last = evented = 0.0
for done, (entry, verdict) in enumerate(verdicts, 1):
if verdict == "up_to_date":
up_to_date.append(entry)
else:
mismatched.append(entry)
now = time.monotonic()
# The program driving the installer gets the count the
# terminal gets: a screen with a bare timer over 6 GB on an
# SD card read as hung.
if EVENTS.on and (now - evented >= EVENT_PROGRESS_INTERVAL
or done == len(present)):
evented = now
EVENTS.emit("checking", files_done=done, files_total=len(present))
if shown is not None and (now - last >= 0.1 or done == len(present)):
last = now
print(f"\r read {done}/{len(present)}", end="", file=shown.stream,
flush=True)
if shown is not None:
print("\r\033[K", end="", file=shown.stream, flush=True)
return to_download, up_to_date, mismatched
# Where a file in place that this run replaces is kept: a folder beside the
# one written to, never inside it. Several emulators find their BIOS by
# content, not by name: DuckStation, SwanStation and Rustation read every
# file of the BIOS folder, BizHawk walks its firmware folder recursively. A
# kept copy anywhere under that folder could be taken for the BIOS.
BACKUP_DIR = "retrobios-backup"
# Written into every run folder the installer creates. --restore only accepts
# a folder holding it, so a folder someone else placed (a shared BIOS folder
# on a network share) is never copied over the user's files.
BACKUP_MARKER = ".retrobios-backup"
def _check_holder(holder: Path) -> os.stat_result:
"""Refuse a backup holder the user's files must not go into.
A link would send them wherever it points. On a system with user ids, a
folder another user owns was not made by this user's runs, and its owner
could read or swap what is moved in. A storage that keeps no owner per
file gives every file one owner: Android's shared storage shows a folder
Termux has just made as another user's, as does a FAT card. A holder
owned like the folder it sits in is that storage's owner, not someone
else's folder. Returns what was checked, so the caller can confirm the
same folder is still there once it has written into it.
"""
info = os.lstat(holder)
if not stat.S_ISDIR(info.st_mode):
raise OSError(errno.ELOOP, f"{holder} is a link or not a folder")
getuid = getattr(os, "getuid", None)
if (getuid is not None and info.st_uid != getuid()
and info.st_uid != os.lstat(holder.parent).st_uid):
raise OSError(errno.EPERM, f"{holder} belongs to another user")
return info
def _same_folder(path: Path, checked: os.stat_result) -> bool:
"""Whether path is still the folder checked, not a link swapped in since."""
now = os.lstat(path)
return (stat.S_ISDIR(now.st_mode)
and (now.st_dev, now.st_ino) == (checked.st_dev, checked.st_ino))
_SAVE_SPLITS = {(True, True): "a folder per system, then one per core, under",
(True, False): "a folder per system under",
(False, True): "a folder per core under"}
def save_where_words(where: str) -> tuple[str, str]:
"""(words, folder) for where the saves event says files go: the folder
without the <system> and <core> it ends with, and those said in words.
"go to: /sdcard/RetroArch/saves/<core>" read as a folder named <core>."""
parts = re.split(r"[\\/]", where)
by_core = bool(parts) and parts[-1] == "<core>"
if by_core:
parts = parts[:-1]
by_system = bool(parts) and parts[-1] == "<system>"
if by_system:
parts = parts[:-1]
folder = where[:len(os.sep.join(parts))] if (by_core or by_system) else where
return _SAVE_SPLITS.get((by_system, by_core), ""), folder
def saves_line(display: str, count: int, where: str) -> str:
"""Where the files read from the frontend's save directory go."""
words, folder = save_where_words(where)
return (f"{_plural(count, 'file')} read from {display}'s save directory "
f"{'goes' if count == 1 else 'go'} to {words + ' ' if words else ''}"
f"{shown_path(folder)}")
def unplaced_line(display: str, count: int, remedy: str) -> str:
"""The files read from an unknown save directory, left out."""
return (f"{_plural(count, 'file')} read from {display}'s save directory left out: "
f"its place is not known. {remedy}")
def save_lines(files: list[dict], omitted: list[dict], bios_path: Path | None,
display: str) -> list[str]:
"""The save directory lines of a plan, over the files a choice keeps:
106 were said to go there for a --system sony-playstation that kept
none of them, and ROCKNIX's 44 left out were said only at the end, as
"the frontend's"."""
lines = []
count = sum(1 for entry in files if entry.get("root") == "save")
where = _SAVE_WHERE.get(bios_path) if bios_path is not None else None
if count and where is not None:
lines.append(saves_line(display, count, where))
left = sum(1 for entry in omitted if entry.get("reason") == "no_save_directory")
if left:
why = _SAVE_WHY.get(bios_path) if bios_path is not None else None
lines.append(f"{_plural(left, 'file')} read from {display}'s save directory left "
f"out: {why}." if why else
unplaced_line(display, left, "Name it with --save-dir."))
return lines
+769
View File
@@ -0,0 +1,769 @@
"""The checks a file list passes before any of it is trusted."""
from __future__ import annotations
import urllib.parse
from pathlib import PurePosixPath
from installer.constants import (
MAX_DOWNLOAD_SIZE,
MAX_MANIFEST_FILES,
MAX_SELECTION_TAGS,
MAX_TOTAL_DOWNLOAD_SIZE,
OMISSION_REASONS,
SELECTION_FIELDS,
TROUBLESHOOTING_PAGE,
_LOOPBACK_HOSTS,
_SHA1_RE,
_SHA256_RE,
)
from installer.events import _clean_mapping
from installer.paths import RELATIVE_ROOTS, _entry_key, _roms_relation, _safe_relative_path, _safe_target_dir
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/<platform>.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}")
+743
View File
@@ -0,0 +1,743 @@
"""Narrowing a file list to a board, cores, regions, systems and one file per slot."""
from __future__ import annotations
from collections.abc import Callable, Collection, Iterable
from installer.constants import (
AREA_TERRITORIES,
FILE_GROUP,
OTHER_SYSTEMS,
REGIONS,
REGION_ALIASES,
WORLD_REGION,
_REGION_PARENT,
)
from installer.cores import SYSTEM_KEY_FILES, SYSTEM_SHORT_NAMES, did_you_mean, entry_systems
from installer.embedded import _name_key
from installer.manifest import _COPY_FIELDS
from installer.paths import _entry_key
def _for_cores(entry: dict, chosen: set[str]) -> dict | None:
"""The copy of a core file the chosen cores read, or None.
A destination holds one file. When several cores read it and disagree
on its content, the manifest carries the first core's copy and the
others as alternatives, in the order the pack builder tries them: a
pack built without the first core carries the next one's copy.
"""
if chosen.intersection(entry.get("cores") or []):
return entry
for alternative in entry.get("alternatives", []):
if chosen.intersection(alternative["cores"]):
kept = {
k: v for k, v in entry.items()
if k not in _COPY_FIELDS
and k not in ("alternatives", "slot_choices", "declared_choices")
}
kept.update((k, alternative[k]) for k in _COPY_FIELDS if k in alternative)
return kept
return None
def _settle_slot(
entry: dict,
chosen: set[str],
kept_system: Callable[[str], bool] | None = None,
) -> dict:
"""A platform file as a pack built for the chosen cores carries it.
Where a core's own source contradicts the platform and the frontend only
checks the path, the pack serves the core's copy: the first of
`slot_choices` naming a chosen core decides. Otherwise the platform
answers, through the first of `declared_choices` whose systems remain.
"""
declared = entry.get("declared_choices")
if declared is None:
return entry
platform_copy = next(
(c for c in declared
if kept_system is None or any(kept_system(s) for s in c["systems"])),
declared[0],
)
copy = next(
(c for c in entry.get("slot_choices", []) if chosen.intersection(c["cores"])),
None,
)
if copy is None or "sha1" not in copy:
copy = platform_copy
kept = {
k: v for k, v in entry.items()
if k not in _COPY_FIELDS
and k not in ("slot_choices", "declared_choices", "declared_copy")
}
kept.update((k, copy[k]) for k in _COPY_FIELDS if k in copy and k != "cores")
kept["cores"] = None
if copy is not platform_copy and copy.get("sha1") != platform_copy.get("sha1"):
# What the platform checks here, for the `declared` event.
kept["declared_copy"] = {k: platform_copy[k] for k in _COPY_FIELDS
if k in platform_copy and k != "cores"}
return kept
def _filter_by_target(
files: list[dict], target_cores: list[str]
) -> list[dict]:
"""Keep the platform's files, and the core files the given cores read."""
chosen = set(target_cores)
result: list[dict] = []
for f in files:
if f.get("cores") is None:
result.append(_settle_slot(f, chosen))
continue
kept = _for_cores(f, chosen)
if kept is not None:
result.append(kept)
return result
def designated_cores(
manifest: dict, names: list[str], target: str | None = None
) -> set[str]:
"""The cores a list of names designates, the way the pack builder reads it.
A target list, or a core found installed, names a core the buildbot's
way (`mednafen_psx`), and a file names the profile that reads it
(`beetle_psx`). `core_names` gives each profile its other names. A core
only the platform's RetroArch downloader brings runs on the boards
`downloaded_cores` gives it: Batocera's bcm2711 list names its own
amiberry, and the buildbot's amiberry core is no download there.
"""
wanted = set(names)
chosen = set(wanted)
for profile, aliases in (manifest.get("core_names") or {}).items():
if wanted.intersection(aliases):
chosen.add(profile)
if target is not None:
chosen -= {
profile for profile, boards in (manifest.get("downloaded_cores") or {}).items()
if target not in boards
}
return chosen
def offered_here(
manifest: dict, entry: dict, cores: set[str], target: str | None
) -> set[str]:
"""The cores a board reads this file for.
A roms folder can offer a core on some boards only (ROCKNIX writes
uae4arm for roms/amiga under the devices it builds it for): on another
board, that core reads nothing there, even when the board runs it for
another folder. `offered_boards` gives those boards.
"""
offered = manifest.get("offered_boards") or {}
if target is None or not offered:
return cores
tree = {"roms": "roms", None: "install"}.get(entry.get("root"))
if tree is None:
return cores
dest = str(entry.get("dest", ""))
return {
core for core in cores
if not any(
place["root"] == tree and dest.startswith(place["folder"] + "/")
and target not in place["boards"]
for place in offered.get(core) or []
)
}
def narrow_to_cores(
manifest: dict,
names: list[str],
files: list[dict] | None = None,
omitted: list[dict] | None = None,
declared_by_info: Collection[str] = (),
target: str | None = None,
) -> tuple[list[dict], list[dict]]:
"""Keep what the named cores read, as a pack built for them carries.
A file a core loads stays when that core is named. A file of the
platform's own list stays when one of its systems does: a system goes
when none of the cores `system_cores` gives it is named, and a system
it does not list stays whatever is named. A dropped system's file gives
way to the first named core claiming its destination. A manifest without
the two maps keeps the platform's list whole and matches cores by name.
A destination in `declared_by_info`, what the .info of an installed core
no profile describes declares, stays whatever is named. `target` is the
board the names are the list of.
"""
cores = designated_cores(manifest, names, target)
reach = manifest.get("system_cores") or {}
info_dests = {dest.casefold() for dest in declared_by_info}
def kept_system(system: str) -> bool:
return system not in reach or bool(cores.intersection(reach[system]))
displaced: list[dict] = []
def kept(entries: list[dict]) -> list[dict]:
result: list[dict] = []
for entry in entries:
if str(entry.get("dest", "")).casefold() in info_dests:
result.append(_for_cores(entry, cores) or _settle_slot(entry, cores))
continue
if entry.get("cores") is not None:
here = offered_here(manifest, entry, cores, target)
copy = _for_cores(entry, here)
if copy is not None:
result.append(copy)
continue
# None of the cores served here is named: a named core that
# wants the slot and has nothing held is a file left out.
claim = next(
(c for c in entry.get("absent_claims", [])
if here.intersection(c.get("cores") or [])),
None,
)
if claim is not None:
displaced.append({"dest": entry["dest"], **claim})
continue
# The systems declaring the file, where they are fewer than the
# ones reading it.
systems = entry.get("declared_in") or entry_systems(entry)
if not systems or any(kept_system(s) for s in systems):
result.append(_settle_slot(entry, cores, kept_system))
continue
# The system is dropped, which frees its destination for the
# first named core claiming it, as in a pack built for them.
copy = _for_cores(entry, cores)
if copy is not None:
result.append(copy)
return result
files = manifest.get("files", []) if files is None else files
omitted = manifest.get("omitted_files", []) if omitted is None else omitted
kept_files = kept(files)
return kept_files, kept(omitted) + displaced
def canonical_region(raw: str) -> str:
"""One region name or alias, spelled the way manifests spell it."""
key = raw.strip().lower()
key = REGION_ALIASES.get(key, key)
if key not in REGIONS:
import difflib
close = difflib.get_close_matches(key, [*REGION_ALIASES, *REGIONS], n=3, cutoff=0.5)
hint = f" Close matches: {', '.join(close)}." if close else ""
raise ValueError(
f"unknown region: {raw.strip()}.{hint} "
f"Short forms: {', '.join(REGION_ALIASES)}. Regions: "
f"{', '.join(sorted(REGIONS))}"
)
return key
def _region_comparable(a: str, b: str) -> bool:
return (
a == b
or _REGION_PARENT.get(a) == b
or _REGION_PARENT.get(b) == a
or a in AREA_TERRITORIES.get(b, ())
or b in AREA_TERRITORIES.get(a, ())
)
def _region_rank(file_regions: set[str], requested: list[str]) -> int:
for index, wanted in enumerate(requested):
if any(_region_comparable(wanted, region) for region in file_regions):
return index
return len(requested)
def region_drops(
entries: list[dict],
requested: list[str],
systems: list[str] | None = None,
held: set[str] | None = None,
) -> set[str]:
"""Destinations a region priority list withdraws, as _entry_key spells them.
The pack builder's rule (region.resolve_region_drops), replayed over the
groups the manifest records. Per group, the best-ranked regional file
stays. A world file beats unmatched regional ones the code does not search
before it (`priority`, lower first). When nothing matches and no world
file exists, every regional file stays, so a group is never emptied. A
file with no region never competes and always stays.
A core extra competes whatever systems are chosen, while a platform's own
declaration competes only when its system is kept, as in the pack.
``held`` names the destinations the manifest can install. A match it
lacks never displaces a held file: the American BIOS stays under
--region japan when the Japanese one is missing. A group named after a
single file (FILE_GROUP) competes with nothing and keeps nothing.
"""
if not requested:
return set()
kept_systems = set(systems) if systems else None
groups: dict[str, list[tuple[set, str, int | None]]] = {}
for entry in entries:
regions = entry.get("regions")
if not regions:
continue
joined = list(entry.get("region_groups") or [])
joined += [
group for group in entry.get("region_system_groups") or []
if kept_systems is None or group in kept_systems
]
priority = entry.get("priority")
if not isinstance(priority, int) or isinstance(priority, bool):
priority = None
for group in joined:
groups.setdefault(group, []).append((set(regions), _entry_key(entry), priority))
keep: set[str] = set()
drop: set[str] = set()
for group_id, members in groups.items():
if FILE_GROUP in group_id:
continue
world = {dest for regions, dest, _p in members if WORLD_REGION in regions}
ranks = {dest: priority for _regions, dest, priority in members}
regional = [
(_region_rank(regions, requested), dest)
for regions, dest, _p in members
if WORLD_REGION not in regions
]
keep |= world
if not regional:
continue
matched = [(rank, dest) for rank, dest in regional if rank < len(requested)]
winners, rivals = matched, world
if held is not None:
winners = [(rank, dest) for rank, dest in matched if dest in held]
rivals = world & held
if winners:
best = min(rank for rank, _dest in winners)
keep |= {
dest for rank, dest in matched
if rank == best or (rank < best and dest not in (held or ()))
}
drop |= {dest for _rank, dest in regional if dest not in keep}
elif rivals:
world_ranks = [ranks[dest] for dest in rivals]
known_ranks = [rank for rank in world_ranks if rank is not None]
best_world = min(known_ranks) if len(known_ranks) == len(world_ranks) else None
for _rank, dest in regional:
ours = ranks[dest]
if best_world is not None and ours is not None and ours < best_world:
keep.add(dest)
else:
drop.add(dest)
else:
keep |= {dest for _rank, dest in regional}
return drop - keep
def narrow(
files: list[dict],
omitted: list[dict],
systems: list[str],
cores: list[str],
regions: list[str],
) -> tuple[list[dict], list[dict]]:
"""Keep what the chosen systems, cores and regions need.
A core choice keeps the platform's own list and narrows only the files
cores load, the rule --target already follows. Regions are then decided
the way the pack builder decides them under --system: over the chosen
systems' declarations and every core extra. The system filter comes last.
"""
if cores:
files = _filter_by_target(files, cores)
omitted = _filter_by_target(omitted, cores)
if regions:
# The builder's held set: what the collection serves. An omission
# answers the request but takes no installable file's place, unless
# the builder holds it (held: true) and only this download lacks it:
# the pack drops the fallback it displaces, and so does this.
held = {_entry_key(f) for f in files} | {
_entry_key(o) for o in omitted if o.get("held")
}
dropped = region_drops(files + omitted, regions, systems, held)
files = [f for f in files if _entry_key(f) not in dropped]
omitted = [o for o in omitted if _entry_key(o) not in dropped]
if systems:
wanted = set(systems)
files = [f for f in files if _chosen(f, wanted)]
omitted = [o for o in omitted if _chosen(o, wanted)]
return files, omitted
def _chosen(entry: dict, wanted: set[str]) -> bool:
systems = entry_systems(entry)
if not systems:
return OTHER_SYSTEMS in wanted
return bool(wanted & set(systems))
def _merged_slot(claims: dict) -> tuple[int | None, tuple, frozenset]:
"""One key's rank, regions and sets over the emulators claiming it, as
the pack builder merges them (slot.merge_claims). Two ranks that differ,
or a rank beside an emulator declaring the file without one, leave the
file unranked: neither order may win for a pack serving both cores."""
ranks = {rank for claim in claims.values() for rank in claim.get("ranks", [])
if rank is not None}
ranked_by = {name for name, claim in claims.items()
if any(rank is not None for rank in claim.get("ranks", []))}
unranked_by = {name for name, claim in claims.items() if None in claim.get("ranks", [])}
conflict = len(ranks) > 1 or bool(ranked_by and unranked_by - ranked_by)
regions = tuple(sorted({r for claim in claims.values() for r in claim.get("regions", [])}))
sets = frozenset((name, group) for name, claim in claims.items()
for group in claim.get("sets", []))
return (None if conflict or not ranks else min(ranks)), regions, sets
def slot_drops(entries: list[dict], held: set[str],
reach: Collection[str] | None = None) -> set[str]:
"""Destinations --one-per-slot withdraws, as _entry_key spells them.
The pack builder's rule (slot.resolve_slot_drops), replayed over the
`slot` each entry records. A slot is a group and the regions the code
selects the file for, split where no set links its files. In a slot of
two files or more, the one ranked first by `priority:` (lower first)
stays and the others go, and only when every file of it is ranked and
one ranks best: otherwise every file stays. `held` names what the run
can install, as for the regions. `reach` is the cores of the board: the
claims of the others are no part of its order.
"""
bucketed: dict[tuple[str, tuple], list[tuple[str, int | None, frozenset]]] = {}
keep: set[str] = set()
for entry in entries:
slot = entry.get("slot")
key = _entry_key(entry)
if not isinstance(slot, dict) or key not in held:
continue
# One lookup per name the groups list the file under (`also`).
for chain in [slot, *slot.get("also", [])]:
merged = None
for claims in chain.get("keys", []):
here = {name: claim for name, claim in claims.items()
if reach is None or name in reach}
if here:
merged = _merged_slot(here)
break
if merged is None:
keep.add(key)
continue
rank, regions, sets = merged
for group in chain.get("groups", []):
bucketed.setdefault((group, regions), []).append((key, rank, sets))
drop: set[str] = set()
for found in bucketed.values():
for candidates in _linked_by_set(found):
if len(candidates) < 2 or any(rank is None for _key, rank in candidates):
keep.update(key for key, _rank in candidates)
continue
best = min(rank for _key, rank in candidates if rank is not None)
winners = [key for key, rank in candidates if rank == best]
if len(winners) != 1:
keep.update(key for key, _rank in candidates)
continue
keep.add(winners[0])
drop.update(key for key, _rank in candidates if key != winners[0])
return drop - keep
def _linked_by_set(found: list[tuple[str, int | None, frozenset]]
) -> list[list[tuple[str, int | None]]]:
"""The files of one slot split where no set links them: a rank orders
the members of one set, and files in no set are compared together."""
parent = list(range(len(found)))
def root(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
first_of: dict[object, int] = {}
for i, (_key, _rank, sets) in enumerate(found):
for set_key in sets or {None}:
if set_key in first_of:
parent[root(i)] = root(first_of[set_key])
else:
first_of[set_key] = i
parts: dict[int, list[tuple[str, int | None]]] = {}
for i, (key, rank, _sets) in enumerate(found):
parts.setdefault(root(i), []).append((key, rank))
return list(parts.values())
def one_per_slot(files: list[dict], omitted: list[dict],
reach: Collection[str] | None = None) -> tuple[list[dict], list[dict]]:
"""The files and omissions --one-per-slot keeps. What the builder holds
and this download lacks (held: true) displaces a file as in the pack."""
held = {_entry_key(f) for f in files} | {_entry_key(o) for o in omitted if o.get("held")}
dropped = slot_drops(files + omitted, held, reach)
return ([f for f in files if _entry_key(f) not in dropped],
[o for o in omitted if _entry_key(o) not in dropped])
def truth_lists(manifest: dict, files: list[dict],
omitted: list[dict]) -> tuple[list[dict], list[dict]]:
"""What --source truth installs: the files the emulator profiles prove a
core reads, as `generate_pack.py --source truth` packs them. The full
list marks what that list lacks (truth: false) and carries what only it
holds (truth_files, truth_omitted)."""
return ([f for f in files if f.get("truth", True)] + list(manifest.get("truth_files") or []),
[o for o in omitted if o.get("truth", True)]
+ list(manifest.get("truth_omitted") or []))
def standalone_entries(manifest: dict, layouts: dict, profile: str) -> list[dict] | None:
"""The files a profile's standalone build reads, as entries of the list:
None for a profile without one. An item [dest, sha1] takes its download
from the copy of the list with that content."""
if profile not in layouts:
return None
copies = {
copy["sha1"]: copy
for entry in [*manifest.get("files", []), *(manifest.get("truth_files") or [])]
for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]
if copy.get("sha1") and (copy.get("repo_path") or copy.get("release_asset"))
}
result: list[dict] = []
for item in layouts[profile]:
if isinstance(item, list):
dest, sha1 = item
copy = copies[sha1]
result.append({"dest": dest, **{k: copy[k] for k in _COPY_FIELDS
if k in copy and k != "cores"},
"cores": [profile]})
else:
result.append({**item, "cores": [profile]})
return result
def standalone_layout(manifest: dict, layouts: dict, profiles: list[str],
files: list[dict], omitted: list[dict]
) -> tuple[list[dict], list[dict]]:
"""--emulator with --standalone: the platform's own files of the systems
the emulators run, and beside them each emulator's standalone build, in
profile order, first at a destination wins, as `generate_pack.py
--emulator --standalone` packs them."""
built: dict[str, dict] = {}
for profile in sorted(profiles):
for entry in standalone_entries(manifest, layouts, profile) or []:
built.setdefault(_entry_key(entry), entry)
own = [entry for entry in files
if entry.get("cores") is None and _entry_key(entry) not in built]
return own + list(built.values()), [o for o in omitted if o.get("cores") is None]
# What --find reads a hash as, by its length in hex digits.
FIND_KINDS = {40: "sha1", 64: "sha256", 32: "md5", 8: "crc32"}
def find_by_hash(files: list[dict], value: str) -> tuple[str, list[dict], bool]:
"""The entries of a list whose content has this hash: the kind read
from its length, the matches, each at its destination with the copy
that has it, and whether the list records that kind at all."""
value = value.strip().lower()
kind = FIND_KINDS.get(len(value), "")
matches: list[dict] = []
recorded = False
seen: set[tuple[str, str]] = set()
for entry in files:
for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]:
if kind in copy:
recorded = True
if str(copy.get(kind, "")).lower() != value:
continue
found = dict(entry)
for field in ("alternatives", "slot_choices", "declared_choices", "declared_copy"):
found.pop(field, None)
found.update((k, copy[k]) for k in _COPY_FIELDS if k in copy)
if (_entry_key(found), found.get("sha1", "")) not in seen:
seen.add((_entry_key(found), found.get("sha1", "")))
matches.append(found)
return kind, matches, recorded
def recorded_axes(files: list[dict], omitted: Iterable[dict] = ()) -> frozenset:
"""What a file list lets --system, --core and --region narrow by: its
systems, its cores, its regions. A list from an older release records
none. The MinUI family's records cores and regions and no system: all
three were refused on it, by a remedy that fetched the same list."""
entries = [*files, *omitted]
systems = any("systems" in entry for entry in entries)
if not systems and not any("regions" in entry for entry in entries):
# Systems and regions came in one release: a list with neither is
# older, its cores read by nothing that narrows.
return frozenset()
# A current list records the regions of the files a region selects, and
# none when it has no such file: --region then keeps every file, as the
# pack built with it does.
axes = {"regions", *(["systems"] if systems else [])}
if any(copy.get("cores") for entry in files
for copy in [entry, *entry.get("alternatives", []), *entry.get("slot_choices", [])]):
axes.add("cores")
return frozenset(axes)
def records_selection(files: list[dict]) -> bool:
"""Whether a manifest records anything narrowing reads. Older ones do not."""
return bool(recorded_axes(files))
def available_choices(files: list[dict], omitted: list[dict]) -> dict[str, list[str]]:
"""The systems, cores and regions a manifest lets one narrow to."""
systems = {s for e in files + omitted for s in entry_systems(e)}
ordered = sorted(systems)
if any(not entry_systems(f) for f in files):
ordered.append(OTHER_SYSTEMS)
cores = {
c for f in files
for copy in [f, *f.get("alternatives", []), *f.get("slot_choices", [])]
for c in (copy.get("cores") or [])
}
regions = {
r for e in files + omitted for r in (e.get("regions") or [])
if r != WORLD_REGION
}
return {
"systems": ordered,
"cores": sorted(cores),
"regions": sorted(regions),
}
def choosable_cores(files: list[dict], omitted: list[dict],
systems: Collection[str] = ()) -> list[str]:
"""The cores a choice is made among, for the files a run keeps once
the save entries it cannot place and the game data --no-game-data cuts
are left out, of the systems chosen (every system for none). Cores on
the screen and c in line mode list these and count "N of M" out of
them: the screen listed the whole file list's 189 where the run
accepted 181."""
if systems:
files, omitted = narrow(files, omitted, list(systems), [], [])
return available_choices(files, omitted)["cores"]
def core_files(files: list[dict], core: str) -> list[dict]:
"""The files one core adds to the platform's own: what line mode's
Cores question and the screen's Cores rows size."""
return _filter_by_target([entry for entry in files if entry.get("cores") is not None],
[core])
def resolve_choices(
values: list[str], known: list[str], label: str,
aliases: dict[str, str] | None = None,
holders: dict[str, list[str]] | None = None,
) -> list[str]:
"""Names given on the command line, matched without regard to case.
Each value is one name or a comma-separated list. A whole value that is
itself a name wins over splitting it: Recalbox names one system
`msx1,msx2,msxturbor`. An unknown name is refused, never ignored, since
carrying on would install something other than what was asked.
aliases maps another name of a known one to it, as Batocera's `psx`
stands for sony-playstation. A known name always wins over an alias.
holders maps a system the list files under other ids to those ids
(key_file_holders): an unknown name for it is answered with them.
"""
aliases = {alias: name for alias, name in (aliases or {}).items() if name in known}
by_lower = {name.lower(): name for name in known}
for alias, name in aliases.items():
by_lower.setdefault(alias.lower(), name)
# Spelled as the site writes it (Sony PlayStation), a name is still one
# name when no other one reads the same once case and spacing go.
by_key: dict[str, str | None] = {}
for name in known:
key = _name_key(name)
by_key[key] = None if key in by_key else name
for alias, name in aliases.items():
by_key.setdefault(_name_key(alias), name)
chosen: list[str] = []
unknown: list[str] = []
for value in values:
value = value.strip()
tokens = [value] if value.lower() in by_lower else value.split(",")
for token in (t.strip() for t in tokens):
if not token:
continue
picked = by_lower.get(token.lower()) or by_key.get(_name_key(token))
if picked is None:
unknown.append(token)
elif picked not in chosen:
chosen.append(picked)
if unknown:
if not known:
raise ValueError(f"unknown {label}: {', '.join(unknown)}. This list records none.")
listing = {"system": "--list-systems", "emulator": "--list-emulators"}.get(
label, "--list-cores")
hints, inside_from = aliases, 4
held = holders or {}
stands_for: dict[str, str] = {}
notes = ""
if label == "system":
# gba is the end of nintendo-gba: three letters are enough here.
hints = {**{short: name for short, name in SYSTEM_SHORT_NAMES.items()
if name in known}, **aliases}
inside_from = 3
stands_for = {_name_key(system): system for system in held}
for short, name in SYSTEM_SHORT_NAMES.items():
if name in held:
stands_for.setdefault(_name_key(short), name)
named = dict.fromkeys(
stands_for[_name_key(token)] for token in unknown
if _name_key(token) in stands_for)
notes = "".join(
f"This list files {SYSTEM_KEY_FILES[system]} under "
f"{', '.join(held[system])}. " for system in named)
meant = {key: held[system] for key, system in stands_for.items()}
raise ValueError(
f"unknown {label}: {', '.join(unknown)}. {notes}"
f"{did_you_mean(unknown, known, listing, hints, inside_from, meant)}"
)
if values and not chosen:
raise ValueError(f"--{label} needs at least one name")
return chosen
def resolve_regions(values: list[str]) -> list[str]:
"""A region priority list, best first, from names or aliases."""
chosen: list[str] = []
for value in values:
for token in value.split(","):
if token.strip():
region = canonical_region(token)
if region not in chosen:
chosen.append(region)
if values and not chosen:
raise ValueError("--region needs at least one region")
return chosen
def parse_selection(text: str, count: int, ordered: bool = False) -> list[int]:
"""Numbers typed at a prompt: `3`, `1,4`, `2-5`, or `all`, 1-based.
Returned sorted, or in the typed order when the order is a priority.
"""
if text.strip().lower() in ("all", "*"):
return list(range(1, count + 1))
chosen: list[int] = []
for token in (t.strip() for t in text.split(",")):
if not token:
continue
low, sep, high = token.partition("-")
try:
start = int(low)
end = int(high) if sep else start
except ValueError:
raise ValueError(f"not a number or range: {token}") from None
if start > end or start < 1 or end > count:
raise ValueError(f"out of range: {token} (1-{count})")
for number in range(start, end + 1):
if number not in chosen:
chosen.append(number)
return chosen if ordered else sorted(chosen)
+480
View File
@@ -0,0 +1,480 @@
"""TLS, connections and the downloads of file lists."""
from __future__ import annotations
import datetime
import errno
import http.client
import json
import os
import socket
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any, NoReturn
from installer.constants import (
CONNECT_TIMEOUT,
DEFAULT_RELEASE_REF,
MANIFEST_URL,
MAX_MANIFEST_BYTES,
MAX_RETRIES,
MAX_STANDALONE_BYTES,
MAX_TARGETS_BYTES,
RELEASE_REF,
STANDALONE_DIR,
STANDALONE_URL,
TARGETS_URL,
TARGET_PLATFORMS,
)
from installer.embedded import display_name
from installer.events import EVENTS
from installer.manifest import NETWORK_ADVICE, _check_standalone_layouts, _validate_manifest, _validate_targets
from installer.offline import LOCAL, _Offline, _network_allowed, offline_named, offline_undo, offline_words
from installer.pack_source import read_local_manifest
from installer.paths import _read_limited_json
from installer.probe import _is_file
# The installer was written after this day. A clock that reads earlier is
# wrong, and TLS then finds every certificate not yet valid: a handheld
# with no clock battery boots on 1970 or 1980.
CLOCK_FLOOR = datetime.date(2026, 1, 1)
# Where systems keep their trusted certificates, for a Python built to look
# elsewhere: Debian, Fedora, openSUSE, the BSDs and macOS, Homebrew, Termux.
CA_BUNDLES = (
"/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem", "/etc/ssl/cert.pem",
"/usr/local/etc/openssl/cert.pem", "/opt/homebrew/etc/openssl@3/cert.pem",
"/data/data/com.termux/files/usr/etc/tls/cert.pem",
)
# Set from --verbose: the error text Python gives stays beside the words.
_RAW_ERRORS = threading.Event()
def _default_ca_present() -> bool:
"""Whether the certificates this Python reads by default exist."""
import ssl
paths = ssl.get_default_verify_paths()
for value in (os.environ.get("SSL_CERT_FILE"), paths.cafile, paths.openssl_cafile):
if value and Path(value).is_file():
return True
for value in (os.environ.get("SSL_CERT_DIR"), paths.capath, paths.openssl_capath):
try:
if value and any(Path(value).iterdir()):
return True
except OSError:
continue
return False
def _known_bundle() -> str:
"""A certificate bundle the system keeps where this Python does not look."""
return next((path for path in CA_BUNDLES if Path(path).is_file()), "")
def _ca_bundle_found() -> bool:
"""Whether any list of trusted certificates is on this machine.
Windows verifies against its own store, which Python reads directly.
"""
return os.name == "nt" or _default_ca_present() or bool(_known_bundle())
def network_words(
exc: BaseException, today: datetime.date | None = None, verbose: bool | None = None,
) -> tuple[str, str]:
"""The reason a request failed, and the same in words a beginner reads.
The reason is clock, no_ca, no_ssl, network, or offline for a request the run
was told not to make. Offline, the run printed
"[Errno -2] Name or service not known": the raw text now follows the
words only under --verbose.
"""
if isinstance(exc, _Offline):
return "offline", str(exc)
reason = getattr(exc, "reason", None)
inner = reason if isinstance(reason, BaseException) else exc
raw = str(reason or exc)
code, words = "network", ""
cert_error = getattr(sys.modules.get("ssl"), "SSLCertVerificationError", None)
if (isinstance(exc, urllib.error.URLError) and raw.startswith("unknown url type")
and not hasattr(urllib.request, "HTTPSHandler")):
# urllib defines no HTTPS handler in a Python built without ssl:
# three attempts and a word on the connection blamed the network.
code = "no_ssl"
words = ("This Python was built without its ssl module and cannot use HTTPS. "
"Run the installer with another Python 3.8 or newer")
elif cert_error is not None and isinstance(inner, cert_error):
today = today or datetime.date.today()
if not _ca_bundle_found():
code = "no_ca"
words = ("This system has no list of trusted certificates to check the "
"server with. Install the ca-certificates package, or name a "
"certificate bundle with SSL_CERT_FILE, then run again")
elif today < CLOCK_FLOOR:
code = "clock"
words = (f"The clock reads {today.isoformat()}: connect to Wi-Fi and let the "
"time sync, or set the date, then run again")
else:
words = "the server's certificate was rejected"
bundle = "" if _default_ca_present() else _known_bundle()
words += (f": this Python reads no certificate list, run again with "
f"SSL_CERT_FILE={bundle}" if bundle
else ", which a proxy or a filter on this network can cause")
elif isinstance(inner, socket.gaierror):
words = "no internet connection, or the server name could not be looked up"
elif isinstance(inner, (socket.timeout, TimeoutError)):
words = "the connection timed out"
elif isinstance(inner, ConnectionRefusedError):
words = "the server refused the connection"
elif isinstance(inner, OSError) and inner.errno in (
errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN):
words = "no internet connection: the network cannot be reached"
elif isinstance(inner, (ConnectionResetError, ConnectionAbortedError,
http.client.HTTPException)):
words = "the connection was cut"
if not words:
return code, raw
if _RAW_ERRORS.is_set() if verbose is None else verbose:
words += f" [{raw}]"
return code, words
def _address_lines(url: str) -> list[str]:
"""The address that failed, and the override that chose it if one did.
A RETROBIOS_BASE_URL left from a mirror that is down read as a network
fault: neither the host nor the variable was named.
"""
lines = [f" Address: {url}"]
if os.environ.get("RETROBIOS_BASE_URL"):
lines.append(" RETROBIOS_BASE_URL is set in this environment and chose that "
"address: unset it to read from the project itself.")
return lines
def _open_socket(
address: tuple[str, int], timeout: object, source_address: tuple[str, int] | None = None,
) -> socket.socket:
"""A connection given CONNECT_TIMEOUT to open, then the caller's timeout."""
limit = min(CONNECT_TIMEOUT, timeout) if isinstance(timeout, (int, float)) else CONNECT_TIMEOUT
sock = socket.create_connection(address, limit, source_address)
sock.settimeout(timeout if isinstance(timeout, (int, float)) else socket.getdefaulttimeout())
return sock
class _BoundedHTTPConnection(http.client.HTTPConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _open_socket
class _BoundedHTTPHandler(urllib.request.HTTPHandler):
def do_open(self, http_class: Any, req: Any, **kwargs: Any) -> Any:
return super().do_open(_BoundedHTTPConnection, req, **kwargs)
def install_bounded_opener() -> None:
"""Every request of the run opens its connection in CONNECT_TIMEOUT.
The proxy variables are read as before: build_opener keeps its
ProxyHandler, and only the HTTP and HTTPS handlers are replaced.
"""
handlers: list[type] = [_BoundedHTTPHandler]
if hasattr(http.client, "HTTPSConnection"):
class _BoundedHTTPSConnection(http.client.HTTPSConnection):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._create_connection = _open_socket
class _BoundedHTTPSHandler(urllib.request.HTTPSHandler):
def do_open(self, http_class: Any, req: Any, **kwargs: Any) -> Any:
return super().do_open(_BoundedHTTPSConnection, req, **kwargs)
handlers.append(_BoundedHTTPSHandler)
urllib.request.install_opener(urllib.request.build_opener(*handlers))
# The wait for each answer of a file list, its first byte included: a
# server that takes the connection and never answers (a captive portal, a
# stuck proxy) held the run 93 s on three waits of 30 s. A list is a few
# MB, never a slow stream.
LIST_TIMEOUT = 15.0
# Attempts after a wait ran out, for the connection (a TLS handshake a
# captive portal never finishes) or for the answer once connected (a stuck
# proxy): once more, a stall is rarely a blip.
STALLED_ATTEMPTS = 2
def _stalled(exc: BaseException) -> bool:
"""Whether exc is a wait that ran out: urllib raises a connect timeout
as a URLError whose reason is the timeout, a silent answer as the
timeout itself."""
reason = getattr(exc, "reason", None)
return isinstance(exc, socket.timeout) or isinstance(reason, socket.timeout)
def _fetch_json(
url: str, limit: int, label: str, attempts: int = MAX_RETRIES,
timeout: float | None = None, raw: bool = False,
) -> Any:
"""A JSON document, tried MAX_RETRIES times like every file download.
raw gives its bytes, for a document checked against a digest.
A file list fetched once ended the run on one timeout over flaky Wi-Fi.
A 4xx answer or an invalid document is final: asking again changes
nothing, and a server gone silent is asked once more only.
"""
_network_allowed(label)
timeout = LIST_TIMEOUT if timeout is None else timeout
for attempt in range(1, attempts + 1):
# The tries this failure gets: "(2/3)" then "after 2 attempts" for
# a server gone silent, asked once more only.
tries = attempts
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
if raw:
return _read_limited_json(resp, limit, label, raw=True)
return _read_limited_json(resp, limit, label)
except urllib.error.HTTPError as exc:
if exc.code < 500 and exc.code != 429 or attempt == attempts:
raise
delay = _retry_delay(attempt, exc.headers.get("Retry-After") if exc.headers else None)
problem = f"HTTP {exc.code}"
except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
code, problem = network_words(exc)
# A wrong clock or no certificate list fails every attempt alike.
if (attempt == attempts or code != "network"
or (_stalled(exc) and attempt >= STALLED_ATTEMPTS)):
if isinstance(exc, http.client.HTTPException):
raise ConnectionError(f"connection cut: {exc!r}") from exc
# How many were made, for the line that says so.
exc.__dict__["attempts"] = attempt
raise
delay = _retry_delay(attempt, None)
if _stalled(exc):
tries = min(attempts, STALLED_ATTEMPTS)
# Said, or three 30-second attempts read as a frozen program.
print(f" The {label} did not arrive ({problem}), trying again "
f"({attempt + 1}/{tries}) in {delay:.0f} s.", file=sys.stderr)
time.sleep(delay)
raise AssertionError("unreachable")
def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn:
"""Stop on a file list that arrived and is not valid."""
words = f"the file list is not valid: {exc}"
if isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError)):
# The parser's "Expecting value: line 1 column 1" told no one
# anything, where the full screen names the usual cause.
words = ("what arrived is not a file list: a Wi-Fi sign-in page or a cut "
"download looks like this")
EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat,
message=words)
print(f" For {display_name(plat)}, {words}.", file=sys.stderr)
if words.startswith("what arrived"):
for line in _address_lines(url):
print(line, file=sys.stderr)
print(" Check the connection (sign in to the Wi-Fi if it asks), then run the "
"same command again.", file=sys.stderr)
sys.exit(1)
def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError) -> NoReturn:
"""Stop on a file list the server answered with an HTTP error."""
EVENTS.emit(
"error", stage="manifest", reason="not_found" if exc.code == 404 else "network",
platform=plat, message=f"the file list could not be fetched: HTTP {exc.code}",
)
if exc.code == 404 and os.environ.get("RETROBIOS_BASE_URL"):
print(f" No file list for {plat} there.", file=sys.stderr)
for line in _address_lines(url):
print(line, file=sys.stderr)
sys.exit(1)
if exc.code == 404:
# Asked once, a 4xx being final. The name was checked before any
# request, so the revision is what has no such list.
print(f" No file list for {plat} at {RELEASE_REF}.", file=sys.stderr)
if RELEASE_REF != DEFAULT_RELEASE_REF:
print(f" RETROBIOS_REF={RELEASE_REF} has no list for {plat}: unset it, or "
"pick a newer tag from https://github.com/Abdess/retrobios/releases.",
file=sys.stderr)
else:
print(" The repository may be moving its files: run the same command "
"again in a few minutes.", file=sys.stderr)
sys.exit(1)
print(f" Could not fetch the file list for {plat}: HTTP {exc.code}", file=sys.stderr)
for line in _address_lines(url):
print(line, file=sys.stderr)
print(NETWORK_ADVICE, file=sys.stderr)
sys.exit(1)
def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn:
"""Stop on a file list the network did not bring."""
code, words = network_words(exc)
EVENTS.emit("error", stage="manifest", reason=code, platform=plat,
message=words if code != "network"
else f"the file list could not be fetched: {words}")
if code == "offline":
print(f" No file list for {plat}: {offline_words()}. Give --manifest FILE "
f"(a copy of install/{plat}.json) or --from-pack PACK, or run "
f"{offline_undo()}.", file=sys.stderr)
sys.exit(1)
if code != "network":
print(f" Could not fetch the file list for {plat}.", file=sys.stderr)
print(f" {words}.", file=sys.stderr)
sys.exit(1)
tries = getattr(exc, "attempts", MAX_RETRIES)
print(f" Could not fetch the file list for {plat} after {tries} "
f"attempts: {words}", file=sys.stderr)
for line in _address_lines(url):
print(line, file=sys.stderr)
print(NETWORK_ADVICE, file=sys.stderr)
sys.exit(1)
def fetch_manifest(plat: str) -> dict:
"""Download platform manifest JSON, or read the one this run was given."""
if LOCAL.manifest is not None:
return read_local_manifest(LOCAL.manifest, plat)
if LOCAL.pack is not None:
try:
return _validate_manifest(LOCAL.pack.manifest(plat), plat)
except ValueError as exc:
print(f" The file list in {LOCAL.pack.name} is not valid: {exc}",
file=sys.stderr)
sys.exit(1)
url = MANIFEST_URL.format(platform=plat)
try:
return _validate_manifest(_fetch_json(url, MAX_MANIFEST_BYTES, "file list"), plat)
except ValueError as exc:
_manifest_invalid(plat, url, exc)
except urllib.error.HTTPError as exc:
_manifest_http_error(plat, url, exc)
except (urllib.error.URLError, OSError) as exc:
_manifest_unreachable(plat, url, exc)
def _pack_alone(plat: str) -> bool:
"""A pack read without a file list for plat: one built before packs
carried their install list records the systems of its files only."""
return (LOCAL.pack is not None and LOCAL.manifest is None
and (LOCAL.pack.install_list or {}).get("platform") != plat)
def local_targets(plat: str) -> "dict | None":
"""The cores per board this run has without the network: the list the
pack carries, else targets/<platform>.json beside --manifest, where the
repository keeps it (install/targets/). None when there is neither."""
if LOCAL.pack is not None and LOCAL.pack.targets is not None \
and plat in LOCAL.pack.platforms():
return LOCAL.pack.targets
if LOCAL.manifest is None:
return None
beside = LOCAL.manifest.parent / "targets" / f"{plat}.json"
raw = _read_capped(beside, MAX_TARGETS_BYTES)
if raw is None:
return None
try:
return _validate_targets(json.loads(raw.decode("utf-8")))
except (UnicodeDecodeError, ValueError) as exc:
print(f" Error: the target list {beside} is not valid: {exc}", file=sys.stderr)
sys.exit(1)
def fetch_standalone(plat: str, manifest: dict) -> dict:
"""What each standalone build reads, for --standalone only: the file
beside --manifest (standalone/<platform>.json, where the repository
keeps it), else downloaded as the list is. Missing, unreachable or
invalid, the run stops on one line, code 1."""
beside = (LOCAL.manifest.parent / STANDALONE_DIR / f"{plat}.json"
if LOCAL.manifest is not None else None)
url = STANDALONE_URL.format(platform=plat)
where = str(beside) if beside is not None and _is_file(beside) else url
try:
if where != url:
raw = _read_capped(Path(where), MAX_STANDALONE_BYTES)
data = json.loads((raw or b"").decode("utf-8"))
else:
data = _fetch_json(url, MAX_STANDALONE_BYTES, "standalone layout")
return _check_standalone_layouts(data, manifest, plat)
except urllib.error.HTTPError as exc:
problem = f"HTTP {exc.code}"
except (urllib.error.URLError, OSError) as exc:
problem = str(exc) if isinstance(exc, _Offline) else network_words(exc)[1]
except (UnicodeDecodeError, ValueError) as exc:
problem = f"not valid: {exc}"
EVENTS.emit("error", stage="manifest", reason="unavailable", platform=plat,
message=f"--standalone needs {where}: {problem}")
print(f"Error: --standalone needs {where}, which could not be read ({problem}).",
file=sys.stderr)
sys.exit(1)
def fetch_targets(plat: str, attempts: int = MAX_RETRIES,
timeout: float | None = None) -> "dict | None":
"""The target core list: the one this run has at hand, else downloaded.
Empty on 404, where the platform publishes no targets. None when the list
could not be read: a timeout says nothing about the platform, and
answering "no targets" for it sent users to the full pack. A run without
the network and with no list at hand is refused, code 2, before any
file is written.
"""
held = local_targets(plat)
if held is not None:
return held
if LOCAL.offline and plat not in TARGET_PLATFORMS:
return {}
if LOCAL.offline:
source = (f"{LOCAL.pack.name} carries none" if LOCAL.pack is not None
else f"{offline_named()} makes no request")
print(f"Error: --target needs the {display_name(plat)} board list ({source}). Put "
f"install/targets/{plat}.json beside the --manifest file, or go online.",
file=sys.stderr)
sys.exit(2)
url = TARGETS_URL.format(platform=plat)
try:
return _validate_targets(_fetch_json(url, MAX_TARGETS_BYTES, "target list",
attempts=attempts, timeout=timeout))
except urllib.error.HTTPError as exc:
if exc.code == 404:
return {}
print(f" Error: failed to fetch targets for {plat}: {exc}", file=sys.stderr)
for line in _address_lines(url):
print(line, file=sys.stderr)
print(NETWORK_ADVICE, file=sys.stderr)
return None
except ValueError as exc:
print(f" Error: the target list for {plat} is not valid: {exc}", file=sys.stderr)
return None
except (urllib.error.URLError, OSError) as exc:
print(f" Error: failed to fetch targets for {plat}: "
f"{network_words(exc)[1]}", file=sys.stderr)
for line in _address_lines(url):
print(line, file=sys.stderr)
print(NETWORK_ADVICE, file=sys.stderr)
return None
def _retry_delay(attempt: int, retry_after: str | None) -> float:
"""Seconds before the next attempt: what the server asks, else 1, 2, 4."""
if retry_after:
try:
return min(max(float(retry_after), 0.0), 60.0)
except ValueError:
pass
return float(min(2 ** (attempt - 1), 8))
def _read_capped(path: Path, limit: int) -> bytes | None:
try:
with open(path, "rb") as handle:
data = handle.read(limit + 1)
except OSError:
return None
return data if len(data) <= limit else None
+114
View File
@@ -0,0 +1,114 @@
"""The offline mode and the local sources a run reads in place of the network."""
from __future__ import annotations
import json
import os
import weakref
from pathlib import Path
from typing import TYPE_CHECKING
from installer.constants import AVAILABLE_PLATFORMS, MAX_MANIFEST_BYTES
from installer.invocation import OFFLINE_VARIABLE, offline_requested
if TYPE_CHECKING:
from installer.from_folders import FolderIndex
from installer.pack_source import PackSource
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
+833
View File
@@ -0,0 +1,833 @@
"""How a run ends: failures, remedies and the next step, on the screen and in events."""
from __future__ import annotations
import errno
import http.client
import os
import socket
import sys
import urllib.error
from collections.abc import Callable
from pathlib import Path
from typing import Any, NamedTuple, NoReturn
from installer.cards import dest_drive
from installer.constants import BASE_URL, GAME_DATA, OMISSION_REASONS, OTHER_SYSTEMS, SITE_URL, TROUBLESHOOTING_PAGE
from installer.cores import entry_systems
from installer.detect_os import detected_os
from installer.embedded import _mounted_cards, card_bound, display_name, shown_path
from installer.invocation import _INVOCATION, Invocation, offline_requested
from installer.local_files import BACKUP_DIR
from installer.network import _address_lines
from installer.offline import LOCAL, OFFLINE_WORDS, offline_named, offline_undo
from installer.pack_source import NOT_IN_PACK, NOT_KEPT, NOT_WRITABLE, READ_ONLY
from installer.paths import _entry_path
from installer.probe import _held, _is_file
from installer.record import KEPT, _kept_lines
from installer.tally import Tally, installed_words, kinds_definition
from installer.terminal import OUTPUT, SAID_FAILED, Terminal, format_duration
from installer.text import _plural, agree, format_size, screen_text
def _locations(paths: list[Path]) -> str:
"""Where the run wrote, naming every destination when it served several."""
return ", ".join(shown_path(p) for p in paths) if paths else "nowhere"
# A write the drive had no room for: the same run fails the same way until
# space is freed or another drive is named.
DRIVE_FULL = "the drive is full"
# What a run says when every file is in place, on the screen and in line
# mode: the site's "How to check" quotes it (scripts/generate_site.py).
EVERYTHING_IN_PLACE = "Every file on the list is in place."
# The plan's two rows a beginner reads first: the README and the site name
# them from here, so they say what the screen shows.
TUI_INSTALL_ROW = "Install"
TUI_SYSTEMS_ROW = "Choose systems"
# The first screen's title: a setup found here, or none, and the list.
# which-pack names them from here.
TUI_FOUND_TITLE = "Where to install?"
TUI_CHOOSE_TITLE = "Which setup?"
# Asked after Which setup? where nothing was found, and on a card.
TUI_FOLDER_TITLE = "Which folder?"
def _on_read_only_mount(path: Path) -> bool:
"""Whether the file system holding path, or the folder it would go in,
is mounted read-only (a card Linux remounts read-only after an error)."""
if not hasattr(os, "statvfs"):
return False
probe = path
while not _held(probe) and probe.parent != probe:
probe = probe.parent
try:
return bool(os.statvfs(probe).f_flag & os.ST_RDONLY)
except OSError:
return False
def read_only_words(path: Path) -> str:
"""The remedy for a folder on a read-only file system, in one sentence
that the plan, the result and line mode all say: root cannot write it
either, and the plan offered sudo for it."""
place = path.absolute()
card = any(mount == place or mount in place.parents for mount in _mounted_cards())
return (f"The {'card' if card else 'drive'} is read-only: unlock it or mount it "
"read-write, then run again.")
# What Termux needs to write shared storage, said by the plan, the result
# and line mode alike.
TERMUX_STORAGE_WORDS = ("Run termux-setup-storage once and allow the storage permission "
"Android asks for, then run it again.")
def write_remedy(path: Path, plat: str, hint: Invocation, commands: bool = True) -> list[str]:
"""What the screens say a user can do about a folder they cannot write:
the read-only remedy, or the same choice run as an administrator, the
command carrying every option of the run (hint). The sudo line dropped
--from-pack and --manifest, and stopped at the file list with
--offline. commands is False where no command can be typed (a pad)."""
if _on_read_only_mount(path):
return [read_only_words(path)]
if hint.os_type == "android":
# Termux has no sudo: its shared storage is reached once Android
# gives it the storage permission.
return [TERMUX_STORAGE_WORDS]
if not commands:
return []
if hint.os_type == "windows":
return ["Or run the installer as an administrator."]
# sudo changes the home folder, and with it what is detected: the folder
# is named so root writes here.
return ["Or run it as root, this folder named: "
+ hint.command(plat, path, elevated=True)]
def _write_advice(path: Path, assumed: bool, plat: str = "",
hint: Invocation | None = None) -> str:
"""What to do about a folder this run could not write, the command
built by hint (the run's own invocation by default).
sudo fixes a root-owned BIOS folder on the console itself. On another
machine it would create that folder on the wrong disk: a platform named
but not found here is a card or share mounted elsewhere, named by --dest.
Windows has no sudo, and Termux reaches shared storage once
termux-setup-storage has run. A read-only mount refuses root as well,
so sudo is never offered for it.
"""
hint = hint or _INVOCATION
if _on_read_only_mount(path):
again = f"\n {hint.command(plat, path)}" if plat else ""
return (f" {read_only_words(path)} {path} is on a file system mounted "
"read-only, which no user can write, sudo included (a card or drive "
"the system switched to read-only after an error needs a check "
f"first: fsck, or chkdsk on Windows).{again}")
if assumed:
return (f" {path} is where the platform keeps its BIOS on its own system, "
"and it was not found here. If this machine prepares its card or "
"share, run it again with --dest pointing at that folder:\n"
f" {hint.command(plat, '<that folder>')}")
if plat and hint.os_type == "windows":
return (" This user cannot write there. Run it again from a PowerShell window "
"opened as administrator:\n"
f" {hint.command(plat, path)}\n"
" Or choose another folder with --dest.")
if plat and hint.os_type == "android":
return (f" This user cannot write there. {TERMUX_STORAGE_WORDS}\n"
f" {hint.command(plat, path)}\n"
" Or choose another folder with --dest.")
if plat:
# sudo resets HOME to root's on Debian, Ubuntu, Arch and SteamOS:
# the same command detected nothing there, fell back to a folder
# under /root and reported success.
return (" This user cannot write there. Run it again with sudo, naming the "
"folder so root does not look in its own home:\n"
f" {hint.command(plat, path, elevated=True)}\n"
" Or choose another folder with --dest.")
if hint.os_type == "windows":
return (" This user cannot write there: run the same command from a PowerShell "
"window opened as administrator, or choose another folder with --dest.")
return (" This user cannot write there: run the same command with sudo, "
"or choose another folder with --dest.")
class OfflineReason(str):
"""A file not fetched because the run was told to make no request."""
class NetworkReason(str):
"""A failure the connection caused: cut, timed out, refused by a server
or a proxy. The summary names the network instead of the folder."""
url = ""
class HttpReason(str):
"""A file the server answered for with an error of its own (HTTP 404):
the summary names the address, where "HTTP 404" alone told the user
neither what failed nor that running again changes nothing."""
url = ""
def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]:
"""The address the first refused file was asked at, and what chose it:
a mirror named with RETROBIOS_BASE_URL that holds the lists and not yet
the files, or a list out of step with the files it names."""
refused = [reason for _dest, reason in failures if isinstance(reason, HttpReason)]
if not refused:
return []
more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else ""
lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."]
if os.environ.get("RETROBIOS_BASE_URL"):
return lines + _address_lines(refused[0].url)[1:]
return lines + [" The file list names files the server does not hold, and running "
"again changes nothing until the two match.",
f" More help: {TROUBLESHOOTING_PAGE}"]
def _transfer_failure(exc: BaseException) -> bool:
"""Whether a download error came from the connection, not the disk."""
# urlopen raises URLError for the name lookup, the connection and TLS.
# A cut read surfaces as a timeout (socket.timeout is no TimeoutError
# before 3.10), a reset, an SSL error or a size that does not add up.
ssl_error = getattr(sys.modules.get("ssl"), "SSLError", ())
if isinstance(exc, (urllib.error.URLError, http.client.HTTPException, ValueError,
ConnectionError, TimeoutError, socket.timeout)):
return True
if ssl_error and isinstance(exc, ssl_error):
return True
return isinstance(exc, OSError) and exc.errno in (
errno.ECONNRESET, errno.ECONNREFUSED, errno.ECONNABORTED, errno.ETIMEDOUT,
errno.EHOSTUNREACH, errno.ENETUNREACH, errno.ENETDOWN, errno.EPIPE,
)
NETWORK_FAILURE_ADVICE = (
" The transfers were cut or refused on the way: check the connection, and "
"HTTPS_PROXY if this network needs a proxy.\n"
f" More help: {TROUBLESHOOTING_PAGE}")
def _status_print(term: Terminal | None) -> Callable[..., None]:
"""print, with the status words of what it prints in their roles when
term paints (Terminal.status)."""
if term is None or not term.colour:
return print
def say(*parts: object, **kwargs: Any) -> None:
print(*(term.status(str(part)) for part in parts), **kwargs)
return say
class _Ending(NamedTuple):
"""What every ending of a run reads, worked out by _report_outcome."""
say: Callable[..., None]
paths: list[Path]
downloaded: int
up_to_date: int
errors: int
omitted: int
offline: int
failures: list[tuple[str, str]] | None
sources: str
kept: list[str]
advice: list[str]
same_lines: list[str]
installed_kinds: str
omitted_entries: list[dict]
unplaced: int
platform_of: dict[Path, str]
hints: list[str]
same_choice: str
missing: Tally | None
def _say_failures(say: Callable[..., None], failures: list[tuple[str, str]] | None) -> None:
"""The failed files the progress has not named, one cause said once."""
reasons = {reason for _dest, reason in failures or []}
# A failure the progress already named on its FAILED line is not named
# again: line mode listed each one twice.
unsaid = [failure for failure in failures or [] if failure[0] not in SAID_FAILED]
if failures and len(failures) > 1 and len(reasons) == 1 and reasons != {""}:
# One cause, said once: a read-only folder listed ten of its files
# and "... and 266 more" above the advice that fixes them all.
said = f", first {unsaid[0][0]}" if unsaid else ""
say(f" failed: {_plural(len(failures), 'file')} ({reasons.pop()}){said}")
else:
for dest, reason in unsaid[:10]:
say(f" failed: {dest}" + (f" ({reason})" if reason else ""))
if len(unsaid) > 10:
say(f" ... and {len(unsaid) - 10} more")
def _failure_advice(
paths: list[Path], failures: list[tuple[str, str]], assumed: set[Path] | None,
platform_of: dict[Path, str] | None,
) -> list[str]:
"""What to do about the causes of the failed files, one line each."""
refused = any(reason == NOT_WRITABLE for dest, reason in failures
if not Path(dest).is_absolute())
advice = [
_write_advice(path, path in (assumed or set()), (platform_of or {}).get(path, ""))
for path in paths
] if refused else []
advice += [_write_advice(folder, False) for folder in sorted({
Path(dest).parent for dest, reason in failures
if Path(dest).is_absolute() and reason == NOT_WRITABLE
})]
if any(reason == DRIVE_FULL for _dest, reason in failures):
advice.append(f" The drive holding {_locations(paths)} is full: free up space, or "
"install to another drive with --dest, then run again.")
if any(reason == READ_ONLY for _dest, reason in failures):
advice.append(" Files marked read-only are in the way: clear that attribute "
"(or delete them), then run again.")
advice += _http_failure_lines(failures)
if any(isinstance(reason, NetworkReason) for _dest, reason in failures):
advice.append(NETWORK_FAILURE_ADVICE)
if os.environ.get("RETROBIOS_BASE_URL"):
# A mirror that is down read as this machine's connection.
advice += _address_lines(BASE_URL)[1:]
if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures):
# The same run fails the same way: "retry only those" sent a phone
# user round the loop with nothing changed.
advice.append(" The files in place were left as they were, as no backup folder could "
"be made for them. Move them out of the folder, then run again to "
"install the new ones.")
return advice
def _kept_and_unplaced(omitted_entries: list[dict], notes: list[str] | None,
) -> tuple[list[str], int]:
"""The lines every ending repeats, and the count of files left out for
an unknown save directory."""
# Left out for an unknown save directory, said with that reason in
# every ending: "the collection does not hold it" blamed the collection.
unplaced = [entry for entry in omitted_entries
if entry.get("reason") == "no_save_directory"]
kept = _kept_lines() + ([
f"{_plural(len(unplaced), 'file')} read from "
f"{unplaced[0].get('frontend') or 'the frontend'}'s save directory left out: "
+ (f"{unplaced[0]['save_why']}." if unplaced[0].get("save_why")
else f"its place is not known. {LINE_SAVE_REMEDY}")] if unplaced else [])
kept += list(notes or [])
return kept, len(unplaced)
def _end_offline(end: _Ending) -> NoReturn:
"""End a run --offline left files out of."""
say, paths, downloaded, errors, offline = (
end.say, end.paths, end.downloaded, end.errors, end.offline)
sources = end.sources
remedy = _offline_remedy()
if not downloaded and not errors:
say(f"\nNothing installed: {agree(offline, 'file needs', 'files need')} "
"the internet, which "
f"{offline_named()} does not use.")
say(f" {remedy}")
for line in end.kept:
say(line)
if end.up_to_date:
say(f"{_plural(end.up_to_date, 'file')} already in place at "
f"{_locations(paths)}.")
for line in end.same_lines:
say(line)
sys.exit(2)
failed = f", {errors} failed" if errors else ""
if downloaded and sources:
# One count, the remedy under it, as the screen's result: the
# count came twice, "installed" then "copied". The failed files are
# in it.
say(f"\nFinished with files missing. {sources}")
sources = ""
elif downloaded:
say(f"\nFinished with files missing. {_plural(downloaded, 'file')} installed, "
f"{offline} not fetched ({offline_named()}){failed}.")
else:
# Nothing written: "Finished with files missing. 0 files installed"
# read as a part done.
say(f"\nNothing installed: {_plural(offline, 'file')} not fetched "
f"({offline_named()}){failed}.")
if sources:
say(f" {sources}")
if end.installed_kinds:
say(end.installed_kinds)
missing = end.missing
if missing is not None and missing.bios and missing.games:
# The kinds still missing, as the screen's result says them,
# before the remedy: "They are not in OLD" followed the files
# installed.
say(f" Still missing: {installed_words(missing.bios, missing.games)}.")
# Under the files it is about: after the save-directory line, "They"
# read as that one file.
say(f" {remedy}")
say(f"BIOS folder: {_locations(paths)}")
for line in end.kept + end.advice + end.same_lines:
say(line)
sys.exit(1 if downloaded else 2)
def _end_nothing_installed(end: _Ending) -> NoReturn:
"""End a run whose every file failed."""
say, paths, failures = end.say, end.paths, end.failures
say(f"\nNothing was installed. {_plural(end.errors, 'file')} failed.")
if failures and all(isinstance(r, (NetworkReason, HttpReason, OfflineReason))
for _d, r in failures):
# The folder was never the problem: naming it as the place being
# written to sent people looking at their disk.
say(f"BIOS folder: {_locations(paths)}")
elif _retry_words(failures):
# Nothing was written: every file is one the pack lacks.
say(f"BIOS folder: {_locations(paths)}")
else:
say(f"BIOS folder that was being written to: {_locations(paths)}")
for line in end.kept + end.advice:
say(line)
say(_retry_words(failures) or "Run the same command again once that is resolved. "
"Files already installed are kept.")
for line in end.same_lines:
say(line)
sys.exit(2)
def _end_with_errors(end: _Ending) -> NoReturn:
"""End a run that installed files and failed others."""
say, failures = end.say, end.failures
# One count: "42 files installed, 2 files failed." over "38 files
# copied from E:\, 4 downloaded, 2 still missing." said it twice,
# the failed files as missing ones.
say(f"\nFinished with errors. {end.sources}" if end.sources else
f"\nFinished with errors. {_plural(end.downloaded, 'file')} installed, "
f"{_plural(end.errors, 'file')} failed.")
if end.installed_kinds:
say(end.installed_kinds)
say(f"BIOS folder: {_locations(end.paths)}")
for line in end.kept + end.advice:
say(line)
retry = _retry_words(failures)
if retry:
say(retry)
elif not all(str(reason).startswith(NOT_KEPT) or reason == DRIVE_FULL
for _dest, reason in failures or []):
say("Run the same command again to retry only those.")
for line in end.same_lines:
say(line)
sys.exit(1)
def _say_left_out(end: _Ending) -> None:
"""The files a run that ended well did not install, and the hints after them."""
say, paths = end.say, end.paths
skipped = [entry for entry in end.omitted_entries
if entry.get("reason") != "no_save_directory"]
if end.omitted > end.unplaced and OUTPUT.verbose:
for line in _omission_lines(end.omitted - end.unplaced, skipped,
Path(paths[0]) if len(paths) == 1 else None):
say(line)
elif end.omitted > end.unplaced and any(entry.get("required") for entry in skipped):
# A file an emulator cannot start without is no detail: counted.
say(needed_absent_words(sum(1 for entry in skipped if entry.get("required")),
"--verbose"))
# RomM's scan is the step after the install: the other hints say how to
# install less, a detail.
for line in end.hints:
if OUTPUT.verbose or line == ROMM_SCAN_WORDS:
say(line)
def _end_done(end: _Ending) -> None:
"""End a run that installed every file it could."""
say, paths, downloaded, up_to_date = end.say, end.paths, end.downloaded, end.up_to_date
sources = end.sources
# No zero count, the screen's words: "Done. 0 files installed, 22
# files already up to date" beside its "Everything is in place"
in_place = f" {_plural(up_to_date, 'file')} already in place." if up_to_date else ""
if not downloaded:
say(f"\nDone. {EVERYTHING_IN_PLACE}")
elif sources and "," not in sources and not KEPT.summary():
# Every file from one place: "22 files installed." over "22 files
# copied from packx." said one count twice.
say(f"\nDone. {sources}{in_place}")
sources = ""
else:
say(f"\nDone. {_plural(downloaded, 'file')} installed.{in_place}")
if sources:
say(f" {sources}")
if end.installed_kinds:
say(end.installed_kinds)
if OUTPUT.verbose or not OUTPUT.where_said:
say(f"BIOS folder: {_locations(paths)}")
for line in end.kept:
say(line)
_say_left_out(end)
if end.same_choice and OUTPUT.verbose:
# After the questions, as the screen's result ends: "the same
# command" was one that asked them.
for line in end.same_lines:
say(line)
say("To check this later, run that command with --check.")
elif OUTPUT.verbose:
say("To check this later, run the same command with --check.")
say(next_step_words(end.platform_of, paths))
class OutcomeDetails(NamedTuple):
"""What a run's end says besides its counts (_report_outcome)."""
failures: list[tuple[str, str]] | None = None
transferred: int = 0
seconds: float = 0.0
declined: int = 0
assumed: set[Path] | None = None
omitted_entries: list[dict] | None = None
platform_of: dict[Path, str] | None = None
hints: list[str] | None = None
sources: str = ""
offline: int = 0
kinds: tuple[Tally, int] | None = None
same_choice: str = ""
notes: list[str] | None = None
missing: Tally | None = None
def _report_outcome(
paths: list[Path],
downloaded: int,
up_to_date: int,
errors: int,
omitted: int,
interrupted: bool,
*,
details: OutcomeDetails | None = None,
term: Terminal | None = None,
) -> None:
"""Close the run on what happened, and leave with a status that says so.
kinds is the count of the files installed (tally) and of the data
tree files, given for a list marking its game data, said apart. notes
are lines every ending repeats (a list built for another version).
missing is the count of the files --offline left out, by kind, given as
kinds is.
A run that installed nothing used to end on the word Done and a zero exit,
which reads as success to a person and to a script alike. offline counts
the files --offline left out at a terminal, kept apart from a "no" to
the size question: counted with it, 14,696 files missing ended on Done
and exit 0 once 4 came from this machine. They end the run as files
that failed do, 1 when some were installed and 2 when none were, the
codes the full screen's run gives. term paints the status words.
"""
d = details or OutcomeDetails()
failures, transferred, seconds, declined = d.failures, d.transferred, d.seconds, d.declined
offline, same_choice, notes = d.offline, d.same_choice, d.notes
say = _status_print(term)
# The command making the same choice ends every result the screen ends
# with it: "Finished with files missing" gave none.
same_lines = ([f"Same choice without questions: {screen_text(same_choice)}"]
if same_choice and OUTPUT.verbose else [])
# A file --offline left out is not a failure, whether the run asked or
# not: without questions it was "14698 files failed", and "Run the same
# command again to retry only those", which cannot fetch them.
left = [failure for failure in failures or [] if isinstance(failure[1], OfflineReason)]
if left:
failures = [failure for failure in failures or []
if not isinstance(failure[1], OfflineReason)]
errors = max(0, errors - len(left))
offline += len(left)
if transferred and seconds > 0 and OUTPUT.verbose:
verb = "copied from the pack" if LOCAL.pack is not None else "downloaded"
say(f"\n{format_size(transferred)} {verb} in "
f"{format_duration(seconds)} ({format_size(int(transferred / seconds))}/s).")
_say_failures(say, failures)
if declined and not downloaded and not errors and not interrupted and not offline:
say(f"\nNothing installed: {_plural(declined, 'file')} not downloaded, as answered.")
if up_to_date:
say(f"{_plural(up_to_date, 'file')} already in place at {_locations(paths)}.")
for note in notes or []:
say(note)
return
kept, unplaced = _kept_and_unplaced(d.omitted_entries or [], notes)
if interrupted:
say(f"\nStopped. {_plural(downloaded, 'file')} installed.")
for line in kept:
say(line)
say("Run the same command again to carry on from here. Nothing is lost.")
sys.exit(130)
# A standalone copy fails by absolute path, in an emulator's folder
# rather than the BIOS folder: that folder is where the write went.
elsewhere = sorted({Path(dest).parent for dest, _reason in failures or []
if Path(dest).is_absolute()})
advice = _failure_advice(paths, failures or [], d.assumed, d.platform_of)
paths = paths + [folder for folder in elsewhere if folder not in paths]
# The kinds installed, on every end that installed some, under where
# they came from: as the screen's result says them.
installed_kinds = (f" Installed: {installed_words(d.kinds[0].bios, d.kinds[0].games, d.kinds[1])}."
if d.kinds and d.kinds[0].files and downloaded and OUTPUT.verbose else "")
end = _Ending(
say=say, paths=paths, downloaded=downloaded, up_to_date=up_to_date, errors=errors,
omitted=omitted, offline=offline, failures=failures, sources=d.sources, kept=kept,
advice=advice, same_lines=same_lines, installed_kinds=installed_kinds,
omitted_entries=d.omitted_entries or [], unplaced=unplaced,
platform_of=d.platform_of or {}, hints=d.hints or [], same_choice=same_choice,
missing=d.missing,
)
if offline:
_end_offline(end)
if errors and not downloaded:
_end_nothing_installed(end)
if errors:
_end_with_errors(end)
_end_done(end)
NEXT_ON_CARD = "Next: put the card back in the device and start a game."
# On the device detection found the installer running on (KNULLI, Batocera):
# that system is already started.
NEXT_ON_DEVICE = "Next: start a game."
def next_step_words(platform_of: dict[Path, str], paths: list[Path]) -> str:
"""The step after an install that ended well: a card goes back in its
device, a setup on this machine is started."""
setups = [(platform_of.get(path, ""), path) for path in paths]
if setups and all(plat and on_its_card(plat, path) for plat, path in setups):
return NEXT_ON_CARD
if setups and all(plat and detected_os(plat, path) for plat, path in setups):
return NEXT_ON_DEVICE
names = list(dict.fromkeys(display_name(plat) for plat, path in setups if plat))
if len(names) == 1:
return f"Next: start {names[0]} and play."
return "Next: start your emulators and play."
def _offline_remedy(folders: list[str] | None = None, named: bool = False) -> str:
"""Where files --offline does not fetch can still come from: the
folders --from named (folders, on the screen) are not suggested again.
One wording for line mode, a run without questions, --check and the
screen. named: the line before already says what the folders lack."""
labels = (folders if folders is not None
else [index.label for index in LOCAL.folders])
if labels and named:
return f"Run the installer again with a pack (--from-pack) or {offline_undo()}."
if labels:
names = ", ".join(screen_text(shown_path(label)) for label in labels)
return (f"They are not in {names}: run the installer again with a pack "
f"(--from-pack) or {offline_undo()}.")
return ("Copy them from an old card or a folder (--from), or run the installer "
f"again with a pack (--from-pack) or {offline_undo()}.")
def _retry_words(failures: list | None) -> str:
"""What to do when every failure is a file the pack does not hold: a
second run fails them the same way, and "run it again to retry only
those" sent people round. "" otherwise."""
lacking = [dest for dest, reason in failures or [] if str(reason) == NOT_IN_PACK]
if not lacking or len(lacking) != len([
dest for dest, reason in failures or [] if not str(reason).startswith(NOT_KEPT)]):
return ""
name = LOCAL.pack.name if LOCAL.pack is not None else "The pack"
return (f"{name} does not hold {'it' if len(lacking) == 1 else 'them'}: a newer pack, "
"or a run without --from-pack, installs "
f"{'it' if len(lacking) == 1 else 'them'}.")
def _check_fetch_line(fetch: int, beside: str, lacking: int = 0, wrong: bool = False) -> str:
"""What --check says a run without it does with the files not in place:
offline, those it cannot fetch are said so, not "run it to fetch them".
With a pack, those it holds are copied and those it lacks are said lacking
(lacking): "fetch them" was said with a pack and no network."""
if LOCAL.pack is not None:
held = fetch - lacking
if not held:
return (f" {LOCAL.pack.name} holds none of them: a newer pack, or a run "
"without --from-pack, installs them.")
return (f" Run the same command without --check to copy {held} of them from "
f"{LOCAL.pack.name}. A wrong copy is replaced, and the one in "
f"place kept in {BACKUP_DIR} beside {beside}.")
if _offline_only():
if not fetch:
return " Run the same command without --check to copy them into place."
return (f" {agree(fetch, 'file needs', 'files need')} the "
f"internet, which {offline_named()} does not use. {_offline_remedy()}")
# What becomes of a wrong copy is said where there is one.
return (" Run the same command without --check to fetch them."
+ (f"\n A wrong copy is replaced, and the one in place kept in {BACKUP_DIR} "
f"beside {beside}." if OUTPUT.verbose or wrong else ""))
def _offline_failure(reason: str) -> bool:
"""Whether a failure a run reported is a file --offline left out."""
return OFFLINE_WORDS in reason or "makes no network request" in reason
# The definitions in a few words, for a help with no room for the sentences.
_SHORT_DEFINITIONS = (
("Game data:", "Game data: what a game reads, of no use to other cores."),
("Data files:", "Data files: an emulator's own data folder."),
)
def game_data_missing(names: str, count: int, folders: list[Path]) -> str:
"""The game data a run could not supply, and the folder each goes in:
"Copy it from your own copy of the game" named no folder."""
one = count == 1
places = list(dict.fromkeys(f"{shown_path(folder)}{os.sep}" for folder in folders))
where = (f" into {', '.join(places[:3])}" + (f" and {len(places) - 3} more folders"
if len(places) > 3 else "")) if places else ""
# The names first, the kind after them in a word: the definition was
# spliced into this sentence, and said again on its own line.
return (f"Not available here: {names}, game data "
f"{'its game reads' if one else 'their games read'}. Copy "
f"{'it' if one else 'them'} from an owned copy of the game{where}.")
def not_installable_words(count: int, required: int, reasons: dict[str, int]) -> str:
"""The line under the index count for the files the list leaves out:
"(1 required, not found: 37)" read as a sum."""
need = ("" if not required else ", required" if count == 1
else f", {required} of them required")
if set(reasons) == {"not_found"}:
return (f"Not installable: {agree(count, 'file is', 'files are')} not in the "
f"collection{need}.")
why = ", ".join(f"{OMISSION_REASONS.get(reason, reason)} ({number})"
for reason, number in sorted(reasons.items()))
return f"Not installable: {_plural(count, 'file')}{need}. Why: {why}."
def _omission_lines(count: int, entries: list[dict], bios_path: Path | None = None) -> list[str]:
"""What was skipped, the files an emulator cannot start without first.
"395 file are not in the collection yet" named nothing and gave one
reason for all, while the manifest says which file and why. Game data
is said apart, with the folder it goes in, as the screen says it.
"""
one = count == 1
lines = [f"{_plural(count, 'file')} {'was' if one else 'were'} not installed: "
f"the collection does not hold {'it' if one else 'them'}, or its copy "
f"fails {'its' if one else 'their'} check."]
needed = [e for e in entries if e.get("required")]
games = [e for e in needed if e.get("category") == GAME_DATA]
lines += _needed_lines([e for e in needed if e.get("category") != GAME_DATA],
"Needed to start an emulator")
if games:
names = ", ".join(str(e.get("dest") or e.get("name")) for e in games[:3]) + (
f" and {len(games) - 3} more" if len(games) > 3 else "")
folders = []
for entry in games:
try:
folders.append(_entry_path(bios_path, entry).parent if bios_path else None)
except ValueError:
continue
lines.append(" " + game_data_missing(names, len(games), [f for f in folders if f]))
# Defined on a line of its own, the sentence above naming the files.
lines.append(" " + kinds_definition(True, False))
return lines
def needed_absent_words(count: int, where: str) -> str:
"""The count of files an emulator cannot start without that the
collection does not hold, said in every mode: where names what lists
them, --verbose in line mode, Details on the screen."""
return (f"{_plural(count, 'file')} an emulator needs {'is' if count == 1 else 'are'} "
f"not available here ({where} names "
f"{'it' if count == 1 else 'them'}).")
def _absent_required(omitted: list[dict], bios_path: Path) -> list[dict]:
"""Required entries the manifest leaves out that the user has not placed."""
absent = []
for entry in omitted:
dest = entry.get("dest") or entry.get("name", "")
if not entry.get("required", True) or not dest:
continue
try:
placed = _is_file(_entry_path(bios_path, {**entry, "dest": dest}))
except ValueError:
# A path climbing out of the folder is never one we read, and one
# below a save directory this run does not know is not looked at.
placed = False
if not placed:
absent.append(entry)
return absent
def _needed_lines(entries: list[dict], heading: str, every: bool = False) -> list[str]:
"""Required files the collection lacks, by system with the emulators reading them.
A bare list (DARK.GOB, Data.rsdk, ... and 69 more) left a Batocera user
unable to tell whether their PlayStation was concerned.
"""
by_system: dict[str, tuple[set[str], set[str]]] = {}
for entry in entries:
system = str(entry.get("system") or ", ".join(entry_systems(entry)) or OTHER_SYSTEMS)
names, cores = by_system.setdefault(system, (set(), set()))
names.add(str(entry.get("dest") or entry.get("name")))
cores.update(str(core) for core in entry.get("cores") or [])
if not by_system:
return []
count = sum(len(names) for names, _cores in by_system.values())
lines = [f" {heading} ({_plural(count, 'file')}):"]
systems = sorted(by_system)
shown = systems if every else systems[:8]
for system in shown:
names, cores = by_system[system]
readers = f" ({', '.join(sorted(cores))})" if cores else ""
lines.append(f" {system}{readers}: {', '.join(sorted(names))}")
# Each emulator's own page, one click away: the index alone sent the
# user searching several hundred pages for theforceengine.
lines += [f" {SITE_URL}emulators/{core}/" for core in sorted(cores)]
if not every and len(systems) > 8:
# A file several systems share is a group of its own, counted as one.
unit = "groups" if any(", " in system for system in systems) else "systems"
more = len(systems) - 8
lines.append(f" ... and {more} more {unit if more > 1 else unit[:-1]} "
"(--check --verbose lists them all)")
if all(by_system[system][1] for system in shown):
lines.append(" Each emulator's page, linked above, says what these files are.")
else:
lines.append(f" Each emulator's page says what these files are: {SITE_URL}emulators/")
return lines
# Asked before, in an interactive run: past this size a download is worth a
# second thought, and --system, --core or --region can make it smaller.
CONFIRM_FROM_BYTES = 1024 * 1024 * 1024
# A --dry-run plan: file names per system, the systems shown when the
# listing is taller than the screen, and the lines around the listing.
PLAN_FILES_PER_SYSTEM = 8
PLAN_LARGEST_SYSTEMS = 10
PLAN_FRAME_LINES = 6
# Past this many systems a group sharing files is named by its first two.
PLAN_GROUP_TITLES = 3
# Answers that stop: every menu before this one taught q as quit.
_REFUSALS = ("n", "q", "quit", "exit", "stop", "abort")
def _offline_only() -> bool:
"""--offline without a pack: what is not on this machine cannot come."""
return offline_requested() and LOCAL.pack is None
def on_its_card(plat: str, dest: Path, system: str = "") -> bool:
"""Whether dest, a card mounted here, is the SD card of the system it
is for (system, else the one detection names): line mode and the
screen say "free some space on the card" alike."""
system = system or detected_os(plat, dest)
return bool(system and card_bound(system, plat) and dest_drive(dest) is not None)
# RomM serves the firmware rows its library scan records (rommapp/romm 5.4.0,
# backend/endpoints/firmware.py:148,175 read db_firmware_handler.list_firmware),
# and its folder watcher is off unless ENABLE_RESCAN_ON_FILESYSTEM_CHANGE is
# set (backend/config/__init__.py:284, backend/watcher.py:106): files put in
# place stay unseen by the player until a scan.
ROMM_SCAN_WORDS = ("RomM lists the firmware its library scan has recorded: start a scan "
"in RomM so that its player finds these files.")
LINE_SAVE_REMEDY = "Name it with --save-dir next time."
+949
View File
@@ -0,0 +1,949 @@
"""--pack: a pack written for a card a computer fills."""
from __future__ import annotations
import argparse
import contextlib
import hashlib
import io
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import zipfile
import zlib
from collections.abc import Iterable
from pathlib import Path, PurePosixPath
from typing import NamedTuple
from installer.arguments import PACK_NAME_END
from installer.constants import PLATFORM_NAMES, TARGET_PLATFORMS, _stop
from installer.datadirs import install_data_directory
from installer.download import _drive_full
from installer.embedded import display_name, shown_path
from installer.events import EVENTS
from installer.from_folders import plan_local_copies
from installer.games import MAX_MARKER_BYTES, _PART_MARKER
from installer.local_files import BACKUP_DIR
from installer.network import fetch_targets, local_targets
from installer.offline import LOCAL
from installer.outcome import DRIVE_FULL
from installer.pack_source import MAX_PARTS, _PART_FILE, pack_name_platforms
from installer.plan import download_files
from installer.probe import _is_dir
from installer.terminal import OUTPUT, Terminal, _kernel32, detail
from installer.text import _plural, format_size, screen_text
class PackPart:
"""What one part's marker says, and the folder it was found in."""
def __init__(self, pack: str, index: int, count: int,
parts: tuple[tuple[str, int], ...], folder: Path) -> None:
self.pack = pack
self.index = index
self.count = count
self.parts = parts
self.folder = folder
def read_part_marker(path: Path) -> PackPart | None:
"""The marker at path, None when it is not one split_pack wrote."""
match = _PART_MARKER.match(path.name)
if match is None:
return None
try:
with open(path, "rb") as handle:
text = handle.read(MAX_MARKER_BYTES).decode("utf-8")
except (OSError, UnicodeDecodeError):
return None
pack = ""
index = count = 0
parts: list[tuple[str, int]] = []
for line in text.splitlines():
key, _sep, value = line.partition(":")
value = value.strip()
if key == "pack":
pack = value
elif key == "part":
numbers = value.split(" of ")
if len(numbers) == 2 and all(n.isdigit() for n in numbers):
index, count = int(numbers[0]), int(numbers[1])
elif key == "file":
size, _space, name = value.partition(" ")
if size.isdigit() and _PART_FILE.match(name.strip()):
parts.append((name.strip(), int(size)))
if (
not pack.endswith("_BIOS_Pack.zip")
or not 1 <= index <= count <= MAX_PARTS
or len(parts) != count
or (index, count) != (int(match["index"]), int(match["count"]))
):
return None
return PackPart(pack, index, count, tuple(parts), path.parent)
def find_part_markers(root: Path) -> list[PackPart]:
"""Markers in root and in the folders right below it.
A part extracted into a folder named after itself (the default of
several archive tools) leaves its marker one level down.
"""
found: list[PackPart] = []
try:
entries = sorted(root.iterdir())
except OSError:
return found
for entry in entries:
if entry.is_file():
marker = read_part_marker(entry)
if marker:
found.append(marker)
elif entry.is_dir() and not entry.is_symlink() and entry.name != BACKUP_DIR:
try:
below = sorted(entry.iterdir())
except OSError:
continue
for child in below:
marker = read_part_marker(child) if child.is_file() else None
if marker:
found.append(marker)
return found
def split_pack_lines(root: Path) -> list[str]:
"""What --check says about the parts of a pack extracted into root: one
missing, or one extracted into a folder of its own."""
by_pack: dict[str, list[PackPart]] = {}
for marker in find_part_markers(root):
by_pack.setdefault(marker.pack, []).append(marker)
lines: list[str] = []
for pack, markers in sorted(by_pack.items()):
listed = max(markers, key=lambda m: m.count)
here = {m.index for m in markers if m.folder == root and m.count == listed.count}
missing = [n for n in range(1, listed.count + 1) if n not in here]
deep = sorted({m.folder for m in markers if m.folder != root})
if not missing and not deep:
continue
lines.append(f"\n {pack} comes in {listed.count} parts, all needed.")
for folder in deep:
names = sorted(m.index for m in markers if m.folder == folder)
which = ", ".join(str(n) for n in names)
lines.append(f" {'Parts' if len(names) > 1 else 'Part'} {which} went into "
f"{folder}, a folder of its own: move what it holds up into {root}.")
absent = [n for n in missing
if not any(m.index == n and m.folder != root for m in markers)]
for number in absent:
name, size = listed.parts[number - 1]
lines.append(f" missing: part {number}, {name} ({format_size(size)})")
if absent:
lines.append(f" Download {'it' if len(absent) == 1 else 'them'} and extract "
f"into {root}, beside the other parts.")
return lines
def pack_lacks(entries: list[dict]) -> list[dict]:
"""The entries the pack given to this run does not hold, none without
a pack: they cannot be installed from it."""
return [] if LOCAL.pack is None else [e for e in entries if LOCAL.pack.find(e) is None]
def pack_holds_trees(data_dirs: list[dict]) -> bool:
"""Whether the pack given to this run holds a file of any of these data
trees, which an install takes from it. A file of the tree, by its path:
a member below the tree's folder was the test, and blueMSX's tree,
whose folder is the BIOS folder itself, held every BIOS file of any
pack. One holding none of the files offered and focused Install, and
its result counted 8252 failed beside 10888 missing."""
if LOCAL.pack is None:
return False
names = LOCAL.pack.members
for entry in data_dirs:
lead = f"{str(entry.get('dest') or '').rstrip('/')}/" if entry.get("dest") else ""
if any(f"{lead}{rel}" in names for rel in entry.get("files") or {}):
return True
return False
def pack_lacks_words(count: int, total: int) -> str:
"""The pack's missing files, said before the plan names a size."""
name = LOCAL.pack.name if LOCAL.pack is not None else "the pack"
if count >= total:
return (f"{name} holds none of these {_plural(total, 'file')}: nothing can be "
"installed from it.")
return (f"{count} of these {total} files {'is' if count == 1 else 'are'} not in "
f"{name}: {'it' if count == 1 else 'they'} cannot be installed from it.")
PACK_MEMBER_DATE = (1980, 1, 1, 0, 0, 0)
PACK_COMPRESSLEVEL = 9
# FAT32 holds no file of 4 GiB or more (its size field is 32 bits). A pack
# that would pass that on such a drive is written in parts of at most this
# many bytes, the margin keeping each well under.
FAT_FILE_LIMIT = 4 * 1024 ** 3 - 1
FAT_PART_BYTES = 4 * 1024 ** 3 - 64 * 1024 ** 2
# The marker each part carries at its root, as scripts/split_pack.py writes
# it: the sizes at a fixed width, so its length does not depend on them.
PART_SIZE_WIDTH = 13
# A member may grow under deflate (zlib's deflateBound is under one byte in
# a thousand, plus a few), and its headers carry a ZIP64 field past 2 GiB.
# A part is planned on these bounds, never on the compressed size, which is
# known only once written.
_ZIP_LOCAL_BYTES = 30 + 20
_ZIP_CENTRAL_BYTES = 46 + 28
_ZIP_END_BYTES = 22 + 56 + 20
class PackError(Exception):
"""A pack that cannot be made as asked. left names the files a failure
could not take away, none when nothing was left behind."""
def __init__(self, words: str, left: list[Path] | None = None) -> None:
super().__init__(words)
self.left = list(left or [])
class PackWritten(NamedTuple):
"""What write_pack did: the files of the pack, the earlier files of
its name it removed, and those it could not remove or left as they
are, each with the reason."""
files: list[Path]
removed: list[Path]
kept: list[tuple[Path, str]]
class PackMember(NamedTuple):
"""One member of a pack being made: its name, the bytes it must hold
and the file they are read from."""
name: str
sha1: str
size: int
source: Path
def pack_default_name(plat: str, narrowed: bool) -> str:
"""<Platform>_BIOS_Pack.zip, with _Custom when the choice narrows the
list, as generate_pack.py names a narrowed pack."""
stem = PLATFORM_NAMES.get(plat, plat).replace(" ", "_")
return f"{stem}{'_Custom' if narrowed else ''}{PACK_NAME_END}"
def pack_path(given: Path, plat: str, narrowed: bool) -> Path:
"""The pack --pack names: the file given, or the default name inside a
folder given."""
path = Path(os.path.expanduser(str(given)))
if _is_dir(path) or str(given).endswith(("/", os.sep)):
path = path / pack_default_name(plat, narrowed)
return path.absolute()
def mountinfo_types(text: str) -> list[tuple[str, str]]:
"""(mount point, file system type) of each line of /proc/self/mountinfo:
the point is field 5, its space, tab and backslash written as octal
escapes, the type the first field after the " - " separator (proc(5))."""
mounts = []
for line in text.splitlines():
head, _sep, tail = line.partition(" - ")
fields = head.split(" ")
if len(fields) > 4 and tail:
point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), fields[4])
mounts.append((point, tail.split(" ")[0]))
return mounts
def mount_list_types(text: str) -> list[tuple[str, str]]:
"""(mount point, file system type) of each line macOS's mount prints:
"/dev/disk4s1 on /Volumes/CARD (msdos, local, nodev)"."""
return [(found[1], found[2]) for found in
(re.match(r".+? on (.+) \(([^,)]+)", line) for line in text.splitlines())
if found]
def fat_mounted(target: Path, mounts: list[tuple[str, str]]) -> bool:
"""Whether the deepest mount holding target is FAT (vfat on Linux,
msdos on macOS)."""
best = ""
kind = ""
for point, fstype in mounts:
mount = Path(point)
if (target == mount or mount in target.parents) and len(point) >= len(best):
best, kind = point, fstype
return kind.lower() in ("vfat", "msdos", "fat")
def fat32_drive(folder: Path) -> bool:
"""Whether folder is on a FAT32 (or FAT16) drive, which holds no file of
4 GiB: the mount table's type on Linux, the volume's file system on
Windows, the mount list on macOS. False where the system does not say."""
probe = folder
while not _is_dir(probe) and probe != probe.parent:
probe = probe.parent
if os.name == "nt":
try:
import ctypes
root = ctypes.create_unicode_buffer(261)
kind = ctypes.create_unicode_buffer(261)
kernel = _kernel32()
if not kernel.GetVolumePathNameW(str(probe), root, 261):
return False
if not kernel.GetVolumeInformationW(root, None, 0, None, None, None, kind, 261):
return False
except (AttributeError, OSError):
return False
return kind.value.upper() in ("FAT32", "FAT")
try:
target = probe.resolve()
if sys.platform == "darwin":
listing = subprocess.run(["/sbin/mount"], capture_output=True, text=True,
timeout=5, check=False).stdout
return fat_mounted(target, mount_list_types(listing))
text = Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace")
except (OSError, subprocess.SubprocessError):
return False
return fat_mounted(target, mountinfo_types(text))
def pack_layout(files: list[dict], data_dirs: list[dict]) -> tuple[
dict[str, tuple[str, int]], list[dict], dict[str, dict]]:
"""Where each file of the choice goes in the pack: the members, by name,
with their SHA-1 and size, the list manifest.json carries (path, sha1,
size, systems) of the BIOS files, and the entry each member that no
data tree holds is fetched as.
A data tree's files take the path the reader looks under. A BIOS file
is stored once by its SHA-1: at its dest, a file of another root (the
save directory, an emulator's folder) under the root's name, and below
by-sha1/ when another file already holds that name. A BIOS file whose
bytes a tree holds is read from the tree's member."""
members: dict[str, tuple[str, int]] = {}
for entry in data_dirs:
lead = f"{str(entry.get('dest') or '').rstrip('/')}/" if entry.get("dest") else ""
for rel, meta in sorted((entry.get("files") or {}).items()):
members.setdefault(f"{lead}{rel}", (str(meta["sha1"]), int(meta["size"])))
by_sha1: dict[str, str] = {}
for name, (sha1, _size) in sorted(members.items()):
by_sha1.setdefault(sha1, name)
systems: dict[str, set[str]] = {}
listed: set[str] = set()
sources: dict[str, dict] = {}
for entry in sorted(files, key=lambda f: (str(f.get("root") or ""), str(f["dest"]))):
sha1 = str(entry["sha1"]).lower()
systems.setdefault(sha1, set()).update(entry.get("systems") or [])
if sha1 not in by_sha1:
root = str(entry.get("root") or "")
name = f"{root}/{entry['dest']}" if root else str(entry["dest"])
if name in members:
name = f"by-sha1/{sha1}/{PurePosixPath(str(entry['dest'])).name}"
members[name] = (sha1, int(entry["size"]))
by_sha1[sha1] = name
sources[name] = entry
listed.add(by_sha1[sha1])
rows = []
for name in sorted(listed):
sha1, size = members[name]
row: dict = {"path": name, "sha1": sha1, "size": size}
if systems.get(sha1):
row["systems"] = sorted(systems[sha1])
rows.append(row)
return members, rows, sources
def pack_install_list(manifest: dict, files: list[dict], omitted: list[dict],
data_dirs: list[dict]) -> dict:
"""The platform's list narrowed to the choice, which the pack carries:
--from-pack with no option installs what the choice kept, the same
files at the same places."""
narrowed = {key: value for key, value in manifest.items()
if key not in ("files", "case_variants", "omitted_files",
"data_directories")}
narrowed["files"] = [entry for entry in files if not entry.get("case_variant")]
variants = [{key: value for key, value in entry.items() if key != "case_variant"}
for entry in files if entry.get("case_variant")]
if variants or "case_variants" in manifest:
narrowed["case_variants"] = variants
narrowed["omitted_files"] = list(omitted)
if data_dirs or "data_directories" in manifest:
narrowed["data_directories"] = list(data_dirs)
return narrowed
def pack_manifest(plat: str, install_list: dict, rows: list[dict],
targets: dict | None) -> bytes:
"""manifest.json of a pack made here, as --from-pack reads it."""
entries = [*install_list.get("files", []), *install_list.get("omitted_files", [])]
records = {"systems"} if any("systems" in entry for entry in entries) else set()
if any(copy.get("cores") for entry in install_list.get("files", [])
for copy in [entry, *entry.get("alternatives", []),
*entry.get("slot_choices", [])]):
records.add("cores")
if records or any("regions" in entry for entry in entries):
records.add("regions")
data: dict = {"platform": plat, "files": rows}
for key in ("system_titles", "system_names"):
if install_list.get(key):
data[key] = install_list[key]
data["list_records"] = sorted(records)
if install_list.get("version"):
data["list_version"] = install_list["version"]
data["install_list"] = install_list
if targets is not None:
data["targets"] = targets
return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
def _member_bound(name: str, size: int) -> int:
"""The most bytes a member can take in a part: both headers and its
data deflated at worst."""
encoded = len(name.encode("utf-8"))
return _ZIP_LOCAL_BYTES + _ZIP_CENTRAL_BYTES + 2 * encoded + size + size // 1000 + 64
def pack_bound(manifest_size: int, members: list[PackMember]) -> int:
"""The most bytes the pack can take as one ZIP."""
return (_ZIP_END_BYTES + _member_bound("manifest.json", manifest_size)
+ sum(_member_bound(member.name, member.size) for member in members))
def part_file_name(name: str, index: int, count: int) -> str:
return f"{name[: -len('.zip')]}.part{index}of{count}.zip"
def part_marker_name(name: str, index: int, count: int) -> str:
return f"{name[: -len('.zip')]}.part{index}of{count}.txt"
def part_marker_text(name: str, index: int, sizes: list[int]) -> bytes:
"""The marker of part index, in the words scripts/split_pack.py writes
and read_part_marker reads back."""
count = len(sizes)
lines = [
"RetroBIOS split pack",
f"This folder holds part {index} of {count} of {name}.",
"Every part is needed: extract them all into this same folder.",
"The installer's --check names a part missing from the folder.",
"",
f"pack: {name}",
f"part: {index} of {count}",
]
lines += [f"file: {size:>{PART_SIZE_WIDTH}} {part_file_name(name, number, count)}"
for number, size in enumerate(sizes, 1)]
return ("\n".join(lines) + "\n").encode("utf-8")
def _marker_bound(name: str, count: int) -> int:
marker = len(part_marker_name(name, count, count).encode("utf-8"))
return 30 + 46 + 2 * marker + len(part_marker_text(name, count, [0] * count))
def plan_pack_parts(name: str, manifest_size: int, members: list[PackMember],
limit: int | None) -> list[list[PackMember]]:
"""The members of each part, in pack order, manifest.json in the first.
One part without a limit, or when the whole pack stays under it. Each
part's bound stays under the limit, room kept for its marker, the plan
made again until the count it assumed is the count it gives."""
if limit is None or pack_bound(manifest_size, members) < limit:
return [list(members)]
count = 2
while True:
floor = _ZIP_END_BYTES + _marker_bound(name, count)
parts: list[list[PackMember]] = [[]]
size = floor + _member_bound("manifest.json", manifest_size)
if size >= limit:
raise PackError(f"the list alone needs {format_size(size)}, more than a part "
f"of {format_size(limit)} holds")
for member in members:
weight = _member_bound(member.name, member.size)
if floor + weight >= limit:
raise PackError(f"{member.name} ({format_size(member.size)}) does not fit "
f"in a part of {format_size(limit)}")
if size + weight >= limit or len(parts[-1]) >= 0xFFFE:
parts.append([])
size = floor
parts[-1].append(member)
size += weight
if len(parts) > MAX_PARTS:
raise PackError(f"the pack would take {len(parts)} parts, more than "
f"{MAX_PARTS}: give a larger size")
if len(parts) <= count:
return parts
count = len(parts)
# ZipInfo's level is private before Python 3.13 (compress_level there, the
# old name kept as its alias), so typeshed does not declare it.
_ZIPINFO_LEVEL = "_compresslevel"
def _pack_info(name: str, compress: int = zipfile.ZIP_DEFLATED) -> zipfile.ZipInfo:
"""A member header that depends on its name alone."""
info = zipfile.ZipInfo(name, date_time=PACK_MEMBER_DATE)
info.compress_type = compress
# A ZipInfo given to writestr or open keeps its own level, the
# archive's left unread: without it every member was deflated at 6.
setattr(info, _ZIPINFO_LEVEL,
PACK_COMPRESSLEVEL if compress == zipfile.ZIP_DEFLATED else None)
info.create_system = 3
info.external_attr = 0o100644 << 16
return info
def _write_member(archive: zipfile.ZipFile, member: PackMember) -> None:
"""Copy one member into the archive, its SHA-1 and size checked on the
bytes written, before the archive is closed."""
info = _pack_info(member.name)
info.file_size = member.size
digest = hashlib.sha1()
size = 0
with open(member.source, "rb") as src, archive.open(info, "w") as out:
while True:
chunk = src.read(1024 * 1024)
if not chunk:
break
digest.update(chunk)
size += len(chunk)
out.write(chunk)
if size != member.size or digest.hexdigest() != member.sha1:
raise PackError(f"{member.name} does not match the list: {size} bytes of SHA-1 "
f"{digest.hexdigest()}, the list says {member.size} of "
f"{member.sha1}")
def _patch_marker(path: Path, marker: str, body: bytes) -> None:
"""Write the real marker over its placeholder of the same length: the
data, and the CRC-32 of the local and the central header."""
with zipfile.ZipFile(path) as archive:
first = archive.infolist()[0]
central = int(archive.start_dir)
if first.filename != marker or first.file_size != len(body) or first.header_offset:
raise PackError(f"{path.name} does not start with its marker")
crc = zlib.crc32(body).to_bytes(4, "little")
with open(path, "r+b") as handle:
local = handle.read(30)
if local[:4] != b"PK\x03\x04":
raise PackError(f"{path.name} has no local header at its start")
data = (30 + int.from_bytes(local[26:28], "little")
+ int.from_bytes(local[28:30], "little"))
handle.seek(14)
handle.write(crc)
handle.seek(data)
handle.write(body)
handle.seek(central)
if handle.read(4) != b"PK\x01\x02":
raise PackError(f"{path.name} has no central directory where it says")
handle.seek(central + 16)
handle.write(crc)
def _part_contents(name: str, index: int, count: int, manifest: bytes,
chosen: list[PackMember]) -> list[tuple[str, int]]:
"""(name, size) of each member of a part, in the order written."""
held = ([(part_marker_name(name, index, count),
len(part_marker_text(name, index, [0] * count)))] if count > 1 else [])
held += [("manifest.json", len(manifest))] if index == 1 else []
return held + [(member.name, member.size) for member in chosen]
def _discard(paths: Iterable[Path]) -> list[Path]:
"""Delete each file, the ones that could not be deleted returned."""
left = []
for path in paths:
try:
path.unlink(missing_ok=True)
except OSError:
left.append(path)
return left
def _of_this_pack(path: Path, name: str) -> bool:
"""Whether path is a regular file that is a pack of this name: a part
whose marker names it, or a ZIP holding a manifest.json."""
try:
if not stat.S_ISREG(os.lstat(path).st_mode):
return False
with zipfile.ZipFile(path) as archive:
names = archive.namelist()
markers = [member for member in names if _PART_MARKER.match(member)]
if markers:
text = archive.read(markers[0])[:MAX_MARKER_BYTES].decode("utf-8", "replace")
return f"pack: {name}" in text.splitlines()
return "manifest.json" in names
except (OSError, zipfile.BadZipFile, ValueError):
return False
def _aside_name(path: Path) -> Path:
"""A name beside path no file holds, for the earlier pack while the
new one takes its place."""
for number in range(1000):
aside = path.with_name(f".{path.name}.{os.getpid()}.{number}.old")
if not os.path.lexists(aside):
return aside
raise PackError(f"no free name beside {path.name} to set it aside")
def write_pack(path: Path, manifest: bytes, members: list[PackMember],
limit: int | None) -> PackWritten:
"""Write the pack at path, or in parts beside it when a limit is given
and the pack would pass it.
Each file is written beside its final name, every member checked
against its SHA-1 and the archive read back with its CRCs. Then the
earlier files of this pack (whole, or in parts) are set aside, the new
ones renamed in, and the earlier ones deleted. A failure before the new
set is whole puts the earlier set back and deletes the new files: the
folder holds the pack before or the pack after, never a mix. A file
deleted at the end that cannot be is reported, the pack being written."""
name = path.name
plan = plan_pack_parts(name, len(manifest), members, limit)
count = len(plan)
finals = ([path] if count == 1 else
[path.with_name(part_file_name(name, index, count))
for index in range(1, count + 1)])
scratches: list[Path] = []
try:
for index, (final, chosen) in enumerate(zip(finals, plan), 1):
handle, made = tempfile.mkstemp(prefix=f".{final.name}.", suffix=".partial",
dir=str(path.parent))
os.close(handle)
scratches.append(Path(made))
with zipfile.ZipFile(made, "w", zipfile.ZIP_DEFLATED,
compresslevel=PACK_COMPRESSLEVEL) as archive:
if count > 1:
archive.writestr(
_pack_info(part_marker_name(name, index, count), zipfile.ZIP_STORED),
part_marker_text(name, index, [0] * count))
if index == 1:
archive.writestr(_pack_info("manifest.json"), manifest)
for member in chosen:
if _stop.is_set():
raise KeyboardInterrupt
_write_member(archive, member)
sizes = [scratch.stat().st_size for scratch in scratches]
if count > 1:
for index, scratch in enumerate(scratches, 1):
_patch_marker(scratch, part_marker_name(name, index, count),
part_marker_text(name, index, sizes))
for index, (scratch, chosen) in enumerate(zip(scratches, plan), 1):
shown = finals[index - 1].name
with zipfile.ZipFile(scratch) as archive:
held = [(info.filename, info.file_size) for info in archive.infolist()]
damaged = archive.testzip()
if damaged is not None:
raise PackError(f"{shown}: {damaged} does not read back")
if count > 1 and archive.read(part_marker_name(name, index, count)) != \
part_marker_text(name, index, sizes):
raise PackError(f"{shown}: its marker does not read back")
if held != _part_contents(name, index, count, manifest, chosen):
raise PackError(f"{shown} does not read back as written")
if limit is not None and count > 1 and sizes[index - 1] >= limit:
raise PackError(f"{shown} reached the limit of {format_size(limit)}")
except BaseException as exc:
left = _discard(scratches)
if left and isinstance(exc, (OSError, PackError)):
raise PackError(str(exc), left) from exc
raise
return _swap_in(path, scratches, finals)
def _swap_named(path: Path, finals: list[Path]) -> list[Path]:
"""The files beside path that the new pack may replace."""
stem = path.name[: -len(".zip")]
named: list[Path] = []
for old in _listed_paths(path.parent):
part = _PART_FILE.match(old.name)
if old == path or old in finals or (part is not None and part["stem"] == stem):
named.append(old)
return named
def _swap_restore(exc: OSError | PackError, name: str, scratches: list[Path],
finals: list[Path], aside: list[tuple[Path, Path]],
placed: list[Path]) -> PackError:
"""Undo a swap that failed: the new files discarded, the earlier pack put
back where it can be."""
left = _discard([*placed, *(scratch for scratch, final in zip(scratches, finals)
if final not in placed)])
unrestored = []
for old, moved in reversed(aside):
try:
os.replace(moved, old)
except OSError:
unrestored.append((old, moved))
words = f"{name} could not be put in place: {exc.strerror or exc}" \
if isinstance(exc, OSError) else str(exc)
if unrestored:
words += ". The earlier pack is set aside as " + ", ".join(
f"{moved.name} (was {old.name})" for old, moved in unrestored)
return PackError(words, [*left, *(moved for _old, moved in unrestored)])
def _swap_in(path: Path, scratches: list[Path], finals: list[Path]) -> PackWritten:
"""Put the new files in place of the earlier pack of this name."""
name = path.name
named = _swap_named(path, finals)
kept: list[tuple[Path, str]] = []
earlier: list[Path] = []
aside: list[tuple[Path, Path]] = []
placed: list[Path] = []
try:
for old in named:
if old in finals:
if not stat.S_ISREG(os.lstat(old).st_mode):
raise PackError(f"{old.name} is in the way and is not a file")
earlier.append(old)
elif _of_this_pack(old, name):
earlier.append(old)
else:
kept.append((old, "it is not a part of this pack, left as it is"))
for old in earlier:
moved = _aside_name(old)
os.replace(old, moved)
aside.append((old, moved))
for scratch, final in zip(scratches, finals):
os.replace(scratch, final)
placed.append(final)
except (OSError, PackError) as exc:
raise _swap_restore(exc, name, scratches, finals, aside, placed) from exc
removed = []
for old, moved in aside:
if old in finals:
if _discard([moved]):
kept.append((moved, "the earlier copy could not be deleted"))
continue
if _discard([moved]):
kept.append((moved, f"the earlier {old.name}, set aside, could not be deleted"))
else:
removed.append(old)
return PackWritten(finals, removed, kept)
def _listed_paths(folder: Path) -> list[Path]:
"""The files of a folder, [] when it cannot be listed."""
return [folder / name for name in sorted(_listed(folder))]
def _pack_targets(plat: str) -> dict | None:
"""The cores per board the pack carries, as a pack built by the
repository does: the list at hand offline, else the one fetched. None
for a platform that publishes none, or a list that cannot be read."""
if plat not in TARGET_PLATFORMS:
return None
if LOCAL.offline:
return local_targets(plat)
with contextlib.redirect_stderr(io.StringIO()):
return fetch_targets(plat)
def _pack_event(plat: str, path: Path, members: dict[str, tuple[str, int]],
parts: list[Path], status: str, message: str, size: int = 0) -> None:
EVENTS.emit("pack", platform=plat, path=str(path), files=len(members),
bytes=sum(length for _sha1, length in members.values()), size=size,
parts=[str(part) for part in parts], status=status, message=message)
def _pack_refused(plat: str, path: Path, words: str, code: int,
members: dict[str, tuple[str, int]] | None = None) -> int:
"""Say why no pack is made, the event saying it too: code."""
print(f"Error: {screen_text(words)}. No pack was written.", file=sys.stderr)
_pack_event(plat, path, members or {}, [], "failed", f"{words}.")
return code
def pack_parts_words(count: int, limit: int | None, fat: bool) -> str:
"""How the pack is written, in one line: whole, or in parts and why."""
if count == 1:
return "One ZIP."
each = f"In {count} parts of at most {format_size(limit or 0)}"
return f"{each}, as FAT32 holds no file of 4 GB." if fat else f"{each}."
def pack_space_bytes(files: int, bound: int, data_dirs: list[dict]) -> int:
"""What making a pack takes on its drive: the files fetched, the ZIP at
its largest, and the largest source archive of a data tree, which is
downloaded whole beside its tree until the tree is read. A pack read
as the source fetches no archive."""
archives = [int(entry.get("archive_size") or 0) for entry in data_dirs
if entry.get("files") and isinstance(entry.get("archive_size"), int)]
return files + bound + (max(archives, default=0) if LOCAL.pack is None else 0)
def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[dict],
omitted: list[dict], data_dirs: list[dict], narrowed: bool,
term: Terminal) -> int:
"""--pack: the choice downloaded into a pack instead of a folder, every
member checked against its SHA-1 before the ZIP is closed. Returns the
exit code: 0 once written (or listed with --dry-run), 1 when a file
could not be had or the pack written, 2 when nothing was tried."""
path = pack_path(args.pack, plat, narrowed)
display = display_name(plat, manifest)
if not path.name.endswith(PACK_NAME_END):
return _pack_refused(plat, path, f"{path.name} does not end with {PACK_NAME_END}, "
"which --from-pack and the parts of a pack read", 2)
if not _is_dir(path.parent):
return _pack_refused(plat, path, f"the folder {shown_path(path.parent)} does not "
"exist", 2)
spelled = pack_name_platforms(path.name)
if spelled and plat not in spelled:
return _pack_refused(plat, path, f"{path.name} names a pack for "
f"{' and '.join(display_name(name) for name in spelled)}, and "
f"this one is for {display_name(plat)}", 2)
members, rows, sources = pack_layout(files, data_dirs)
if not members:
return _pack_refused(plat, path, "the choice keeps no file to put in a pack", 2)
body = pack_manifest(plat, pack_install_list(manifest, files, omitted, data_dirs), rows,
_pack_targets(plat))
planned = [PackMember(name, sha1, size, Path())
for name, (sha1, size) in sorted(members.items())]
fat = fat32_drive(path.parent)
limit = args.split
if fat and (limit is None and pack_bound(len(body), planned) > FAT_FILE_LIMIT
or limit is not None and limit > FAT_PART_BYTES):
limit = FAT_PART_BYTES
try:
plan = plan_pack_parts(path.name, len(body), planned, limit)
except PackError as exc:
return _pack_refused(plat, path, str(exc), 2, members)
count = len(plan)
finals = ([path] if count == 1 else
[path.with_name(part_file_name(path.name, index, count))
for index in range(1, count + 1)])
total = sum(size for _sha1, size in members.values())
print(f"\nPack for {display}: {_plural(len(members), 'file')} ({format_size(total)}).")
print(f"Pack: {shown_path(path)}")
how = pack_parts_words(count, limit, fat and limit == FAT_PART_BYTES)
if count > 1:
print(f" {how}")
if args.dry_run:
for name in sorted(members):
detail(f" {screen_text(name)} ({format_size(members[name][1])})")
if not OUTPUT.verbose:
print(" --verbose lists the files.")
_pack_event(plat, path, members, finals, "planned", how)
return 0
needed = pack_space_bytes(total, pack_bound(len(body), planned), data_dirs)
try:
free = shutil.disk_usage(path.parent).free
except OSError:
free = needed
if free < needed:
return _pack_refused(plat, path, f"the drive holding {shown_path(path.parent)} has "
f"{format_size(free)} free, and making the pack needs "
f"{format_size(needed)}", 2, members)
staging = Path(tempfile.mkdtemp(prefix=f".{path.name}.", suffix=".staging",
dir=str(path.parent)))
try:
return _fill_pack(args, _PackFill(plat, path, body, members, sources, data_dirs,
limit), staging, term)
except KeyboardInterrupt:
_stop.set()
print("\n Stopped. No pack was written.", file=sys.stderr)
_pack_event(plat, path, members, [], "failed", "Stopped before the pack was written.")
return 130
finally:
shutil.rmtree(staging, ignore_errors=True)
class _PackFill(NamedTuple):
"""The pack _fill_pack writes: its path, manifest, members and their sources."""
plat: str
path: Path
body: bytes
members: dict[str, tuple[str, int]]
sources: dict[str, dict]
data_dirs: list[dict]
limit: int | None
def _fill_pack(args: argparse.Namespace, pack: _PackFill, staging: Path,
term: Terminal) -> int:
"""Fetch every member into staging, then write the pack from it."""
plat, path, body, members, sources, data_dirs, limit = pack
staged = [{**{key: value for key, value in entry.items()
if key not in ("root", "core_folder", "case_variant")}, "dest": name}
for name, entry in sorted(sources.items())]
copies = plan_local_copies(staged, staging, None, LOCAL.folders)
fetched = sum(int(entry.get("size") or 0) for entry in staged)
EVENTS.emit("download", platform=plat, files=len(staged), bytes=fetched)
detail(f"\nDownloading {_plural(len(staged), 'file')} ({format_size(fetched)})...")
failed, interrupted = download_files(staged, staging, jobs=args.jobs,
verbose=args.verbose, term=term, copies=copies)
if interrupted:
raise KeyboardInterrupt
owners: dict[str, Path] = {}
trees_failed: list[tuple[str, str]] = []
for index, entry in enumerate(data_dirs):
lead = f"{str(entry.get('dest') or '').rstrip('/')}/" if entry.get("dest") else ""
root = staging / ".trees" / str(index)
names = [f"{lead}{rel}" for rel in sorted(entry.get("files") or {})]
owned = [name for name in names if name in members and name not in sources
and name not in owners]
if not owned:
continue
detail(f" {entry.get('ref', 'data')}: {_plural(len(names), 'data file')}...")
counts = install_data_directory(entry, root)
problem = (str(counts["error"]) if counts["error"]
else f"{counts['changed']} changed in its source" if counts["changed"]
else f"{counts['absent']} not in its source" if counts["absent"]
else "")
if problem:
trees_failed.append((str(entry.get("ref", "data")), problem))
continue
for name in owned:
owners[name] = root.joinpath(*PurePosixPath(name).parts)
if failed or trees_failed:
lines = [*failed, *trees_failed]
print(f"\n {_plural(len(lines), 'file')} could not be had: no pack was written.",
file=sys.stderr)
for dest, reason in lines[: None if args.verbose else 5]:
print(f" {screen_text(dest)}: {screen_text(str(reason))}", file=sys.stderr)
if len(lines) > 5 and not args.verbose:
print(f" ... and {len(lines) - 5} more (--verbose lists them)", file=sys.stderr)
_pack_event(plat, path, members, [], "failed",
f"{_plural(len(lines), 'file')} could not be had: no pack was written.")
return 1
ordered = [PackMember(name, sha1, size,
owners[name] if name in owners
else staging.joinpath(*PurePosixPath(name).parts))
for name, (sha1, size) in sorted(members.items())]
detail(f"\nWriting {path.name}...")
try:
result = write_pack(path, body, ordered, limit)
except (OSError, PackError) as exc:
words = (DRIVE_FULL if isinstance(exc, OSError) and _drive_full(exc)
else exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc))
left = exc.left if isinstance(exc, PackError) else []
after = ("Left behind, to delete: " + ", ".join(shown_path(f) for f in left) + "."
if left else "No pack was left behind.")
print(f"\n {path.name} could not be written: {screen_text(str(words))}. "
f"{screen_text(after)}", file=sys.stderr)
_pack_event(plat, path, members, [], "failed",
f"{path.name} could not be written: {words}. {after}")
return 1
written = result.files
for old in result.removed:
print(f" Removed the earlier {shown_path(old)}.")
for old, why in result.kept:
print(f" {shown_path(old)}: {why}.")
size = sum(part.stat().st_size for part in written)
print(f"\nPack made: {_plural(len(members), 'file')}, {format_size(size)}"
+ (f", in {len(written)} parts" if len(written) > 1 else "") + ".")
for part in written if len(written) > 1 else []:
print(f" {shown_path(part)}")
print("Install from it on the other device with --from-pack.")
_pack_event(plat, path, members, written, "written",
f"{path.name}: {_plural(len(members), 'file')}, every one checked.", size)
return 0
def _listed(folder: Path) -> list[str]:
try:
return os.listdir(folder)
except OSError:
return []
+462
View File
@@ -0,0 +1,462 @@
"""Packs read in place of the network, and the checked writes every copy goes through."""
from __future__ import annotations
import contextlib
import errno
import functools
import json
import os
import re
import sys
import tempfile
import zipfile
import zlib
from collections.abc import Callable, Iterator
from pathlib import Path
from typing import IO, ContextManager
from installer.arguments import PACK_NAME_END
from installer.constants import (
AVAILABLE_PLATFORMS,
MAX_MANIFEST_BYTES,
PLATFORM_NAMES,
_SHA1_RE,
_UMASK,
_Interrupted,
_stop,
)
from installer.detect_os import _VERSION_TEXT
from installer.events import EVENTS
from installer.local_files import _digest_file
from installer.manifest import _validate_manifest, _validate_targets
from installer.offline import LOCAL
from installer.paths import _entry_place
from installer.probe import _exists, _is_file
from installer.record import KEPT, _NotKept, _clear_read_only, _kept_slot
from installer.terminal import Progress
from installer.text import _CONTROLS
_SHARING_VIOLATIONS = (32, 33)
# A write refused by the file system: retrying cannot change it, and the
# summary names the two ways out.
NOT_WRITABLE = "folder not writable"
def _write_refused(exc: OSError) -> bool:
# A sharing violation is a file another process holds open, which a
# later attempt can find released: no refusal of the folder.
if getattr(exc, "winerror", None) in _SHARING_VIOLATIONS:
return False
return isinstance(exc, PermissionError) or exc.errno == errno.EROFS
# A file already at the destination, marked read-only, whose content differs,
# and whose attribute could not be cleared: replacing it is refused while its
# folder stays writable.
READ_ONLY = "file in place is read-only"
# A file in place whose content differs, which could not be moved aside: it
# is left as it is rather than lost.
NOT_KEPT = "file in place could not be kept aside"
def _read_only_file(dest: Path) -> bool:
return _is_file(dest) and not os.access(dest, os.W_OK) and _folder_writable(dest.parent)
def _folder_writable(path: Path) -> bool:
"""Whether a file can be created under path, read from its nearest
existing folder: a BIOS folder not created yet is as writable as the
folder it would go in."""
probe = path
while not _exists(probe) and probe.parent != probe:
probe = probe.parent
return os.access(probe, os.W_OK)
# A pack too large for one release file is published as ZIP parts
# (scripts/split_pack.py), each holding at its root a marker that names the
# pack, the part and every part with its size. Extracted with the files,
# the markers say which part a folder lacks.
_PART_FILE = re.compile(r"^(?P<stem>.+_BIOS_Pack)\.part(?P<index>\d+)of(?P<count>\d+)\.zip$")
MAX_PARTS = 999
# A system id as the file lists write them (sony-playstation, other).
_SYSTEM_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._+-]{0,63}")
class PackSource:
"""A pack already downloaded, whole or in parts, read in place of the network.
Every file it gives is checked against the hashes the file list records,
as a download is.
"""
def __init__(self, paths: list[Path]) -> None:
self.files = self._resolve(paths)
first = _PART_FILE.match(self.files[0].name)
self.name = f"{first['stem']}.zip" if first else self.files[0].name
self.archives: list[zipfile.ZipFile] = []
self.members: dict[str, tuple[zipfile.ZipFile, zipfile.ZipInfo]] = {}
# The system titles and names the pack's list records, if any.
self.names: dict[str, dict] = {}
# What its platform's install list narrows by (systems, cores,
# regions), None for a pack that does not say: the remedy for an
# option the pack cannot apply names that list only when it can.
self.list_records: frozenset | None = None
# The version of the platform's list the pack was built from, "" for
# a pack that does not record it.
self.list_version = ""
# The platform's install list and its cores per board, which a pack
# built since carries: with them a pack alone narrows to a board as
# the network list does. None for a pack that carries none.
self.install_list: dict | None = None
self.targets: dict | None = None
try:
for path in self.files:
archive = zipfile.ZipFile(path)
self.archives.append(archive)
for info in archive.infolist():
if not info.is_dir():
self.members.setdefault(info.filename, (archive, info))
except (OSError, zipfile.BadZipFile) as exc:
self.close()
raise ValueError(f"{path.name} cannot be read as a ZIP ({exc}). A download "
"cut short gives this: download it again.") from exc
try:
self.listed = self._pack_list()
except ValueError:
# A ZIP that is no pack: its archives closed, not left open.
self.close()
raise
self.by_sha1 = {f["sha1"]: f["path"] for f in self.listed}
@staticmethod
def _resolve(paths: list[Path]) -> list[Path]:
"""The archives of one pack: a whole ZIP, or every one of its parts."""
given: list[Path] = []
for path in paths:
if path.is_dir():
given += sorted(p for p in path.iterdir()
if p.is_file() and p.name.endswith(".zip")
and "_BIOS_Pack" in p.name)
elif path.is_file():
given.append(path)
else:
# "X does not exist" named neither the option nor the packs
# beside it, where a typo in the name is the usual cause.
near = sorted(p.name for p in path.parent.glob("*_BIOS_Pack*.zip")
if p.is_file()) if path.parent.is_dir() else []
beside = (f" The packs in {path.parent}: {', '.join(near[:3])}"
+ (f" and {len(near) - 3} more" if len(near) > 3 else "") + "."
if near else "")
raise ValueError(f"{path} does not exist: --from-pack names a pack ZIP, "
f"its parts or the folder holding them.{beside}")
if not given:
raise ValueError(f"no pack ZIP in {', '.join(map(str, paths))}")
packs: dict[str, list[Path]] = {}
for path in given:
part = _PART_FILE.match(path.name)
packs.setdefault(f"{part['stem']}.zip" if part else path.name, []).append(path)
if len(packs) > 1:
raise ValueError(f"these are several packs ({', '.join(sorted(packs))}): "
"name the one to install from")
name, chosen = next(iter(packs.items()))
whole = [p for p in chosen if not _PART_FILE.match(p.name)]
if whole:
return whole[:1]
counts = [int(part["count"]) for part in (_PART_FILE.match(p.name) for p in chosen)
if part is not None]
count = counts[0]
if count > MAX_PARTS or any(other != count for other in counts):
raise ValueError(f"the parts of {name} disagree on how many there are")
stem = name[: -len(".zip")]
folders = list(dict.fromkeys(p.parent for p in chosen))
found: list[Path] = []
missing: list[str] = []
for number in range(1, count + 1):
part_name = f"{stem}.part{number}of{count}.zip"
place = next((folder / part_name for folder in folders
if (folder / part_name).is_file()), None)
if place is None:
missing.append(part_name)
else:
found.append(place)
if missing:
where = ", ".join(map(str, folders))
raise ValueError(f"{name} comes in {count} parts and {len(missing)} "
f"{'is' if len(missing) == 1 else 'are'} not in {where}: "
f"{', '.join(missing)}")
return found
def _pack_list(self) -> list[dict]:
"""The file list the pack carries, every file with its SHA-1 and size."""
held = self.members.get("manifest.json")
if held is None:
raise ValueError(f"{self.name} holds no manifest.json. Name the file list "
"with --manifest.")
archive, info = held
if info.file_size > MAX_MANIFEST_BYTES:
raise ValueError(f"the manifest.json of {self.name} exceeds "
f"{MAX_MANIFEST_BYTES} bytes")
try:
data = json.loads(archive.read(info).decode("utf-8"))
except (OSError, zipfile.BadZipFile, UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValueError(f"the manifest.json of {self.name} cannot be read: {exc}") from exc
files = data.get("files") if isinstance(data, dict) else None
if not isinstance(files, list):
raise ValueError(f"the manifest.json of {self.name} lists no files")
# What a pack built since records of its systems (generate_pack.py
# pack_systems): --system and Choose systems then work with the pack
# alone. An older pack records none, and is read as before.
# A pack is a file anyone can hand over: an id or a name holding a
# control character would reach the terminal as an escape, and is
# dropped.
records = data.get("list_records")
if isinstance(records, list) and all(isinstance(axis, str) for axis in records):
self.list_records = frozenset(records) & {"systems", "cores", "regions"}
version = data.get("list_version")
if isinstance(version, str) and _VERSION_TEXT.fullmatch(version):
self.list_version = version
if isinstance(data.get("install_list"), dict):
self.install_list = data["install_list"]
if data.get("targets") is not None:
try:
self.targets = _validate_targets(data["targets"])
except ValueError:
# Read as a pack that carries none: --target is then refused
# with the reason, never applied from a broken list.
self.targets = None
for key in ("system_titles", "system_names"):
held = data.get(key)
if isinstance(held, dict):
self.names[key] = {
system: value for system, value in held.items()
if _SYSTEM_ID.fullmatch(str(system)) and (
isinstance(value, str) and not _CONTROLS.search(value)
or isinstance(value, list) and all(
isinstance(name, str) and not _CONTROLS.search(name)
for name in value))}
listed = []
for item in files:
if (
isinstance(item, dict)
and isinstance(item.get("path"), str)
and isinstance(item.get("sha1"), str)
and _SHA1_RE.fullmatch(item["sha1"].lower())
and isinstance(item.get("size"), int)
):
entry = {"path": item["path"], "sha1": item["sha1"].lower(),
"size": item["size"]}
systems = item.get("systems")
if isinstance(systems, list) and all(
isinstance(name, str) and _SYSTEM_ID.fullmatch(name)
for name in systems):
entry["systems"] = list(systems)
listed.append(entry)
return listed
def platforms(self) -> list[str]:
"""The platforms the pack's name spells, several for a grouped pack."""
spelled = pack_name_platforms(self.name)
# A pack made by --pack says its platform inside, which a name of
# the user's, or a file renamed, does not change.
named = (self.install_list or {}).get("platform")
if named in AVAILABLE_PLATFORMS and named not in spelled:
return [named]
return spelled
def manifest(self, plat: str) -> dict:
"""A file list for plat: the install list the pack carries, else one
built from the pack's own, the same files at the same places, as
extracting the pack would leave them, with the systems it records."""
if self.install_list is not None and self.install_list.get("platform") == plat:
return self.install_list
return {
"manifest_version": 2,
"platform": plat,
**({"version": self.list_version} if self.list_version else {}),
**{key: value for key, value in self.names.items() if value},
"files": [
{"dest": f["path"], "sha1": f["sha1"], "size": f["size"],
"repo_path": f"bios/{f['path']}",
**({"systems": f["systems"]} if "systems" in f else {})}
for f in self.listed
],
}
def find(self, entry: dict) -> tuple[zipfile.ZipFile, zipfile.ZipInfo] | None:
"""The member holding an entry's bytes: by its SHA-1 in the pack's list,
else at its destination. The size has to agree either way."""
sha1 = str(entry.get("sha1", "")).lower()
for name in (self.by_sha1.get(sha1), entry.get("dest")):
held = self.members.get(name) if isinstance(name, str) else None
if held is not None and held[1].file_size == entry.get("size"):
return held
return None
def tree(self, prefix: str) -> Iterator[tuple[str, int, Callable[[], IO[bytes]]]]:
"""(path in the tree, size, opener) of every member below prefix."""
lead = f"{prefix.rstrip('/')}/" if prefix else ""
for name, (archive, info) in self.members.items():
if name.startswith(lead):
yield name[len(lead):], info.file_size, functools.partial(archive.open, info)
def close(self) -> None:
for archive in self.archives:
archive.close()
self.archives = []
NOT_IN_PACK = "not in the pack"
def pack_name_platforms(name: str) -> list[str]:
"""The platforms a pack's name spells, as PackSource reads them."""
if not name.endswith(PACK_NAME_END):
return []
stem = "_" + name[: -len(PACK_NAME_END)] + "_"
return [plat for plat in AVAILABLE_PLATFORMS
if f"_{PLATFORM_NAMES[plat].replace(' ', '_')}_" in stem]
def read_local_manifest(path: Path, plat: str) -> dict:
"""A file list saved on disk, checked as a downloaded one is."""
try:
with open(path, "rb") as handle:
raw = handle.read(MAX_MANIFEST_BYTES + 1)
except OSError as exc:
print(f" Cannot read the file list {path}: {exc.strerror or exc}.", file=sys.stderr)
sys.exit(1)
try:
if len(raw) > MAX_MANIFEST_BYTES:
raise ValueError(f"it exceeds {MAX_MANIFEST_BYTES} bytes")
try:
data = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValueError(f"not JSON ({exc})") from exc
return _validate_manifest(data, plat)
except ValueError as exc:
EVENTS.emit("error", stage="manifest", reason="invalid", platform=plat,
message=f"the file list is not valid: {exc}")
print(f" The file list {path} is not valid for {plat}: {exc}", file=sys.stderr)
sys.exit(1)
def _extract_from_pack(
f: dict, bios_path: Path, dest: Path, progress: Progress | None,
) -> tuple[str, bool, str]:
"""Copy one file out of the pack, checked like a download."""
pack = LOCAL.pack
held = pack.find(f) if pack is not None else None
if held is None:
return f["dest"], False, NOT_IN_PACK
archive, info = held
return _write_verified(f, bios_path, dest, lambda: archive.open(info), progress,
"the pack", named=f"{info.filename} inside {archive.filename}")
class _SourceUnreadable(Exception):
"""The bytes to write could not be read: the source's fault, never the
folder's, so it falls back like any copy that failed."""
def unreadable_words(exc: BaseException) -> str:
"""Why a file or a ZIP member could not be read, in words."""
if isinstance(exc, RuntimeError) and "encrypted" in str(exc):
return "it is encrypted, a password is needed"
if isinstance(exc, NotImplementedError):
return "it is packed with a compression method this installer cannot read"
if isinstance(exc, (zipfile.BadZipFile, zlib.error, EOFError)):
return "it is damaged"
if isinstance(exc, OSError) and exc.strerror:
return exc.strerror
return str(exc) or type(exc).__name__
def _place_verified(f: dict, bios_path: Path, dest: Path, tmp_path: Path, size: int,
expected: dict[str, str], held_in: str) -> None:
"""Put the written file at dest once its size and hashes are the list's."""
if size != f["size"]:
raise ValueError(f"{held_in} holds {size} bytes, the list records {f['size']}")
actual = _digest_file(tmp_path, tuple(expected))
for name, label in (("sha256", "SHA-256"), ("sha1", "SHA-1")):
if name in expected and actual[name] != expected[name]:
raise ValueError(f"{label} mismatch in {held_in}")
os.chmod(tmp_path, (0o777 if f.get("executable") else 0o666) & ~_UMASK)
_clear_read_only(dest)
KEPT.keep(*_kept_slot(*_entry_place(bios_path, f)), dest, expected, tmp_path)
os.replace(tmp_path, dest)
def _write_verified(
f: dict, bios_path: Path, dest: Path,
source: Callable[[], ContextManager[IO[bytes]]], progress: Progress | None,
held_in: str, local: bool = False, named: str = "",
) -> tuple[str, bool, str]:
"""Write the bytes source opens at dest once they match the list's size
and hashes, the file in place kept aside first when it differs.
The source is opened before the temporary file, and its read errors
are told apart from the write errors: a copy that could not be read
was reported as a folder not writable. named is the source in the
reason then, held_in when empty."""
expected = {name: f[name].lower() for name in ("sha256", "sha1") if f.get(name)}
tmp_path: Path | None = None
counted = 0
def unreadable(exc: BaseException) -> _SourceUnreadable:
return _SourceUnreadable(f"{named or held_in} could not be read: "
f"{unreadable_words(exc)}")
try:
with contextlib.ExitStack() as stack:
try:
src = stack.enter_context(source())
except _MEMBER_ERRORS as exc:
raise unreadable(exc) from exc
out = stack.enter_context(tempfile.NamedTemporaryFile(
mode="wb", dir=dest.parent, prefix=f".{dest.name}.", suffix=".part",
delete=False,
))
tmp_path = Path(out.name)
size = 0
while True:
if _stop.is_set():
raise _Interrupted()
try:
chunk = src.read(min(1024 * 1024, f["size"] + 1 - size))
except _MEMBER_ERRORS as exc:
raise unreadable(exc) from exc
if not chunk:
break
size += len(chunk)
if size > f["size"]:
raise ValueError(f"{held_in} holds more bytes than the list records")
out.write(chunk)
if progress is not None:
progress.add(len(chunk), resumed=local, network=False)
counted += len(chunk)
_place_verified(f, bios_path, dest, tmp_path, size, expected, held_in)
tmp_path = None
return f["dest"], True, ""
except _Interrupted:
return f["dest"], False, "stopped"
except _NotKept as exc:
return f["dest"], False, f"{NOT_KEPT} ({exc})"
except (_SourceUnreadable, ValueError, *_MEMBER_ERRORS) as exc:
if progress is not None and counted:
progress.add(-counted, resumed=local, network=False)
if isinstance(exc, OSError) and _write_refused(exc):
return f["dest"], False, READ_ONLY if _read_only_file(dest) else NOT_WRITABLE
return f["dest"], False, str(exc)
finally:
if tmp_path is not None and tmp_path.exists():
tmp_path.unlink()
# Errors a member of someone's ZIP can raise on reading: damaged, encrypted
# (RuntimeError), or packed with a method zipfile lacks.
_MEMBER_ERRORS = (OSError, EOFError, RuntimeError, NotImplementedError,
zipfile.BadZipFile, zlib.error)
+332
View File
@@ -0,0 +1,332 @@
"""Where each entry of a file list lands, kept under its BIOS folder."""
from __future__ import annotations
import http.client
import json
import os
import re
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import NamedTuple
from installer.text import _CONTROLS
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<ESC>]0;PWN<BEL>.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.<folder>_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 <home>/<name>."""
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
+300
View File
@@ -0,0 +1,300 @@
"""The plan shown before a download, and the download of every file."""
from __future__ import annotations
import concurrent.futures
import shutil
import sys
from collections.abc import Collection
from pathlib import Path
from installer.constants import _stop, _writing
from installer.cores import entry_systems
from installer.datadirs import data_fetch_bytes
from installer.download import _download_one
from installer.embedded import shown_path
from installer.events import EVENTS
from installer.from_folders import LocalCopy, _bytes
from installer.invocation import _INVOCATION
from installer.line_ui import _sized
from installer.offline import LOCAL, offline_named, offline_undo
from installer.outcome import (
EVERYTHING_IN_PLACE,
PLAN_FILES_PER_SYSTEM,
PLAN_FRAME_LINES,
PLAN_GROUP_TITLES,
PLAN_LARGEST_SYSTEMS,
_REFUSALS,
_offline_only,
)
from installer.pack_source import NOT_WRITABLE, _folder_writable
from installer.probe import _exists
from installer.prompt import _ask
from installer.record import OTHER_TITLE, system_title
from installer.tally import parts_words, tally
from installer.terminal import Progress, Terminal, terminal_size
from installer.text import _plural, cell_width, format_size
def _confirm(prompt: str) -> bool:
"""Yes unless the answer refuses: n, no, or one of the quit words."""
answer = _ask(prompt).strip().lower()
return not (answer.startswith("n") or answer in _REFUSALS)
def _plan_by_system(
to_download: list[dict], verbose: bool, manifest: dict | None,
) -> tuple[dict[str, list[dict]], dict[str, str]]:
"""The files of a plan by system, and the title each system is listed by."""
by_system: dict[str, list[dict]] = {}
titles: dict[str, str] = {}
for entry in to_download:
names = [system_title(name, manifest) for name in entry_systems(entry)]
system = ", ".join(names) or OTHER_TITLE
by_system.setdefault(system, []).append(entry)
# Batocera's group of systems sharing MAME's device ROMs was one line
# of 732 characters, ten rows on an 80-column terminal.
titles[system] = (system if verbose or len(names) <= PLAN_GROUP_TITLES
else f"{', '.join(names[:2])} and {len(names) - 2} more systems")
return by_system, titles
def _plan_listing(
by_system: dict[str, list[dict]], titles: dict[str, str], term: Terminal, verbose: bool,
) -> list[tuple[str, str]]:
"""Each system of a plan and its files."""
shown = None if verbose else PLAN_FILES_PER_SYSTEM
# (line, its text without styles), the second measuring the rows it takes.
listing: list[tuple[str, str]] = []
for system in sorted(by_system):
entries = sorted(by_system[system], key=lambda e: e["dest"])
listing.append((f" {term.bold(titles[system])} {_sized(entries)}",
f" {titles[system]} {_sized(entries)}"))
listing += [(f" {entry['dest']} {term.dim(format_size(entry.get('size', 0)))}",
f" {entry['dest']} {format_size(entry.get('size', 0))}")
for entry in entries[:shown]]
if shown is not None and len(entries) > shown:
more = f" ... and {len(entries) - shown} more"
listing.append((more, more))
return listing
def _print_largest_systems(
to_download: list[dict], by_system: dict[str, list[dict]], titles: dict[str, str],
term: Terminal,
) -> None:
"""The largest systems of a plan taller than the screen."""
largest = sorted(by_system, key=lambda s: (-_bytes(by_system[s]), s))
# A file several systems share is a group of its own: "88 systems"
# were 66 systems, as the full screen counts them, and 22 groups.
systems = {name for entry in to_download for name in entry_systems(entry)}
groups = (f"{_plural(len(systems), 'system')} in {len(largest)} groups"
if systems and len(systems) != len(largest)
else _plural(len(largest), 'system'))
print(f" {groups}, the largest first:")
for system in largest[:PLAN_LARGEST_SYSTEMS]:
print(f" {term.bold(titles[system])} {_sized(by_system[system])}")
if len(largest) > PLAN_LARGEST_SYSTEMS:
# Counted as the line above counts: the groups, when it names them.
unit = "group" if "groups" in groups else "system"
more = len(largest) - PLAN_LARGEST_SYSTEMS
print(f" ... and {more} more {unit}{'s' if more > 1 else ''}: --verbose lists "
"every system and its files.")
def _print_plan(
to_download: list[dict], bios_path: Path, term: Terminal,
trees: Collection[tuple[dict, dict[str, dict]]] = (),
kept: dict[Path, list[int]] | None = None,
copied: Collection[str] = (),
verbose: bool = False,
manifest: dict | None = None,
) -> None:
"""What a real run would fetch: the totals first, then by system, each
by the title the list and the screen give it, and nothing written.
The data trees count in the total and come before the closing line:
printed after it, they left 2636 RetroArch files out of the figure a
user plans an SD card from. A listing taller than the screen pushed the
total out of sight (599 lines for RetroArch): it gives way to the
largest systems, and --verbose lists every file.
"""
counts = tally(to_download)
filled = [(entry, needed) for entry, needed in trees if needed]
tree_counts = tally(meta for _entry, needed in filled for meta in needed.values())
tree_files = tree_counts.files
# One count for the plan, the screen's: "8252
# files, and 2636 data files" read as two kinds of one thing. The kinds
# follow, adding up to it.
total = counts.files + tree_files
tree_bytes = sum(data_fetch_bytes(entry, needed) for entry, needed in filled)
parts = ([f"{_plural(total, 'file')} ({format_size(counts.size + tree_bytes)})"]
if total else [])
split = parts_words(counts if (manifest or {}).get("categorized")
else tally({"size": e.get("size")} for e in to_download),
tree_files, tree_bytes)
if split and filled:
split += f", the data files extracted from {_plural(len(filled), 'archive')}"
# A pack is copied from, not downloaded: "Would download 23 files" was
# said of a run that makes no network request.
verb = "copy" if LOCAL.pack is not None else "download"
if not parts and not copied:
print(f"\n {EVERYTHING_IN_PLACE} A real run would {verb} nothing.")
return
if parts and _offline_only():
# --offline fetches none of them: "Would download" promised a
# transfer the run never makes, where the screen says "need the
# internet".
one = total == 1
print(f"\n{' and '.join(parts)} {'needs' if one else 'need'} the internet, which "
f"{offline_named()} does not use. Run {offline_undo()}, and they would go "
f"to {shown_path(bios_path)}:")
elif parts:
source = " from the pack" if LOCAL.pack is not None else ""
print(f"\nWould {verb} {' and '.join(parts)}{source} to {shown_path(bios_path)}:")
if parts and split:
print(f" {split}.")
for line in copied:
print(line)
if not parts:
print(f"\n Nothing to {verb}.")
by_system, titles = _plan_by_system(to_download, verbose, manifest)
listing = _plan_listing(by_system, titles, term, verbose)
columns, screen = terminal_size()
# A line wider than the terminal wraps: counted as one, the total the
# listing must leave in view scrolled out of sight.
rows = sum(-(-max(1, cell_width(plain)) // max(1, columns)) for _line, plain in listing)
if verbose or rows + len(filled) + PLAN_FRAME_LINES <= screen:
for line, _plain in listing:
print(line)
else:
_print_largest_systems(to_download, by_system, titles, term)
for entry, needed in filled:
source = LOCAL.pack.name if LOCAL.pack is not None else entry["url"]
fetched = data_fetch_bytes(entry, needed)
archive = ("" if fetched == sum(meta.get("size", 0) for meta in needed.values())
else f" (a {format_size(fetched)} archive)")
print(f" {term.bold(entry['ref'] + ' data')} {_sized(list(needed.values()))}, "
f"from {source}{archive}")
for folder, (count, size) in sorted((kept or {}).items()):
print(f"\n Would keep {_plural(count, 'file')} already there ({format_size(size)}), "
f"whose contents differ, in {folder}")
print("\n Nothing was written. Run without --dry-run to install.")
def _check_free_space(bios_path: Path, needed: int, plat: str = "", code: int = 2,
card: bool = False) -> None:
"""Stop before writing when the volume cannot hold the download.
Reported against the nearest existing ancestor, since the destination
may not exist yet. The run ends with code: 2 when nothing was installed,
the status a script reads as "nothing installed", 1 after an earlier
platform of the run installed files.
"""
probe = bios_path
while not _exists(probe) and probe != probe.parent:
probe = probe.parent
try:
free = shutil.disk_usage(probe).free
except OSError:
return
if free >= needed:
return
print(f"\nNot enough space on the drive holding {bios_path}.", file=sys.stderr)
print(f" Needed: {format_size(needed)}. Free: {format_size(free)}.",
file=sys.stderr)
if card:
# Its system reads this card alone: another drive, with RetroArch's
# list, was offered for an Onion card.
print(f" Free up {format_size(needed - free)} on the card, then run it again: "
"its system reads its BIOS files there only.", file=sys.stderr)
sys.exit(code)
if not plat:
print(f" Free up {format_size(needed - free)}, or use --dest to install "
"to another drive.", file=sys.stderr)
sys.exit(code)
# --dest alone used to mean RetroArch's list: the platform is named, so
# a Batocera install moved to a USB drive stays Batocera's.
print(f" Free up {format_size(needed - free)}, or install to another drive:\n"
f" {_INVOCATION.command(plat, '<folder on another drive>')}",
file=sys.stderr)
sys.exit(code)
def download_files(
files: list[dict], bios_path: Path, jobs: int = 8, verbose: bool = False,
term: Terminal | None = None, progress: Progress | None = None,
copies: dict[int, LocalCopy] | None = None,
) -> tuple[list[tuple[str, str]], bool]:
"""Download files in parallel.
Returns the destinations that failed, each with its reason, and whether
the run was interrupted. progress.installed counts the files written.
Every future is submitted up front, so a bare KeyboardInterrupt would
let the pool drain the queue in full: the stop flag is what makes Ctrl+C
end the run rather than only stop the reporting.
"""
failed: list[tuple[str, str]] = []
interrupted = False
_stop.clear()
_writing.set()
term = term or Terminal()
if progress is None:
progress = Progress(len(files), sum(f.get("size", 0) for f in files), term)
with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool:
future_map = {
pool.submit(_download_one, f, bios_path, verbose, progress,
(copies or {}).get(id(f))): f
for f in files
}
refused = False
refused_events = 0
try:
for future in concurrent.futures.as_completed(future_map):
dest, success, reason = future.result()
if refused:
# The folder they all go in refused the first: each
# would fail alike, counted without a line of its own,
# though a program reading the events still gets one.
if not success:
failed.append((dest, NOT_WRITABLE))
refused_events += 1
EVENTS.emit(
"downloaded", dest=dest, ok=False, reason=NOT_WRITABLE,
size=future_map[future].get("size", 0),
files_done=progress.files + refused_events,
files_total=progress.total_files, bytes_done=progress.bytes,
bytes_total=progress.expected_bytes,
)
continue
if _stop.is_set():
continue
progress.done(dest, success, reason)
EVENTS.emit(
"downloaded", dest=dest, ok=success, reason=reason,
size=future_map[future].get("size", 0), files_done=progress.files,
files_total=progress.total_files, bytes_done=progress.bytes,
bytes_total=progress.expected_bytes,
)
if not success:
failed.append((dest, reason))
if reason == NOT_WRITABLE and not _folder_writable(bios_path):
# A read-only card or share: hundreds of identical
# FAILED lines buried the one cause and its advice.
refused = True
_stop.set()
except KeyboardInterrupt:
interrupted = True
_stop.set()
progress.finish()
print("\n Stopping. Files already installed are kept.")
# The pool has run every future by now: a file that landed after Ctrl+C
# is on disk and counts.
progress.landed = [
entry for future, entry in future_map.items()
if not future.cancelled() and future.exception() is None and future.result()[1]
]
progress.installed = len(progress.landed)
progress.finish()
progress.emit_transfer()
return failed, interrupted
+154
View File
@@ -0,0 +1,154 @@
"""The line question that picks a setup among those found."""
from __future__ import annotations
from installer.detect_os import detect_os
from installer.embedded import _SHARE_FOLDERS, _name_key, card_setup, display_name
from installer.offline import LOCAL
from installer.prompt import _ask, _no_widow, _quit
from installer.setups import _SETUP_DEVICES, TuiRow, _setup_devices, android_hint, setup_list
from installer.terminal import terminal_size
from installer.text import _wrap
def _row_name(row: TuiRow) -> str:
"""The name a setup row is typed back with: a platform id, or the name
of a system that runs from its SD card."""
value = row.value
if row.action == "cardsystem" and isinstance(value, tuple):
return str(value[1])
return str(value)
def _row_platform(row: TuiRow) -> str:
"""The platform of the system a cardsystem row stands for."""
value = row.value
return str(value[0]) if isinstance(value, tuple) else ""
def _line_setups(setups: list | None = None, mounted: set | None = None,
os_type: str = "") -> list[tuple[str, str]]:
"""(name typed back, label) of each choice of the line menus, the
screen's setup list (setup_list) in its order, numbered: Onion was
reachable only as RetroArch, whose folder on a computer is the
computer's, and the numbers followed another order than the rows."""
def devices(names: list[str]) -> str:
# The devices that run it, three at most: the name its owner knows.
more = f", +{len(names) - 3}" if len(names) > 3 else ""
return ", ".join(names[:3]) + more
choices = []
for row in setup_list(setups or [], mounted or set(), "", os_type or detect_os(),
LOCAL.serves()):
name = _row_name(row)
if row.action == "cardsystem":
listed = list(_SETUP_DEVICES.get(name, ()))
shown = devices(listed) or f"{display_name(_row_platform(row))} files"
choices.append((name, f"{row.label} ({shown})"))
else:
listed = list(_setup_devices(name, os_type or detect_os())) \
if card_setup(name, name) else []
choices.append((name, row.label + (f" ({devices(listed)})" if listed else "")))
return choices
def _line_matches(choices: list[tuple[str, str]], typed: str, setups: list | None = None,
mounted: set | None = None, os_type: str = "") -> list[tuple[int, str]]:
"""(index, label) of the choices a typed device or system name finds,
with the screen filter's own matcher: "miyoo" was refused, the line
menu knowing only setup names. The label names what was matched first,
as the screen's row does on its right: "miyoo mini" listed MinUI with
RG28XX, RG34XX and RG34XX SP."""
found = {_row_name(row): row for row in setup_list(
setups or [], mounted or set(), typed, os_type or detect_os(), LOCAL.serves())}
matched = []
for index, (name, label) in enumerate(choices):
row = found.get(name)
if row is None:
continue
named = row.right.split(", ") if row.right else []
more = f", +{len(named) - 3}" if len(named) > 3 else ""
matched.append((index, f"{row.label} ({', '.join(named[:3])}{more})" if named
else label))
return matched
def _choose_platform(title: str, default: str = "", setups: list | None = None,
mounted: set | None = None) -> str:
"""One setup from the numbered list, Enter taking the default: a
platform id, or the name of a system that runs from its SD card, which
normalize_platform turns into its list.
A device several systems run lists them all, and Enter after that list
takes none of them: it took RetroArch, which none of them was. A number
out of range is said as one, never read as a device name.
"""
os_type = detect_os()
choices = _line_setups(setups, mounted, os_type)
if default and default not in {name for name, _label in choices}:
# A file list for another setup: Enter takes the first row, where
# the screen's focus falls (_platform_focus).
default = choices[0][0] if choices else ""
print(f"\n{title}")
# Wrapped at the width between words, its devices under its name: left
# to the terminal, "Miyoo Flip" was folded inside "Miy" and "oo" below
# 40 columns.
cols = terminal_size()[0] - 1
width = len(str(len(choices)))
for i, (_name, label) in enumerate(choices, 1):
number = f" {i:>{width}}) "
pieces = _no_widow(_wrap(label, max(cols - len(number), 8), ""),
max(cols - len(number), 8))
print(number + pieces[0])
for piece in pieces[1:]:
print(" " * len(number) + piece)
print(" q) quit")
print("Type a number, a setup's name, or the device's name (Miyoo Mini, R36S).")
usage = (f" Type a number from 1 to {len(choices)}, a setup name or the "
"device's name, or q to quit.")
while True:
prompt = f"> [Enter for {display_name(default)}] " if default else "> "
choice = _ask(prompt)
if not choice:
if default:
return default
print(usage)
continue
if choice.lower() == "q":
_quit()
if choice.isdigit():
if 1 <= int(choice) <= len(choices):
return choices[int(choice) - 1][0]
print(usage)
continue
key = _name_key(choice)
for name, _label in choices:
if key and key in (_name_key(name), _name_key(display_name(name))):
return name
found = _line_matches(choices, choice, setups, mounted, os_type) if key else []
if len(found) == 1:
print(f" {found[0][1]}")
return choices[found[0][0]][0]
if found:
print(f" {len(found)} setups run on '{choice.strip()}':")
for index, label in found:
print(f" {index + 1}) {label}")
print(" Type the number of the right one.")
default = ""
continue
hint = android_hint(choice, os_type)
print(f" {hint}" if hint else usage)
def drive_example(os_type: str, label: str, below: str = "", plat: str = "") -> str:
"""Where a drive mounted here is, as this system writes it, for the
example a refusal gives: macOS mounts it at /Volumes/<label>, WSL at
/mnt/<letter>, Windows names a letter. A Linux path with $USER was
given on every system, which PowerShell does not expand. plat, a
system reached over the network, names its network share on Windows."""
if os_type == "windows":
if plat in _SHARE_FOLDERS:
return _SHARE_FOLDERS[plat]
return "E:\\" + below.replace("/", "\\")
root = {"darwin": f"/Volumes/{label}", "wsl": "/mnt/e",
"android": f"/storage/{label}"}.get(os_type, f"/media/$USER/{label}")
return f"{root}/{below}" if below else root
+174
View File
@@ -0,0 +1,174 @@
"""File system probes that note a folder this user may not read instead of failing."""
from __future__ import annotations
import errno
import os
import re
import sys
import threading
from collections.abc import Callable
from pathlib import Path
from typing import Any
from installer.events import EVENTS
from installer.text import screen_text
# 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)
+68
View File
@@ -0,0 +1,68 @@
"""The line questions: an answer typed, a quit, a folder typed."""
from __future__ import annotations
import os
import sys
from pathlib import Path
from installer.probe import _host_path
from installer.text import _glued_words, cell_width
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]
+1059
View File
File diff suppressed because it is too large. Load diff
+1011
View File
File diff suppressed because it is too large. Load diff
+2159
View File
File diff suppressed because it is too large. Load diff
+629
View File
@@ -0,0 +1,629 @@
"""The setups a device or a computer holds, and how they are named and told apart."""
from __future__ import annotations
import argparse
import os
import re
import unicodedata
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple
from installer.constants import AVAILABLE_PLATFORMS, DEFAULT_DESTS
from installer.detect_frontends import _UNNAMEABLE, _android_storage_root, detect_platforms
from installer.detect_os import _DETECTED_OS, _FROM_CARD, _os_default_dests, card_title, detected_os, detected_shown
from installer.embedded import (
_SHARE_FOLDERS,
_mount_name,
_mounted_cards,
_name_key,
_systems_reading,
card_bound,
card_setup,
card_setups,
card_system,
display_name,
doubt_words,
drive_kind,
)
from installer.local_files import _retroarch_config_at
from installer.probe import _DETECTION_REFUSED, _is_dir, _is_file
from installer.text import _plural
if TYPE_CHECKING:
from installer.tui_state import TuiState
def _card_word(system: tuple[str, Path, str]) -> str:
"""A mounted drive's kind as the first screen writes it: SD card, or
SHARE drive."""
return "SD card" if drive_kind(system) == "card" else drive_kind(system)
# Platforms with no install location of their own: the BIOS folder sits
# beside the executable, wherever the archive was extracted.
PORTABLE_ONLY = {
"bizhawk": "BizHawk reads the Firmware folder beside EmuHawk, and none was found.",
}
def _default_dest(os_type: str, platform_name: str) -> Path | None:
"""Fall back path for a platform named on the command line but not found,
or None where no folder on this OS is one the platform reads.
A home directory is meaningless for RetroArch on Android, where Termux
owns the home and the frontend reads from shared storage. ~/bios is read
by no platform, RetroBat lives on Windows only, and a Batocera or Recalbox
path on Windows resolved to the root of the current drive: 8.7 GB under
C:\\userdata\\bios, reported done.
"""
default = _built_in_dest(os_type, platform_name)
if default is not None and (_refused_near(default) or platform_name in _UNNAMEABLE):
# The Flatpak's own folder at 000 hid the retroarch.cfg naming
# ~/Games/bios, and 6.6 GB were offered to a folder it does not read.
return None
return default
def _built_in_dest(os_type: str, platform_name: str) -> Path | None:
"""The platform's usual folder on this OS, whatever detection met."""
if os_type == "android" and platform_name == "retroarch":
return _android_storage_root() / "RetroArch" / "system"
if platform_name in PORTABLE_ONLY or (os_type == "windows" and platform_name
not in _os_default_dests(os_type)):
return None
return (_os_default_dests(os_type).get(platform_name)
or (None if platform_name == "retrobat" else DEFAULT_DESTS.get(platform_name)))
def _refused_near(default: Path) -> bool:
"""Whether detection met a closed folder under HOME, where configs that
could name another folder live, or above the default itself."""
home = Path.home()
place = default.absolute()
return any(home in (folder, *folder.parents) or folder in (place, *place.parents)
for folder, _why in _DETECTION_REFUSED)
def _folded(text: str) -> str:
"""Text compared without case or accents, as a filter reads it."""
decomposed = unicodedata.normalize("NFKD", text)
return "".join(char for char in decomposed if not unicodedata.combining(char)).casefold()
class TuiRow(NamedTuple):
"""One row a screen lists: what Enter does on it, and what it shows."""
action: str
label: str
right: str = ""
value: object = None
style: str = ""
# Shorter forms of right, longest first, for a narrow screen: the label
# keeps its room before the right-hand text does.
narrow: tuple = ()
# A name cut to the room left when no form of narrow but a count fits:
# "1 device" named nothing where "TrimUI Smart P..." fits.
cut: str = ""
# The right-hand text is never cut: the label is, once its shortest
# form does not fit beside it (a system's size).
keep_right: bool = False
# The column the right-hand text starts at, one for the whole list: the
# setup list's devices had three right edges at 120 columns.
align: int = 0
def _matches(text: str, needle: str) -> bool:
return not needle or _folded(needle) in _folded(text)
# Every device the setup lists name, once, as its maker or its store spells
# the model, with the maker: a system list writes the model, and the filter
# also finds it by its maker's name. Two lists spelled one device two ways
# (Powkiddy RK2023 and RK2023, RGCUBEXX and RG CubeXX, Flip2 and Flip 2), and
# a device typed as one list wrote it found that system alone. A test holds
# every list to these names and each name to one spelling.
_DEVICES: dict[str, str] = {
**{model: "Anbernic" for model in (
"RG28XX", "RG34XX", "RG34XX SP", "RG35XX", "RG35XX 2024", "RG35XX H",
"RG35XX Plus", "RG35XX Pro", "RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX",
"RG ARC", "RG ARC-S", "RG 55G1", "RG351", "RG351M", "RG351MP", "RG351P", "RG351V",
"RG353", "RG353M", "RG353P", "RG353PS", "RG353V", "RG353VS", "RG503", "RG552")},
**{model: "Powkiddy" for model in (
"RGB10", "RGB10X", "RGB10 Max", "RGB10 Max 2", "RGB10 Max 3", "RGB10 Max 3 Pro",
"RGB20 Pro", "RGB20S", "RGB20SX", "RGB30", "RK2023", "X35H", "X35S", "X55", "V10",
"PowKiddy Q20 Mini", "PowKiddy Q90", "PowKiddy V90")},
**{model: "Miyoo" for model in (
"Miyoo A30", "Miyoo Flip", "Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus")},
**{model: "TrimUI" for model in ("TrimUI Brick", "TrimUI Smart", "TrimUI Smart Pro")},
**{model: "Retroid" for model in (
"Retroid Pocket", "Retroid Pocket 5", "Retroid Pocket 6", "Retroid Pocket Flip 2",
"Retroid Pocket Mini", "Retroid Pocket Nova")},
**{model: "AYN" for model in (
"AYN Odin", "AYN Odin 2", "AYN Odin 3", "AYN Thor", "AYN Loki Max",
"AYN Loki Mini Pro", "AYN Loki Zero")},
**{model: "AYANEO" for model in (
"AYANEO Pocket", "AYANEO Air", "AYANEO Air Plus", "AYANEO Air Pro", "AYANEO 2",
"AYANEO 2S", "AYANEO 2021", "AYANEO Geek", "AYANEO Next")},
**{model: "Hardkernel" for model in (
"Odroid Go", "Odroid Go Advance", "Odroid Go Super", "Odroid Go Ultra")},
**{model: "MagicX" for model in (
"MagicX XU10", "MagicX XU Mini M", "MagicX XU20 V32", "MagicX Mini Zero 28")},
**{model: "GameForce" for model in ("GameForce Ace", "GameForce Chi")},
**{model: "SJGAM" for model in ("SJGAM M21", "SJGAM M22 Pro")},
**{model: "" for model in (
"R33S", "R35S", "R36H", "R36S", "R36S Plus", "R36S Soysauce", "R40XX Pro Max",
"XF40H", "K36", "M17", "BittBoy", "Pocket Go", "Sup M3", "XYC Q8", "Android",
# dArkOS names these two by model alone (v08272026 release notes).
"A10 Mini", "Miniloong Pocket 1")},
"G350": "BattleXP",
"GKD Pixel": "GKD",
"GKD Pixel 2": "GKD",
"Mangmi Air X": "Mangmi",
"Orange Pi Zero 2w": "Orange Pi",
"Steam Deck": "Valve",
"ROG Ally": "ASUS",
}
# The devices whose own system is Android. On a computer RetroArch's row is
# that computer's RetroArch, and a Retroid Pocket owner found it in one press
# and got the computer's folder. Listed only where RetroBIOS runs on Android.
_ANDROID_DEVICES = ("Android", "Retroid Pocket", "Retroid Pocket 5", "AYN Odin", "AYN Odin 3")
def _device_key(text: str) -> str:
"""A device name compared without case, spaces or punctuation, + read as
Plus: RG CubeXX, RGCUBEXX and rg-cubexx are one device, Mini+ is Mini Plus."""
return _name_key(re.sub(r"\s*\+", " plus", _folded(text)))
# The devices people type in the setup filter instead of the setup they run,
# beside the setups a first-party page says each one runs, spelled as
# _DEVICES spells them. Keys are platform ids or the system names of
# _EMBEDDED_RULES, and a device that runs several setups is under each. The
# handheld systems' lists are those of platforms/_guides.yml (handheld_guide,
# each with its devices_source), and a test holds the two equal.
_SETUP_DEVICES: dict[str, tuple[str, ...]] = {
"ArkOS": ("RG353M", "RG353V", "RG503", "RGB30", "RK2023", "RG351MP", "RG351V", "R35S",
"RGB10"),
"muOS": ("RG35XX H", "RG35XX Plus", "RG35XX SP", "RG35XX 2024", "RG34XX", "RG40XX H",
"RG40XX V", "RG28XX", "RG CubeXX", "TrimUI Brick", "TrimUI Smart Pro"),
"Onion": ("Miyoo Mini", "Miyoo Mini Plus"),
"spruceOS": ("Miyoo A30", "Miyoo Flip", "Miyoo Mini", "Miyoo Mini Plus",
"Miyoo Mini Flip", "TrimUI Smart Pro", "TrimUI Brick",
"RG35XX Plus", "RG40XX H", "RGB30"),
"Allium": ("Miyoo Mini", "Miyoo Mini Plus", "Miyoo Mini Flip"),
# The stock Linux these devices ship with runs /mnt/vendor/bin/dmenu.bin:
# GarlicOS/bootloader_anbernic_rg35xxplus 45b489b4, README.md:4.
"Anbernic stock firmware": ("RG35XX Plus", "RG35XX H", "RG35XX SP", "RG28XX"),
"ArchR": ("R36S", "R33S", "R36S Soysauce", "Odroid Go Advance", "Odroid Go Super",
"RG351V", "RG351M", "GameForce Chi", "MagicX XU10", "RGB10", "RGB10X", "K36"),
"CrossMix-OS": ("TrimUI Smart Pro",),
"dArkOS": ("RG353M", "RG353V", "RG503", "RGB30", "RGB20 Pro", "RK2023", "RG351MP", "RGB10",
"G350", "Odroid Go Advance", "A10 Mini", "Miniloong Pocket 1"),
# JELOS 7b2e116c, packages/hardware/quirks/devices: one folder per device
# it was built for, the handhelds here.
"JELOS": ("RG351M", "RG351V", "RG353M", "RG353P", "RG353V", "RG353VS", "RG503", "RG552",
"R33S", "R36S", "GameForce Ace", "GameForce Chi", "Odroid Go Advance",
"Odroid Go Super", "Odroid Go Ultra", "MagicX XU10", "RGB10", "RGB10 Max 3",
"RGB10 Max 3 Pro", "RGB20S", "RGB30", "RK2023", "X55", "AYANEO Air",
"AYANEO Air Plus", "AYANEO Air Pro", "AYANEO 2", "AYANEO 2S", "AYANEO 2021",
"AYANEO Geek", "AYANEO Next", "AYN Loki Max", "AYN Loki Mini Pro",
"AYN Loki Zero"),
"KOLOS": ("RG353P", "RG353M", "RG353V", "RG353VS", "RG503", "RK2023", "RGB30",
"RGB10 Max 3"),
"Koriki": ("Miyoo Mini",),
"MiyooCFW": ("BittBoy", "Pocket Go", "PowKiddy Q90", "PowKiddy V90", "PowKiddy Q20 Mini",
"Sup M3", "XYC Q8"),
"plumOS": ("MagicX XU20 V32",),
"RetroOZ": ("Odroid Go Super", "Odroid Go Advance", "RGB10 Max", "RGB10 Max 2"),
"UnofficialOS": ("R35S", "R36S", "RG351M", "RG351P", "RG351V", "RG353M", "RG353P",
"RG353V", "RG503", "RG552", "RGB30", "RGB20 Pro", "Odroid Go Advance",
"Odroid Go Super"),
# The Android tile of the handheld group (_guides.yml): goretroid.com
# "OS: Android 13" for the Retroid Pocket 5, ayntec.com "Android 15" for
# the AYN Odin 3. The guide runs RetroArch on Steam Deck (run: steamdeck)
# and on Windows, which the ROG Ally runs (rog.asus.com spec,
# "Windows 11 Home").
"retroarch": ("Steam Deck", "ROG Ally", "Android", "Retroid Pocket", "Retroid Pocket 5",
"AYN Odin", "AYN Odin 3"),
"emudeck": ("Steam Deck", "ROG Ally"),
"retrodeck": ("Steam Deck",),
"retrobat": ("ROG Ally",),
"bizhawk": ("ROG Ally",),
# _guides.yml runs_on, each cited there.
"batocera": ("Steam Deck",),
"amberelec": ("RG351", "RG552"),
"emuelec": ("Odroid Go",),
# shauninman/MinUI dbf89435, README.md:65-90, Supported Devices.
"minui": ("RG28XX", "RG34XX", "RG34XX SP", "RG35XX", "RG35XX Plus", "RG35XX H",
"RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX", "GKD Pixel", "M17",
"MagicX XU Mini M", "MagicX Mini Zero 28", "Miyoo A30", "Miyoo Flip",
"Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus", "RGB30", "TrimUI Brick",
"TrimUI Smart", "TrimUI Smart Pro"),
"nextui": ("TrimUI Brick", "TrimUI Smart Pro"),
# Turro75/MyMinUI 72ed4f3d, README.md:11-35, List of working devices.
"myminui": ("RG35XX", "Miyoo Mini", "Miyoo Mini Flip", "Miyoo Mini Plus", "Miyoo A30",
"SJGAM M21", "SJGAM M22 Pro", "R36S", "R36H", "R36S Plus", "R40XX Pro Max",
"XF40H", "RG351P", "RG353V", "RG353VS", "RG353P", "RG353PS", "RG353M", "V10",
"RGB30", "RG35XX SP"),
# rocknix.org/devices, read 2026-10-26.
"rocknix": ("RG351", "RG353", "RG503", "RG552", "RG 55G1", "RG ARC", "RG35XX 2024",
"RG35XX Plus", "RG35XX Pro", "RG35XX H", "RG35XX SP", "RG28XX", "RG40XX V",
"RG40XX H", "RG CubeXX", "RG34XX", "AYANEO Pocket", "AYN Odin 2",
"AYN Odin 3", "AYN Thor", "GameForce Ace", "Odroid Go Advance",
"Odroid Go Super", "Odroid Go Ultra", "MagicX XU Mini M", "Mangmi Air X",
"RGB10", "RGB10X", "RK2023", "RGB20SX", "RGB20 Pro", "RGB30", "X35S", "X35H",
"X55", "MagicX XU10", "Retroid Pocket 5", "Retroid Pocket 6",
"Retroid Pocket Flip 2", "Retroid Pocket Mini", "Retroid Pocket Nova", "R33S",
"R35S", "R36S", "K36"),
# knulli.org, read 2026-10-26.
"knulli": ("RG ARC-S", "RG28XX", "RG34XX", "RG35XX", "RG35XX Plus", "RG35XX H",
"RG35XX 2024", "RG35XX SP", "RG40XX H", "RG40XX V", "RG CubeXX",
"Retroid Pocket 5", "Retroid Pocket Flip 2", "Retroid Pocket Mini",
"Miyoo Flip", "Orange Pi Zero 2w", "RGB30", "X55", "TrimUI Brick",
"TrimUI Smart Pro", "G350", "GKD Pixel 2"),
}
def _setup_devices(name: str, os_type: str = "") -> tuple[str, ...]:
"""The devices a setup row names: an Android device only where this
installer runs on Android, RetroArch's row being this machine's."""
devices = _SETUP_DEVICES.get(name, ())
if name == "retroarch" and os_type != "android":
devices = tuple(device for device in devices if device not in _ANDROID_DEVICES)
return devices
def android_hint(needle: str, os_type: str) -> str:
"""What a filter that names an Android device and finds nothing says:
RetroArch is the Android setup, and its row on a computer is that
computer's (_setup_devices). "android" matched nothing, with no word."""
if os_type == "android" or not any(_device_found(device, needle)
for device in _ANDROID_DEVICES):
return ""
return "On Android, choose RetroArch: run RetroBIOS on the device itself."
def _device_needle(needle: str) -> str:
"""The filter text with a model's short form spelled out: owners write
RP5 for the Retroid Pocket 5, as the store names it."""
short = re.fullmatch(r"\s*rp\s*(\d+)\s*", needle, re.IGNORECASE)
if short:
return f"Retroid Pocket {short.group(1)}"
return needle
# A list that names a family stands for each of its models: ROCKNIX lists
# RG351 and RG353, and the RG353V typed from the box found every system but
# it. AmberELEC's RG351 is the series it was made for (amberelec.org).
_DEVICE_FAMILIES: dict[str, tuple[str, ...]] = {
"RG351": ("RG351P", "RG351M", "RG351V", "RG351MP"),
"RG353": ("RG353P", "RG353M", "RG353V", "RG353VS", "RG353PS"),
}
def _device_found(device: str, needle: str) -> bool:
"""Whether typed text names device, by its model, with or without its
maker: Powkiddy RK2023 and RK2023 are one device. A family is found by
the name of any of its models."""
key = _device_key(_device_needle(needle))
if not key:
return False
maker = _device_key(_DEVICES.get(device, ""))
return any(key in _device_key(model) or key in maker + _device_key(model)
for model in (device, *_DEVICE_FAMILIES.get(device, ())))
def _setup_matches(plat: str, systems: list[str], needle: str,
os_type: str = "") -> list[str] | None:
"""What the filter names for plat: its devices and systems that match,
[] when plat's own name does, None when nothing does. A device counts
for each setup it runs."""
if not needle or _name_found(f"{plat} {display_name(plat)}", needle):
return []
devices = [device for device in _setup_devices(plat, os_type)
if _device_found(device, needle)]
named = [system for system in systems if _name_found(system, needle) or any(
_device_found(device, needle) for device in _SETUP_DEVICES.get(system, ()))]
return _computer_named(plat, needle) + devices + named or None
def _system_matches(name: str, needle: str) -> list[str] | None:
"""What the filter names for a card system: [] when its name does, the
devices that run it that match, None when nothing does."""
if not needle or _name_found(name, needle):
return []
return [device for device in _SETUP_DEVICES.get(name, ())
if _device_found(device, needle)] or None
def _name_found(name: str, needle: str) -> bool:
"""Whether typed text names a setup, compared as a device is: spruce os,
unofficial os and cross mix found nothing on the screen, and line mode
took Unofficial OS."""
key = _device_key(needle)
return _matches(name, needle) or bool(key) and key in _device_key(name)
def _comma_forms(names: list[str]) -> tuple:
"""Shorter forms of a list for a narrow screen, each cut at a comma:
"Miyoo Mini, +2" where "Miyoo ...s" said nothing."""
return tuple(", ".join(names[:keep]) + f", +{len(names) - keep}"
for keep in range(len(names) - 1, 0, -1))
def _device_forms(names: list[str]) -> tuple:
"""A setup row's devices cut for a narrow screen, the setup's name kept
whole: at 40 columns KNULLI and ROCKNIX lost every device, and
"CrossMix-OS, SD ca" was cut mid-word. The last form counts them, and a
row naming no device can leave its right column empty."""
if not names:
return ("",)
if len(names) == 1:
# A count of one names nothing: the name is cut instead (TuiRow.cut).
return ()
return (*_comma_forms(names), _plural(len(names), "device"))
def _device_setup(state: TuiState, plat: str, system: str) -> Path | None:
"""The folder detection found for system on this machine itself, never
a card mounted in a reader: on a computer a card is looked for."""
return _found_device(state.setups, state.mounted_setups, plat, system)
def _found_device(setups: list, mounted: set, plat: str, system: str) -> Path | None:
return next((path for name, path, _label in setups if name == plat
and (name, path) not in mounted
and detected_os(name, path) == system), None)
def setup_folder(os_type: str, setups: list, mounted: set, plat: str,
system: str) -> tuple[Path | None, str]:
"""(folder, kind) offered for a setup taken from the setup list, on the
screen's Which folder? and at line mode's folder question. kind is
"found" (detected here), "share" (a system a computer reaches on its
SHARE drive, no folder of its own here) or "usual" (its built-in one).
The folder detected here comes before the built-in one: line mode, by
o then RetroArch, offered ~/.config/retroarch/system and filled it,
when the retroarch.cfg found here names another folder. A card in a
reader is its own system's, never this computer's RetroArch, and a
system that runs from its card is found on the device itself only."""
bound = card_bound(system, plat)
if bound:
found = _found_device(setups, mounted, plat, bound[0])
return found, "found" if found else "usual"
found = next((path for name, path, _label in setups if name == plat
and (name, path) not in mounted), None)
if found is not None:
return found, "found"
if plat in _SHARE_FOLDERS:
# /userdata/bios exists on the Batocera machine alone: a computer
# sees its share drive or its network share.
return None, "share"
return _default_dest(os_type, plat), "usual"
def setup_list(setups: list, mounted: set, needle: str = "",
os_type: str = "", serves: frozenset = frozenset()) -> list[TuiRow]:
"""The setup list, the screen's and the numbered one of line mode: each
platform, then each system that runs from its SD card, with what the
filter named. setups and mounted are what detection found here, as
TuiState holds them.
Every card system is a row of its own that asks for its card, with or
without the filter, from card_setups(): RetroArch's row listed muOS,
JELOS and fourteen more, and A on it led an R36S owner to this
computer's RetroArch folder. RetroArch's row is this computer's. A card
row names the devices that run it, the name a handheld's owner knows:
"Onion, SD card" beside "RetroArch files" said nothing to a Miyoo Mini
owner. With nothing found here the card rows come right after RetroArch
(_cards_first). Line mode listed them in another order, and its 8 was
the screen's 19. serves, when not empty, keeps the setups that read
the file list given (LocalSources.serves).
"""
every_card = card_setups()
cards = {setup.name for setup in every_card}
cards_setups = [setup for setup in every_card if not serves or setup.plat in serves]
systems = _systems_reading()
desktop: list[TuiRow] = []
handheld: list[tuple[str, TuiRow]] = []
for plat in AVAILABLE_PLATFORMS:
if serves and plat not in serves:
continue
others = [name for name in systems.get(plat, []) if name not in cards]
named = _setup_matches(plat, others, needle, os_type)
if named is None:
continue
setup = card_setup(plat, plat)
label = display_name(plat)
if (setup and plat not in _DESK_CARDS
and _found_device(setups, mounted, plat, setup.name) is None):
label += ", SD card"
# The systems and devices the filter named, else a card's devices.
shown = named or (list(_setup_devices(plat, os_type)) if setup else [])
row = TuiRow("platform", label, ", ".join(shown), plat, narrow=_device_forms(shown),
cut=shown[0] if shown else "")
if setup and plat not in _DESK_CARDS:
handheld.append((label, row))
else:
desktop.append(row)
for setup in cards_setups:
if setup.name == display_name(setup.plat):
continue
named = _system_matches(setup.name, needle)
if named is None:
continue
label = setup.name
if _found_device(setups, mounted, setup.plat, setup.name) is None:
label += ", SD card"
shown = named or list(_SETUP_DEVICES.get(setup.name, ()))
handheld.append((label, TuiRow("cardsystem", label, ", ".join(shown)
or f"{display_name(setup.plat)} files",
(setup.plat, setup.name),
narrow=_device_forms(shown),
cut=shown[0] if shown else "")))
handheld.sort(key=lambda item: item[0].casefold())
cards_rows = [row for _label, row in handheld]
if _cards_first(setups):
# The setups this computer runs lead, before the cards: RetroBat
# was row 27 of 34 on Windows, after 23 SD card rows.
here = _DESKTOP_LEAD.get(os_type, ("retroarch",))
lead = sorted((row for row in desktop if row.value in here),
key=lambda row: here.index(row.value))
rest = [row for row in desktop if row.value not in here]
return [*lead, *cards_rows, *rest]
return [*desktop, *cards_rows]
# The systems that run from an SD card on a board kept on a desk, not in
# the hand: their row stays among the platforms, and the handhelds' block,
# which leads when nothing is found here, keeps Onion four presses away.
_DESK_CARDS = frozenset({"misterfpga", "lakka"})
# The setups a computer runs, by its system, first in the setup list when
# nothing was found here. RetroBat runs on Windows alone (retrobat.org), and
# under WSL its folder is the Windows side's (_os_default_dests). EmuDeck has
# a Windows edition (emudeck-we).
_DESKTOP_LEAD: dict[str, tuple[str, ...]] = {
"windows": ("retroarch", "retrobat", "emudeck"),
"wsl": ("retroarch", "retrobat", "emudeck"),
}
# The computer systems people type in the setup filter, with the setups each
# one runs: "windows" and "mac" matched nothing. RetroArch runs on the three
# (retroarch.com), RetroBat on Windows only, EmuDeck has a Windows edition
# and a Linux one (SteamOS), RetroDECK is a Linux Flatpak, BizHawk publishes
# Windows and Linux builds, RetroPie runs on Debian and Ubuntu.
_COMPUTER_SYSTEMS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
"Windows": (("windows", "pc"), ("retroarch", "retrobat", "emudeck", "bizhawk")),
"macOS": (("macos", "mac", "osx", "macbook"), ("retroarch",)),
"Linux": (("linux", "ubuntu", "debian", "steamos"),
("retroarch", "emudeck", "retrodeck", "bizhawk", "retropie")),
}
def _computer_named(plat: str, needle: str) -> list[str]:
"""The computer systems the filter names that run plat."""
key = _device_key(needle)
# Two letters are a word on their way: "wi" said "No setup matches"
# between "w" and "win". "pc" is one of the words.
if len(key) < 2:
return []
return [name for name, (words, plats) in _COMPUTER_SYSTEMS.items()
if plat in plats and any(word.startswith(key) for word in words)]
def _cards_first(setups: list) -> bool:
"""Whether the card rows follow RetroArch: nothing was found here, so
this is a computer a handheld's card is prepared on, or a console the
detection does not know. A pad cannot type in the filter, and Onion was
row 30 of 34: 29 presses of Down. Right after RetroArch it is row 19,
in view after five presses of L1/R1 at 40x12, which page by the rows
drawn (_page_step). A row that opened a list of the
cards cost one more press than the list it opened."""
return not setups
def _setup_label(plat: str, path: Path | None) -> str:
system = detected_shown(plat, path) if path is not None else ""
name = display_name(plat)
return f"{system} ({name} files)" if system and system != name else name
def _install_kind(path: Path) -> str:
"""What sets one install of a frontend apart from another of the same."""
# The config detection read it from says how it was installed: the
# Flatpak's system directory can be anywhere its config names.
found = _retroarch_config_at(path)
text = path.as_posix() + (" " + Path(found[0]).as_posix() if found else "")
for marker, word in (("/.var/app/", "Flatpak"), ("/steamapps/", "Steam"),
("/snap/", "Snap")):
if marker in text:
return word
if _is_file(path.parent / "retroarch.cfg"):
return "portable"
return ""
def tell_apart(setups: list[tuple]) -> list[tuple]:
"""Two setups that read alike get the word that separates them: the
Flatpak and the native RetroArch were both "RetroArch" at 40 columns.
The one no package names is "installed", and two of those keep the
end of their folder, the only thing that tells them apart."""
labels = [label for _plat, _path, label in setups]
kinds = [_install_kind(path) or "installed" for _plat, path, _label in setups]
named = list(zip(labels, kinds))
return [(plat, path, label if labels.count(label) == 1
else f"{label} ({kind})" if named.count((label, kind)) == 1
else f"{label} ({'/'.join(path.parts[-2:])})")
for (plat, path, label), kind in zip(setups, kinds)]
def _tui_passthrough(args: argparse.Namespace) -> list[tuple[str, str | None]]:
"""Options the screens do not change, handed to every run unchanged."""
flags: list[tuple[str, str | None]] = []
if args.romm_firmware is not None:
flags.append(("--romm-firmware", str(args.romm_firmware)))
for flag in ("--save-dir", "--cores-dir"):
value = getattr(args, flag[2:].replace("-", "_"))
if value is not None:
flags.append((flag, str(Path(value).absolute())))
flags.extend((flag, None) for flag in ("--standalone-copies", "--verbose")
if getattr(args, flag[2:].replace("-", "_")))
return flags
def found_setups(os_type: str) -> tuple[list[tuple[str, Path, str]], set]:
"""(setups, mounted): what detection finds here, each with its label,
then each card mounted in a reader whose own files name its system, and
the (platform, folder) of those cards. The screen's "Found on this
machine" and line mode's "Found" read this one list: line mode looked
at this machine alone, and a mounted Onion card was never offered."""
found = detect_platforms(os_type)
cards = [(card_system(mount), mount) for mount in _mounted_cards()]
setups = [(name, path, _setup_label(name, path)) for name, path in found]
mounted: set = set()
# On the device itself its own card is the system found, by its own
# path (muOS reads /run/muos/storage/bios, a bind of MUOS/bios).
here = {detected_os(name, path) for name, path in found}
taken = []
for card, mount in cards:
if card is None:
# A drive whose files fit two systems is said, never guessed.
words = doubt_words(mount)
if words:
print(f" {words}")
continue
if (card[0], card[1]) not in found and card[2] not in here:
_DETECTED_OS.setdefault((card[0], card[1]), card[2])
_FROM_CARD.add((card[0], card[1]))
mounted.add((card[0], card[1]))
taken.append((card, mount))
systems = [card[2] for card, _mount in taken]
counts = {mount: _bios_count(card[1]) for card, mount in taken
if systems.count(card[2]) > 1}
# Two cards of one system read alike: each says what its BIOS folder
# holds, and the one with fewer files, the card being set up rather
# than the old one, comes first.
taken.sort(key=lambda item: (systems.index(item[0][2]), counts.get(item[1], -1)))
for card, mount in taken:
kind = _card_word(card)
held = counts.get(mount)
what = ("" if held is None else ", no BIOS folder" if held < 0
else f", {_plural(held, 'BIOS file')}")
setups.append((card[0], card[1],
f"{card_title(card[2])} {kind} ({_mount_name(mount)}{what})"))
return tell_apart(setups), mounted
def _bios_count(folder: Path, cap: int = 99999) -> int:
"""How many files a card's BIOS folder holds, -1 when it has none."""
if not _is_dir(folder):
return -1
count = 0
for _top, _dirs, files in os.walk(folder):
count += len(files)
if count >= cap:
break
return count
+309
View File
@@ -0,0 +1,309 @@
"""Standalone emulators: their folders and the copies a launcher makes."""
from __future__ import annotations
import argparse
import os
import shutil
import sys
from pathlib import Path, PurePosixPath
from installer.datadirs import _copy_targets
from installer.detect_frontends import launchbox_bios_dirs, launchbox_root
from installer.invocation import offline_requested
from installer.line_ui import _sized
from installer.local_files import BACKUP_DIR, check_local, unreachable_words
from installer.network import fetch_manifest
from installer.outcome import EVERYTHING_IN_PLACE, OutcomeDetails, _check_fetch_line, _report_outcome
from installer.pack_source import NOT_KEPT, NOT_WRITABLE, _write_refused
from installer.paths import _destination_path, _within
from installer.plan import _check_free_space, _confirm, _print_plan, download_files
from installer.probe import _closed_to_this_user, _exists, _is_dir
from installer.record import KEPT, _NotKept, _replace_with_copy, plan_kept
from installer.terminal import Progress, Terminal
def standalone_folders_here(
manifest: dict, os_type: str, extra_dirs: dict[str, Path] | None = None,
) -> list[Path]:
"""The emulator folders of the manifest's standalone copies that exist
on this machine: the ones --standalone-copies would write to."""
found: list[Path] = []
for entry in manifest.get("standalone_copies", []):
if "note" in entry:
continue
for folder in _copy_targets(entry, os_type, extra_dirs):
if folder not in found and _is_dir(folder):
found.append(folder)
return found
# The file lists a machine with standalone emulators and no platform is
# served from: EmuDeck's holds the Switch keys, RetroArch's the PPSSPP atlas
# and the Flycast flash, and each copy entry names its folders.
STANDALONE_SOURCES = ("emudeck", "retroarch")
def standalone_plan(
manifests: list[dict], os_type: str, extra_dirs: dict[str, Path] | None = None,
) -> list[tuple[Path, list[dict]]]:
"""What each emulator folder found here receives, by its own file name.
The standalone copies of the manifests, read as do_standalone_copies
reads them, but taken from the file lists rather than from a platform
tree already installed: an ES-DE user with DuckStation and PCSX2 and no
RetroArch had no tree to copy from. The first list that holds a name for
a folder serves it.
"""
from fnmatch import fnmatch
plan: dict[Path, dict[str, dict]] = {}
for manifest in manifests:
files = manifest.get("files", [])
by_dest = {entry["dest"]: entry for entry in files}
for copy in manifest.get("standalone_copies", []):
if "note" in copy:
continue
if "pattern" in copy:
sources = [entry for entry in files
if fnmatch(PurePosixPath(entry["dest"]).name, copy["pattern"])]
else:
held = by_dest.get(copy.get("source") or copy["file"])
sources = [held] if held else []
for folder in _copy_targets(copy, os_type, extra_dirs):
if not sources or not _is_dir(folder):
continue
chosen = plan.setdefault(folder, {})
for entry in sources:
# `as`: the name the emulator reads, when it is not the
# platform's (melonDS's dsisd.bin, xemu's eeprom.bin).
name = copy.get("as") or PurePosixPath(entry["dest"]).name
chosen.setdefault(name, {**entry, "dest": name})
return [(folder, list(entries.values())) for folder, entries in plan.items() if entries]
def _check_standalone_folder(to_download: list[dict], mismatched: list[dict],
verbose: bool) -> None:
"""What --check says of one standalone emulator folder."""
for entry in mismatched:
print(f" wrong copy: {entry['dest']}")
wrong = {id(entry) for entry in mismatched}
missing = [entry for entry in to_download if id(entry) not in wrong]
for entry in missing[:10] if not verbose else missing:
print(f" missing: {entry['dest']}")
if not verbose and len(missing) > 10:
print(f" ... and {len(missing) - 10} more missing (--verbose lists them all)")
if not to_download:
print(f" {EVERYTHING_IN_PLACE}")
def _install_standalone_folders(
args: argparse.Namespace, os_type: str, term: Terminal, interactive: bool,
) -> bool:
"""Fill the standalone emulator folders found here, with no platform.
False when this machine has none, the run then going on to the platform
question or hint.
"""
if offline_requested():
# Their folders are named by file lists this run cannot fetch: the
# first refusal ended an --offline run that asked nothing of EmuDeck
# on "No file list for emudeck".
return False
manifests = [fetch_manifest(plat) for plat in STANDALONE_SOURCES]
lb_root = launchbox_root(os_type)
plan = standalone_plan(manifests, os_type,
launchbox_bios_dirs(lb_root) if lb_root else None)
if not plan:
return False
print(" Found standalone emulator folders:")
for folder, entries in plan:
print(f" {folder} {_sized(entries)}")
if interactive and not (args.check or args.dry_run or args.yes) and not _confirm(
"\nInstall the BIOS files these emulators read into their folders? [Y/n] "
):
return False
downloaded = up_to_date_count = errors = 0
pending = 0
failures: list[tuple[str, str]] = []
transferred, seconds = 0, 0.0
interrupted = False
for folder, entries in plan:
print(f"\n{folder}:")
to_download, up_to_date, mismatched = check_local(entries, folder, jobs=args.jobs)
to_download.extend(mismatched)
up_to_date_count += len(up_to_date)
if args.check:
_check_standalone_folder(to_download, mismatched, args.verbose)
pending += len(to_download)
continue
if args.dry_run:
_print_plan(to_download, folder, term, kept=plan_kept(mismatched, folder),
verbose=args.verbose)
continue
if not to_download:
print(f" {EVERYTHING_IN_PLACE}")
continue
size = sum(entry.get("size", 0) for entry in to_download)
_check_free_space(folder, size, code=1 if downloaded else 2)
progress = Progress(len(to_download), size, term)
failed, interrupted = download_files(
to_download, folder, jobs=args.jobs, verbose=args.verbose,
term=term, progress=progress,
)
downloaded += progress.installed
errors += len(failed)
failures.extend((str(folder / dest), reason) for dest, reason in failed)
transferred += progress.transferred()
seconds += progress.elapsed()
if interrupted:
break
if args.check:
if pending:
print("\n" + _check_fetch_line(pending, "its folder"))
sys.exit(3)
return True
if args.dry_run:
return True
_report_outcome(
[folder for folder, _entries in plan], downloaded, up_to_date_count, errors,
0, interrupted,
details=OutcomeDetails(failures=failures, transferred=transferred, seconds=seconds),
term=term,
)
return True
def _print_standalone_note(entry: dict, os_type: str) -> None:
"""A note entry's message, said when its emulator is found here."""
detect_paths = entry.get("detect", {}).get(os_type, [])
if not detect_paths and os_type == "wsl":
detect_paths = entry.get("detect", {}).get("linux", [])
for dp in detect_paths:
expanded = Path(os.path.expandvars(os.path.expanduser(dp)))
if _is_dir(expanded):
print(f" {entry['note']}")
break
def _standalone_sources(entry: dict, bios_path: Path) -> list[Path]:
"""The files of the BIOS folder a standalone copy entry copies."""
from fnmatch import fnmatch
if "pattern" in entry:
# A kept file is never a source, when the backup had to go
# inside the BIOS folder.
return [
f for f in bios_path.rglob("*")
if fnmatch(f.name, entry["pattern"]) and f.is_file()
and BACKUP_DIR not in f.relative_to(bios_path).parts
]
# `source` is where this platform's manifest put the file, and `file`
# names it as the registry does for every platform, and laid out
# that way it was missing wherever the pack places it elsewhere.
src = _destination_path(bios_path, entry.get("source") or entry["file"])
return [src] if _exists(src) else []
def _copy_standalone_file(src: Path, dest: Path, resolved_dir: Path,
failures: list[tuple[str, str]] | None) -> bool:
"""Copy one file into an emulator folder, False when it was refused."""
linked = dest.is_symlink()
# A crafted source name would climb out of the directory.
if not linked and not _within(dest, resolved_dir):
print(f" ERROR: {dest}: {OUTSIDE_TARGET}")
if failures is not None:
failures.append((str(dest), OUTSIDE_TARGET))
return False
try:
KEPT.keep(resolved_dir, PurePosixPath(dest.name), dest, {}, src)
except _NotKept as exc:
print(f" ERROR: {dest}: {NOT_KEPT} ({exc})")
if failures is not None:
failures.append((str(dest), f"{NOT_KEPT} ({exc})"))
return False
try:
if linked:
# Writing through a link already at the name would
# leave the folder the user opted into. The link
# itself gives way to the file.
_replace_with_copy(src, dest)
print(f" {dest}: link replaced by the file")
else:
shutil.copy2(src, dest)
except OSError as exc:
print(f" ERROR: {dest}: {exc.strerror or exc}")
if failures is not None:
reason = NOT_WRITABLE if _write_refused(exc) else str(
exc.strerror or exc)
failures.append((str(dest), reason))
return False
return True
def do_standalone_copies(
manifest: dict, bios_path: Path, os_type: str,
extra_dirs: dict[str, Path] | None = None,
failures: list[tuple[str, str]] | None = None,
) -> tuple[int, int, int]:
"""Copy BIOS files to standalone emulator directories.
Supports:
- file: single file copy
- pattern: glob match (e.g. "scph*.bin")
- note: informational message when detect path exists
- WSL fallback to linux targets
extra_dirs maps the emulator id of an entry to a root that replaces the
default per-OS locations, for setups such as LaunchBox that keep their
emulators outside them. The layout below the root is the same.
Returns (copied, skipped, failed): skipped is a target directory that
does not exist, failed a copy the system refused (permission, disk
full, read-only mount) or a name leading out of the folder, which used
to be counted as "dir not found". A link already at a file's name is
replaced by the file, never written through.
Each failure is also appended to failures, by absolute path, for the
summary to name.
"""
copies = manifest.get("standalone_copies", [])
if not copies:
return 0, 0, 0
copied = 0
skipped = 0
failed = 0
for entry in copies:
# Note entries: print message if emulator detected
if "note" in entry:
_print_standalone_note(entry, os_type)
continue
sources = _standalone_sources(entry, bios_path)
if not sources:
continue
for target_dir in _copy_targets(entry, os_type, extra_dirs):
closed = _closed_to_this_user(target_dir)
if closed is not None:
# Android 11 and later keep each app's Android/data folder
# to that app, there or not: Termux cannot copy Dolphin's
# IPL.bin there, and cannot tell whether Dolphin is installed.
print(f" {target_dir}: {unreachable_words(closed)}, not copied")
skipped += len(sources)
continue
if not _is_dir(target_dir):
skipped += len(sources)
continue
resolved_dir = target_dir.resolve()
for src in sources:
dest = target_dir / (entry.get("as") or src.name)
if _copy_standalone_file(src, dest, resolved_dir, failures):
copied += 1
else:
failed += 1
return copied, skipped, failed
OUTSIDE_TARGET = "name leads outside the emulator folder"
+320
View File
@@ -0,0 +1,320 @@
"""What a check counts, and the files a list leaves out, in words and in events."""
from __future__ import annotations
import platform
from collections.abc import Iterable
from pathlib import Path
from typing import NamedTuple
from installer.constants import CATEGORY_LABELS, GAME_DATA, OMISSION_REASONS, OTHER_SYSTEMS
from installer.cores import entry_systems
from installer.detect_os import _parse_os_release
from installer.embedded import display_name
from installer.events import EVENTS
from installer.local_files import _classify_local
from installer.narrowing import _settle_slot
from installer.paths import _entry_path
from installer.text import _plural, format_size
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()
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:
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 "")
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:
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)
def declared_copy(entry: dict) -> dict:
"""The copy the platform's own list checks at a platform file's slot.
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.
"""
recorded = entry.get("declared_copy")
if recorded is not None:
return recorded
declared = entry.get("declared_choices")
if declared:
return declared[0]
return entry
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
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 _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 _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)]
# What game data is, said wherever it is counted or chosen.
GAME_DATA_WORDS = "game data: files a game or a game engine reads, of no use to the other cores"
# The third kind: the files of an emulator's data folder (a data_directories
# entry of the list), apart from BIOS files and game data.
DATA_FILES_WORDS = ("data files: the files an emulator reads from a data folder of its own, "
"such as Dolphin's Sys and PPSSPP's assets")
+508
View File
@@ -0,0 +1,508 @@
"""Colours, the progress line and the terminal facts the output depends on."""
from __future__ import annotations
import os
import re
import shutil
import sys
import threading
import time
from collections.abc import Mapping
from pathlib import Path
from typing import Any, TextIO
from installer.events import EVENTS
from installer.text import format_size
def _kernel32() -> Any:
"""kernel32 from ctypes.windll, which typeshed declares for win32 only.
AttributeError where the system has no windll."""
import importlib
return importlib.import_module("ctypes").windll.kernel32
def _enable_ansi() -> bool:
"""Whether escape sequences reach the terminal as colour and redraws.
Windows 10 consoles interpret them once virtual terminal processing is
switched on. Older ones print them raw, so the answer is then no.
"""
if os.name != "nt":
return True
try:
import ctypes
kernel32 = _kernel32()
handle = kernel32.GetStdHandle(-11)
mode = ctypes.c_uint32()
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
return False
return bool(kernel32.SetConsoleMode(handle, mode.value | 0x0004))
except (AttributeError, OSError):
return False
# The roles text is painted with, from the 16 basic colours only: a
# handheld's Linux console has no more. The screens and the line questions
# name a role, never a code. Magenta is the hue that stays legible on black
# and on white in the xterm, VGA, Tango and Campbell palettes, so it is the
# accent, bold. Yellow reads poorly on white: it paints a status word, never
# a sentence. Bold red is bright red on the Linux console, where plain red on
# black is the weakest pair.
COLOUR_ROLES = {
"accent": "1;35",
"success": "32",
"warning": "33",
"failure": "1;31",
"muted": "2",
"strong": "1",
# The accent reversed: the row in focus, its > kept for no colour.
"selected": "7;35",
}
# The words a status takes its role from, wherever it is said. A count of
# zero is no news and stays plain: "0 missing" is not a warning.
_STATUS_WORDS = tuple((re.compile(pattern), role) for pattern, role in (
(r"(?<!of )\b[1-9][\d,]* (?:files? )?(?:installed|in place|already in place"
r"|ok|copied|downloaded)\b|\bDone\b|\bEvery file on the list is in place\b|^ *ok\b", "success"),
(r"(?<!of )\b[1-9][\d,]* (?:files? )?(?:failed|refused)\b|\bFAILED\b|\bfailed:"
r"|\bFinished with errors\b|\bNothing was installed\b|\bSomething went wrong\b",
"failure"),
(r"(?<!of )\b[1-9][\d,]* (?:files? )?(?:(?:still )?missing|wrong cop(?:y|ies)|not fetched"
r"|left out|not downloaded)\b|\bFinished with files missing\b|\bNothing installed\b"
r"|\bStopped\b|\bLeft out\b|\bNot enough space\b", "warning"),
))
def _apart(spans: list[tuple[int, int, str]]) -> list[tuple[int, int, str]]:
"""The spans in order, none empty, the longer kept where two overlap."""
kept: list[tuple[int, int, str]] = []
for span in sorted(spans, key=lambda span: (span[0], -span[1])):
if span[1] > span[0] and (not kept or span[0] >= kept[-1][1]):
kept.append(span)
return kept
def status_spans(text: str) -> list[tuple[int, int, str]]:
"""(start, end, role) of the status words in text, in order, apart."""
return _apart([(match.start(), match.end(), role) for pattern, role in _STATUS_WORDS
for match in pattern.finditer(text)])
def _sgr(role: str) -> str:
"""The SGR sequence of a role, or of roles joined by + ("strong+success")."""
return "\033[0;" + ";".join(COLOUR_ROLES[name] for name in role.split("+")) + "m"
def painted(text: str, spans: list[tuple[int, int, str]], base: str = "") -> str:
"""text with each span in its role and the rest in the base role, a code
written where the role changes and the colours reset at the end. The
characters are those of text, in the same order. A span in "plain"
takes the terminal's own colours."""
pieces: list[tuple[str, str]] = []
at = 0
for start, end, role in spans:
pieces += [(text[at:start], base), (text[start:end], role)]
at = end
pieces.append((text[at:], base))
out: list[str] = []
current = ""
for piece, role in pieces:
role = "" if role == "plain" else role
if not piece:
continue
if role != current:
out.append(_sgr(role) if role else "\033[0m")
current = role
out.append(piece)
if current:
out.append("\033[0m")
return "".join(out)
_SGR = re.compile(r"\x1b\[[0-9;]*m")
def unpainted(text: str) -> str:
"""text without its SGR codes."""
return _SGR.sub("", text)
class Terminal:
"""What the output stream can show: a live line, colour, or neither.
A pipe or a log gets plain lines, and NO_COLOR and TERM=dumb or unset are
honoured, as is a terminal whose description moves no cursor the ANSI way
(vt52), or names fewer than 8 colours (vt100), which keeps the line live
and plain.
As no-color.org reads it, an empty NO_COLOR is not set: `NO_COLOR= cmd`
turned colour off. FORCE_COLOR or CLICOLOR_FORCE paints a pipe, for a
log viewer that shows colour, and never makes the line live.
"""
def __init__(self, stream: TextIO | None = None, quiet: bool = False) -> None:
self.stream = stream or sys.stdout
self.quiet = quiet
isatty = getattr(self.stream, "isatty", None)
# An unset TERM is a dumb one, as the full screen reads it. A Windows
# console sets none and draws the sequences once _enable_ansi is on.
term = os.environ.get("TERM", "")
self.live = (bool(isatty and isatty()) and term != "dumb"
and (bool(term) or os.name == "nt")
and not terminal_without_ansi(os.environ))
forced = any(os.environ.get(name, "0") not in ("", "0")
for name in ("FORCE_COLOR", "CLICOLOR_FORCE"))
self.colour = (
((self.live and not terminal_few_colours(os.environ)) or forced)
and not os.environ.get("NO_COLOR") and _enable_ansi()
)
if not self.colour:
self.live = self.live and os.name != "nt"
def paint(self, text: str, role: str) -> str:
return f"\033[{COLOUR_ROLES[role]}m{text}\033[0m" if self.colour else text
def status(self, text: str) -> str:
"""text with its status words in their roles (status_spans)."""
return painted(text, status_spans(text)) if self.colour else text
def ok(self, text: str) -> str:
return self.paint(text, "success")
def bad(self, text: str) -> str:
return self.paint(text, "failure")
def dim(self, text: str) -> str:
return self.paint(text, "muted")
def bold(self, text: str) -> str:
return self.paint(text, "strong")
class _Output:
"""What a run's text says. By default: what will happen, where, the
progress, the result and the next step. --verbose adds every step, list
and reason, the lines a beginner lost the result among. where_said is
set once the BIOS folder was named before the result."""
verbose = False
where_said = False
OUTPUT = _Output()
def detail(*args: Any, **kwargs: Any) -> None:
"""Print a line only --verbose shows."""
if OUTPUT.verbose:
print(*args, **kwargs)
def format_duration(seconds: float) -> str:
"""0:42, 3:05 or 1:02:09."""
seconds = max(0, int(seconds + 0.5))
hours, rest = divmod(seconds, 3600)
minutes, secs = divmod(rest, 60)
return f"{hours}:{minutes:02}:{secs:02}" if hours else f"{minutes}:{secs:02}"
# The fewest columns a line question lays itself out in: below it a row is
# all number, and the terminal folds what is printed whatever it is.
LINE_MIN_COLS = 20
def terminal_size() -> tuple[int, int]:
"""(columns, lines) of the terminal line mode prints to, the one reading
every layout of it makes. Python 3.8 gives a pty of no size as 0 and 0,
where 3.11 falls back to 80 and 24: a list laid out in 0 columns never
ended, the plan printed an empty heading, and the progress line lost
every figure but its percentage."""
size = shutil.get_terminal_size((80, 24))
return max(size.columns or 80, LINE_MIN_COLS), size.lines or 24
class Progress:
"""Bytes and files across the parallel downloads, shown as they move.
On a terminal one line redraws in place: a bar, the bytes, the speed and
the time left. Elsewhere each finished file gets its line with --verbose,
as a log wants it. Failures are always printed, quiet or not.
"""
BAR = 24
def __init__(self, total_files: int, total_bytes: int, term: Terminal,
events: bool = True) -> None:
self.total_files = total_files
self.expected_bytes = total_bytes
self.total_bytes = max(total_bytes, 1)
self.term = term
self.files = 0
self.bytes = 0
self.resumed = 0
# Bytes that came from this machine and not the network: a copy
# found here, the pack, a resumed partial copy.
self.local = 0
# Files written to their place, which a stopped run counts: the
# queue's length said "118 files installed" over 8 on disk.
self.installed = 0
# The entries of those files, which the end of the run counts apart.
self.landed: list[dict] = []
self.start = time.monotonic()
self._drawn = 0.0
self._evented = self.start
self._lock = threading.Lock()
# A data tree's archive draws the line and writes no event: the
# progress events count the files of the download event.
self.events = events
def expect(self, total_bytes: int) -> None:
"""The size the transfer turns out to have, once its server says it."""
with self._lock:
self.expected_bytes = total_bytes
self.total_bytes = max(total_bytes, 1)
def add(self, count: int, resumed: bool = False, network: bool | None = None) -> None:
"""count bytes written, resumed ones left out of the speed. network
is whether they came over the network, by default unless resumed."""
with self._lock:
self.bytes += count
if resumed:
self.resumed += count
fetched = not resumed if network is None else network
if not fetched:
self.local += count
now = time.monotonic()
if self.term.live and not self.term.quiet and now - self._drawn >= 0.1:
self._drawn = now
self._draw()
if self.events and EVENTS.on and now - self._evented >= EVENT_PROGRESS_INTERVAL:
self._evented = now
EVENTS.emit("progress", files_done=self.files, files_total=self.total_files,
bytes_done=self.bytes, bytes_total=self.expected_bytes)
self.emit_transfer()
def emit_transfer(self) -> None:
"""The transfer event: of the bytes done, those this machine held
and those the network brought."""
EVENTS.emit("transfer", bytes_local=self.local,
bytes_network=self.bytes - self.local)
def forget_resumed(self, count: int) -> None:
with self._lock:
self.resumed -= count
self.local -= count
def transferred(self) -> int:
"""Bytes fetched by this run, a resumed partial copy excluded."""
return self.bytes - self.resumed
def done(self, dest: str, ok: bool, reason: str = "") -> None:
with self._lock:
self.files += 1
line = None
if not ok and not self.term.quiet:
why = f" ({reason})" if reason else ""
line = f" {self.term.bad('FAILED')} {dest}{why}"
SAID_FAILED.add(dest)
elif not self.term.live and not self.term.quiet and OUTPUT.verbose:
line = f" [{self.files}/{self.total_files}] {dest} {self.term.ok('ok')}"
if line is not None:
self._clear()
print(line, file=self.term.stream, flush=True)
if self.term.live and not self.term.quiet:
self._draw()
def finish(self) -> None:
with self._lock:
self._clear()
def elapsed(self) -> float:
return time.monotonic() - self.start
def _clear(self) -> None:
if self.term.live and not self.term.quiet:
print("\r\033[K", end="", file=self.term.stream, flush=True)
def _draw(self) -> None:
share = min(self.bytes / self.total_bytes, 1.0)
elapsed = self.elapsed()
# A resumed partial copy was on disk before the run started: counted
# in the share, never in the speed.
speed = self.transferred() / elapsed if elapsed > 0 else 0
left = (self.total_bytes - self.bytes) / speed if speed > 0 else 0
# Copies from a folder here count in no speed: "0 B/s 0:00 left"
# was drawn under them, as the screen does not.
timed = [f"{format_size(int(speed))}/s", f"{format_duration(left)} left"] \
if self.transferred() > 0 else []
parts = [
f"{share * 100:5.1f}%",
f"{format_size(self.bytes)} / {format_size(self.total_bytes)}",
*timed,
f"({self.files}/{self.total_files} files)",
]
# One physical line, whatever the width: \r\033[K clears only the
# line the cursor is on, so a wrapped line left a ghost per redraw
# on an 80-column console. The bar gives way first, then the least
# telling figures.
width = terminal_size()[0] - 1
while True:
tail = " ".join(parts)
room = width - len(tail) - 6
if room >= 10 or len(parts) == 1:
break
parts.pop()
if room >= 10:
bar_width = min(self.BAR, room)
filled = int(share * bar_width)
text = f" [{'#' * filled}{'-' * (bar_width - filled)}] {tail}"
else:
text = f" {tail}"
print(f"\r\033[K{text[:width]}", end="", file=self.term.stream, flush=True)
# --events: one JSON object per line on stdout, for a program driving the
# installer (the handheld port shows its screens from them). Each kind has
# exactly these keys besides "event", in this order, and nothing else.
EVENT_SCHEMA = 1
# Seconds between two progress events while bytes arrive.
EVENT_PROGRESS_INTERVAL = 0.5
# The files a FAILED line of the progress named in this run: the end of
# the run names the others.
SAID_FAILED: set[str] = set()
# Where ncurses finds a terminal's compiled description after $TERMINFO,
# ~/.terminfo and $TERMINFO_DIRS.
_TERMINFO_DIRS = ("/etc/terminfo", "/lib/terminfo", "/usr/share/terminfo",
"/usr/lib/terminfo", "/usr/share/lib/terminfo")
# cursor_address, string capability 10 of term(5).
_TERMINFO_CUP = 10
# max_colors, numeric capability 13.
_TERMINFO_COLORS = 13
def _terminfo_folders(env: Mapping[str, str]) -> list[Path]:
folders = [Path(env["TERMINFO"])] if env.get("TERMINFO") else []
if env.get("HOME"):
folders.append(Path(env["HOME"]) / ".terminfo")
# An empty entry stands for the system's folders, which come last anyway.
folders += [Path(part) for part in env.get("TERMINFO_DIRS", "").split(":") if part]
return folders + [Path(folder) for folder in _TERMINFO_DIRS]
def _terminfo_header(data: bytes) -> tuple[int, int, int, int, int] | None:
"""Of a compiled term(5) entry: the width of a number, the counts of
names bytes, booleans, numbers and strings. None when data is none."""
if len(data) < 12:
return None
# The legacy format stores numbers in 2 bytes, the extended one in 4.
width = {0o432: 2, 0o1036: 4}.get(int.from_bytes(data[0:2], "little", signed=True))
if width is None:
return None
names, bools, numbers, strings = (int.from_bytes(data[at:at + 2], "little", signed=True)
for at in (2, 4, 6, 8))
return width, names, bools, numbers, strings
def terminfo_number(data: bytes, index: int) -> int | None:
"""Numeric capability index of a compiled term(5) entry, -1 when the
entry lacks it, None when data is no compiled entry."""
header = _terminfo_header(data)
if header is None:
return None
width, names, bools, numbers, _strings = header
if index >= numbers:
return -1
start = 12 + names + bools
start += start % 2 + index * width
if start + width > len(data):
return None
value = int.from_bytes(data[start:start + width], "little", signed=True)
return value if value >= 0 else -1
def terminfo_string(data: bytes, index: int) -> str | None:
"""String capability index of a compiled term(5) entry, "" when the
entry lacks it, None when data is no compiled entry."""
def short(at: int) -> int:
return int.from_bytes(data[at:at + 2], "little", signed=True)
header = _terminfo_header(data)
if header is None:
return None
width, names, bools, numbers, strings = header
offsets = 12 + names + bools
offsets += offsets % 2 + numbers * width
if index >= strings:
return ""
at = short(offsets + 2 * index)
if at < 0:
return ""
start = offsets + 2 * strings + at
end = data.find(b"\0", start)
if end < 0:
return None
return data[start:end].decode("latin-1")
def _terminfo_data(term: str, env: Mapping[str, str]) -> bytes | None:
"""TERM's compiled description, the first found, None when none is:
Windows, Android and many handheld images carry none."""
if not term or "/" in term or term.startswith("."):
return None
for folder in _terminfo_folders(env):
# Linux files xterm under x/, macOS under 78/.
for sub in (term[0], f"{ord(term[0]):02x}"):
try:
return (folder / sub / term).read_bytes()
except (OSError, ValueError):
continue
return None
def terminal_cursor_address(term: str, env: Mapping[str, str]) -> str | None:
"""How TERM's description here moves the cursor, "" when it cannot,
None when no description is found, and the screen is not held back
for it."""
data = _terminfo_data(term, env)
return None if data is None else terminfo_string(data, _TERMINFO_CUP)
def terminal_colours(term: str, env: Mapping[str, str]) -> int | None:
"""The colours TERM's description here names, 0 when it names none
(vt100), None when no description is found or it cannot be read."""
data = _terminfo_data(term, env)
if data is None:
return None
count = terminfo_number(data, _TERMINFO_COLORS)
return None if count is None else max(count, 0)
def terminal_few_colours(env: Mapping[str, str]) -> str:
"""Why TERM's description here leaves colour off, "" when it does not:
no description is no refusal, as for the cursor."""
if os.name == "nt":
return ""
term = env.get("TERM", "")
count = terminal_colours(term, env)
if count is not None and count < 8:
return f"TERM={term} names {count} colours, fewer than 8"
return ""
def terminal_without_ansi(env: Mapping[str, str]) -> str:
"""Why TERM's description here says the ANSI sequences the screen and
the progress line write would print as text, "" when it does not."""
if os.name == "nt":
return ""
term = env.get("TERM", "")
cup = terminal_cursor_address(term, env)
if cup == "":
return f"TERM={term} cannot move the cursor"
if cup is not None and not cup.startswith(("\x1b[", "\x9b")):
return f"TERM={term} does not take the escape sequences the screen is drawn with"
return ""
+281
View File
@@ -0,0 +1,281 @@
"""Counts, sizes and words wrapped to the width of a line or a cell."""
from __future__ import annotations
import re
import unicodedata
from installer.invocation import _INVOCATION
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
File diff suppressed because it is too large. Load diff
+648
View File
@@ -0,0 +1,648 @@
"""The result, removal, pack and help screens, and the view that draws every screen."""
from __future__ import annotations
import textwrap
from collections.abc import Callable
from pathlib import Path
from installer.embedded import display_name, shown_path
from installer.line_ui import TUI_MIN_COLS, _pad
from installer.outcome import _SHORT_DEFINITIONS
from installer.removal import backup_words
from installer.run import TUI_MAX_WIDTH, TUI_MIN_ROWS
from installer.setups import TuiRow
from installer.text import _plural, _wrap, cell_width, fit, format_size
from installer.tui_rows import _CHECKLISTS, _PAGERS, _push, _replace, tui_rows
from installer.tui_state import TUI_PAD_ROUTES, TUI_ROUTES, TuiState, _removing_misplaced
from installer.tui_text import TuiKey, _details, _short_path, _styled
from installer.tui_view import (
TUI_LONG_LIST,
_ROW_VERBS,
_armed,
_back_hint,
_compose,
_hint,
_pager,
_pager_items,
_removal_text,
_route_hint,
_screen_definition,
_scroll,
_scrolled,
_shown,
_status_footer,
_tap_hint,
_text_lines,
_view_browse,
_view_cardroot,
_view_checking,
_view_command,
_view_confirm,
_view_cores,
_view_create,
_view_device,
_view_emulators,
_view_folder,
_view_games,
_view_installing,
_view_misplaced,
_view_options,
_view_path,
_view_plan,
_view_platforms,
_view_preview,
_view_regions,
_view_setup,
_view_systems,
_view_unreadable,
armed_words,
tui_action_outcome,
tui_outcome,
)
def _fail(state: TuiState, lines: list[str], code: int) -> list[tuple]:
state.error_title = ""
state.error = [line for line in lines if line.strip()] or [
f"The installer stopped with code {code} and said nothing."]
state.error_code = code or 1
state.running = False
_replace(state, "error")
return []
def _only_match(state: TuiState) -> TuiRow | None:
"""The one setup the filter leaves, when it leaves one."""
if state.screen != "platforms" or not state.filters.get("platforms"):
return None
rows = [row for row in tui_rows(state) if row.action != "filter"]
return rows[0] if len(rows) == 1 else None
def _armed_hint(state: TuiState, parts: tuple, width: int) -> tuple:
"""The bar with the entry a first tap armed saying that a second one
presses it, in the longest words the bar keeps whole: at 40 columns
"click or tap again" was cut inside its last word, and the bar's B
went with it."""
key = _armed(state)
if key is None:
return parts
at = next((index for index, part in enumerate(parts) if " " in part
and _bar_click(state, part.split(" ", 1)[0]) == key), None)
if at is None:
return parts
part = parts[at]
verb = part.split(" ", 1)[1]
said = armed_words(state, width)
forms = (f"{part}: {said}",
f"{part.split(' ', 1)[0]} {' '.join(verb.split()[:3])}: {said}")
# Every entry kept first, then every one but the help, then the armed
# one whole: on a phone at 40 columns Esc Quit went first.
for keep in (len(parts), len([p for p in parts if not p.startswith("? ")]), 1):
for form in forms:
armed = (*parts[:at], form, *parts[at + 1:])
drawn = _hint(width, *armed)
if form.split(" ", 1)[1] in drawn and len(drawn.split(" ")) >= keep:
return armed
return (*parts[:at], forms[-1], *parts[at + 1:])
def _view_result(state: TuiState, width: int, height: int) -> tuple:
title, lines = tui_outcome(state)
lines = _shown(state, lines)
# The outcome in bold, its counts in their roles: it led a list of
# lines drawn alike.
lines[0] = _styled(lines[0], "title")
rows = tui_rows(state)
if rows:
focused = rows[max(0, min(state.focus.get(state.screen, 0), len(rows) - 1))]
# Exit in focus: A says it, and B saying it again named one action
# twice.
return (title, _compose(state, width, height, lines, rows),
("A/Enter Choose",) if focused.action == "exit"
else ("A/Enter Choose", "B/Esc Exit"))
if state.app_running:
return (title, _pager(state, width, height, lines), ("Writing to the card...",))
return (title, _pager(state, width, height, lines),
("A/Enter Exit", "Y/o Details", *_scroll(state, lines, width, height)))
def _view_error(state: TuiState, width: int, height: int) -> tuple:
"""The message and its rows. A message longer than the room the rows
leave scrolls, with a line saying which lines are in view: at 40x12 the
offline screen dropped its remedy without a word."""
rows = tui_rows(state)
text = _text_lines(list(state.error), width)
room = height - len(rows) - (1 if rows else 0)
hint: tuple = ("A/Enter Choose", "B/Esc Back")
if len(text) > room >= 2:
first = max(0, min(state.focus.get("error_text", 0), len(text) - (room - 1)))
state.focus["error_text"] = first
text = _scrolled(text, first, room)
text[-1].mark = ("scroll", "error", 0)
page = (TUI_ROUTES.get(state.pad, TUI_ROUTES["both"]).help["page"]
or "PgUp/PgDn").split(", ")[0]
hint += (f"{page} Scroll",)
return (state.error_title or "Something went wrong",
_compose(state, width, height, text, rows), hint)
def _view_quit(state: TuiState, width: int, height: int) -> tuple:
rows = tui_rows(state)
focus = max(0, min(state.focus.get("quit", 0), len(rows) - 1))
# On Stay, A says Stay: a second "B/Esc Stay" beside it named one choice
# twice.
hint = (("A/Enter Choose",) if rows[focus].action == "stay"
else ("A/Enter Choose", "B/Esc Stay"))
return ("Quit?",
_compose(state, width, height, ["Quit without installing? Nothing was written."],
rows), hint)
def _view_details(state: TuiState, width: int, height: int) -> tuple:
items = _pager_items(state)
return ("Details", _pager(state, width, height, items),
("A/Enter Back", *_scroll(state, items, width, height)))
def _open_details(state: TuiState) -> list[tuple]:
if state.screen == "result":
# Looked at, they are said again in the terminal after Exit.
state.details_seen = True
return _push(state, "details")
def _take_action_event(state: TuiState, event: dict) -> bool:
"""An event of a More run, kept for its screen: whether it was one."""
kind = event.get("event")
if kind == "pack" and state.run == "pack_plan":
state.pack_plan = event
elif kind == "pack" and state.run == "pack":
state.pack_done = event
elif kind in ("progress", "downloaded") and state.run == "pack":
state.pack_fetched = (int(event["files_done"]), int(event["files_total"]))
elif kind == "removal_plan" and state.run in ("removal_plan", "remove"):
state.removal = event
elif kind == "backup" and state.run == "backups":
state.backups = [*(state.backups or []), event]
elif kind in ("removed", "restored", "backup") and state.run in (
"remove", "restore", "delete_backup"):
state.action_events.append(event)
else:
return False
return True
def _action_ended(state: TuiState, code: int, tail: list[str]) -> list[tuple]:
"""A More run's end: the plan, the list, or what the action did."""
if state.run == "pack_plan":
return _fail(state, tail, code) if state.pack_plan is None else []
if state.run == "pack":
state.pack_code = code if code >= 0 else 128 - code
return []
if state.run == "removal_plan":
if state.removal is None:
return _fail(state, tail, code)
return []
if state.run == "backups":
if state.backups is None and code:
return _fail(state, tail, code)
state.backups = state.backups or []
return []
state.action_code = code if code >= 0 else 128 - code
return []
def _view_more(state: TuiState, width: int, height: int) -> tuple:
return ("More", _compose(state, width, height, [], tui_rows(state),
[], _status_footer(state)),
("A/Enter Open", "B/Esc Back", "? Help"))
def _view_remove(state: TuiState, width: int, height: int) -> tuple:
if state.record is None:
before = ["No install record here: no file is known to be the installer's, so "
"nothing is removed."]
else:
before = ["Choose what to remove. A file changed or added by hand stays."]
return ("Remove files", _compose(state, width, height, before, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def _view_removal(state: TuiState, width: int, height: int) -> tuple:
if state.running or state.removal is None:
return ("Remove files", _compose(state, width, height,
["Reading what can be removed..."], []),
("B/Esc Back", "? Help"))
lines = _shown(state, _removal_text(state))
lines = [piece for line in lines for piece in (
[_styled(part, "folder" if index else "") for index, part in enumerate(
_wrap(str(line), width, " "))]
if getattr(line, "style", "") == "path" and cell_width(str(line)) > width
else [line])]
return ("Remove files", _compose(state, width, height, lines, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def _view_backups(state: TuiState, width: int, height: int) -> tuple:
if state.running or state.backups is None:
return ("Backups", _compose(state, width, height, ["Reading the backups..."], []),
("B/Esc Back", "? Help"))
if not state.backups:
before = ["No backup of this folder."]
else:
before = [{"look": "Newest first.", "restore": "Choose the backup to put back.",
"delete_backup": "Choose the backup to delete."}[state.backups_for]]
return ("Backups", _compose(state, width, height, before, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def _view_backup(state: TuiState, width: int, height: int) -> tuple:
item = state.backup_chosen or {}
lines = [f"{backup_words(str(item.get('date', '')))}: "
f"{_plural(int(item.get('files', 0)), 'file')}, "
f"{format_size(int(item.get('bytes', 0)))}."]
return ("Backup", _compose(state, width, height, lines, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def _confirm_action_text(state: TuiState) -> list[str]:
if state.action == "remove":
plan = state.removal or {}
if _removing_misplaced(state):
return [f"Remove {_plural(plan.get('files', 0), 'copy')} in the wrong place for "
f"good? {format_size(plan.get('bytes', 0))} is freed. The files where "
"the cores read them stay."]
if state.removal_backup:
return [f"Move {_plural(plan.get('files', 0), 'file')} to a backup? The space "
"is freed once the backup is deleted."]
return [f"Remove {_plural(plan.get('files', 0), 'file')} for good? "
f"{format_size(plan.get('bytes', 0))} is freed."]
item = state.backup_chosen or {}
when = backup_words(str(item.get("date", "")))
if state.action == "restore":
return [f"Put back the {_plural(int(item.get('files', 0)), 'file')} of {when}? "
"Each one replaces the file at its place."]
return [f"Delete the backup of {when} for good? "
f"{format_size(int(item.get('bytes', 0)))} is freed."]
def _view_actconfirm(state: TuiState, width: int, height: int) -> tuple:
return ("Confirm", _compose(state, width, height, _confirm_action_text(state),
tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def tui_pack_text(state: TuiState) -> list:
"""The pack's plan: what goes in and its size, where, how many parts,
the part files behind Details."""
plan = state.pack_plan or {}
if plan.get("status") != "planned":
return [str(plan.get("message") or "No pack can be made of this choice.")]
parts = list(plan.get("parts") or [])
lines: list = [f"{_plural(int(plan['files']), 'file')}, "
f"{format_size(int(plan['bytes']))}, for "
f"{display_name(state.platform, state.manifest)}."]
shown = Path(str(parts[0] if parts else plan["path"]))
lines.append(_styled(f"Pack: {_short_path(shown, state.home)}", "path"))
lines.append(str(plan.get("message") or "")
if len(parts) > 1 else "One ZIP, installed with --from-pack.")
if len(parts) > 1:
lines += _details(["", "Parts:"] + [f" {Path(part).name}" for part in parts])
return lines
def tui_pack_outcome(state: TuiState) -> list:
"""What making the pack did, in one line, then where."""
done = state.pack_done or {}
if done.get("status") != "written":
lines: list = [_styled("No pack was made.", "failure")]
if done.get("message"):
lines.append(str(done["message"]))
lines += _details(list(state.tail))
return lines
parts = list(done.get("parts") or [])
lines = [f"Pack made: {_plural(int(done['files']), 'file')}, "
f"{format_size(int(done['size']))}"
+ (f", in {len(parts)} parts." if len(parts) > 1 else ".")]
shown = Path(str(parts[0] if parts else done["path"]))
lines.append(_styled(f"Pack: {_short_path(shown, state.home)}", "path"))
lines.append("On the other device, install from it with --from-pack.")
if len(parts) > 1:
lines += _details(["", "Parts:"] + [f" {Path(part).name}" for part in parts])
return lines
def _wrapped_paths(lines: list, width: int) -> list:
"""A path line too wide for the screen, folded over the next lines."""
return [piece for line in lines for piece in (
[_styled(part, "folder" if index else "") for index, part in enumerate(
_wrap(str(line), width, " "))]
if getattr(line, "style", "") == "path" and cell_width(str(line)) > width
else [line])]
def _view_packplan(state: TuiState, width: int, height: int) -> tuple:
if state.running or state.pack_plan is None:
return ("Make a pack", _compose(state, width, height,
["Reading what goes into the pack..."], []),
("B/Esc Back", "? Help"))
lines = _wrapped_paths(_shown(state, tui_pack_text(state)), width)
return ("Make a pack", _compose(state, width, height, lines, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
def _view_packdone(state: TuiState, width: int, height: int) -> tuple:
if state.running:
fetched = state.pack_fetched
words = (f"Making the pack: {fetched[0]} of {fetched[1]} files."
if fetched else "Making the pack...")
return ("Working", _compose(state, width, height, [words], []), ("B/Esc Stop",))
lines = _wrapped_paths(_shown(state, tui_pack_outcome(state)), width)
lines[0] = _styled(str(lines[0]), "title")
return ("Done" if state.pack_code == 0 else "Not done",
_compose(state, width, height, lines, tui_rows(state)),
("A/Enter Close", "B/Esc Back", "? Help"))
def _view_actdone(state: TuiState, width: int, height: int) -> tuple:
if state.running:
words = {"remove": "Removing the files...", "restore": "Putting the files back...",
"delete_backup": "Deleting the backup..."}[state.action]
return ("Working", _compose(state, width, height, [words], []), ("B/Esc Stop",))
lines = _shown(state, tui_action_outcome(state))
lines[0] = _styled(str(lines[0]), "title")
return ("Done" if state.action_code == 0 else "Not done",
_compose(state, width, height, lines, tui_rows(state)),
("A/Enter Choose", "B/Esc Back", "? Help"))
_TUI_VIEWS: dict[str, Callable[[TuiState, int, int], tuple]] = {
"setup": _view_setup, "platforms": _view_platforms, "folder": _view_folder,
"browse": _view_browse, "path": _view_path, "create": _view_create,
"checking": _view_checking, "plan": _view_plan, "systems": _view_systems,
"options": _view_options, "regions": _view_regions, "cores": _view_cores,
"preview": _view_preview, "command": _view_command, "confirm": _view_confirm,
"installing": _view_installing, "result": _view_result, "error": _view_error,
"quit": _view_quit, "cardroot": _view_cardroot, "misplaced": _view_misplaced,
"unreadable": _view_unreadable, "games": _view_games, "details": _view_details,
"device": _view_device, "emulators": _view_emulators, "more": _view_more,
"remove": _view_remove, "removal": _view_removal, "backups": _view_backups,
"backup": _view_backup, "actconfirm": _view_actconfirm, "actdone": _view_actdone,
"packplan": _view_packplan, "packdone": _view_packdone,
}
def _route_extras(state: TuiState) -> list[tuple[str, str]]:
"""What a route's own buttons do that no key of the table says."""
if state.pad == "muxterm":
return [("Select", "Keyboard on or off"), ("Menu", "Close the terminal")]
if state.pad == "miyoo":
return [("B", "Sends no key here")]
return []
def _help_list_keys(state: TuiState, names: dict[str, str]) -> list[tuple[str, str]]:
"""The keys a screen's own list adds to the help: ticks, filters, order."""
screen = state.screen
keys: list[tuple[str, str]] = []
if screen in ("systems", "cores"):
keys.append(("a, n", "All, none"))
elif screen in ("regions", "emulators"):
keys.append(("n", "None"))
if screen == "platforms":
keys.append(("/", "Filter by setup or device name"))
elif screen in _CHECKLISTS:
keys.append(("/", "Filter"))
if screen in ("platforms", *_CHECKLISTS) and state.filters.get(screen):
keys.append((names["esc"], "Clear the filter"))
if screen == "regions":
keys.append(("Left/Right", "Move a region up or down the order"))
if screen == "options":
keys.append(("Left/Right", "Change a value"))
if screen in ("plan", "systems", "confirm"):
keys.append((names["options"], "Change"))
if screen in ("plan", "confirm"):
keys.append(("d", "Details"))
elif screen == "result" and not tui_rows(state):
keys.append((f"{names['options']}, d" if names["options"] else "d", "Details"))
return keys
def _help_lines(state: TuiState) -> list[tuple[str, str]]:
screen = state.screen
names = {action: name or "" for action, name in
TUI_ROUTES.get(state.pad, TUI_ROUTES["both"]).help.items()}
# gptokeyb's kill: Start pressed first also chooses the row in focus.
kill = ([(names["kill"], "Quit at once")]
if state.pad in ("gptokeyb", "gptokeyb_muxterm") else [])
if screen == "installing":
return [(names["stop"], "Stop: what is done stays done"),
*([(names["kill"], "Stop")] if names["kill"] else []),
*_route_extras(state), *_help_key(state)]
if state.editing:
# Typing a filter: Space, a, n and q type there, and the help listed
# them as ticks, all, none and quit.
return [("Enter", "Done"), ("Esc", "Clear the filter"),
("Backspace", "Delete a character"), ("Ctrl-U", "Clear"), ("Ctrl-C", "Quit"),
*_route_extras(state)]
if screen == "path":
return [(names["enter"], "Use this folder"), ("Backspace", "Delete a character"),
("Ctrl-U", "Clear"), (names["esc"], "Back"), ("Ctrl-C", "Quit"),
*_route_extras(state)]
keys = [(names["move"], "Move")]
if len(tui_rows(state)) > TUI_LONG_LIST or screen in _PAGERS:
keys += [*([(names["page"], "Page")] if names["page"] else []),
*([("Home/End, g/G", "First, last")] if state.pad in ("both", "keys")
else [])]
primary = _primary(state) or _TUI_VIEWS[screen](state, 80, 24)[2][0]
ok = names["ok"]
if primary.startswith("A/"):
# A bar that offers no A (Confirm while it counts) names none here.
keys.append((ok, primary.split(" ", 1)[-1]))
if screen in _CHECKLISTS:
keys.append((names["tick"], "Tick, untick"))
# How a tap acts, before what the list says elsewhere: last, it was the
# line a 40x12 help cut.
keys += _tap_help(state)
keys += _help_list_keys(state, names)
# The result's bar calls B Exit: the help called it Quit.
back = "Exit" if screen == "result" else "Quit" if len(state.stack) == 1 else "Back"
keys += [(names["back"], back), ("q, Ctrl-C", "Quit"), *kill, *_route_extras(state),
*_help_key(state)]
return keys
def _tap_help(state: TuiState) -> list[tuple[str, str]]:
"""How a tap acts on this screen, where the terminal reports clicks."""
if not state.mouse:
return []
if state.screen in (*_CHECKLISTS, "regions"):
# One rule for the three lists of ticks: A ticks, a tap as A.
return [("Tap", "Tick or untick a row, as A")]
if state.screen in _PAGERS and not tui_rows(state):
return [("Tap", "A bottom line entry presses its key"),
*([("Shift+drag", "Select text to copy")] if state.screen == "result"
and state.os_type != "android" and state.pad not in TUI_PAD_ROUTES
else [])]
# Said at every size, 40x12 included: Install below waits for a second
# tap, and the help is where a reader looks when nothing happened.
armed = [row.action for row in tui_rows(state) if row.action in ("install", "addapp")]
if state.screen == "plan" and "install" in armed:
return [("Tap", "A row or Install: click or tap twice")]
if state.screen == "result" and armed:
return [("Tap", "A row or Put it on the card: tap twice")]
return [("Tap", "A row: tap twice to open it")]
def _help_key(state: TuiState) -> list[tuple[str, str]]:
"""? and F1, named only where a keyboard may send them: no pad route
maps a button to either."""
return [("?, F1", "This help")] if state.pad in ("both", "keys") else []
def _primary(state: TuiState) -> str | None:
"""What A does on the row in focus, for the first entry of the bar."""
rows = tui_rows(state)
if not rows:
return None
row = rows[max(0, min(state.focus.get(state.screen, 0), len(rows) - 1))]
verb = _ROW_VERBS.get(row.action)
if row.action == "filter" and _only_match(state) is not None:
verb = "Choose"
if row.action == "zip" and state.browse_for == "pack":
verb = "Use this pack"
return f"A/Enter {verb}" if verb else None
def _view_help(state: TuiState, width: int, height: int) -> tuple:
keys = _help_lines(state)
column = min(22, max(cell_width(key) for key, _what in keys) + 2)
def drawn(entries: list[tuple[str, str]]) -> list[str]:
# Two spaces at least: a key as wide as the column touched its text
# ("Select Keyboard on or off" on muxterm).
lines = []
for key, what in entries:
if cell_width(key) > column - 2:
lines.append(f"{key} {what}")
continue
# Wrapped under its own column: wrapped by the screen, a long text
# ran back to the left edge ("/ Filter (Esc clears)" at 40x12).
words = textwrap.wrap(what, max(8, width - column)) or [""]
lines.append(f"{_pad(key, column)}{words[0]}")
lines += [" " * column + word for word in words[1:]]
return lines
extra = []
if state.screen in ("setup", "plan", "browse", "folder") and state.dest is not None:
extra = ["", f"BIOS folder: {shown_path(state.dest)}"]
more = ["", state.status_more] if state.status_more else []
# What the plan's kinds are: at 40 columns the plan has no room for the
# sentence, and the game data row was a choice nothing explained
# Said before the keys a list also says elsewhere.
words = _screen_definition(state)
defined = ["", *textwrap.wrap(words, width)] if words else []
# Cut from its end at 40x12, the help lost Quit and This help with no
# sign: what a list's keys also say elsewhere goes first.
for spare in ("First, last", "All, none", "extra", "Filter by setup or device name",
"Filter", "Change", "Details", "This help", "gap", "definitions"):
if (len(drawn(keys)) + len(extra) + len(defined)
+ len(_text_lines(more, width)) <= height):
break
if spare == "extra":
extra = []
elif spare == "gap":
# The blank line before the definitions, before a definition
# is shortened: the Tap line that says Install takes a second
# tap is kept at every size.
defined = defined[1:] if defined[:1] == [""] else defined
elif spare == "definitions":
# The short form at 40x12, whole: the long one was cut in the
# middle of its second sentence.
short = [brief for long_form, brief in _SHORT_DEFINITIONS if long_form in words]
room = height - len(drawn(keys)) - len(extra) - len(_text_lines(more, width))
# Still too long: a definition left out whole, never cut in a
# sentence.
while len(short) > 1 and len(textwrap.wrap(" ".join(short), width)) > room:
short.pop()
defined = textwrap.wrap(" ".join(short), width) if short else []
else:
keys = [entry for entry in keys if entry[1] != spare]
return ("Keys", _compose(state, width, height, drawn(keys) + defined + extra + more, []),
("Any key or a tap closes this help" if state.mouse
else "Any key closes this help",))
def tui_view(state: TuiState, cols: int, rows: int) -> list[str]:
"""The screen as rows lines of at most cols cells, from the state alone."""
if cols < TUI_MIN_COLS or rows < TUI_MIN_ROWS:
# How large, and how large it is now: "larger" alone left the
# reader resizing by guess.
lines: list[str] = [_styled("")] * rows
said = [fit(text, cols) for text in (
"Make the window larger:",
f"{TUI_MIN_COLS}x{TUI_MIN_ROWS} or more, now {cols}x{rows}")][:rows]
top = max(0, (rows - len(said)) // 2)
for index, text in enumerate(said):
lines[top + index] = _styled(" " * max(0, (cols - cell_width(text)) // 2) + text)
return lines
width = min(cols, TUI_MAX_WIDTH) - 2
height = rows - 3
view = _view_help if state.help else _TUI_VIEWS[state.screen]
title, body, hint = view(state, width, height)
primary = _primary(state) if not state.help and hint[0].startswith("A/Enter") else None
if primary:
hint = (primary, *hint[1:])
if state.editing == state.screen and not state.help:
# Typing: Space and ? go into the filter, so the bar names the two
# keys that end it, not Tick and Help.
hint = ("Enter Done", "Esc Clear")
routed = _route_hint(state, _back_hint(state, hint), width)
tapped = _tap_hint(state, routed)
if (tapped != routed and "? Help" in _hint(width, *routed)
and "? Help" not in _hint(width, *tapped)):
# At 40 columns "/tap" pushed "? Help" off the bar: the help, which
# says how a tap acts, keeps its entry.
tapped = routed
hint = _armed_hint(state, tapped, width)
lines = [_styled(fit(f" RetroBIOS: {title}", cols), "head"), _styled("")]
# A long line is drawn whole, the terminal folding it into the rows
# after it (_text_lines): cut to the width, a copied path lost its end.
for line in body[:height]:
drawn = _styled(" " + line if line.style == "long" else fit(" " + line, cols),
line.style)
drawn.mark = line.mark
drawn.command = getattr(line, "command", False)
lines.append(drawn)
lines += [_styled("")] * (rows - 1 - len(lines))
# Never the last cell of the screen: a terminal may scroll when it is written.
bar = _styled(fit(" " + _hint(width, *hint), cols - 1), "hint")
bar.mark = ("bar",)
lines.append(bar)
return lines
# The keys the bar's entries name, as a click on the entry presses them. A
# pair of keys (Left/Right, PgUp/PgDn) is no button: which one is meant
# cannot be told.
_BAR_CLICKS = {
"A/Enter": TuiKey("enter"), "A": TuiKey("enter"), "Enter": TuiKey("enter"),
"Start": TuiKey("enter"), "B/Esc": TuiKey("esc"), "B": TuiKey("esc"),
"Esc": TuiKey("esc"), "X/Space": TuiKey("char", " "), "X": TuiKey("char", " "),
"Space": TuiKey("char", " "), "Y/o": TuiKey("char", "o"), "Y": TuiKey("char", "o"),
"o": TuiKey("char", "o"), "/": TuiKey("char", "/"), "Ctrl-U": TuiKey("ctrl-u"),
"X/Space/tap": TuiKey("char", " "), "X/tap": TuiKey("char", " "),
"Space/tap": TuiKey("char", " "), "A/Enter/tap": TuiKey("enter"), "A/tap": TuiKey("enter"),
"Ctrl-C": TuiKey("ctrl-c"),
# F1 and not ?, which the path screen types into the path.
"?": TuiKey("f1"),
}
def _bar_click(state: TuiState, name: str) -> TuiKey | None:
"""The key a bar entry's name stands for, on the route the bar names."""
route = TUI_ROUTES.get(state.pad)
if route is not None and name not in _BAR_CLICKS:
name = next((key for key, mine in route.bar.items() if mine == name), name)
return _BAR_CLICKS.get(name)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+929
View File
@@ -0,0 +1,929 @@
"""The full-screen interface: its state, how it starts, and the runs it starts."""
from __future__ import annotations
import argparse
import io
import os
import re
import sys
import time
from collections.abc import Iterable, Mapping
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple, TextIO
from installer.app import CardApp, card_app
from installer.invocation import OFFLINE_VARIABLE, Invocation, offline_option
from installer.line_ui import TUI_MIN_COLS, emulator_names
from installer.narrowing import choosable_cores
from installer.offline import LOCAL, OFFLINE_FLAG_VALUE
from installer.probe import _is_dir
from installer.record import RECORD_NARROWING, record_argv, record_options
from installer.run import TUI_LIST_ENV, TUI_MIN_ROWS, TUI_MOUSE_ENV, TUI_RECORD_ENV
from installer.tally import leave_out_game_data
from installer.terminal import _enable_ansi, terminal_few_colours, terminal_without_ansi
from installer.text import screen_text
if TYPE_CHECKING:
from installer.tui_session import TuiHits
# Full-screen interface
#
# A bare run at a terminal opens it, and --tui asks for it. It decides and the
# installer acts: every check and install is this file run again as a child,
# with --events, the contract the handheld port reads, and the choices made on
# screen as its options. The line questions stay behind --plain, for screen
# readers and for any terminal this cannot drive. Stdlib only: curses is
# missing from Windows CPython and from some Buildroot images.
class TuiState:
"""Everything the screens show. Nothing here touches the terminal."""
def __init__(self, os_type: str = "linux", home: Path | None = None) -> None:
self.os_type = os_type
self.home = home or Path("/home/user")
# The buttons the bar names: a pad route (TUI_PAD_ROUTES), "keys"
# for a keyboard alone, "both" where the code cannot tell.
self.pad: str = "both"
self.stack: list = ["setup"]
self.focus: dict = {}
self.filters: dict = {}
self.editing: str = ""
self.help: bool = False
self.status: str = ""
# What the status says in full, shown under it where there is room
# and in the help: the folder refused and what was looked for.
self.status_more: str = ""
self.cols: int = 80
self.rows: int = 24
# A check started before the loop's first tick counted the
# machine's uptime.
self.now: float = time.monotonic()
# (platform, folder, label) for each setup found here.
self.setups: list = []
# (platform, card) of each mounted drive whose files fit two systems
# (share_doubt): offered under each, never taken for one.
self.doubts: list = []
# (platform, folder) of the setups that are a card in a reader, not
# this machine: a setup chosen for that system asks for its card.
self.mounted_setups: set = set()
self.notes: list = []
# The folders detection could not look in, one line each.
self.refused: list = []
self.platform: str = ""
self.dest: Path | None = None
# A --dest given without --platform: the list asks whose files go there.
self.dest_given: Path | None = None
self.folder_default: Path | None = None
# What folder_default is, for the words above it: "usual" (the
# platform's built-in folder), "found" (the one detected here),
# "chosen" (the run's folder, from Change folder) or "closed" (the
# one chosen could not be opened, none is offered).
self.folder_kind: str = "usual"
# (system, BIOS folder below the card root) when the setup asked for
# runs from an SD card: the folder screen offers the mounted cards.
self.card_bound: tuple[str, str] | None = None
# What card_choice said of the card chosen (a stick nothing names
# taken for KNULLI), kept from Create the folder? to the plan.
self.card_note: str = ""
# The rows the last view drew in its list, what a page moves by.
self.page_rows: int = 0
self._init_frame()
self._init_run()
self._init_install()
def _init_frame(self) -> None:
# The targets of the frame on screen (tui_hits), the target a
# button went down on, and per screen the first row of a list the
# wheel scrolled.
self.hits: TuiHits | None = None
self.pressed: tuple | None = None
# The row a tap last focused, with its screen and depth: a second
# tap on it opens it. A screen just opened has none, so the row it
# opens on is never chosen by one tap.
self.tapped: tuple | None = None
# Whether the terminal reports clicks here (tui_mouse_blocker): the
# help and the bar say how to tap only then.
self.mouse: bool = False
self.list_top: dict = {}
# The mounted cards of that system, as last looked for.
self.cards: list | None = None
# (width and text, lines) of the last pager wrapped.
self.pager_cache: tuple | None = None
self.path_text: str = ""
self.browse_dir: Path | None = None
self.browse_rows: list = []
self.manifest: dict | None = None
self.manifest_for: str = ""
self.manifest_path: Path | None = None
self.manifest_given: bool = False
self.error: list = []
self.error_title: str = ""
self.error_code: int = 1
# Typed over in one key: a field opening on a long path took one
# Backspace per character before anything could be typed.
self.path_selected: bool = False
# The ticks kept across a check run again for new options.
self.keep_ticked: set | None = None
# The regions in the order Preferred regions opened on: kept while
# it is open, whatever is ticked.
self.region_order: list[str] = []
# The cores of every system listed, after "Cores of the other systems".
self.cores_all: bool = False
# None pressed on Cores: no core ticked, which no option says
# (state.cores empty is every core). Done is refused until one is.
self.no_cores: bool = False
# The cores --core named, as line mode names them on its head.
self.cli_cores: list = []
# The names of the systems ticked before a check counted again, and
# those of them that hold nothing under its options.
self.ticked_names: dict[str, str] = {}
self.emptied: list[str] = []
# Systems ticked that the last check did not list, game data left
# out: still the choice, ticked again by the check that lists them
#, as line mode's g keeps its choice.
self.hidden_ticks: set[str] = set()
# Choose systems asked on a plan --system narrowed: the systems are
# opened once the check of every system is in.
self.widen: bool = False
# The plan row a recount started from, focused again once it is in:
# the plan came back on Install, and a second Enter to undo the
# Game data change opened Confirm.
self.refocus: str = ""
# The --system plan Choose systems widened, by _CHECK_FIELDS.
self.widened_from: dict | None = None
# (files read, files to read) while the check hashes what is in place.
self.reading: tuple | None = None
# Folders to copy BIOS files from (--from), and what the check found.
self.from_folders: list = []
self.found: list = []
# What the browser is choosing: the BIOS folder, or one to copy from.
self.browse_for: str = "dest"
# Files an install copies from this machine, whose bytes are no
# download: dest to (folder, reason), reason set for a misplaced one.
self.local_dests: dict = {}
# Per --from folder, its scanned event, and the files on those
# folders that could not be read (unreadable events).
self.scanned: list = []
self.unreadable: list = []
def _init_run(self) -> None:
# The child run in progress: check, confirm, preview or install.
self.run: str = ""
self.running: bool = False
self.run_id: int = 0
self.started: float = 0.0
self.checked_flags: list = []
self.check: dict | None = None
# The systems the check's list lets one choose among (choices event).
self.choices: list | None = None
# The install's error event when its BIOS folder could not be made.
self.dest_error: dict | None = None
# The dests the check set aside before any choice (the set_aside
# event), None before it says: Cores chooses among the rest.
self.set_aside: set | None = None
# The run's file list and the Cores rows' sizes, kept while the
# list, the set aside files and the game data choice stay.
self.run_files_cache: tuple | None = None
self.core_sizes_cache: tuple | None = None
self.files: list = []
# Every destination the check named, in place or not: the second
# spellings a folder that keeps case installs are among them.
self.checked_dests: set = set()
self.systems: list = []
self.facts: dict = {}
self.dry: dict | None = None
self.dry_files: list = []
self.dry_summary: dict | None = None
# Closed by RETROBIOS_IDLE_EXIT, no key ever pressed.
self.idle_closed = False
# The check run's summary: what it left out and why.
self.check_summary: dict | None = None
# The saves event of the check: the files that go to the save folder.
self.saves: dict | None = None
# The version event of the check: the list built for another
# release than the one this machine runs, said on the plan and the
# result as line mode says it.
self.version: str = ""
# The note in one line, for a plan with no room for its sentences.
self.version_short: str = ""
# The board event of the check: the board read from the system or
# its card, said on the plan.
self.board: str = ""
# The same of the confirm or preview run, and of the install: a
# choice of systems can leave the save file out, or keep it.
self.dry_saves: dict | None = None
self.done_saves: dict | None = None
# The confirm screen waits for A even when the plan is unchanged:
# it was opened by Space, which never installs by itself.
self.must_confirm: bool = False
# Choices, each one an option of the command line.
self.ticked: set = set()
# The ticks the systems list opened with: Back with none ticked
# brings them back, nothing having been chosen.
self.ticked_before: set | None = None
self.cli_systems: list = []
self.regions: list = []
self.cli_regions: list = []
self.cores: list = []
self.no_game_data: bool = False
# --one-per-slot and --standalone, set on Change or given.
self.one_per_slot: bool = False
self.standalone: bool = False
# --no-game-data on the command line: the plan has no game data row,
# as line mode has no g then.
self.cli_no_game_data: bool = False
# A quit the user chose, said as one (tui_quit).
self.quit_asked: bool = False
self.installed_only: bool = False
self.jobs: int = 8
self.passthrough: list = []
# Whether Details were opened on the result: the terminal keeps
# them after Exit too.
self.details_seen = False
def _init_install(self) -> None:
# The install.
self.download: dict | None = None
self.progress: dict | None = None
# (time, bytes from the network) of the last transfer events: what
# came from this machine (a copy, the pack, a partial file resumed)
# is never in a speed.
self.samples: list = []
self.network: int = 0
self.finished: list = []
self.summary: dict | None = None
self.code: int | None = None
self.stopping: bool = False
self.tail: list = []
self.log: str = ""
self.exit_code: int | None = None
# The RetroBIOS app on the card the BIOS folder is on: asked for
# (--add-app, the options), what putting it did (the app event),
# and the card, read once per folder.
self.add_app: bool = False
self.app: dict | None = None
self.app_running: bool = False
self.card_for: Path | None = None
self.card: CardApp | None = None
# The games on the card (--for-games): None until a look at the card
# or the user decides, then whether the runs read them. games_choice
# says who decided: "probe", "user" or "cli".
self.for_games: bool | None = None
self.games_choice: str = ""
# A games folder named with --for-games FOLDER.
self.games_folder: Path | None = None
self.required_only: bool = False
# The (platform, folder) the card was looked at for, and how many of
# its folders hold a game.
self.games_probed: tuple | None = None
self.games_here: int = 0
# The check's games event, its reading progress, and why what the
# games need could not be read.
self.games: dict | None = None
self.games_reading: tuple | None = None
self.games_unavailable: dict | None = None
# The install record of the setup and folder chosen (read for
# record_for), whose choice the plan opens on when the command line
# chose nothing (cli_choice), and the options of it no row shows.
self.record: dict | None = None
self.record_for: tuple | None = None
self.record_flags: list = []
self.cli_choice: bool = False
# Opened on the plan of the one setup found: its Change where row
# goes back to the setups.
self.opened_on_plan: bool = False
# The device chosen on Device (--target, "" for the board the run
# reads itself) or every board (--every-board), the emulators
# ticked on Emulators (--emulator), and the packs read in place of
# the network (--from-pack).
self.target: str = ""
self.every_board: bool = False
self.emulators: list[str] = []
self.packs: list[Path] = []
# The platform's board list, as fetched for Device: None until it
# comes or when it could not be read, and why.
self.targets: dict | None = None
self.targets_for: str = ""
self.targets_problem: str = ""
# (platform, folder, board, applied, here) of the last board event:
# kept across checks, a --target chosen since stops the event.
self.board_seen: tuple | None = None
# More: what to remove (the --system of a removal, none for
# everything), whether into a backup, the plan its dry run read,
# the backups listed and why, the one chosen, the action confirmed
# (remove, restore, delete_backup), its events and its code.
self.removal_scope: list[tuple[str, str]] = []
self.removal_backup: bool = False
self.removal: dict | None = None
self.backups: list[dict] | None = None
self.backups_for: str = "look"
self.backup_chosen: dict | None = None
self.action: str = ""
self.action_events: list[dict] = []
self.action_code: int | None = None
# Whether the folder checked has a backup, read once each check.
self.has_backups: bool = False
# Make a pack: the folder it goes in (Downloads by default), what
# its dry run said (the pack event), what the run made, its count
# of files fetched so far and its code.
self.pack_dir: Path | None = None
self.pack_plan: dict | None = None
self.pack_done: dict | None = None
self.pack_fetched: tuple[int, int] | None = None
self.pack_code: int | None = None
@property
def screen(self) -> str:
return self.stack[-1]
def _env_on(env: Mapping[str, str], name: str) -> bool:
return env.get(name, "") not in ("", "0")
def plain_requested(args: argparse.Namespace, env: Mapping[str, str] | None = None) -> bool:
"""Whether the line questions were asked for: --plain, RETROBIOS_PLAIN, ACCESSIBLE."""
env = os.environ if env is None else env
return bool(args.plain) or _env_on(env, "RETROBIOS_PLAIN") or _env_on(env, "ACCESSIBLE")
# Each handheld launcher names the buttons that reach the interface
# (ports/shared/tui.txt exports RB_PAD as this), so the bar names those
# buttons and no others.
TUI_PAD_ENV = "RETROBIOS_PAD"
class TuiRoute(NamedTuple):
"""How one input route names the keys, read by the screen and by
scripts/generate_installer_doc.py for the key table of the page.
bar maps a key of the bottom line, written in the "both" form ("A/Enter
Install"), to the route's own name, None for a key the route lacks: a PC
user read "A/Enter", a muOS player was told a Select+Start that muxterm
does not have. help names each action of the help screen, the buttons
first, then the keys a keyboard plugged in also has, None for an action
the route lacks. stop is what stops an install the second time, then the
first time.
"""
bar: Mapping[str, str | None]
help: Mapping[str, str | None]
stop: tuple[str, str]
# retrobios.gptk: A Enter, B Esc, X Space, Y Tab, L1 and R1 a page, Start
# Enter, Select Esc, Select then Start the kill.
_GPTOKEYB = TuiRoute(
{"A/Enter": "A", "B/Esc": "B", "X/Space": "X", "Y/o": "Y", "?": None, "/": None,
"Ctrl-C": "Select+Start", "Enter": "A", "Esc": "B", "Ctrl-U": None},
{"move": "D-pad, Up/Down", "page": "L1/R1, PgUp/PgDn", "ok": "A, Start, Enter",
"tick": "X, Space, Right/Left", "options": "Y, Tab, o", "back": "B, Select, Esc",
"stop": "B, Esc, Ctrl-C", "kill": "Select, then Start", "enter": "A, Enter",
"esc": "B, Esc"},
("B", "B or Select+Start"))
# keys is a keyboard's, and both names the button and the key where nothing
# says which one is held. The others are the values of RETROBIOS_PAD.
TUI_ROUTES: dict[str, TuiRoute] = {
"keys": TuiRoute(
{"A/Enter": "Enter", "B/Esc": "Esc", "X/Space": "Space", "Y/o": "o"},
{"move": "Up/Down, k/j", "page": "PgUp/PgDn", "ok": "Enter",
"tick": "Space, Right/Left", "options": "o, Tab", "back": "Esc, Backspace",
"stop": "Esc, Ctrl-C", "kill": None, "enter": "Enter", "esc": "Esc"},
("Esc or Ctrl-C", "Esc or Ctrl-C")),
"both": TuiRoute(
{},
{"move": "Up/Down, k/j", "page": "PgUp/PgDn, L1/R1", "ok": "A/Enter, Start",
"tick": "X, Space, Right/Left", "options": "Y, o, Tab", "back": "B/Esc, Backspace",
"stop": "B/Esc, Ctrl-C", "kill": "Select+Start", "enter": "Enter", "esc": "Esc"},
("B or Ctrl-C", "B, Ctrl-C or Select+Start")),
"gptokeyb": _GPTOKEYB,
# gptokeyb2 with retrobios.gptk inside muxterm, which no longer reads the
# pad: the gptokeyb buttons. muxterm keeps PgUp and PgDn for its
# scrollback, and the launcher sends nothing on L1 and R1 there: Left and
# Right page.
"gptokeyb_muxterm": _GPTOKEYB._replace(help={**_GPTOKEYB.help,
"page": "D-pad Left/Right",
"tick": "X, Space"}),
# muxterm's own keys: Start Enter, B Backspace, Y Space, Menu closes the
# terminal. A, X, L1 and R1 send nothing, Select shows its keyboard, and
# the D-pad's Left and Right page a list.
"muxterm": TuiRoute(
{"A/Enter": "Start", "B/Esc": "B", "X/Space": "Y", "Y/o": None, "?": None,
"/": None, "Ctrl-C": "Menu", "Enter": "Start", "Esc": None, "Ctrl-U": None},
{"move": "D-pad, Up/Down", "page": "D-pad Left/Right", "ok": "Start, Enter",
"tick": "Y, Space", "options": "o, Tab", "back": "B, Esc, Backspace",
"stop": "B, Esc, Ctrl-C", "kill": None, "enter": "Start, Enter", "esc": "Esc"},
("B", "B")),
# RetroBIOS.sh.keys: the gptokeyb buttons, and no combo that ends the run.
"evmapy": TuiRoute(
{"A/Enter": "A", "B/Esc": "B", "X/Space": "X", "Y/o": "Y", "?": None, "/": None,
"Ctrl-C": None, "Enter": "A", "Esc": "B", "Ctrl-U": None},
{"move": "D-pad, Up/Down", "page": "L1/R1, PgUp/PgDn", "ok": "A, Start, Enter",
"tick": "X, Space, Right/Left", "options": "Y, Tab, o",
"back": "B, Select, Esc", "stop": "B, Esc, Ctrl-C", "kill": None,
"enter": "A, Enter", "esc": "B, Esc"},
("B", "B")),
# Buttons that are keys already: A Space, Start Enter, L2 Tab, R2
# Backspace. B is Left Ctrl, a modifier: alone it sends no byte to a
# terminal (the console's keyboard driver only records its state), so
# the interface never sees it, nor X, Y and Select (Shift, Alt, Ctrl).
"miyoo": TuiRoute(
{"A/Enter": "A", "B/Esc": "R2", "X/Space": "A", "Y/o": "L2", "?": None, "/": None,
"Ctrl-C": None, "Enter": "Start", "Esc": None, "Ctrl-U": None},
{"move": "D-pad, Up/Down", "page": "L1/R1, PgUp/PgDn", "ok": "A, Start, Enter",
"tick": "A, Space, Right/Left", "options": "L2, Tab, o",
"back": "R2, Esc, Backspace", "stop": "R2, Esc, Ctrl-C", "kill": None,
"enter": "Start, Enter", "esc": "Esc"},
("R2", "R2")),
}
TUI_PAD_ROUTES = tuple(name for name in TUI_ROUTES if name not in ("keys", "both"))
# Set by Steam for what it starts, and by gamescope: a controller may be
# all there is, mapped by Steam Input to keys nobody here can name.
_STEAM_MARKERS = ("SteamGamepadUI", "SteamDeck", "SteamGameId", "GAMESCOPE_WAYLAND_DISPLAY")
# Seconds the interface waits for a first key, no run going, before it
# closes, set by a launcher whose mapper may never open the pad: the screen
# would otherwise hold a handheld that has no other way out.
TUI_IDLE_ENV = "RETROBIOS_IDLE_EXIT"
TUI_IDLE_WORDS = "No button pressed, closing."
def tui_idle_exit(env: Mapping[str, str] | None = None) -> float | None:
"""The seconds RETROBIOS_IDLE_EXIT names, None when unset or not a
positive number."""
env = os.environ if env is None else env
try:
seconds = float(env.get(TUI_IDLE_ENV, "").strip())
except ValueError:
return None
return seconds if 0 < seconds < float("inf") else None
def tui_pad_route(os_type: str, env: Mapping[str, str] | None = None) -> str:
"""The keys the hints name: a launcher's pad route, "keys" at a desktop,
"both" (button and key) where nothing says which one is held."""
env = os.environ if env is None else env
named = env.get(TUI_PAD_ENV, "").strip().lower()
if named:
return named if named in TUI_PAD_ROUTES else "both"
if any(env.get(name) for name in _STEAM_MARKERS):
return "both"
if os_type in ("windows", "darwin", "wsl"):
return "keys"
# A Linux console is where a handheld draws: a desktop or a remote
# shell is a keyboard's.
if os_type == "linux" and env.get("TERM") != "linux" and any(
env.get(name) for name in ("DISPLAY", "WAYLAND_DISPLAY", "SSH_CONNECTION",
"SSH_TTY")):
return "keys"
return "both"
def _terminal_size(stream: TextIO) -> tuple[int, int]:
try:
size = os.get_terminal_size(stream.fileno())
except (OSError, ValueError, AttributeError, io.UnsupportedOperation):
return 0, 0
return size.columns, size.lines
def colour_blocker(env: Mapping[str, str], stream: TextIO) -> str:
"""Why the full-screen interface draws without colour, "" when it paints
with the roles of COLOUR_ROLES. The text is the same either way."""
if env.get("NO_COLOR"):
return "NO_COLOR is set"
isatty = getattr(stream, "isatty", None)
if not (isatty and isatty()):
return "the output is not a terminal"
if os.name != "nt" and env.get("TERM", "") in ("", "dumb"):
return "TERM is dumb or not set"
return terminal_few_colours(env)
def _tui_flag_blocker(args: argparse.Namespace) -> str:
"""The option of a run without questions, said as the reason."""
for flag, given in (
("--check", args.check), ("--dry-run", args.dry_run),
("--list-platforms", args.list_platforms), ("--list-targets", args.list_targets),
("--list-systems", args.list_systems), ("--list-cores", args.list_cores),
("--list-emulators", args.list_emulators), ("--events", args.events),
("--quiet", args.quiet), ("--yes", args.yes), ("--no-input", args.no_input),
("--restore", args.restore is not None),
("--pack", getattr(args, "pack", None) is not None),
):
if given:
return f"{flag} runs without questions"
return ""
def _tui_keys_blocker(stdin: TextIO) -> str:
"""Why single key presses cannot be read here, "" when they can."""
if os.name == "nt":
import importlib
try:
importlib.import_module("msvcrt")
except ImportError:
return "this Python has no msvcrt to read keys"
if not _enable_ansi():
return "this console does not draw escape sequences (Windows 10 or later does)"
return ""
try:
import termios
except ImportError:
return "this Python has no termios to read keys"
try:
termios.tcgetattr(stdin.fileno())
except (termios.error, OSError, ValueError, AttributeError,
io.UnsupportedOperation) as exc:
return f"single key presses cannot be read here ({exc})"
return ""
def tui_blocker(
args: argparse.Namespace, stdin: TextIO | None = None, stdout: TextIO | None = None,
env: Mapping[str, str] | None = None,
) -> str:
"""Why the full-screen interface cannot run here, "" when it can."""
env = os.environ if env is None else env
stdin = stdin or sys.stdin
stdout = stdout or sys.stdout
flag_blocker = _tui_flag_blocker(args)
if flag_blocker:
return flag_blocker
for name, stream in (("input", stdin), ("output", stdout)):
isatty = getattr(stream, "isatty", None)
if not (isatty and isatty()):
return f"the {name} is not a terminal"
if os.name != "nt" and env.get("TERM", "") in ("", "dumb"):
return "TERM is dumb or not set"
drawing = terminal_without_ansi(env)
if drawing:
return drawing
# A pseudo-terminal nobody sized reports 0x0: script(1) fed from a pipe
# is one, and the line questions run there as they always have.
cols, rows = _terminal_size(stdout)
if cols < TUI_MIN_COLS or rows < TUI_MIN_ROWS:
return (f"the terminal is {cols}x{rows}, smaller than "
f"{TUI_MIN_COLS}x{TUI_MIN_ROWS}")
return _tui_keys_blocker(stdin)
def line_mode_reason(blocker: str, env: Mapping[str, str] | None = None) -> str:
"""Why the questions come line by line, in one line, for a terminal the
full screen cannot draw on: its size or its TERM. "" for a run that
asks nothing (--check, a pipe), and for a pseudo-terminal nobody sized
(script fed from a pipe is 0x0), which is no window."""
env = os.environ if env is None else env
small = re.match(r"the terminal is (\d+x\d+), smaller than", blocker)
if small:
if "0" in small[1].split("x"):
return ""
return (f"The window is {small[1]}: questions come line by line "
f"({TUI_MIN_COLS}x{TUI_MIN_ROWS} for the full screen).")
if blocker == "TERM is dumb or not set":
term = screen_text(env.get("TERM", ""))
return (f"TERM={term}: questions come line by line." if term
else "TERM is not set: questions come line by line.")
if blocker.startswith("TERM="):
return f"{blocker}: questions come line by line."
return ""
# TERM values of terminals that report no mouse the xterm way: the Linux
# console (gpm is its own protocol), the DEC VTs and BSD consoles.
_NO_MOUSE_TERMS = ("linux", "vt", "cons", "ansi")
def tui_mouse_blocker(
stdin: TextIO | None = None, stdout: TextIO | None = None,
env: Mapping[str, str] | None = None,
) -> str:
"""Why the full screen leaves the mouse to the terminal, "" when it
asks for clicks. A pad route has no pointer and its mapper may send
anything a report would be confused with, and RETROBIOS_NO_MOUSE keeps
the terminal's own selection everywhere."""
env = os.environ if env is None else env
stdin = stdin or sys.stdin
stdout = stdout or sys.stdout
if _env_on(env, TUI_MOUSE_ENV):
return f"{TUI_MOUSE_ENV} is set"
if env.get(TUI_PAD_ENV, "").strip():
return f"{TUI_PAD_ENV} names a controller route"
if os.name == "nt":
# msvcrt.getwch reads keys, never a console mouse record.
return "a Windows console reports no clicks as keys"
for name, stream in (("input", stdin), ("output", stdout)):
isatty = getattr(stream, "isatty", None)
if not (isatty and isatty()):
return f"the {name} is not a terminal"
term = env.get("TERM", "").strip().lower()
if term in ("", "dumb", "unknown") or term.startswith(_NO_MOUSE_TERMS):
return f"TERM={term} reports no clicks" if term else "TERM is not set"
return ""
def tui_wants_mouse(state: TuiState, lines: list[str]) -> bool:
"""Whether the frame takes clicks: not where a command or the result is
shown, so the terminal's own selection copies it as it always has, nor
where a path is typed, which a middle or right click pastes into."""
if state.help:
return True
if state.screen == "result":
# A tap on the bar's Exit closes it, where a touch screen has no
# Enter: the result is printed again in the terminal once the
# screen closes, its commands selected there as anywhere.
return True
if state.screen in ("command", "path"):
return False
# Read from the frame's model: a command wrapped over lines was missed
# by a match on the drawn text, its URL cut in two.
return not any(getattr(line, "command", False) for line in lines)
def _tui_system_flags(state: TuiState) -> list[tuple[str, str | None]]:
"""The --system the screen's ticks stand for."""
needed = {row["system"] for row in state.systems
if row["missing"] + row["wrong_hash"] > 0}
if state.systems and not needed <= state.ticked:
return [("--system", name) for name in sorted(state.ticked)]
return [("--system", name) for name in state.cli_systems]
def tui_flags(state: TuiState) -> list[tuple[str, str | None]]:
"""The options that carry the choices made on screen, CLI ones included."""
flags = list(state.passthrough)
if state.target:
flags.append(("--target", state.target))
if state.every_board:
flags.append(("--every-board", None))
flags += [("--emulator", name) for name in state.emulators]
flags += [("--from-pack", str(pack)) for pack in state.packs]
flags += _tui_system_flags(state)
flags += [("--core", name) for name in tui_core_flags(state)]
if state.regions:
flags.append(("--region", ",".join(state.regions)))
if state.for_games:
flags.append(("--for-games", str(state.games_folder) if state.games_folder else None))
if state.required_only:
flags.append(("--required-only", None))
if state.no_game_data:
flags.append(("--no-game-data", None))
if state.standalone and _tui_standalone_offered(state):
flags.append(("--standalone", None))
if state.one_per_slot and _tui_slot_offered(state, flags):
flags.append(("--one-per-slot", None))
if state.installed_only and not any(flag == "--cores-dir" for flag, _v in flags):
flags.append(("--installed-cores", None))
if state.jobs != 8:
flags.append(("--jobs", str(state.jobs)))
flags += state.record_flags
if (state.record is not None and not state.for_games
and not any(flag in RECORD_NARROWING for flag, _value in flags)):
# The whole list, chosen over a recorded narrower one: said so to
# the runs, whose own reading of the record would narrow it again.
flags.append(("--all-files", None))
flags += [("--from", str(folder)) for folder in state.from_folders]
if (os.environ.get(OFFLINE_VARIABLE) == OFFLINE_FLAG_VALUE
and not any(flag == "--offline" for flag, _v in flags)):
# Given as --offline: said so in the command. Set as the variable,
# the runs inherit it and the words name it.
flags.append(("--offline", None))
return flags
_TUI_MODES = {
"check": ["--check", "--events"],
"confirm": ["--dry-run", "--events"],
"preview": ["--dry-run", "--events"],
"install": ["--events", "--yes"],
}
def tui_argv(state: TuiState, run: str, python: str, script: str) -> list[str]:
"""The child that does what the screen decided."""
if run in TUI_ACTION_RUNS:
return tui_action_argv(state, run, python, script)
# --dest=VALUE: a folder typed as -x would otherwise be read as an option.
argv = [python, script, f"--platform={state.platform}", f"--dest={state.dest}"]
if state.manifest_path is not None:
argv.append(f"--manifest={state.manifest_path}")
argv += [flag if value is None else f"{flag}={value}" for flag, value in tui_flags(state)]
if run == "install" and state.add_app and _tui_app_ready(state):
# Only the install writes: --check and --dry-run refuse it.
argv.append("--add-app")
return argv + _TUI_MODES[run]
def tui_run_env(state: TuiState, own_list: bool) -> dict | None:
"""The environment of a child run: None for this one's own, else with
the markers the run reads (TUI_LIST_ENV, TUI_RECORD_ENV)."""
marks = {TUI_LIST_ENV: "1"} if own_list else {}
if tui_record_kept(state):
marks[TUI_RECORD_ENV] = "1"
if not marks and TUI_RECORD_ENV not in os.environ:
return None
env = {key: value for key, value in os.environ.items() if key != TUI_RECORD_ENV}
env.update(marks)
return env
def tui_hint(state: TuiState) -> Invocation:
"""The command the screen's choices make, every option of the run in
it: what "Same choice without questions" and the sudo advice give."""
hint = Invocation()
hint.os_type = state.os_type
hint.options = ([("--manifest", str(state.manifest_path))]
if state.manifest_given and state.manifest_path else [])
hint.options += tui_flags(state)
if state.add_app and _tui_app_ready(state):
hint.options.append(("--add-app", None))
# The runs inherit the variable, a command shown to the user does not.
if offline_option(False) and ("--offline", None) not in hint.options:
hint.options.append(("--offline", None))
return hint
def tui_command(state: TuiState) -> str:
"""The same choice as one command, in the form the run was started with."""
return tui_hint(state).command(state.platform, state.dest)
def _tui_card(state: TuiState) -> CardApp | None:
"""The card the BIOS folder is on, read once for each folder."""
if state.dest is None:
return None
if state.card_for != state.dest:
state.card_for, state.card = state.dest, card_app(state.dest)
return state.card
def _tui_app_ready(state: TuiState) -> bool:
"""Whether the RetroBIOS app can go on this card: its system has one,
and the run may use the network to fetch it."""
card = _tui_card(state)
return card is not None and card.place is not None and not LOCAL.offline
def _tui_installed(state: TuiState) -> bool:
"""An install that finished with every file in place."""
summary = state.summary or {}
return bool(summary) and not summary.get("interrupted") and not summary.get("failed") \
and state.code == 0
def _app_offer(state: TuiState) -> bool:
"""The result offers the app: the install finished, the card can take
it, and it was neither asked for nor put already."""
return (state.screen == "result" and state.app is None and not state.app_running
and _tui_installed(state) and _tui_app_ready(state))
def tui_run_files(state: TuiState) -> tuple[list[dict], list[dict]]:
"""The files and omissions the run chooses among, as the check counted
them: the list without what it set aside before any choice (the save
entries of a save directory it cannot place), the game data left out
when the plan leaves it out. Line mode chooses among the same (bare)."""
manifest = state.manifest or {}
key = (id(state.manifest), frozenset(state.set_aside or ()), state.no_game_data)
if state.run_files_cache is not None and state.run_files_cache[0] == key:
return state.run_files_cache[1]
aside = state.set_aside or set()
files = [entry for entry in manifest.get("files") or [] if entry.get("dest") not in aside]
omitted = list(manifest.get("omitted_files") or [])
if state.no_game_data:
files, omitted = leave_out_game_data(files, omitted)[:2]
state.run_files_cache = (key, (files, omitted))
return files, omitted
def _core_base(state: TuiState) -> list[str]:
"""The cores a choice on Cores is made among: those of the systems
chosen, every core the run accepts else (choosable_cores, as line
mode counts them)."""
return choosable_cores(*tui_run_files(state), _tui_systems_chosen(state))
def tui_core_flags(state: TuiState) -> list[str]:
"""The --core the run is given: the cores ticked, none when every core
of the systems chosen is (the run keeps the same files)."""
if not state.cores or set(_core_base(state)) <= set(state.cores):
return []
return list(state.cores)
def _tui_systems_chosen(state: TuiState) -> list[str]:
"""The systems the run is narrowed to, [] for every system."""
return [value for _flag, value in _tui_system_flags(state) if value]
def _tui_standalone_offered(state: TuiState) -> bool:
"""Whether Change offers --standalone: emulators are chosen, the list
records a standalone build for each of them, and no region, core or
system choice narrows the run, which the option refuses beside it."""
manifest = state.manifest or {}
layouts = manifest.get("standalone_builds") or []
if not state.emulators or not layouts or not _tui_standalone_fits(state):
return False
names = emulator_names(manifest, *tui_run_files(state))
return all(names.get(name) in layouts for name in state.emulators)
def _tui_standalone_fits(state: TuiState) -> bool:
"""No region, core or system choice: --standalone takes none."""
return not (state.regions or tui_core_flags(state) or _tui_system_flags(state))
def _tui_slot_offered(state: TuiState, flags: list[tuple[str, str | None]]) -> bool:
"""Whether Change offers --one-per-slot: the list records its slots and
the choice is the whole list, as the pack builder decides slots over it
(no system, emulator or game choice narrows it first)."""
return bool((state.manifest or {}).get("slot_fields")) and not any(
flag in ("--system", "--emulator", "--for-games", "--declared-only")
for flag, _value in flags)
def _record_key(options: Iterable[tuple[str, str | None]]) -> list:
"""A choice in a form two spellings of it share: one name per --system
and --core, in any order."""
pairs = record_options(record_argv(options))
return sorted((flag, name.strip()) for flag, value in pairs
for name in ((value or "").split(",") if flag in ("--system", "--core")
else [value or ""]) if name.strip() or value is None)
def tui_record_kept(state: TuiState) -> bool:
"""Whether the plan's choice is the one the record keeps."""
if state.record is None:
return False
return _record_key(tui_flags(state)) == _record_key(
record_options(state.record["choice"]))
# The runs More starts, each a child as an install is: what --remove would
# take (removal_plan), the removal, the backups listed, one put back and
# one deleted.
TUI_ACTION_RUNS = ("removal_plan", "remove", "backups", "restore", "delete_backup",
"pack_plan", "pack")
# The plan's options a pack's run leaves out: each reads or writes the BIOS
# folder of this machine, which --pack refuses.
TUI_PACK_DROPPED = ("--dest", "--installed-cores", "--cores-dir", "--save-dir",
"--standalone-copies", "--add-app", "--romm-firmware", "--for-games",
"--required-only")
def tui_pack_dir(state: TuiState) -> Path:
"""The folder the pack goes in: the one chosen, else Downloads where
there is one, else the home folder."""
if state.pack_dir is not None:
return state.pack_dir
downloads = state.home / "Downloads"
return downloads if _is_dir(downloads) else state.home
def tui_pack_argv(state: TuiState, run: str, python: str, script: str) -> list[str]:
"""The child that makes the pack, or lists it (pack_plan): the plan's
choice, none of the options of this machine's folder. The games of a
folder named stay a choice, the card's own are not read for a pack."""
argv = [python, script, f"--platform={state.platform}"]
if state.manifest_path is not None:
argv.append(f"--manifest={state.manifest_path}")
flags = [flag for flag in tui_flags(state) if flag[0] not in TUI_PACK_DROPPED]
if state.for_games and state.games_folder:
flags.append(("--for-games", str(state.games_folder)))
if state.required_only:
flags.append(("--required-only", None))
argv += [flag if value is None else f"{flag}={value}" for flag, value in flags]
argv.append(f"--pack={tui_pack_dir(state)}{os.sep}")
return argv + (["--dry-run", "--events"] if run == "pack_plan" else ["--events", "--yes"])
def tui_action_argv(state: TuiState, run: str, python: str, script: str) -> list[str]:
"""The child of a More action: its own options and none of the plan's,
whose --system is an install's choice, not what to remove. A pack
takes the plan's choice."""
if run in ("pack_plan", "pack"):
return tui_pack_argv(state, run, python, script)
if run in ("restore", "delete_backup"):
folder = str((state.backup_chosen or {}).get("folder", ""))
flag = "--restore" if run == "restore" else "--delete-backup"
return [python, script, f"{flag}={folder}", "--events",
*(["--yes"] if run == "delete_backup" else [])]
argv = [python, script, f"--platform={state.platform}", f"--dest={state.dest}"]
if run == "backups":
return argv + ["--backups", "--events"]
if state.manifest_path is not None:
argv.append(f"--manifest={state.manifest_path}")
argv += ["--remove", *(f"{flag}={value}" if value else flag
for flag, value in state.removal_scope)]
if state.removal_backup and not _removing_misplaced(state):
argv.append("--backup")
return argv + (["--dry-run", "--events"] if run == "removal_plan" else ["--events", "--yes"])
def _removing_misplaced(state: TuiState) -> bool:
"""Whether the removal is of the copies in the wrong place, which are
deleted: they were never a setup's, so no backup gives them back."""
return ("--misplaced", "") in state.removal_scope
+451
View File
@@ -0,0 +1,451 @@
"""Keys read from the terminal and the lines painted back."""
from __future__ import annotations
import codecs
import os
import re
import unicodedata
from collections.abc import Callable, Iterable
from pathlib import Path
from typing import NamedTuple
from installer.embedded import shown_path
from installer.invocation import Invocation
from installer.line_ui import _pad
from installer.run import _COLOUR_BASES, _FOLDER_LABEL, _KEY_NUMBER, _PASTE_END, _PROGRESS_BAR, _STYLES
from installer.terminal import COLOUR_ROLES, _apart, painted, status_spans
from installer.text import _char_width, cell_width, fit, screen_text
from installer.tui_state import TUI_ROUTES
class TuiKey(NamedTuple):
"""One key press: a name ("up", "enter"), or "char" or "paste" and the text."""
name: str
text: str = ""
class TuiMouse(NamedTuple):
"""One mouse report: the button (0 left, 1 middle, 2 right, 3 a legacy
release, 64 and 65 the wheel, plus 4, 8 and 16 for Shift, Meta and
Ctrl), the cell counted from 1, and whether the button went up."""
button: int
col: int
row: int
release: bool = False
name: str = "mouse"
text: str = ""
def _sgr_mouse(params: str, final: str) -> TuiMouse | None:
"""An SGR report: ESC [ < button ; column ; row, M pressed, m released."""
parts = params[1:].split(";")
if len(parts) != 3 or not all(part.isdigit() for part in parts):
return None
button, col, row = (int(part) for part in parts)
return TuiMouse(button, col, row, final == "m")
def _x10_mouse(data: str) -> TuiMouse | None:
"""A legacy report: three characters, each 32 plus its value, read from
the bytes before UTF-8 decoding (TerminalInput): a position byte past
127 is no character of its own."""
codes = [ord(char) - 32 for char in data]
if any(not 0 <= code <= 223 for code in codes):
return None
button, col, row = codes
if col < 1 or row < 1:
return None
return TuiMouse(button, col, row, button & 3 == 3 and not button & 64)
_CSI_KEYS = {"A": "up", "B": "down", "C": "right", "D": "left", "H": "home", "F": "end",
"Z": "shift-tab"}
_TILDE_KEYS = {"1": "home", "7": "home", "4": "end", "8": "end", "5": "pgup", "6": "pgdn",
"3": "delete", "11": "f1"}
_SS3_KEYS = {"A": "up", "B": "down", "C": "right", "D": "left", "H": "home", "F": "end",
"P": "f1", "M": "enter"}
# msvcrt.getwch gives these after a \x00 or \xe0 prefix.
_WINDOWS_KEYS = {"H": "up", "P": "down", "K": "left", "M": "right", "I": "pgup",
"Q": "pgdn", "G": "home", "O": "end", "S": "delete", ";": "f1"}
def _plain_key(char: str) -> TuiKey | None:
"""The key one character stands for, None for a control nobody bound."""
named = {"\r": "enter", "\n": "enter", "\x7f": "backspace", "\x08": "backspace",
"\t": "tab", "\x1b": "esc", "\x03": "ctrl-c", "\x04": "ctrl-d",
"\x15": "ctrl-u", "\x1a": "ctrl-z"}.get(char)
if named:
return TuiKey(named)
if char < " " or unicodedata.category(char) in ("Cc", "Cs"):
return None
return TuiKey("char", char)
def _csi_key(params: str, final: str) -> TuiKey | TuiMouse | None:
if params.startswith("<"):
return _sgr_mouse(params, final) if final in "Mm" else None
if final == "~":
if params == "200":
return TuiKey("paste-start")
name = _TILDE_KEYS.get(params.split(";")[0])
return TuiKey(name) if name else None
name = _CSI_KEYS.get(final)
if name is None:
return None
if params in ("", "1"):
return TuiKey(name)
if params == "1;2" and name in ("up", "down"):
return TuiKey(f"shift-{name}")
return None
def _escape(buffer: str) -> tuple[int, TuiKey | TuiMouse | None]:
"""The sequence at the start of buffer: the characters it takes and its
key (None for one nobody bound), or 0 while more are needed to tell."""
if len(buffer) < 2:
return 0, None
if buffer[1] == "[":
if buffer[2:3] == "M":
# A legacy mouse report: three bytes of button and position
# follow, read as a report and never as keys.
return (6, _x10_mouse(buffer[3:6])) if len(buffer) >= 6 else (0, None)
for end in range(2, len(buffer)):
code = ord(buffer[end])
if 0x40 <= code <= 0x7E:
return end + 1, _csi_key(buffer[2:end], buffer[end])
if not 0x20 <= code <= 0x3F:
return 1, TuiKey("esc")
return 0, None
if buffer[1] == "O":
if len(buffer) < 3:
return 0, None
name = _SS3_KEYS.get(buffer[2])
return 3, TuiKey(name) if name else None
return 1, TuiKey("esc")
class KeyDecoder:
"""Keys from what a terminal sends, however the reads split it.
Unknown sequences (F13) are dropped, never taken as text. A mouse
report, SGR or legacy, comes out as a TuiMouse.
"""
def __init__(self) -> None:
self.buffer = ""
self.paste: str | None = None
def feed(self, text: str) -> list[TuiKey | TuiMouse]:
self.buffer += text
return self._drain(final=False)
def flush(self) -> list[TuiKey | TuiMouse]:
"""What is left once the wait for the rest of a sequence is over.
An open paste stays open: over SSH its end arrives later than 40 ms.
"""
return self._drain(final=True)
def close_paste(self) -> list[TuiKey | TuiMouse]:
"""The paste so far, its end never seen, without its newlines."""
text = "".join(char for char in self.paste or "" if char >= " " and char != "\x7f")
self.paste = None
return [TuiKey("paste", text)] if text else []
@property
def waiting(self) -> bool:
return bool(self.buffer) or self.paste is not None
def _drain(self, final: bool) -> list[TuiKey | TuiMouse]:
keys: list[TuiKey | TuiMouse] = []
while self.buffer:
if self.paste is not None:
end = self.buffer.find(_PASTE_END)
if end < 0:
# The end marker may be cut between two reads.
keep = next((n for n in range(len(_PASTE_END) - 1, 0, -1)
if self.buffer.endswith(_PASTE_END[:n])), 0)
cut = len(self.buffer) - keep
self.paste += self.buffer[:cut]
self.buffer = self.buffer[cut:]
break
self.paste += self.buffer[:end]
self.buffer = self.buffer[end + len(_PASTE_END):]
keys += self.close_paste()
continue
if self.buffer[0] == "\x1b":
taken, key = _escape(self.buffer)
if not taken:
if final:
if self.buffer == "\x1b":
keys.append(TuiKey("esc"))
self.buffer = ""
break
self.buffer = self.buffer[taken:]
if key is not None and key.name == "paste-start":
self.paste = ""
elif key is not None:
keys.append(key)
continue
key = _plain_key(self.buffer[0])
self.buffer = self.buffer[1:]
if key is not None:
keys.append(key)
return keys
_X10_START = b"\x1b[M"
class TerminalInput:
"""The text the keys are read from, out of the bytes a terminal sends.
A legacy mouse report is three raw bytes after ESC [ M: a column from
162 and a row from 96 made two of them one UTF-8 character, so the
report came one character short and took the next key as its row. Its
three bytes go to the key decoder one character each, whatever UTF-8
makes of them, and the rest is decoded as text."""
def __init__(self, encoding: str = "utf-8") -> None:
self.text = codecs.getincrementaldecoder(encoding)(errors="replace")
# The report bytes still to come from the next read, and the last
# two bytes read, where a report's ESC [ may have started.
self.need = 0
self.tail = b""
def decode(self, data: bytes) -> str:
out: list[str] = []
if self.need:
raw, data = data[:self.need], data[self.need:]
self.need -= len(raw)
out.append(raw.decode("latin-1"))
joined = self.tail + data
shift = len(self.tail)
start = shift
search = 0
while True:
at = joined.find(_X10_START, search)
if at < 0:
break
report = at + len(_X10_START)
if report <= shift:
# Read whole before: decoded then.
search = at + 1
continue
out.append(self.text.decode(joined[start:report]))
raw = joined[report:report + 3]
out.append(raw.decode("latin-1"))
self.need = 3 - len(raw)
start = search = report + len(raw)
out.append(self.text.decode(joined[start:]))
self.tail = joined[-2:]
return "".join(out)
def flush(self) -> None:
"""The wait for the rest of a report is over: none is owed."""
self.need = 0
def decode_windows_key(first: str, read_next: Callable[[], str]) -> TuiKey | None:
"""A key from msvcrt.getwch: arrows and pages come as a prefix, then a code."""
if first in ("\x00", "\xe0"):
name = _WINDOWS_KEYS.get(read_next())
return TuiKey(name) if name else None
return _plain_key(first)
def ascii_text(text: str) -> str:
"""The text in ASCII, accents dropped (Edition) and any other character
as one ? per cell it took, so the columns stay where they were."""
if text.isascii():
return text
plain = "".join(char for char in unicodedata.normalize("NFKD", text)
if not unicodedata.combining(char))
return "".join(char if char.isascii() else "?" * _char_width(char) for char in plain)
def middle(text: str, width: int) -> str:
"""A long path cut in its middle, its start and its last folders kept."""
if cell_width(text) <= width:
return text
if width <= 3:
return fit(text, width)
room = width - 3
tail = fit(text[::-1], room // 2)[::-1]
return fit(text, room - cell_width(tail)) + "..." + tail
def _columns(left: str, right: str, width: int) -> str:
"""left, and right against the edge when both fit, else left alone."""
room = width - cell_width(right) - 2
if not right or room < 8:
return fit(left, width)
return _pad(fit(left, room), room) + " " + right
# Said under a command a path of which was cut to fit (_command_wrap).
TUI_SHORTENED = "Shortened to fit this window."
class TuiLine(str):
"""A screen line and how it is drawn: "head" (the screen's title),
"title", "focus", "dim", "hint" (the bar), "refusal" or plain.
mark is what a click on the line reaches (tui_hits): ("row", index,
(action, value)) for a row of the list, ("scroll", kind, rows) for the
line saying which lines are in view, ("bar",) for the bar."""
style = ""
mark: tuple | None = None
# A line of a command, however it was wrapped: the mouse is left to the
# terminal on a frame showing one (tui_wants_mouse).
command = False
# Whether the command it holds is typed into PowerShell, from the
# Invocation that made it: its line ends follow its words.
powershell: bool | None = None
# Shown on the Details screen, not on the screen it explains.
detail = False
# A count standing for Details lines: left out where they are shown.
brief = False
def _styled(text: str, style: str = "") -> TuiLine:
line = TuiLine(screen_text(text))
line.style = style
return line
def _detail(text: str, style: str = "") -> TuiLine:
"""A line of the Details screen: an explanation, a list, a reason."""
line = _styled(text, style)
line.detail = True
return line
def _details(lines: Iterable[str]) -> list[TuiLine]:
"""lines as Details lines, each keeping how it is drawn."""
marked = []
for line in lines:
copy = TuiLine(str(line))
for name in ("style", "mark", "command", "powershell"):
if hasattr(line, name):
setattr(copy, name, getattr(line, name))
copy.detail = True
marked.append(copy)
return marked
def _is_detail(line: object) -> bool:
return bool(getattr(line, "detail", False))
def _command_line(text: str, hint: Invocation) -> TuiLine:
"""A line holding a command hint made, wrapped with hint's shell."""
line = _styled(text, "command")
line.powershell = hint.powershell()
return line
def _bar_keys() -> set[str]:
"""Every name a key or a button takes on the bar, on every route."""
keys = {"Enter", "Esc", "Space", "Start", "Select", "Ctrl-C", "?", "/", "X/Space/tap",
"Space/tap"}
for route in TUI_ROUTES.values():
keys.update(route.bar)
keys.update(name for name in route.bar.values() if name)
keys.update(name.strip() for pair in _SHORT_KEYS for name in pair)
keys.update(f"{route.help['page'] or 'PgUp/PgDn'}".split(", ")[0]
for route in TUI_ROUTES.values())
return keys
def _bar_spans(text: str, first: str) -> list[tuple[int, int, str]]:
"""The bar's key names faint, the first in first, its actions plain:
drawn faint, Back and Quit were the hardest words to find on a
handheld, B being its way back."""
spans = []
for number, entry in enumerate(re.finditer(r"\S+(?: \S+)*", text)):
key = entry.group().split(" ", 1)[0]
if entry.group().endswith(TUI_ARMED_SHORT):
# Armed by a first tap: the whole entry stands out, a plain
# ": tap again" looked like no change at all.
spans.append((entry.start(), entry.end(), first))
elif key in _bar_keys() and " " in entry.group():
spans.append((entry.start(), entry.start() + len(key),
first if number == 0 else "muted"))
return spans
def tui_paint(text: str, style: str, colour: bool) -> str:
"""A drawn line as the terminal gets it: its style, and with colour the
roles of its words (COLOUR_ROLES). The characters are those of text.
The title names RetroBIOS in the accent, a headline its counts and
sizes, the bar the key it names first, a line its status words, the
plan and the result the BIOS folder in bold.
"""
if not colour:
if style == "hint":
return painted(text, _bar_spans(text, "strong"))
return _STYLES.get(style, "") + text
base = _COLOUR_BASES.get(style, "")
if style == "folder":
# The rest of a BIOS folder wrapped onto its own line, as bold as
# its start.
start = len(text) - len(text.lstrip(" "))
return painted(text, [(start, len(text.rstrip(" ")), "strong")], base)
if style not in ("", "head", "title", "hint", "refusal"):
return painted(text, [], base)
spans: list[tuple[int, int, str]] = []
if style == "hint":
return painted(text, _bar_spans(text, "accent"))
if style == "head":
at = text.find("RetroBIOS")
if at >= 0:
spans.append((at, at + len("RetroBIOS"), "accent"))
if style == "title":
spans += [(match.start(), match.end(), "accent")
for match in _KEY_NUMBER.finditer(text)]
lead = text.lstrip(" ")
if lead.startswith(_FOLDER_LABEL):
start = len(text) - len(lead) + len(_FOLDER_LABEL)
# The folder alone: on Options the bold ran on into --dest.
end = text.find(" ", start)
spans.append((start, len(text.rstrip(" ")) if end < 0 else end, "strong"))
bar = _PROGRESS_BAR.match(text)
if bar:
spans += [(bar.start(1), bar.end(1), "accent"), (bar.start(2), bar.end(2), "muted")]
# On a bold line a status word stays bold.
spans += [(start, end, f"strong+{role}" if base == "strong"
and not COLOUR_ROLES[role].startswith("1;") else role)
for start, end, role in status_spans(text)]
return painted(text, _apart(spans), base)
def _short_path(path: Path | None, home: Path) -> str:
if path is None:
return ""
text = str(path)
home_text = str(home)
if home_text not in ("", "/", ".") and (text == home_text
or text.startswith(home_text + os.sep)):
return "~" + text[len(home_text):]
return shown_path(text)
# What a check run tells the screen, kept whole when Choose systems widens a
# --system plan: Back with the same ticks gives that plan back.
_CHECK_FIELDS = ("check", "files", "systems", "choices", "set_aside", "found", "scanned",
"unreadable", "saves", "check_summary", "checked_flags", "cli_systems",
"facts", "ticked", "version", "board", "checked_dests", "games",
"games_unavailable")
TUI_ARMED_SHORT = "tap again"
# Shorter key names for a narrow bar: at 40 columns "X/Space Tick" was cut,
# and nothing said how to tick with a controller.
_SHORT_KEYS = (("A/Enter/tap ", "A/tap "), ("A/Enter ", "A "), ("B/Esc ", "B "),
("X/Space/tap ", "X/tap "),
("X/Space ", "X "), ("Y/o ", "Y "), ("Left/Right ", "<> "), ("Up/Down ", "^v "))
+745
View File
@@ -0,0 +1,745 @@
"""Keys, taps and the events of a child run, turned into a new state."""
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING
from installer.detect_os import detect_board
from installer.embedded import display_name
from installer.line_ui import TUI_MIN_COLS
from installer.removal import list_backups
from installer.run import TUI_MIN_ROWS
from installer.setups import TuiRow
from installer.tui_actions import (
_activate,
_checklist,
_device_focus,
_filter_key,
_install_now,
_known_choice,
_move_region,
_option,
_page_step,
_pager_key,
_pager_last,
_path_key,
_same_plan,
_tick,
_toggle_region,
_tui_folder_facts,
tui_interrupt,
tui_quit,
)
from installer.tui_results import _action_ended, _fail, _open_details, _take_action_event, tui_view
from installer.tui_rows import (
TUI_TICK_ROWS,
_CHECKLISTS,
_PAGERS,
_back,
_first_item,
_focus_plan,
_needed,
_push,
_replace,
_start_check,
_start_run,
tui_rows,
)
from installer.tui_state import TUI_ACTION_RUNS, TuiState, _tui_standalone_fits
from installer.tui_text import TuiKey, TuiMouse, _styled
from installer.tui_view import _armed, _bar_commits, _pager_items
if TYPE_CHECKING:
from installer.tui_session import TuiHits
def tui_update(state: TuiState, key: TuiKey | TuiMouse) -> list[tuple]:
"""What a key does on the current screen, and the work it starts. A
choice that --standalone cannot sit beside turns it off, said once."""
effects = _tui_key(state, key)
if state.standalone and state.emulators and not _tui_standalone_fits(state):
state.standalone = False
state.status = TUI_STANDALONE_OFF
return effects
# Said when a choice of regions, cores or systems turns Standalone off.
TUI_STANDALONE_OFF = ("Standalone version off: the build is installed whole, which "
"regions, cores and systems do not narrow.")
def _tui_pad_key(state: TuiState, key: TuiKey) -> TuiKey:
"""The key a handheld's buttons mean on this screen."""
if state.pad == "miyoo":
key = _miyoo_key(state, key)
if (state.pad in _NO_PAGE_PADS and key.name in ("left", "right")
and state.screen not in ("regions", "options")):
# muxterm keeps PgUp and PgDn for its scrollback: the D-pad's Left
# and Right page instead (X or Y still ticks). One system of 66 took
# about 60 Down presses.
key = TuiKey("pgup" if key.name == "left" else "pgdn")
return key
def _tui_run_screen_key(state: TuiState, key: TuiKey, char: str) -> list[tuple]:
"""A key while a check or an install runs."""
if state.screen == "checking":
if char == "q":
return tui_quit(state)
return _back(state) if key.name in ("esc", "backspace") else []
# B, Esc and q are the stops a controller or a plain keyboard has.
if key.name in ("esc", "backspace") or char == "q":
return tui_interrupt(state)
return []
def _tui_focus_move(state: TuiState, key: TuiKey, char: str, rows: list[TuiRow],
focus: int, wrap: bool) -> tuple[int, list[TuiRow]] | None:
"""The focus a move takes the list to, and its rows, None for a key that
moves nothing."""
screen = state.screen
last = len(rows) - 1
page = _page_step(state) if key.name in ("pgup", "pgdn") else 1
name = key.name
if name == "up" or char == "k":
return (last if wrap and focus == 0 else max(0, focus - 1)), rows
if name == "down" or char == "j":
return (0 if wrap and focus == last else min(last, focus + 1)), rows
if name == "pgup":
return max(0, focus - page), rows
if name == "pgdn":
return min(last, focus + page), rows
if name == "home" or char == "g":
return 0, rows
if name == "end" or char == "G":
return last, rows
if name in ("esc", "backspace") and state.filters.get(screen):
# The filter goes first, the screen with the second press, and the
# row in focus stays in focus.
row = rows[focus]
state.filters[screen] = ""
rows = tui_rows(state)
return next((i for i, item in enumerate(rows)
if item.action == row.action and item.value == row.value), focus), rows
return None
def _tui_list_action(state: TuiState, key: TuiKey, char: str, rows: list[TuiRow],
row: TuiRow) -> list[tuple] | None:
"""What a key does on a list of ticks or on the options, None for none."""
screen, name = state.screen, key.name
if screen == "regions" and char == " " and row.action == "region":
return _activate(state, row)
if screen == "regions" and name in ("left", "shift-up", "right", "shift-down"):
_move_region(state, str(row.value), -1 if name in ("left", "shift-up") else 1)
return []
if screen in _CHECKLISTS and row.action in ("system", "core", "emulator") and (
char == " " or name in ("right", "left")):
_tick(state, row, None if char == " " else name == "right")
return []
if screen in (*_CHECKLISTS, "regions") and char == " ":
# X on All, None, Done or the filter: only A, an explicit choice,
# acts there.
return []
if screen in (*_CHECKLISTS, "regions") and char in ("a", "n"):
# All and None by name, at the end of a list of 189 rows.
named = [item for item in rows if item.action == ("all" if char == "a" else "none")]
return _checklist(state, named[0]) if named else []
if screen == "options" and name in ("left", "right"):
return _option(state, row.action, 1 if name == "right" else -1) \
if row.action in ("game_data", "installed", "jobs", "addapp", "offline") \
or (row.action == "from" and name == "left") else []
return None
def _tui_row_action(state: TuiState, key: TuiKey, char: str, rows: list[TuiRow],
row: TuiRow) -> list[tuple] | None:
"""What a key that moves no focus does on a list, None for nothing."""
screen, name = state.screen, key.name
if name in ("esc", "backspace"):
return tui_quit(state) if screen == "result" else _back(state)
if (name == "tab" or char == "o") and screen in ("plan", "systems", "confirm"):
_push(state, "options")
state.focus["options"] = _first_item(state)
return []
if char == "/" and any(item.action == "filter" for item in rows):
# The focus goes to the field typed into: it stayed on None, and the
# bar named None's keys while letters went into the filter.
state.editing = screen
state.focus[screen] = next(i for i, item in enumerate(rows) if item.action == "filter")
return []
listed = _tui_list_action(state, key, char, rows, row)
if listed is not None:
return listed
if char == " ":
return _space(state, row)
if name == "enter":
return _activate(state, row)
return None
def _tui_past_heading(state: TuiState, key: TuiKey, char: str, rows: list[TuiRow],
focus: int, last: int, wrap: bool) -> int:
"""The row a move lands on instead of a heading."""
name = key.name
# A heading names the rows under it and is never in focus: the
# move goes on to the next row its way, else stays where it was.
step = -1 if name in ("up", "pgup", "end") or char in ("k", "G") else 1
moved = name in ("up", "down") or char in ("k", "j")
if not moved and focus in (0, last):
# A page or Home clamped to an end: the first row from that end.
step = 1 if focus == 0 else -1
order = list(range(focus, -1, -1) if step < 0 else range(focus, len(rows)))
if wrap and moved:
order += range(last, focus, -1) if step < 0 else range(focus)
return next((index for index in order if rows[index].action != "heading"),
max(0, min(state.focus.get(state.screen, 0), last)))
def _tui_row_key(state: TuiState, key: TuiKey, char: str, rows: list[TuiRow]) -> list[tuple]:
"""A key on a screen that lists rows."""
screen = state.screen
focus = max(0, min(state.focus.get(screen, 0), len(rows) - 1))
row = rows[focus]
last = len(rows) - 1
# A list of ticks wraps at any length: None and Done, at its end, are
# a few presses up from its first item on a pad.
wrap = len(rows) < 10 or screen in (*_CHECKLISTS, "regions")
moved = _tui_focus_move(state, key, char, rows, focus, wrap)
if moved is None:
acted = _tui_row_action(state, key, char, rows, row)
if acted is not None:
return acted
else:
focus, rows = moved
if rows[focus].action == "heading":
focus = _tui_past_heading(state, key, char, rows, focus, last, wrap)
state.focus[screen] = focus
return []
def _tui_screen_key(state: TuiState, key: TuiKey) -> list[tuple]:
"""A key on the current screen, once no field takes it."""
screen = state.screen
char = key.text if key.name == "char" else ""
if key.name == "f1" or char == "?":
state.help = True
return []
if screen in ("checking", "installing"):
return _tui_run_screen_key(state, key, char)
if char == "q":
return tui_quit(state)
rows = tui_rows(state)
if screen == "error" and key.name in ("pgup", "pgdn"):
# The message scrolls, the rows stay (_view_error).
step = max(1, state.rows - len(rows) - 5)
state.focus["error_text"] = max(0, state.focus.get("error_text", 0)
+ (step if key.name == "pgdn" else -step))
return []
if (char == "d" and screen in ("plan", "confirm", "result") and not (
screen == "confirm" and (state.running or state.dry is None))) or (
screen == "result" and not rows and (char == "o" or key.name == "tab")):
return _open_details(state)
if screen in _PAGERS and not rows:
return _pager_key(state, key)
if not rows:
return _back(state) if key.name in ("esc", "backspace") else []
return _tui_row_key(state, key, char, rows)
def _tui_key(state: TuiState, key: TuiKey | TuiMouse) -> list[tuple]:
"""tui_update for one key."""
if isinstance(key, TuiMouse):
return tui_mouse(state, key)
# A key moves the focus its own way: the next tap focuses again.
state.tapped = None
if key.name in ("ctrl-c", "ctrl-d"):
return tui_interrupt(state)
if state.cols < TUI_MIN_COLS or state.rows < TUI_MIN_ROWS:
return []
if state.help:
state.help = False
return []
if state.app_running:
# The app is being written to the card: it finishes first.
return []
if state.screen == "path" and key.name == "f1":
# ? is typed into the path there: F1 opens the help, which says the
# refusal in full. "? says more" could not be followed on this screen.
state.help = True
return []
if not (key.name == "f1" or (key.name == "char" and key.text == "?")
and state.screen != "path"):
# The help says it in full: the status is the short form.
state.status_more = ""
state.status = ""
if state.screen == "path":
return _path_key(state, key)
if state.editing and key.name == "f1":
# ? is typed into the filter, F1 opens the help: it ended the typing
# and opened nothing. The typing goes on once the help closes.
state.help = True
return []
if state.editing:
return _filter_key(state, key)
return _tui_screen_key(state, _tui_pad_key(state, key))
# Lines one notch of the wheel moves.
TUI_WHEEL_LINES = 3
# Seconds after a screen is drawn during which a press is taken for the
# second tap of a double tap made on the screen before, and dropped. A
# double click is two presses at most 400 ms (GTK, GNOME) to 500 ms
# (Windows, macOS) apart, and the new screen is drawn on the first release,
# about 100 ms after the first press: 0.4 s after the draw covers both. A
# deliberate tap comes later, a reader taking longer than that to find it.
TUI_TAP_SETTLE = 0.4
def _tui_tap_done(state: TuiState, event: TuiMouse, hits: TuiHits, target: tuple | None) -> bool:
"""Whether event ends a tap made on target, a press kept for its release."""
button = event.button & 3
# A tap is a press and a release on one target of one frame: a release
# on a frame drawn after its press is dropped, and so is a press within
# TUI_TAP_SETTLE of a new screen, so the second tap of a double tap that
# changed the screen does nothing on the new one.
seen_on = (hits.frame, state.screen, len(state.stack), state.help, target)
if not event.release:
settled = state.now - hits.shown >= TUI_TAP_SETTLE
state.pressed = seen_on if button == 0 and settled else None
return False
pressed, state.pressed = state.pressed, None
if button not in (0, 3) or pressed != seen_on:
return False
if state.help:
# Any key closes the help, a tap too.
state.help = False
return False
return True
def _tui_tap_row(state: TuiState, target: tuple) -> list[tuple]:
"""A tap on a row of the list."""
rows = tui_rows(state)
index = target[1]
if index >= len(rows) or (rows[index].action, rows[index].value) != target[2]:
return []
screen = state.screen
row = rows[index]
seen = (screen, len(state.stack), row.action, row.value)
if row.action == "heading":
return []
if state.editing:
state.editing = ""
elif row.action in TUI_TICK_ROWS:
state.status = state.status_more = ""
state.focus[screen] = index
state.tapped = seen
if screen == "regions":
_toggle_region(state, row.value)
else:
_tick(state, row, None)
return []
elif (max(0, min(state.focus.get(screen, 0), len(rows) - 1)) == index
and (state.tapped == seen or _armed(state) is not None)):
# A second tap, on the row or on the bar entry that armed it.
state.tapped = None
return tui_update(state, TuiKey("enter"))
state.status = state.status_more = ""
state.focus[screen] = index
state.tapped = seen
return []
def tui_mouse(state: TuiState, event: TuiMouse) -> list[tuple]:
"""What a click, a tap or the wheel does, read against the frame on
screen when it came (state.hits): a frame drawn for another screen, or
a row no longer where it was drawn, does nothing.
A tap acts when the button goes up, on the target it went down on: a
swipe that ends elsewhere does nothing. What it does follows the row's
kind. A tick (a system, a core, a region) is ticked or unticked, as
Space does: a tap that unticks a box elsewhere continued here, and the
next one installed every file. A choice is focused, and opened by a
second tap on the row this screen saw tapped: one terminal row is far
smaller than a finger, and the row a screen opens on (Install on
Confirm) is never chosen by one tap. On a bar entry it presses that
entry's key. The right and middle buttons do nothing, nor a click with
Shift, Meta or Ctrl held, which the terminal keeps for its own
selection and links.
"""
hits = state.hits
if (event.button & 32 or hits is None or hits.screen != state.screen
or hits.help != state.help or hits.size != (state.cols, state.rows)
or hits.depth != len(state.stack)
or state.cols < TUI_MIN_COLS or state.rows < TUI_MIN_ROWS or state.app_running):
state.pressed = None
return []
target = hits.at(event.col - 1, event.row - 1)
if event.button & 64:
if event.release or event.button & 3 > 1 or state.help:
return []
return _wheel(state, hits, 1 if event.button & 1 else -1)
if event.button & 28:
state.pressed = None
return []
if not _tui_tap_done(state, event, hits, target) or target is None:
return []
if target[0] == "key":
return _bar_tap(state, target[1])
if target[0] == "scroll":
return _scroll_tap(state, target[1])
return _tui_tap_row(state, target)
def _bar_tap(state: TuiState, key: TuiKey) -> list[tuple]:
"""A tap on a bar entry. One that writes files (_bar_commits) is drawn
armed by the first tap and pressed by the second on the same screen,
on the bar or on the row it acts on."""
if key.name == "ctrl-c":
if state.run == "install" and state.running:
return tui_interrupt(state)
# A quit chosen with a finger is a quit chosen: QUIT_CODE, never
# the code of an interrupted run.
return tui_quit(state)
if not _bar_commits(state, key):
return tui_update(state, key)
if _armed(state) != key:
state.tapped = ("bar", state.screen, len(state.stack), key)
return []
state.tapped = None
return tui_update(state, key)
def _wheel(state: TuiState, hits: TuiHits, step: int) -> list[tuple]:
"""A notch of the wheel: the list, the message or the text moves, and
the focus moves only when it would leave the rows in view."""
screen = state.screen
lines = step * TUI_WHEEL_LINES
if hits.listing is not None:
first, shown, total = hits.listing
top = max(0, min(first + lines, total - shown))
state.list_top[screen] = top
rows = tui_rows(state)
focus = max(0, min(state.focus.get(screen, 0), len(rows) - 1))
focus = max(top, min(focus, top + shown - 1))
if rows and rows[focus].action == "heading":
# Never on a heading: the row under it, else the one above.
below = focus + 1 < min(len(rows), top + shown)
focus = focus + 1 if below or focus == 0 else focus - 1
state.focus[screen] = focus
elif hits.scroll == "error":
state.focus["error_text"] = max(0, state.focus.get("error_text", 0) + lines)
elif hits.scroll == "pager":
last = _pager_last(state, _pager_items(state))
state.focus[screen] = max(0, min(state.focus.get(screen, 0) + lines, last))
return []
def _scroll_tap(state: TuiState, kind: str) -> list[tuple]:
"""A tap on the line saying which lines are in view: the next page,
and from the last one the first."""
before = (dict(state.focus), dict(state.list_top))
effects = tui_update(state, TuiKey("pgdn"))
# The view keeps a scroll inside the text: measured, not guessed.
tui_view(state, state.cols, state.rows)
if (dict(state.focus), dict(state.list_top)) != before:
return effects
if kind == "error":
state.focus["error_text"] = 0
return effects
return effects + tui_update(state, TuiKey("home"))
# The routes inside muxterm, where no button sends PgUp or PgDn.
_NO_PAGE_PADS = ("muxterm", "gptokeyb_muxterm")
# A Miyoo's L1 and R1 are the keys E and T (codes 18 and 20).
_MIYOO_PAGES = {"e": "pgup", "t": "pgdn"}
def _miyoo_key(state: TuiState, key: TuiKey) -> TuiKey:
"""A Miyoo's buttons as the keys they stand for, outside a text field:
its A is Space, the button that chooses, so it acts as Enter but where
it ticks a system or a core."""
if key.name != "char":
return key
if key.text in _MIYOO_PAGES:
return TuiKey(_MIYOO_PAGES[key.text])
if key.text != " ":
return key
if state.screen in _CHECKLISTS:
rows = tui_rows(state)
row = rows[max(0, min(state.focus.get(state.screen, 0), len(rows) - 1))] \
if rows else None
if row is not None and row.action in ("system", "core"):
return key
return TuiKey("enter")
# Rows Space leaves alone: it is X (tick) on PortMaster and Y on muxterm, a
# key pressed for something else, and these end the run or write.
_SPACE_INERT = ("install", "close", "quit", "exit", "addapp")
def _space(state: TuiState, row: TuiRow) -> list[tuple]:
"""Space opens what a row leads to, and never installs by itself: on
the plan's Install it opens the confirm screen, where A installs."""
if row.action == "install" and state.screen == "plan":
if state.systems and not state.ticked:
state.status = "No system is ticked: tick one, or choose All."
return []
state.must_confirm = True
_push(state, "confirm")
return _start_run(state, "confirm")
if row.action in _SPACE_INERT:
return []
return _activate(state, row)
def _take_scan_event(state: TuiState, kind: str | None, event: dict) -> bool:
"""A check run's reading of the folder: games, files found, choices."""
if kind == "games":
state.games = event
elif kind == "games_unavailable":
state.games_unavailable = event
elif kind == "found":
state.found.append(event)
elif kind == "scanned":
state.scanned.append(event)
elif kind == "unreadable":
state.unreadable.append(event)
elif kind == "choices":
state.choices = list(event["systems"])
elif kind == "set_aside":
state.set_aside = set(event["dests"])
else:
return False
return True
def _take_check_event(state: TuiState, kind: str | None, event: dict) -> None:
if _take_scan_event(state, kind, event):
return
if kind == "board":
state.board = str(event["message"])
# Read on the device itself, or named by the card in a reader: a
# computer preparing a card has no board of its own.
state.board_seen = (state.platform, state.dest, str(event["board"]),
bool(event["applied"]), detect_board(state.platform) is not None)
elif kind == "version":
state.version = str(event["message"])
state.version_short = (f"List for {display_name(state.platform, state.manifest)} "
f"{event['list_version']}, this is "
f"{event['installed_version']}.")
elif kind == "saves":
state.saves = event
elif kind == "data" and state.check is not None:
state.check["data_bytes"] = event["bytes"]
elif kind == "check":
state.check = event
elif kind == "file":
state.checked_dests.add(event.get("dest"))
if event.get("state") != "present":
state.files.append(event)
elif kind == "system":
state.systems.append(event)
elif kind == "summary":
state.check_summary = event
def _take_dry_event(state: TuiState, kind: str | None, event: dict) -> None:
if kind == "saves":
state.dry_saves = event
elif kind == "data" and state.dry is not None:
state.dry["data_bytes"] = event["bytes"]
elif kind == "check":
state.dry = event
elif kind == "file" and event.get("state") != "present":
state.dry_files.append(event)
elif kind == "summary":
state.dry_summary = event
def _take_install_event(state: TuiState, kind: str | None, event: dict) -> None:
if kind == "app":
state.app = event
elif kind == "error" and event.get("stage") == "dest":
# The BIOS folder could not be created: every file fails for that
# one reason, said as it happened.
state.dest_error = event
elif kind == "saves":
state.done_saves = event
elif kind == "found":
state.local_dests[event["dest"]] = (event["folder"], event["reason"])
elif kind == "download":
state.download = event
elif kind == "transfer":
state.network = event["bytes_network"]
state.samples = [sample for sample in state.samples
if sample[0] >= state.now - 10] + [(state.now, state.network)]
elif kind in ("progress", "downloaded"):
state.progress = event
if kind == "downloaded":
state.finished.append((event["dest"], event["ok"], event["reason"]))
elif kind == "summary":
state.summary = event
def _take_event(state: TuiState, event: dict) -> None:
if _take_action_event(state, event):
return
kind = event.get("event")
if kind == "checking" and state.run in ("check", "install"):
state.reading = (event["files_done"], event["files_total"])
elif kind == "games_reading" and state.run in ("check", "install"):
state.games_reading = (event["files_done"], event["files_total"])
elif state.run == "check":
_take_check_event(state, kind, event)
elif state.run in ("confirm", "preview"):
_take_dry_event(state, kind, event)
elif state.run == "install":
_take_install_event(state, kind, event)
def _receive_games_here(state: TuiState, message: tuple) -> list[tuple]:
_kind, plat, dest, count = message
if plat == state.platform and dest == state.dest:
state.games_probed = (plat, dest)
if state.games_choice not in ("user", "cli", "record"):
state.games_here = count or 0
state.for_games, state.games_choice = bool(count), "probe"
return []
def _receive_manifest(state: TuiState, message: tuple) -> list[tuple]:
_kind, plat, manifest = message
if plat != state.platform or state.screen != "checking":
return []
state.manifest, state.manifest_for = manifest, plat
_known_choice(state, plat, manifest)
if state.games_probed is None:
state.games_probed = (plat, state.dest)
return _start_run(state, "check")
def _receive_targets(state: TuiState, message: tuple) -> list[tuple]:
_kind, plat, targets, problem = message
if plat == state.platform:
# Held only once read: a list that could not be read is fetched
# again the next time Device opens.
state.targets, state.targets_problem = targets, problem
state.targets_for = plat if targets is not None else ""
if state.screen == "device":
state.focus["device"] = _device_focus(state)
return []
def _receive_pack_opened(state: TuiState, message: tuple) -> list[tuple]:
_kind, path, pack, problem = message
if state.screen != "browse" or state.browse_for != "pack":
# Left before it opened: never read, closed.
return [("close_pack", pack)] if pack is not None else []
if problem:
state.status = _styled(problem, "refusal")
return []
# The pack's own list, as --from-pack reads it: the list fetched
# before is fetched again from the pack.
state.packs = [path]
state.browse_for = "dest"
state.manifest, state.manifest_for = None, ""
if not state.manifest_given:
state.manifest_path = None
state.targets_for = ""
return [("use_pack", pack), *_start_check(state)]
def _receive_app(state: TuiState, message: tuple) -> list[tuple]:
# Put from the result screen, in this process.
state.app, state.app_running = message[1], False
if not state.app["ok"] and state.code == 0:
state.code = 1
return []
def _receive_manifest_failed(state: TuiState, message: tuple) -> list[tuple]:
_kind, plat, title, lines, code = message
if plat != state.platform or state.screen != "checking":
return []
_fail(state, lines, code)
state.error_title = title
return []
_TUI_RECEIVERS: dict[str, Callable[[TuiState, tuple], list[tuple]]] = {
"games_here": _receive_games_here,
"manifest": _receive_manifest,
"targets": _receive_targets,
"pack_opened": _receive_pack_opened,
"app": _receive_app,
"manifest_failed": _receive_manifest_failed,
}
def _check_ended(state: TuiState, code: int, tail: list[str]) -> list[tuple]:
if state.check is None:
return _fail(state, tail, code)
state.ticked = {row["system"] for row in state.systems if _needed(row)}
state.emptied = []
state.hidden_ticks = set()
if state.keep_ticked is not None:
listed = {row["system"] for row in state.systems}
state.ticked = state.keep_ticked & listed
state.hidden_ticks = state.keep_ticked - listed
if state.keep_ticked and not state.ticked:
# Every system chosen holds nothing under these options:
# said, never taken as every system.
state.emptied = sorted(state.ticked_names.get(name, name)
for name in state.keep_ticked)
state.keep_ticked = None
state.facts = _tui_folder_facts(state)
state.has_backups = state.dest is not None and bool(list_backups(state.dest))
_replace(state, "plan")
refocus, state.refocus = state.refocus, ""
_focus_plan(state, refocus)
if state.widen:
state.widen = False
plan = tui_rows(state)
row = next((row for row in plan if row.action == "systems"), None)
if row is not None:
return _activate(state, row)
return []
def tui_receive(state: TuiState, message: tuple) -> list[tuple]:
"""What the file list fetch and the child runs report back."""
kind = message[0]
receiver = _TUI_RECEIVERS.get(kind)
if receiver is not None:
return receiver(state, message)
_kind, run_id, *rest = message
if run_id != state.run_id:
return []
if kind == "event":
_take_event(state, rest[0])
return []
code, tail = rest
state.running = False
state.tail = [line for line in tail if not line.startswith("RetroBIOS ")]
tail = state.tail
if state.run in TUI_ACTION_RUNS:
return _action_ended(state, code, tail)
if state.run == "check":
return _check_ended(state, code, tail)
if state.run == "confirm" and state.screen == "confirm":
if state.dry is None:
return _fail(state, tail, code)
if _same_plan(state.check, state.dry) and not state.must_confirm:
state.stack.pop()
return _install_now(state)
elif state.run == "install":
state.code = 130 if state.stopping and code < 0 else code if code >= 0 else 128 - code
_replace(state, "result")
return []
File diff suppressed because it is too large. Load diff
+373
View File
@@ -0,0 +1,373 @@
#!/usr/bin/env python3
"""Build install.py from the installer/ package.
install.py ships as one file that needs nothing but the standard library:
the one-line bootstraps, install.sh and install.ps1 pin its SHA-256, and the
portable launchers and the PyPI package carry it as is. Its source is the
installer/ package, one module per concern, each importing from the others
what it uses, so ruff and mypy read every module on its own.
This script joins the modules into one namespace, in the order their imports
give: the package docstring, one block of standard library imports, then each
module body with its imports taken out. It refuses what one namespace cannot
hold: an import from outside the standard library, a name defined by two
modules, an import cycle, an import under another name, and a statement run
at import time that reads a name from a module placed after its own.
Usage:
python scripts/build_installer.py # write install.py
python scripts/build_installer.py --check # exit 1 if install.py differs
"""
from __future__ import annotations
import argparse
import ast
import heapq
import sys
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from artifacts import write_text_atomic
ROOT = Path(__file__).resolve().parent.parent
PACKAGE = "installer"
OUTPUT = "install.py"
COMMAND = "python scripts/build_installer.py"
SHEBANG = "#!/usr/bin/env python3\n"
NOTICE = (
"# Generated by scripts/build_installer.py from the installer/ package. Edit\n"
"# the modules there and run the script: a change made here is overwritten.\n"
)
# C extensions a Python built without their libraries lacks. The installer
# imports them behind a guard that says so, instead of stopping on a
# ModuleNotFoundError traceback.
GUARDED = frozenset({"unicodedata", "zlib"})
GUARD = (
"# Built as C extensions that a Python compiled without their libraries\n"
"# lacks: the run stopped on a ModuleNotFoundError traceback.\n"
"try:\n"
"{imports}"
"except ImportError as _missing:\n"
' print(f"Error: this Python was built without its {{_missing.name}} module, which "\n'
' "the installer needs. Run it with another Python 3.8 or newer.", file=sys.stderr)\n'
" sys.exit(1)\n"
)
LINE_LENGTH = 120
MARKER_WIDTH = 79
_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda,
ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
class BuildError(Exception):
"""The package cannot be joined into one module."""
@dataclass
class Module:
name: str
body: str
statements: list[ast.stmt]
plain: set[tuple[str, str | None]] = field(default_factory=set)
froms: set[tuple[str, str]] = field(default_factory=set)
imports: dict[str, set[str]] = field(default_factory=dict)
type_imports: dict[str, set[str]] = field(default_factory=dict)
defines: set[str] = field(default_factory=set)
def _is_docstring(node: ast.stmt) -> bool:
return (isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant)
and isinstance(node.value.value, str))
def _is_type_checking_block(node: ast.stmt) -> bool:
return (isinstance(node, ast.If) and isinstance(node.test, ast.Name)
and node.test.id == "TYPE_CHECKING" and not node.orelse)
def _is_stdlib(module: str) -> bool:
return module.split(".")[0] in sys.stdlib_module_names
def _package_import(module: Module, node: ast.ImportFrom, where: str, type_only: bool) -> None:
"""Record an import from another module of the package."""
parts = (node.module or "").split(".")
if node.level or len(parts) != 2 or parts[0] != PACKAGE:
raise BuildError(f"{where}:{node.lineno}: import from {PACKAGE}.<module> by its full name")
for alias in node.names:
if alias.asname and alias.asname != alias.name:
raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}: "
"one namespace keeps one name")
target = module.type_imports if type_only else module.imports
target.setdefault(parts[1], set()).update(alias.name for alias in node.names)
def _stdlib_import(module: Module, node: ast.Import | ast.ImportFrom, where: str) -> None:
if isinstance(node, ast.Import):
for alias in node.names:
if not _is_stdlib(alias.name):
raise BuildError(f"{where}:{node.lineno}: {alias.name} is not in the standard library")
module.plain.add((alias.name, alias.asname))
return
for alias in node.names:
if alias.asname and alias.asname != alias.name:
raise BuildError(f"{where}:{node.lineno}: {alias.name} imported as {alias.asname}")
module.froms.add((node.module or "", alias.name))
def _read_header(module: Module, header: list[ast.stmt], where: str) -> None:
for node in header:
if isinstance(node, ast.If):
for sub in node.body:
if not isinstance(sub, ast.ImportFrom):
raise BuildError(f"{where}:{sub.lineno}: a TYPE_CHECKING block holds imports only")
_package_import(module, sub, where, type_only=True)
elif isinstance(node, ast.ImportFrom) and node.module == "__future__":
continue
elif isinstance(node, ast.ImportFrom) and (node.level or not _is_stdlib(node.module or "")):
_package_import(module, node, where, type_only=False)
elif isinstance(node, (ast.Import, ast.ImportFrom)):
_stdlib_import(module, node, where)
def _check_nested_imports(statements: list[ast.stmt], where: str) -> None:
"""Imports below the header are joined as written: inside functions, standard library only."""
for statement in statements:
for node in ast.walk(statement):
if isinstance(node, ast.Import):
names = [alias.name for alias in node.names]
elif isinstance(node, ast.ImportFrom):
names = [node.module or "." * node.level]
else:
continue
for name in names:
if node.col_offset == 0 or not _is_stdlib(name):
raise BuildError(f"{where}:{node.lineno}: import {name} below the header "
"(module imports go first, nested ones from the standard library)")
def _header_length(tree: ast.Module, where: str) -> int:
"""How many leading statements are the docstring, the imports and the TYPE_CHECKING block."""
body = tree.body
if not body or not _is_docstring(body[0]):
raise BuildError(f"{where}: no module docstring")
count = 1
while count < len(body) and (isinstance(body[count], (ast.Import, ast.ImportFrom))
or _is_type_checking_block(body[count])):
count += 1
future = any(isinstance(node, ast.ImportFrom) and node.module == "__future__"
and any(alias.name == "annotations" for alias in node.names) for node in body[:count])
if not future:
raise BuildError(f"{where}: no 'from __future__ import annotations', which install.py holds")
return count
def _module_scope(node: ast.AST) -> Iterator[ast.AST]:
"""The nodes of the module scope, the scopes it opens yielded but not entered."""
stack = [node]
while stack:
current = stack.pop()
yield current
if current is not node and isinstance(current, _SCOPES):
continue
if isinstance(current, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
continue
stack.extend(ast.iter_child_nodes(current))
def _defined_names(statements: list[ast.stmt]) -> set[str]:
names: set[str] = set()
for statement in statements:
for node in _module_scope(statement):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
names.add(node.name)
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
names.add(node.id)
elif isinstance(node, ast.ExceptHandler) and node.name:
names.add(node.name)
return names
def read_module(path: Path) -> Module:
where = f"{PACKAGE}/{path.name}"
source = path.read_text(encoding="utf-8")
tree = ast.parse(source, filename=where)
count = _header_length(tree, where)
lines = source.splitlines(keepends=True)
start = tree.body[count - 1].end_lineno or 0
module = Module(path.stem, "".join(lines[start:]).strip("\n"), tree.body[count:])
_read_header(module, tree.body[1:count], where)
_check_nested_imports(module.statements, where)
module.defines = _defined_names(module.statements)
if "TYPE_CHECKING" in {node.id for statement in module.statements for node in ast.walk(statement)
if isinstance(node, ast.Name)}:
raise BuildError(f"{where}: TYPE_CHECKING read below the header")
return module
def read_package(package: Path) -> dict[str, Module]:
modules = {path.stem: read_module(path) for path in sorted(package.glob("*.py"))
if path.name != "__init__.py"}
owners: dict[str, str] = {}
imported = {alias or name.split(".")[0] for module in modules.values() for name, alias in module.plain}
imported |= {name for module in modules.values() for _source, name in module.froms}
for module in modules.values():
for name in sorted(module.defines):
if name in owners:
raise BuildError(f"{name} is defined in {owners[name]}.py and {module.name}.py")
if name in imported:
raise BuildError(f"{module.name}.py defines {name}, a name the standard library imports bind")
owners[name] = module.name
for module in modules.values():
for other, names in sorted([*module.imports.items(), *module.type_imports.items()]):
if other not in modules or other == module.name:
raise BuildError(f"{module.name}.py imports from {PACKAGE}.{other}, not another module of it")
for name in sorted(names - modules[other].defines):
raise BuildError(f"{module.name}.py imports {name} from {other}.py, which does not define it")
return modules
def module_order(modules: dict[str, Module]) -> list[str]:
"""Each module after the ones it imports outside TYPE_CHECKING, ties in name order."""
waiting = {name: len(module.imports) for name, module in modules.items()}
users: dict[str, set[str]] = {name: set() for name in modules}
for name, module in modules.items():
for dep in module.imports:
users[dep].add(name)
ready = [name for name, count in waiting.items() if count == 0]
heapq.heapify(ready)
order: list[str] = []
while ready:
name = heapq.heappop(ready)
order.append(name)
for user in users[name]:
waiting[user] -= 1
if waiting[user] == 0:
heapq.heappush(ready, user)
if len(order) != len(modules):
cycle = sorted(name for name, count in waiting.items() if count)
raise BuildError(f"import cycle among {', '.join(cycle)}")
return order
def _loads_at_import(statement: ast.stmt) -> Iterator[ast.Name]:
"""The names a statement reads when the module runs, not when its functions are called."""
stack: list[ast.AST] = [statement]
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
args = node.args
stack.extend(default for default in [*args.defaults, *args.kw_defaults] if default is not None)
stack.extend(getattr(node, "decorator_list", []))
continue
if isinstance(node, ast.AnnAssign):
stack.extend(child for child in (node.target, node.value) if child is not None)
continue
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
yield node
stack.extend(ast.iter_child_nodes(node))
def check_import_time(modules: dict[str, Module], order: list[str]) -> None:
position = {name: index for index, name in enumerate(order)}
owners = {name: module.name for module in modules.values() for name in module.defines}
for module in modules.values():
for statement in module.statements:
for node in _loads_at_import(statement):
owner = owners.get(node.id)
if owner is not None and position[owner] > position[module.name]:
raise BuildError(f"{module.name}.py:{node.lineno}: {node.id} is read at import time "
f"but {owner}.py comes later")
def _type_key(name: str) -> tuple[int, str]:
if len(name) > 1 and name.isupper():
return (0, name)
return (1 if name[0].isupper() else 2, name)
def _from_line(module: str, names: set[str]) -> str:
ordered = sorted(names, key=_type_key)
line = f"from {module} import {', '.join(ordered)}"
if len(line) <= LINE_LENGTH:
return line + "\n"
return f"from {module} import (\n" + "".join(f" {name},\n" for name in ordered) + ")\n"
def import_header(modules: dict[str, Module]) -> tuple[str, str]:
"""The merged standard library imports, and the guard of the C extensions among them."""
plain = {entry for module in modules.values() for entry in module.plain}
guarded = sorted(name for name, alias in plain if name in GUARDED and alias is None)
lines = [f"import {name}" + (f" as {alias}" if alias else "") + "\n"
for name, alias in sorted(plain, key=lambda entry: (entry[0].lower(), entry[1] or ""))
if name not in guarded]
froms: dict[str, set[str]] = {}
for module in modules.values():
for source, name in module.froms:
if (source, name) != ("typing", "TYPE_CHECKING"):
froms.setdefault(source, set()).add(name)
lines += [_from_line(source, names) for source, names in sorted(froms.items())]
guard = GUARD.format(imports="".join(f" import {name}\n" for name in guarded)) if guarded else ""
return "".join(lines), guard
def _marker(name: str) -> str:
head = f"# --- {PACKAGE}/{name}.py "
return head + "-" * max(3, MARKER_WIDTH - len(head)) + "\n"
def _docstring(package: Path) -> str:
text = (package / "__init__.py").read_text(encoding="utf-8").strip("\n")
body = ast.parse(text).body
if len(body) != 1 or not _is_docstring(body[0]):
raise BuildError(f"{PACKAGE}/__init__.py holds the docstring of install.py and nothing else")
return text + "\n"
def build(package: Path) -> str:
"""install.py as the package gives it."""
docstring = _docstring(package)
modules = read_package(package)
order = module_order(modules)
check_import_time(modules, order)
imports, guard = import_header(modules)
parts = [SHEBANG, NOTICE, docstring, "from __future__ import annotations\n\n", imports]
if guard:
parts += ["\n", guard]
for name in order:
if modules[name].body:
parts += ["\n\n", _marker(name), "\n", modules[name].body, "\n"]
return "".join(parts)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Build install.py from the installer/ package.")
parser.add_argument("--check", action="store_true",
help="write nothing, exit 1 if install.py differs from what the package builds")
args = parser.parse_args(argv)
try:
text = build(ROOT / PACKAGE)
except BuildError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
target = ROOT / OUTPUT
current = target.read_text(encoding="utf-8") if target.exists() else ""
if args.check:
if current != text:
print(f"{OUTPUT} differs from what {PACKAGE}/ builds: run {COMMAND}", file=sys.stderr)
return 1
print(f"{OUTPUT} is built from {PACKAGE}/")
return 0
if current == text:
print(f"{OUTPUT} unchanged")
return 0
write_text_atomic(str(target), text)
print(f"wrote {OUTPUT}")
return 0
if __name__ == "__main__":
from common import run_cli
run_cli(main)
+164
View File
@@ -0,0 +1,164 @@
"""install.py is built from the installer/ package.
The installer ships as one stdlib-only file that the bootstraps pin by hash,
and its source is a package of modules that import from each other. These
tests hold the committed file to what the package builds and the joining to
what one namespace can hold.
"""
from __future__ import annotations
import tests
import ast
import tempfile
import textwrap
import unittest
from pathlib import Path
import build_installer
REPO_ROOT = Path(__file__).resolve().parents[1]
DOCSTRING = '"""A test installer."""\n'
def _package(root: Path, modules: dict[str, str]) -> Path:
package = root / "installer"
package.mkdir()
(package / "__init__.py").write_text(DOCSTRING, encoding="utf-8")
for name, body in modules.items():
(package / f"{name}.py").write_text(textwrap.dedent(body).lstrip("\n"), encoding="utf-8")
return package
class TheCommittedFileIsTheBuiltOne(unittest.TestCase):
def test_install_py_is_what_the_package_builds(self):
built = build_installer.build(REPO_ROOT / "installer")
self.assertEqual(built, (REPO_ROOT / "install.py").read_text(encoding="utf-8"),
f"install.py differs from installer/: run {build_installer.COMMAND}")
def test_two_builds_give_the_same_bytes(self):
self.assertEqual(build_installer.build(REPO_ROOT / "installer"),
build_installer.build(REPO_ROOT / "installer"))
def test_the_file_says_it_is_generated(self):
head = (REPO_ROOT / "install.py").read_text(encoding="utf-8").splitlines()[:3]
self.assertEqual(head[0], "#!/usr/bin/env python3")
self.assertIn("scripts/build_installer.py", head[1])
def test_every_module_keeps_the_3_8_grammar_and_annotations_unevaluated(self):
for path in sorted((REPO_ROOT / "installer").glob("*.py")):
source = path.read_text(encoding="utf-8")
with self.subTest(module=path.name):
ast.parse(source, filename=path.name, feature_version=(3, 8))
if path.name != "__init__.py":
self.assertIn("from __future__ import annotations\n", source)
class JoiningRefusesWhatOneNamespaceCannotHold(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.root = Path(self._tmp.name)
def tearDown(self):
self._tmp.cleanup()
def assert_refused(self, modules: dict[str, str], words: str) -> None:
package = _package(self.root, modules)
with self.assertRaises(build_installer.BuildError) as caught:
build_installer.build(package)
self.assertIn(words, str(caught.exception))
def test_a_package_joins_in_import_order(self):
package = _package(self.root, {
"b": '''
"""B."""
from __future__ import annotations
import os
from installer.a import A
B = A + os.sep
''',
"a": '''
"""A."""
from __future__ import annotations
import sys
import zlib
A = sys.platform + str(zlib.crc32(b""))
''',
})
text = build_installer.build(package)
self.assertLess(text.index("A = sys.platform"), text.index("B = A + os.sep"))
self.assertIn("import os\nimport sys\n", text)
self.assertNotIn("from installer", text)
self.assertIn("try:\n import zlib\nexcept ImportError as _missing:", text)
self.assertNotIn("\nimport zlib\n", text)
namespace: dict[str, object] = {}
exec(compile(text, "install.py", "exec"), namespace)
self.assertTrue(str(namespace["B"]).endswith("0/"))
def test_an_import_outside_the_standard_library(self):
self.assert_refused({"a": '''
"""A."""
from __future__ import annotations
import yaml
'''}, "not in the standard library")
def test_a_name_two_modules_define(self):
self.assert_refused({
"a": '"""A."""\nfrom __future__ import annotations\n\nX = 1\n',
"b": '"""B."""\nfrom __future__ import annotations\n\nX = 2\n',
}, "X is defined in a.py and b.py")
def test_an_import_cycle(self):
self.assert_refused({
"a": '"""A."""\nfrom __future__ import annotations\n\nfrom installer.b import g\n\n\ndef f():\n return g\n',
"b": '"""B."""\nfrom __future__ import annotations\n\nfrom installer.a import f\n\n\ndef g():\n return f\n',
}, "import cycle among a, b")
def test_a_type_checking_import_is_no_cycle(self):
package = _package(self.root, {
"a": ('"""A."""\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\n'
'if TYPE_CHECKING:\n from installer.b import B\n\n\ndef f(b: B) -> None:\n return None\n'),
"b": '"""B."""\nfrom __future__ import annotations\n\nfrom installer.a import f\n\n\nclass B:\n pass\n',
})
text = build_installer.build(package)
self.assertNotIn("TYPE_CHECKING", text)
self.assertLess(text.index("def f("), text.index("class B:"))
def test_an_import_under_another_name(self):
self.assert_refused({
"a": '"""A."""\nfrom __future__ import annotations\n\nX = 1\n',
"b": '"""B."""\nfrom __future__ import annotations\n\nfrom installer.a import X as Y\n\nZ = Y\n',
}, "imported as Y")
def test_a_name_the_imported_module_does_not_define(self):
self.assert_refused({
"a": '"""A."""\nfrom __future__ import annotations\n\nX = 1\n',
"b": '"""B."""\nfrom __future__ import annotations\n\nfrom installer.a import W\n\nZ = W\n',
}, "imports W from a.py, which does not define it")
def test_a_name_read_at_import_from_a_later_module(self):
# c reads b's name when it runs without importing b: b sorts after c.
self.assert_refused({
"c": '"""C."""\nfrom __future__ import annotations\n\nfrom installer.a import A\n\nC = A + D\n',
"a": '"""A."""\nfrom __future__ import annotations\n\nA = 1\n',
"d": '"""D."""\nfrom __future__ import annotations\n\nD = 2\n',
}, "D is read at import time but d.py comes later")
def test_a_module_without_unevaluated_annotations(self):
self.assert_refused({"a": '"""A."""\nX = 1\n'}, "from __future__ import annotations")
def test_an_import_below_the_header(self):
self.assert_refused({
"a": '"""A."""\nfrom __future__ import annotations\n\nX = 1\nimport os\n',
}, "import os below the header")
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -1812,11 +1812,12 @@ class Rendering(unittest.TestCase):
class TheSectionStandsApart(unittest.TestCase):
def test_no_name_of_the_installer_is_defined_again(self):
"""_run and _system_label were defined twice: the later one won, and
the installer's listing called the interface's."""
the installer's listing called the interface's. The interface is
modules of installer/ now, joined into one namespace with the rest,
so no name is defined twice anywhere in the file."""
import ast
source = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
start = source[:source.index("# Full-screen interface\n#")].count("\n") + 1
seen: dict = {}
for node in ast.parse(source).body:
names = [node.name] if isinstance(node, (ast.FunctionDef, ast.ClassDef)) else [
@@ -1825,7 +1826,7 @@ class TheSectionStandsApart(unittest.TestCase):
for name in names:
seen.setdefault(name, []).append(node.lineno)
twice = {name: lines for name, lines in seen.items()
if len(lines) > 1 and max(lines) >= start}
if len(lines) > 1}
self.assertEqual(twice, {})
+7 -1
View File
@@ -323,8 +323,14 @@ class TroubleshootingLines(unittest.TestCase):
self.assertRegex(" ".join(_wiki(name).split()), r"[Dd]o what the message says")
def test_the_installer_names_what_to_run(self):
import ast
# The function itself, read by its node: install.py is joined from
# installer/, and the definition after it is no fixed neighbour.
source = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
advice = source[source.index("def _write_advice"):source.index("def _plural")]
node = next(node for node in ast.parse(source).body
if isinstance(node, ast.FunctionDef) and node.name == "_write_advice")
advice = ast.get_source_segment(source, node)
self.assertIn("hint.command(plat, path, elevated=True)", advice)