use std::path::Path;
use crate::error::{Med64Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StageWindowPrefs {
pub height: i32,
pub width: i32,
pub set_x: i32,
pub set_y: i32,
}
impl Default for StageWindowPrefs {
fn default() -> Self {
Self { height: 973, width: 1280, set_x: 10, set_y: 25 }
}
}
fn parse_i32(v: &str, fallback: i32) -> i32 {
v.trim().parse().unwrap_or(fallback)
}
pub fn load_stage_properties(path: impl AsRef<Path>) -> Result<StageWindowPrefs> {
let path = path.as_ref();
let text = std::fs::read_to_string(path)
.map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
let mut prefs = StageWindowPrefs::default();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((k, v)) = line.split_once('=') else {
continue;
};
match k.trim() {
"height" => prefs.height = parse_i32(v, prefs.height),
"width" => prefs.width = parse_i32(v, prefs.width),
"setX" => prefs.set_x = parse_i32(v, prefs.set_x),
"setY" => prefs.set_y = parse_i32(v, prefs.set_y),
_ => {}
}
}
Ok(prefs)
}
pub fn write_stage_properties(prefs: &StageWindowPrefs, path: impl AsRef<Path>) -> Result<()> {
let path = path.as_ref();
let body = format!(
"# med64 stage window prefs\n\
height={}\n\
setX={}\n\
setY={}\n\
width={}\n",
prefs.height, prefs.set_x, prefs.set_y, prefs.width
);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).ok();
}
std::fs::write(path, body)
.map_err(|source| Med64Error::WriteIo { path: path.to_path_buf(), source })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stage_prefs_roundtrip() {
let dir = std::env::temp_dir().join(format!("med64-stage-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("conf_spikedetector_stage.properties");
let prefs = StageWindowPrefs { height: 900, width: 1400, set_x: 20, set_y: 40 };
write_stage_properties(&prefs, &path).unwrap();
let loaded = load_stage_properties(&path).unwrap();
assert_eq!(loaded, prefs);
let _ = std::fs::remove_dir_all(dir);
}
}