# SPDX-License-Identifier: MIT """The one front door: any cart or program file in, one :class:`CartDescription` out. docs/cartridge.md, "One front door". Steps, each a small pure function: 1. unwrap ``.zip`` / ``.7z`` (in memory, in place); 2. sniff by content: ``LYNX`` -> LNX, ``BS93`` -> BLL, else raw; 3. strip the header, keep it as *claims*; 4. hash the payload (SHA-1, and CRC-32 for display): an ``.lnx`` and its ``.lyx`` meet at one key; 5. look the key up in the cart table; 6. resolve each field: **user override > table > header > size rule > default** (decided 2026-11-12, open decision 3), with a warning naming both values whenever two sources disagree; 7. return the description, every field with its provenance. Block size is the one field where a losing value is kept: when the table and the header disagree (C14, Zaku (Beta)), the table's value is used and the header's is listed in ``bank0_alternatives`` so that the boot can try it if the cart's directory read fails (decision 3), and record which booted. A header's block size that contradicts the size rule on a full-size payload (Mines 2 (Demo): 2048 on 256 KiB) loses to the size rule (2026-11-19) and is kept the same way. """ from __future__ import annotations import hashlib import json import os import zlib from dataclasses import dataclass, field from pathlib import Path from typing import Any from lynx_python.bootrom import BOOT_ROM_SHA1S from lynx_python.cart.formats import ( ROTATIONS, BllHeader, FormatError, LnxHeader, decode_eeprom, split, unwrap, ) from lynx_python.cart.table import CartTable, default_table BLOCK_SIZES = (256, 512, 1024, 2048) # docs/cartridge.md "Headerless dumps": a full 256-page image of 64/128/256/512 KiB. # HandyROM: "bytes per page is derived by dividing ROM size by 256" (tier 2). SIZE_RULE = {256 * b: b for b in BLOCK_SIZES} class NotACart(FormatError): """The image is a Lynx boot ROM (accepted as one by hash), not a cart.""" @dataclass(frozen=True) class CartDescription: """Everything the board and the frontend need about one cart or program. ``provenance`` maps each resolved field to where it came from: ``user``, ``table:softlist``, ``table:lnx-header``, ``header``, ``size-rule``, ``default`` (and for ``name`` also ``table:nointro`` and ``filename``). """ payload: bytes sha1: str crc32: str kind: str # lnx, raw, bll: what the file was container: str # loose, zip, 7z member: str bank0_block: int bank1_block: int audin: bool rotation: str # none, left, right eeprom: tuple[str, int] | None # (type, organisation in bits) boot: str # "encrypted" (frame at offset 0) or "ram" (BLL) name: str provenance: dict[str, str] warnings: tuple[str, ...] = () bank0_alternatives: tuple[ tuple[int, str], ... ] = () # (block, source) to try if the table's fails header: LnxHeader | BllHeader | None = None bll_load: int | None = None table_lnx_header: dict[str, Any] | None = None # the header we observed for this payload conflicts: tuple[dict[str, Any], ...] = field(default=()) @property def bank0_size(self) -> int: """Bytes of the payload that belong to bank 0 (CART0).""" if self.boot == "ram": return 0 return min(len(self.payload), 256 * self.bank0_block * (2 if self.audin else 1)) @property def bank1(self) -> bytes: return self.payload[self.bank0_size :] if self.bank1_block else b"" def overrides_path() -> Path: """The user's override file (``~/.local/share/lynx-python/overrides.json``).""" base = os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share") return Path(base) / "lynx-python" / "overrides.json" def load_overrides(path: Path | None = None) -> dict[str, dict[str, Any]]: path = path or overrides_path() try: return json.loads(path.read_text("utf-8")) except FileNotFoundError: return {} def save_override(sha1: str, values: dict[str, Any], path: Path | None = None) -> Path: """Record user-supplied fields for a payload (never written next to a ROM).""" path = path or overrides_path() data = load_overrides(path) data.setdefault(sha1, {}).update(values) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", "utf-8") return path def _normalise_override(key: str, value: Any) -> Any: if key == "rotation": if value not in ROTATIONS: raise ValueError(f"rotation must be one of {ROTATIONS}, not {value!r}") return value if key in ("bank0_block", "bank1_block"): value = int(value) if value not in BLOCK_SIZES and not (key == "bank1_block" and value == 0): raise ValueError(f"{key} must be one of {BLOCK_SIZES}") return value if key == "audin": return bool(value) if key == "eeprom": if value in (None, "none", 0): return None if isinstance(value, str): kind, _, org = value.partition(":") return (kind.upper(), int(org or 16)) return (str(value[0]).upper(), int(value[1])) if key == "name": return str(value) raise ValueError(f"unknown override field {key!r}") def describe( data: bytes, *, member: str = "", container: str = "loose", table: CartTable | None = None, overrides: dict[str, Any] | None = None, ) -> CartDescription: """Steps 2-7 on the bytes of one file (already unwrapped).""" table = default_table() if table is None else table kind, header, payload = split(data) if not payload: raise FormatError(f"{member}: empty payload") sha1 = hashlib.sha1(payload).hexdigest() if sha1 in BOOT_ROM_SHA1S: raise NotACart(f"{member}: this is the Lynx boot ROM (SHA-1 {sha1}), not a cart") crc = f"{zlib.crc32(payload) & 0xFFFFFFFF:08x}" entry = table.get(sha1) user = {k: _normalise_override(k, v) for k, v in (overrides or {}).items()} warnings: list[str] = [] provenance: dict[str, str] = {} claims: dict[str, Any] = {} if isinstance(header, LnxHeader): if header.bank0_block in BLOCK_SIZES: claims["bank0_block"] = header.bank0_block else: warnings.append(f"header bank 0 block size {header.bank0_block} is not a block size") if header.bank1_block in (0, *BLOCK_SIZES): claims["bank1_block"] = header.bank1_block else: warnings.append(f"header bank 1 block size {header.bank1_block} is not a block size") claims["audin"] = bool(header.audin & 1) if header.rotation_name is not None: claims["rotation"] = header.rotation_name else: warnings.append(f"header rotation byte {header.rotation} is undefined") claims["eeprom"] = decode_eeprom(header.eeprom) defaults: dict[str, Any] = { "bank1_block": 0, "audin": False, "rotation": "none", "eeprom": None, } rule = SIZE_RULE.get(len(payload)) if kind != "bll": # No rule size: the smallest block whose 256 pages hold the payload (MAME does the # same for a loose .lyx, lynx.cpp; here it is labelled a default, not a fact). defaults["bank0_block"] = next( (b for b in BLOCK_SIZES if 256 * b >= len(payload)), BLOCK_SIZES[-1] ) alternatives: list[tuple[int, str]] = [] resolved: dict[str, Any] = {} for key in ("bank0_block", "bank1_block", "audin", "rotation", "eeprom"): if kind == "bll" and key in ("bank0_block", "bank1_block"): resolved[key], provenance[key] = 0, "bll" continue candidates: list[tuple[Any, str]] = [] if key in user: candidates.append((user[key], "user")) if entry is not None and key in entry.fields: value, source = entry.fields[key] candidates.append((value, f"table:{source}")) if key in claims: candidates.append((claims[key], "header")) if key == "bank0_block" and rule is not None: # A header's block size (read from the file, or recorded in the table from our # own LNX headers) that gives other than 256 pages of a full-size payload loses # to the size rule; it stays in bank0_alternatives. DOC: carts are 256 pages of # the block size (docs/cartridge.md, "Headerless dumps"); OBSERVED (MAME 0.285, # closed box): Mines 2 (Demo)'s .lnx (header 2048) stays black while its .lyx # (size only, 1024) plays, and this board plays it with 1024 too (sweep # 2026-11-19). A curated table entry (softlist) keeps its precedence. header_sources = ("header", "table:lnx-header") demoted = [c for c in candidates if c[1] in header_sources and c[0] != rule] candidates = [c for c in candidates if c not in demoted] candidates.append((rule, "size-rule")) candidates.extend((value, "header") for value, _ in demoted) if key in defaults: candidates.append((defaults[key], "default")) value, source = candidates[0] resolved[key], provenance[key] = value, source for other, other_source in candidates[1:]: if other_source in ("default", "size-rule") and source != "user": # The size rule disagreeing with a table or header is reported once, below. continue if other != value: warnings.append( f"{key}: {source} says {_show(value)}, {other_source} says {_show(other)};" f" using {source}" ) if ( key == "bank0_block" and other_source == "header" and (other, other_source) not in alternatives ): alternatives.append((other, other_source)) if key == "bank0_block" and rule is not None and value != rule and source != "user": warnings.append( f"bank0_block: {source} says {value} but the payload is {len(payload)} bytes" f" (the size rule says {rule}): fewer or more than 256 pages" ) if kind == "bll": boot = "ram" else: boot = "encrypted" if "name" in user: name, provenance["name"] = user["name"], "user" elif entry is not None and entry.name: name, provenance["name"] = ( entry.name, "table:" + (entry.sources[0] if entry.sources else ""), ) elif isinstance(header, LnxHeader) and header.name.strip(): name, provenance["name"] = header.name.strip(), "header" else: name, provenance["name"] = Path(member).stem, "filename" return CartDescription( payload=payload, sha1=sha1, crc32=crc, kind=kind, container=container, member=member, bank0_block=resolved["bank0_block"], bank1_block=resolved["bank1_block"], audin=resolved["audin"], rotation=resolved["rotation"], eeprom=resolved["eeprom"], boot=boot, name=name, provenance=provenance, warnings=tuple(warnings), bank0_alternatives=tuple(alternatives), header=header, bll_load=header.load if isinstance(header, BllHeader) else None, table_lnx_header=entry.lnx_header if entry is not None else None, conflicts=entry.conflicts if entry is not None else (), ) def _show(value: Any) -> str: if isinstance(value, tuple): return ":".join(str(v) for v in value) return str(value) def load( source: str | Path | bytes, *, name: str | None = None, table: CartTable | None = None, overrides: dict[str, Any] | None = None, use_override_file: bool = True, ) -> CartDescription: """Load a cart or BLL program from a path (loose, ``.zip`` or ``.7z``) or bytes. ``overrides`` (field -> value) sit above everything; the user's override file (keyed by payload SHA-1) is consulted below them when ``use_override_file``. """ member, data, container = unwrap(source, name) merged: dict[str, Any] = {} if use_override_file: _, _, payload = split(data) merged.update(load_overrides().get(hashlib.sha1(payload).hexdigest(), {})) merged.update(overrides or {}) return describe(data, member=member, container=container, table=table, overrides=merged)