// SPDX-License-Identifier: MIT //! The one front door: any cart or program file in, one [`CartDescription`] out //! (`cart/loader.py`). //! //! 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. //! //! Differences forced by Rust: the exceptions (`NotACart`, `FormatError`, `ValueError`) //! are one error type, [`LoadError`]; override values arrive as JSON values (the user's //! file is JSON; the command line's strings are given as JSON strings); `provenance` (a //! dict) is a `BTreeMap`; the properties `bank0_size` and `bank1` are methods. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use serde_json::Value; use sha1::{Digest, Sha1}; use crate::bootrom::BOOT_ROM_SHA1S; use crate::cart::formats::{decode_eeprom, split, unwrap, FormatError, Header, Source, ROTATIONS}; use crate::cart::table::{default_table, CartTable, FieldValue}; pub const BLOCK_SIZES: [i64; 4] = [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). fn size_rule(length: usize) -> Option { BLOCK_SIZES .iter() .copied() .find(|&b| 256 * b as usize == length) } /// `NotACart` (the image is a Lynx boot ROM), `FormatError` or `ValueError`. #[derive(Debug, Clone)] pub enum LoadError { NotACart(String), Format(String), Value(String), } impl std::fmt::Display for LoadError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { LoadError::NotACart(s) | LoadError::Format(s) | LoadError::Value(s) => f.write_str(s), } } } impl std::error::Error for LoadError {} impl From for LoadError { fn from(e: FormatError) -> Self { LoadError::Format(e.0) } } /// 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`). #[derive(Clone, Debug)] pub struct CartDescription { pub payload: Vec, pub sha1: String, pub crc32: String, pub kind: &'static str, // lnx, raw, bll: what the file was pub container: &'static str, // loose, zip, 7z pub member: String, pub bank0_block: usize, pub bank1_block: usize, pub audin: bool, pub rotation: String, // none, left, right pub eeprom: Option<(String, u32)>, // (type, organisation in bits) pub boot: &'static str, // "encrypted" (frame at offset 0) or "ram" (BLL) pub name: String, pub provenance: BTreeMap, pub warnings: Vec, pub bank0_alternatives: Vec<(i64, String)>, // (block, source) to try if the table's fails pub header: Option
, pub bll_load: Option, pub table_lnx_header: Option, // the header we observed for this payload pub conflicts: Vec, } impl CartDescription { /// Bytes of the payload that belong to bank 0 (CART0). pub fn bank0_size(&self) -> usize { if self.boot == "ram" { return 0; } self.payload .len() .min(256 * self.bank0_block * if self.audin { 2 } else { 1 }) } pub fn bank1(&self) -> &[u8] { if self.bank1_block != 0 { &self.payload[self.bank0_size()..] } else { &[] } } } /// The user's override file (`~/.local/share/lynx-python/overrides.json`; the /// reference's, so the specification and its transcription share it). pub fn overrides_path() -> PathBuf { let base = match std::env::var("XDG_DATA_HOME") { Ok(v) if !v.is_empty() => PathBuf::from(v), _ => crate::cart::eeprom::home().join(".local").join("share"), }; base.join("lynx-python").join("overrides.json") } pub fn load_overrides(path: Option<&Path>) -> serde_json::Map { let path = path.map(PathBuf::from).unwrap_or_else(overrides_path); match std::fs::read_to_string(&path) { Ok(text) => serde_json::from_str::(&text) .ok() .and_then(|v| v.as_object().cloned()) .unwrap_or_default(), Err(_) => Default::default(), } } /// Record user-supplied fields for a payload (never written next to a ROM). pub fn save_override( sha1: &str, values: &serde_json::Map, path: Option<&Path>, ) -> std::io::Result { let path = path.map(PathBuf::from).unwrap_or_else(overrides_path); let mut data = load_overrides(Some(&path)); let entry = data .entry(sha1.to_string()) .or_insert_with(|| Value::Object(Default::default())); if let Some(map) = entry.as_object_mut() { for (k, v) in values { map.insert(k.clone(), v.clone()); } } if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; } std::fs::write( &path, serde_json::to_string_pretty(&Value::Object(data)).unwrap() + "\n", )?; Ok(path) } fn normalise_override(key: &str, value: &Value) -> Result { match key { "rotation" => { let s = value.as_str().unwrap_or(""); if !ROTATIONS.contains(&s) { return Err(LoadError::Value(format!( "rotation must be one of {ROTATIONS:?}, not {value}" ))); } Ok(FieldValue::Str(s.to_string())) } "bank0_block" | "bank1_block" => { let v = match value { Value::Number(n) => n.as_i64().unwrap_or(-1), Value::String(s) => s.parse().unwrap_or(-1), _ => -1, }; if !BLOCK_SIZES.contains(&v) && !(key == "bank1_block" && v == 0) { return Err(LoadError::Value(format!( "{key} must be one of {BLOCK_SIZES:?}" ))); } Ok(FieldValue::Int(v)) } "audin" => Ok(FieldValue::Bool(match value { Value::Bool(b) => *b, Value::Number(n) => n.as_i64().unwrap_or(0) != 0, Value::String(s) => !s.is_empty(), _ => false, })), "eeprom" => match value { Value::Null => Ok(FieldValue::Eeprom(None)), Value::Number(n) if n.as_i64() == Some(0) => Ok(FieldValue::Eeprom(None)), Value::String(s) if s == "none" => Ok(FieldValue::Eeprom(None)), Value::String(s) => { let (kind, org) = s.split_once(':').unwrap_or((s, "")); let org: u32 = if org.is_empty() { 16 } else { org.parse() .map_err(|_| LoadError::Value(format!("bad eeprom {s}")))? }; Ok(FieldValue::Eeprom(Some((kind.to_uppercase(), org)))) } Value::Array(a) if a.len() == 2 => Ok(FieldValue::Eeprom(Some(( a[0].as_str().unwrap_or("").to_uppercase(), a[1].as_u64().unwrap_or(16) as u32, )))), _ => Err(LoadError::Value(format!("bad eeprom {value}"))), }, "name" => Ok(FieldValue::Str(match value { Value::String(s) => s.clone(), other => other.to_string(), })), _ => Err(LoadError::Value(format!("unknown override field {key:?}"))), } } fn sha1_hex(data: &[u8]) -> String { let digest = Sha1::digest(data); digest.iter().map(|b| format!("{b:02x}")).collect() } /// Steps 2-7 on the bytes of one file (already unwrapped). pub fn describe( data: &[u8], member: &str, container: &'static str, table: Option<&CartTable>, overrides: &serde_json::Map, ) -> Result { let table = table.unwrap_or_else(|| default_table()); let (kind, header, payload) = split(data)?; if payload.is_empty() { return Err(LoadError::Format(format!("{member}: empty payload"))); } let sha1 = sha1_hex(&payload); if BOOT_ROM_SHA1S.contains(&sha1.as_str()) { return Err(LoadError::NotACart(format!( "{member}: this is the Lynx boot ROM (SHA-1 {sha1}), not a cart" ))); } let crc = format!("{:08x}", crc32fast::hash(&payload)); let entry = table.get(&sha1); let mut user: BTreeMap = BTreeMap::new(); for (k, v) in overrides { user.insert(k.clone(), normalise_override(k, v)?); } let mut warnings: Vec = Vec::new(); let mut provenance: BTreeMap = BTreeMap::new(); let mut claims: BTreeMap<&str, FieldValue> = BTreeMap::new(); if let Some(Header::Lnx(h)) = &header { if BLOCK_SIZES.contains(&(h.bank0_block as i64)) { claims.insert("bank0_block", FieldValue::Int(h.bank0_block as i64)); } else { warnings.push(format!( "header bank 0 block size {} is not a block size", h.bank0_block )); } if h.bank1_block == 0 || BLOCK_SIZES.contains(&(h.bank1_block as i64)) { claims.insert("bank1_block", FieldValue::Int(h.bank1_block as i64)); } else { warnings.push(format!( "header bank 1 block size {} is not a block size", h.bank1_block )); } claims.insert("audin", FieldValue::Bool(h.audin & 1 != 0)); match h.rotation_name() { Some(r) => { claims.insert("rotation", FieldValue::Str(r.into())); } None => warnings.push(format!("header rotation byte {} is undefined", h.rotation)), } claims.insert("eeprom", FieldValue::Eeprom(decode_eeprom(h.eeprom))); } let mut defaults: BTreeMap<&str, FieldValue> = BTreeMap::new(); defaults.insert("bank1_block", FieldValue::Int(0)); defaults.insert("audin", FieldValue::Bool(false)); defaults.insert("rotation", FieldValue::Str("none".into())); defaults.insert("eeprom", FieldValue::Eeprom(None)); let rule = size_rule(payload.len()); 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). let block = BLOCK_SIZES .iter() .copied() .find(|&b| 256 * b as usize >= payload.len()) .unwrap_or(BLOCK_SIZES[3]); defaults.insert("bank0_block", FieldValue::Int(block)); } let mut alternatives: Vec<(i64, String)> = Vec::new(); let mut resolved: BTreeMap<&str, FieldValue> = BTreeMap::new(); for key in ["bank0_block", "bank1_block", "audin", "rotation", "eeprom"] { if kind == "bll" && (key == "bank0_block" || key == "bank1_block") { resolved.insert(key, FieldValue::Int(0)); provenance.insert(key.into(), "bll".into()); continue; } let mut candidates: Vec<(FieldValue, String)> = Vec::new(); if let Some(v) = user.get(key) { candidates.push((v.clone(), "user".into())); } if let Some(entry) = &entry { if let Some((value, source)) = entry.fields.get(key) { candidates.push((value.clone(), format!("table:{source}"))); } } if let Some(v) = claims.get(key) { candidates.push((v.clone(), "header".into())); } if key == "bank0_block" { if let Some(r) = rule { // 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. let header_sources = ["header", "table:lnx-header"]; let demoted: Vec<(FieldValue, String)> = candidates .iter() .filter(|c| header_sources.contains(&c.1.as_str()) && c.0 != FieldValue::Int(r)) .cloned() .collect(); candidates.retain(|c| !demoted.contains(c)); candidates.push((FieldValue::Int(r), "size-rule".into())); candidates.extend( demoted .into_iter() .map(|(value, _)| (value, "header".into())), ); } } if let Some(v) = defaults.get(key) { candidates.push((v.clone(), "default".into())); } let (value, source) = candidates[0].clone(); resolved.insert(key, value.clone()); provenance.insert(key.into(), source.clone()); for (other, other_source) in &candidates[1..] { if (other_source == "default" || other_source == "size-rule") && source != "user" { // The size rule disagreeing with a table or header is reported once, below. continue; } if *other != value { warnings.push(format!( "{key}: {source} says {}, {other_source} says {}; using {source}", value.show(), other.show() )); if key == "bank0_block" && other_source == "header" && !alternatives.contains(&(other.as_int(), other_source.clone())) { alternatives.push((other.as_int(), other_source.clone())); } } } if key == "bank0_block" { if let Some(r) = rule { if value != FieldValue::Int(r) && source != "user" { warnings.push(format!( "bank0_block: {source} says {} but the payload is {} bytes \ (the size rule says {r}): fewer or more than 256 pages", value.show(), payload.len() )); } } } } let boot = if kind == "bll" { "ram" } else { "encrypted" }; let name; if let Some(FieldValue::Str(n)) = user.get("name") { name = n.clone(); provenance.insert("name".into(), "user".into()); } else if let Some(n) = entry .as_ref() .and_then(|e| e.name.clone()) .filter(|n| !n.is_empty()) { name = n; let source = entry .as_ref() .and_then(|e| e.sources.first().cloned()) .unwrap_or_default(); provenance.insert("name".into(), format!("table:{source}")); } else if let Some(Header::Lnx(h)) = header.as_ref().filter(|h| match h { Header::Lnx(h) => !h.name.trim().is_empty(), _ => false, }) { name = h.name.trim().to_string(); provenance.insert("name".into(), "header".into()); } else { name = Path::new(member) .file_stem() .map(|s| s.to_string_lossy().to_string()) .unwrap_or_default(); provenance.insert("name".into(), "filename".into()); } let rotation = match &resolved["rotation"] { FieldValue::Str(s) => s.clone(), _ => "none".into(), }; let eeprom = match &resolved["eeprom"] { FieldValue::Eeprom(e) => e.clone(), _ => None, }; let bll_load = match &header { Some(Header::Bll(b)) => Some(b.load), _ => None, }; Ok(CartDescription { payload, sha1, crc32: crc, kind, container, member: member.to_string(), bank0_block: resolved["bank0_block"].as_int() as usize, bank1_block: resolved["bank1_block"].as_int() as usize, audin: resolved["audin"].as_bool(), rotation, eeprom, boot, name, provenance, warnings, bank0_alternatives: alternatives, header, bll_load, table_lnx_header: entry.as_ref().and_then(|e| e.lnx_header.clone()), conflicts: entry.map(|e| e.conflicts).unwrap_or_default(), }) } /// 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`. pub fn load( source: Source, name: Option<&str>, table: Option<&CartTable>, overrides: Option<&serde_json::Map>, use_override_file: bool, ) -> Result { let (member, data, container) = unwrap(source, name)?; let mut merged = serde_json::Map::new(); if use_override_file { let (_, _, payload) = split(&data)?; if let Some(Value::Object(map)) = load_overrides(None).get(&sha1_hex(&payload)) { for (k, v) in map { merged.insert(k.clone(), v.clone()); } } } if let Some(overrides) = overrides { for (k, v) in overrides { merged.insert(k.clone(), v.clone()); } } describe(&data, &member, container, table, &merged) } /// `load(path)` with the override file, as the entry points call it. pub fn load_path( path: &Path, overrides: Option<&serde_json::Map>, ) -> Result { load(Source::Path(path), None, None, overrides, true) }