med64 0.0.2

Headless MED64 electrophysiology toolkit: .modat I/O, spike/burst analysis, assays, spike-rate maps, and CSV/HTML/SVG/HDF5 export
Documentation
//! Last-path loaders for toolkit path-only conf files
//! (`conf_waveformviewer.properties`, `conf_beatdetector.properties`, etc.).
//!
//! Wire-format properties key: `textfile1=` (path-only confs).

use std::path::{Path, PathBuf};

use crate::error::{Med64Error, Result};

/// Load last path from a properties file (`textfile1` key).
///
/// Returns `Ok(None)` when the key is missing or empty. Callers that need a
/// directory default can fall back themselves.
pub fn load_last_path_prefs(path: impl AsRef<Path>) -> Result<Option<PathBuf>> {
    let path = path.as_ref();
    let text = std::fs::read_to_string(path)
        .map_err(|source| Med64Error::Io { path: path.to_path_buf(), source })?;
    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;
        };
        // Wire key in path-only .properties files.
        if k.trim() == "textfile1" {
            let v = unescape_properties(v.trim());
            if v.is_empty() {
                return Ok(None);
            }
            return Ok(Some(PathBuf::from(v)));
        }
    }
    Ok(None)
}

/// Write a minimal properties file containing only the `textfile1` path key.
pub fn write_last_path_prefs(path: impl AsRef<Path>, last_path: Option<&Path>) -> Result<()> {
    let path = path.as_ref();
    let value = last_path.map(|p| p.display().to_string()).unwrap_or_default();
    // Wire key in path-only .properties files.
    let body = format!("# med64 path prefs\ntextfile1={value}\n");
    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 })
}

/// Waveform Viewer main conf (`conf_waveformviewer.properties`) โ€” path only,
/// distinct from [`super::voltage_chart_prefs::VoltageChartExportPrefs`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct VoltageChartPathPrefs {
    pub last_path: String,
}

/// Alias matching the Waveform Viewer conf name.
pub type WaveformViewerPathPrefs = VoltageChartPathPrefs;

pub fn load_voltage_chart_path_prefs(path: impl AsRef<Path>) -> Result<VoltageChartPathPrefs> {
    let mut prefs = VoltageChartPathPrefs::default();
    if let Some(p) = load_last_path_prefs(path)? {
        prefs.last_path = p.display().to_string();
    }
    Ok(prefs)
}

pub fn write_voltage_chart_path_prefs(
    prefs: &VoltageChartPathPrefs,
    path: impl AsRef<Path>,
) -> Result<()> {
    let p = if prefs.last_path.is_empty() { None } else { Some(PathBuf::from(&prefs.last_path)) };
    write_last_path_prefs(path, p.as_deref())
}

/// Minimal properties unescape (`\\`, `\n`, `\uXXXX`).
fn unescape_properties(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some('r') => out.push('\r'),
            Some('\\') => out.push('\\'),
            Some('u') => {
                let mut hex = String::new();
                for _ in 0..4 {
                    if let Some(h) = chars.next() {
                        hex.push(h);
                    }
                }
                if let Ok(code) = u32::from_str_radix(&hex, 16) {
                    if let Some(ch) = char::from_u32(code) {
                        out.push(ch);
                        continue;
                    }
                }
                out.push_str("\\u");
                out.push_str(&hex);
            }
            Some(other) => out.push(other),
            None => out.push('\\'),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn path_prefs_last_path_roundtrip() {
        let dir = std::env::temp_dir().join(format!("med64-pathpref-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("conf_waveformviewer.properties");
        write_last_path_prefs(&path, Some(Path::new("/tmp/data"))).unwrap();
        let loaded = load_last_path_prefs(&path).unwrap();
        assert_eq!(loaded.as_deref(), Some(Path::new("/tmp/data")));
        let prefs = VoltageChartPathPrefs { last_path: "/Users/shared/waves".into() };
        let wv = dir.join("conf_waveformviewer.properties");
        write_voltage_chart_path_prefs(&prefs, &wv).unwrap();
        let again = load_voltage_chart_path_prefs(&wv).unwrap();
        assert_eq!(again, prefs);
        let empty = dir.join("empty.properties");
        write_last_path_prefs(&empty, None).unwrap();
        assert!(load_last_path_prefs(&empty).unwrap().is_none());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn last_path_unicode_escape() {
        let dir = std::env::temp_dir().join(format!("med64-path-u-{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        let path = dir.join("conf_beatdetector.properties");
        // Wire key in path-only .properties files.
        std::fs::write(&path, "textfile1=/tmp/\\u30C6\\u30B9\\u30C8\n").unwrap();
        let loaded = load_last_path_prefs(&path).unwrap().unwrap();
        assert!(loaded.to_string_lossy().contains("ใƒ†ใ‚นใƒˆ"));
        let _ = std::fs::remove_dir_all(dir);
    }
}