use crate::nes::{config::Config, renderer::gui::debugger::Breakpoint};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use tetanes_core::{debug::CodeMap, fs, memory::Memory};
use tracing::{error, info};
const DEBUG_VERSION: &str = "1";
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[must_use]
pub struct AddrLabel {
pub name: String,
pub comment: String,
}
impl AddrLabel {
pub fn is_empty(&self) -> bool {
self.name.trim().is_empty() && self.comment.trim().is_empty()
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[must_use]
pub enum LabelKey {
Cart(u32),
Cpu(u16),
}
impl LabelKey {
pub const fn new(addr: u16, offset: Option<u32>) -> Self {
match offset {
Some(offset) => Self::Cart(offset),
None => Self::Cpu(addr),
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
#[must_use]
pub struct Marks {
pub breakpoints: Vec<Breakpoint>,
pub labels: HashMap<LabelKey, AddrLabel>,
}
impl Marks {
pub fn is_empty(&self) -> bool {
self.breakpoints.is_empty() && self.labels.is_empty()
}
}
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Session {
pub code_map: Option<CodeMap>,
pub marks: Marks,
}
impl Session {
const DIR: &'static str = "debug";
const EXTENSION: &'static str = "dbg";
pub fn path(name: &str) -> PathBuf {
Config::default_data_dir()
.join(Self::DIR)
.join(name)
.with_extension(Self::EXTENSION)
}
pub fn load(name: &str) -> Self {
Self::load_path(Self::path(name))
}
pub fn load_path(path: impl AsRef<Path>) -> Self {
let path = path.as_ref();
if !fs::exists(path) {
return Self::default();
}
match fs::load_version_path(path, DEBUG_VERSION) {
Ok(session) => {
info!("loaded debug session: {path:?}");
session
}
Err(err) => {
error!("failed to load debug session {path:?}: {err:?}");
Self::default()
}
}
}
pub fn save(&self, name: &str) -> fs::Result<()> {
self.save_path(Self::path(name))
}
pub fn save_path(&self, path: impl AsRef<Path>) -> fs::Result<()> {
if self.is_empty() {
return Ok(());
}
fs::save_version_path(path, self, DEBUG_VERSION)
}
pub fn is_empty(&self) -> bool {
self.code_map.is_none() && self.marks.is_empty()
}
pub fn accept(&mut self, memory: &Memory) {
if !self
.code_map
.as_ref()
.is_some_and(|code_map| code_map.covers(memory))
{
self.code_map = None;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tetanes_core::{
cart::Cart,
debug::{Access, ByteKind},
mapper::Nrom,
};
fn cart() -> Cart {
let mut cart = Cart::empty();
cart.mapper = Nrom::load(&mut cart).expect("valid mapper");
cart
}
fn marked(cart: &Cart) -> Session {
let mut code_map = CodeMap::new(cart.memory.len(), cart.memory.rom_crc32());
code_map.mark(0x10, ByteKind::CODE);
Session {
code_map: Some(code_map),
marks: Marks {
breakpoints: vec![Breakpoint {
id: 7,
addr: 0x8123,
end: 0x8123,
offset: Some(0x1234),
access: Access::EXEC,
enabled: true,
breaks: true,
condition: "a == 0x10".to_string(),
}],
labels: HashMap::from([(
LabelKey::Cart(0x1234),
AddrLabel {
name: "reset".to_string(),
comment: "where it all starts".to_string(),
},
)]),
},
}
}
#[test]
fn a_session_reads_back_what_it_wrote() {
let dir = std::env::temp_dir().join("tetanes-debug-session-round-trip");
std::fs::create_dir_all(&dir).expect("scratch dir");
let path = dir.join("session.dbg");
let cart = cart();
let written = marked(&cart);
written.save_path(&path).expect("writes");
let read = Session::load_path(&path);
let code_map = read.code_map.as_ref().expect("a map was written");
assert!(code_map.covers(&cart.memory), "the map still fits the cart");
assert_eq!(read.marks.labels, written.marks.labels);
assert_eq!(read.marks.breakpoints.len(), 1);
let breakpoint = &read.marks.breakpoints[0];
assert_eq!(breakpoint.addr, 0x8123);
assert_eq!(breakpoint.condition, "a == 0x10");
assert!(breakpoint.enabled, "an armed breakpoint comes back armed");
assert_eq!(breakpoint.id, 0, "the window hands ids out again");
std::fs::remove_file(&path).expect("cleans up");
}
#[test]
fn a_map_recorded_against_another_cart_is_refused() {
let cart = cart();
let mut session = marked(&cart);
session.accept(&cart.memory);
assert!(session.code_map.is_some(), "the cart it was recorded for");
let mut other = Cart::empty_sized(0x8000, 0x2000);
other.mapper = Nrom::load(&mut other).expect("valid mapper");
let mut session = marked(&cart);
session.accept(&other.memory);
assert!(session.code_map.is_none(), "a cart of another size");
}
#[test]
fn an_empty_session_writes_no_file() {
let path = std::env::temp_dir().join("tetanes-debug-session-empty.dbg");
Session::default().save_path(&path).expect("writes nothing");
assert!(!fs::exists(&path));
}
}