# SPDX-License-Identifier: MIT """Whole-machine save states: CPU, RAM, ANTIC, GTIA, POKEY, the cartridge and the board. A state is a plain dict (picklable); ``save``/``load`` write and read it under ``~/.local/share/a5200-python/saves/`` unless given a path. The cartridge payload and BIOS are not stored, only the cartridge's SHA-1 and its bank state: a state is restored onto a console holding the same cartridge. """ from __future__ import annotations import pickle from pathlib import Path SAVE_DIR = Path.home() / ".local/share/a5200-python/saves" BOARD_FIELDS = ( "cycles", "halted_cycles", "stalled_cycles", "data_bus", "frames", "_irq_line", "_irq_next", "_stack_writes", "_last_read", "nmis_lost", ) # fmt: skip # 2: pokey-python e276d27 changed the shape of chip.pot in its snapshots, so # states made at the old pin (5a06587, version 1) do not restore. # 3: the restarted pokey-python (6ed1ffa) has a new snapshot shape, and the pot # capacitors (pokey_python.rc.PotRC) are saved with their charge. # 4: the CX53 trak-balls' lag output, the trak-ball pins and the pot targets are # saved and restored as they stand (restore no longer calls Controllers.apply(), # which stepped the lag once more); the pads' key sets are copied at the save. VERSION = 4 def _copied(fields: dict) -> dict: """A pad's fields with its key set copied: the frontend mutates it in place.""" return {key: set(value) if isinstance(value, set) else value for key, value in fields.items()} def snapshot(console) -> dict: board = console.board controllers = console.controllers return { "version": VERSION, "machine": console.machine.name, "cart_sha1": console.cart.sha1, "cpu": board.cpu.capture_state(), "ram": bytes(board.ram), "frame": bytes(board.frame), "antic": board.antic.snapshot(), "gtia": board.gtia.snapshot(), "pokey": board.pokey.snapshot(), "cartridge": board.cartridge.snapshot(), "board": {name: getattr(board, name) for name in BOARD_FIELDS}, "pads": [_copied(vars(pad)) for pad in controllers.pads], "trak_balls": [list(ball.out) for ball in controllers._balls], "trak_pins": list(controllers._trak_pins), "pot_rc": { "target": list(controllers.rc.target), "charge": list(controllers.rc.charge), "when": list(controllers.rc.when), }, } def restore(console, state: dict) -> None: if state.get("version") != VERSION: raise ValueError(f"save state version {state.get('version')} is not {VERSION}") if state["machine"] != console.machine.name: raise ValueError(f"the save state belongs to machine {state['machine']}") if state["cart_sha1"] != console.cart.sha1: raise ValueError("the save state belongs to another cartridge") board = console.board board.cpu.restore_state(state["cpu"]) board.ram[:] = state["ram"] board.frame[:] = state["frame"] board.antic.restore(state["antic"]) board.gtia.restore(state["gtia"]) board.pokey.restore(state["pokey"]) board.cartridge.restore(state["cartridge"]) for name, value in state["board"].items(): setattr(board, name, value) controllers = console.controllers for pad, saved in zip(controllers.pads, state["pads"], strict=True): for key, value in saved.items(): setattr(pad, key, set(value) if isinstance(value, set) else value) # What Controllers.apply() derived at the last frame start is restored as it # stood, never re-derived: apply() steps the trak-ball lag and re-sets GTIA's # trigger latches, and the pads may have changed since it ran (a5200-rust's # finding, 2026-11-14). The pot capacitors (pokey_python.rc.PotRC) are # rewired to the restored chip with their targets and charge. for ball, out in zip(controllers._balls, state["trak_balls"], strict=True): ball.out = list(out) controllers._trak_pins = list(state["trak_pins"]) controllers.wire_pots() controllers.rc.target[:] = state["pot_rc"]["target"] controllers.rc.charge[:] = state["pot_rc"]["charge"] controllers.rc.when[:] = state["pot_rc"]["when"] def save(console, path: str | Path | None = None) -> Path: if path is None: SAVE_DIR.mkdir(parents=True, exist_ok=True) path = SAVE_DIR / f"{console.cart.sha1[:12]}.state" path = Path(path) path.write_bytes(pickle.dumps(snapshot(console), protocol=4)) return path def load(console, path: str | Path | None = None) -> None: if path is None: path = SAVE_DIR / f"{console.cart.sha1[:12]}.state" restore(console, pickle.loads(Path(path).read_bytes()))