//! The peripherals' own storage, kept as the reference's window keeps it //! (`frontend.py`'s `save`, `_load_storage` and `_tape_key`): //! //! - The Turbo File's 8 KiB: `turbo-file.sav`, one for all games (the //! reference keeps one per folder, as the device moves between games), in //! the frontend's save directory (else beside the game). //! - The Data Recorder's cassette: `.tape` there, the level //! changes as the reference's JSON (`[[position, level], ...]`, positions in //! master ticks from the tape's start), so a tape moves between the two. //! - The deck's keys: F9 plays the tape from its start, F10 records over it; //! either again stops it and writes the tape. //! //! Written when the tape stops and when the game unloads, as the reference //! writes on quit; the Turbo File also within a second of a change, since a //! handheld is often switched off without unloading. use famicom_rust::board::Board; use famicom_rust::host::HostInput; use famicom_rust::peripherals::{DataRecorder, FamilyBasicKeyboard, TapeMode, TurboFile}; use std::path::{Path, PathBuf}; /// The Turbo File's size. const TURBO_FILE_SIZE: usize = 0x2000; /// Where the storage lives and what was last written. pub struct Storage { /// None (and so no files) when the frontend names no save directory and /// gives no game path. turbo_file: Option, /// None also when there is no game path to name the tape after. tape: Option, /// The Turbo File as last read or written. written: Vec, frames: u32, /// F9 and F10 last frame (a key acts as it goes down). keys: (bool, bool), } /// The Data Recorder on the board: a Family BASIC Keyboard's (the reference's /// `_recorder`; the Data Recorder alone is plugged as a keyboard with one). pub fn recorder(board: &mut Board) -> Option<&mut DataRecorder> { board .expansion .as_mut()? .as_any_mut() .downcast_mut::()? .recorder .as_mut() } fn turbo_file(board: &mut Board) -> Option<&mut TurboFile> { board .expansion .as_mut()? .as_any_mut() .downcast_mut::() } /// The tape as the reference writes it (`json.dumps` of the list of pairs). pub fn tape_json(tape: &[(i64, u8)]) -> String { let pairs: Vec = tape .iter() .map(|(position, level)| format!("[{position}, {level}]")) .collect(); format!("[{}]", pairs.join(", ")) } /// A tape from the reference's JSON: the integers in order, in pairs. None /// if it is not a list of integer pairs. pub fn parse_tape(text: &str) -> Option> { let text = text.trim(); let inner = text.strip_prefix('[')?.strip_suffix(']')?.trim(); if inner.is_empty() { return Some(Vec::new()); } let mut numbers = Vec::new(); for token in inner.split(|c: char| matches!(c, '[' | ']' | ',') || c.is_whitespace()) { if !token.is_empty() { numbers.push(token.parse::().ok()?); } } if numbers.len() % 2 != 0 { return None; } numbers .chunks(2) .map(|pair| Some((pair[0], u8::try_from(pair[1]).ok()?))) .collect() } impl Storage { /// Read the Turbo File's RAM and the tape into the plugged devices. /// `dir`: the frontend's save directory, else the game's; `game`: the /// game's path, if the frontend gave one. pub fn load(board: &mut Board, dir: Option, game: Option<&Path>) -> Storage { let dir = dir.or_else(|| game.and_then(|g| g.parent()).map(Path::to_path_buf)); let tape = game.and_then(|g| g.file_name()).and_then(|name| { let mut name = name.to_os_string(); name.push(".tape"); Some(dir.as_ref()?.join(name)) }); let mut storage = Storage { turbo_file: dir.map(|d| d.join("turbo-file.sav")), tape, written: Vec::new(), frames: 0, keys: (false, false), }; if let Some(device) = turbo_file(board) { if let Some(Ok(mut data)) = storage.turbo_file.as_ref().map(std::fs::read) { data.resize(TURBO_FILE_SIZE, 0); device.data.copy_from_slice(&data); } storage.written = device.data.clone(); } let path = storage.tape.clone(); if let (Some(deck), Some(path)) = (recorder(board), path) { if let Some(tape) = std::fs::read_to_string(&path) .ok() .and_then(|t| parse_tape(&t)) { deck.tape = tape; } } storage } /// Write the Turbo File (when plugged) and the tape (when it holds /// anything), as the reference's `save`. pub fn save(&mut self, board: &mut Board) { if let (Some(device), Some(path)) = (turbo_file(board), &self.turbo_file) { if std::fs::write(path, &device.data).is_ok() { self.written = device.data.clone(); } } if let (Some(deck), Some(path)) = (recorder(board), &self.tape) { if !deck.tape.is_empty() { let _ = std::fs::write(path, tape_json(&deck.tape)); } } } /// Once a frame, after the input is read: the deck's keys, and the Turbo /// File written within a second of a change. Returns a message to show. pub fn frame(&mut self, board: &mut Board, input: &HostInput) -> Option<&'static str> { let keys = (input.keys.contains("K_F9"), input.keys.contains("K_F10")); let (play, record) = (keys.0 && !self.keys.0, keys.1 && !self.keys.1); self.keys = keys; let mut message = None; if play || record { message = self.tape_key(board, record && !play); } self.frames += 1; if self.frames >= 60 { self.frames = 0; if let Some(device) = turbo_file(board) { if device.data != self.written { self.save(board); } } } message } /// F9: play the tape from its start (again: stop); F10: record over it. fn tape_key(&mut self, board: &mut Board, record: bool) -> Option<&'static str> { let now = board.ppu.time; let deck = recorder(board)?; if deck.mode != TapeMode::Stop { deck.stop(); self.save(board); Some("tape: stopped") } else if record { deck.record(now); Some("tape: recording") } else { deck.play(now); Some("tape: playing") } } } #[cfg(test)] mod tests { use super::*; #[test] fn tape_json_is_the_reference_s() { // json.dumps([(0, 1), (1234, 0)]) in Python. assert_eq!(tape_json(&[(0, 1), (1234, 0)]), "[[0, 1], [1234, 0]]"); assert_eq!(tape_json(&[]), "[]"); } #[test] fn tape_round_trips() { let tape = vec![(0, 1), (35_000, 0), (9_876_543_210, 1)]; assert_eq!(parse_tape(&tape_json(&tape)), Some(tape)); assert_eq!( parse_tape(" [[5,1],\n [6 , 0]] "), Some(vec![(5, 1), (6, 0)]) ); assert_eq!(parse_tape("[]"), Some(Vec::new())); assert_eq!(parse_tape("[[5, 1], [6]]"), None); assert_eq!(parse_tape("{\"a\": 1}"), None); assert_eq!(parse_tape("[[5, 300]]"), None); } }