main
Colby Knox 0.2.98: keep the agent's script project out of the user's Altium workspace (#32) 5d678f6
//! The user's Altium workspace file (`.DsnWrk`) and the agent's script project (altium-bridge#32).
//!
//! Every agent start opens `AdomAgent_<gen>.PrjScr`, and Altium adds it to the open workspace. In a workspace the user
//! saved, that marks the workspace changed: closing Altium asked "Save changes? <workspace>.DsnWrk", and a Save wrote
//! the agent's project into the user's own file, where it was reopened on every launch. Altium's automatic
//! `LastWorkspace` file keeps it the same way.
//!
//! Altium writes the file as INI text: `[ProjectGroup]`, then `[Project1]`, `[Project2]`, ... each with a
//! `ProjectPath=` that may be relative to the file. Lines are handled as bytes so a path in any code page survives.

/// Whether a project path is one of the agent's own script projects.
pub fn is_agent_project(path: &str) -> bool {
    let p = path.replace('/', "\\").to_ascii_lowercase();
    p.contains("\\adomagent_") && p.ends_with(".prjscr")
}

fn decode(bytes: &[u8]) -> String {
    let b = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF][..]).unwrap_or(bytes);
    match std::str::from_utf8(b) {
        Ok(s) => s.to_string(),
        // Altium's own files are ANSI on most machines: Latin-1 keeps every byte as one character
        Err(_) => b.iter().map(|&c| c as char).collect(),
    }
}

/// A path written in the file, made absolute against the file's folder and normalised for comparison
/// (`\`, no `.`/`..`, lower case: Windows paths ignore case).
pub fn resolve(dir: &str, path: &str) -> String {
    let p = path.trim().replace('/', "\\");
    let abs = if p.len() >= 2 && p.as_bytes()[1] == b':' || p.starts_with("\\\\") { p } else { format!("{}\\{}", dir.trim_end_matches('\\'), p) };
    let unc = abs.starts_with("\\\\");
    let mut parts: Vec<&str> = Vec::new();
    for c in abs.split('\\') {
        match c {
            "" | "." => {}
            ".." => { if parts.len() > 1 { parts.pop(); } }
            _ => parts.push(c),
        }
    }
    let joined = parts.join("\\");
    (if unc { format!("\\\\{joined}") } else { joined }).to_lowercase()
}

/// Every `ProjectPath=` in the file, as written.
pub fn project_paths(bytes: &[u8]) -> Vec<String> {
    decode(bytes).lines().filter_map(|l| {
        let t = l.trim();
        t.get(..12).filter(|k| k.eq_ignore_ascii_case("projectpath=")).map(|_| t[12..].to_string())
    }).collect()
}

/// The file without the agent's `[ProjectN]` sections, the rest renumbered from 1. `None` when there is none to remove.
pub fn without_agent_projects(bytes: &[u8]) -> Option<Vec<u8>> {
    let crlf = bytes.windows(2).any(|w| w == b"\r\n");
    let lines: Vec<&[u8]> = bytes.split(|&b| b == b'\n').map(|l| l.strip_suffix(b"\r").unwrap_or(l)).collect();
    // sections: (header line index, end exclusive)
    let is_project_header = |l: &[u8]| {
        let t = String::from_utf8_lossy(l).trim().to_ascii_lowercase();
        t.starts_with("[project") && t.ends_with(']') && t[8..t.len() - 1].chars().all(|c| c.is_ascii_digit()) && t.len() > 9
    };
    let is_header = |l: &[u8]| { let t = String::from_utf8_lossy(l); let t = t.trim(); t.starts_with('[') && t.ends_with(']') };
    let mut out: Vec<Vec<u8>> = Vec::new();
    let mut removed = 0;
    let mut n = 0;
    let mut i = 0;
    while i < lines.len() {
        if is_project_header(lines[i]) {
            let mut j = i + 1;
            while j < lines.len() && !is_header(lines[j]) { j += 1; }
            let agent = lines[i + 1..j].iter().any(|l| {
                let s = decode(l);
                let t = s.trim();
                t.get(..12).map(|k| k.eq_ignore_ascii_case("projectpath=")).unwrap_or(false) && is_agent_project(&t[12..])
            });
            if agent {
                removed += 1;
            } else {
                n += 1;
                out.push(format!("[Project{n}]").into_bytes());
                out.extend(lines[i + 1..j].iter().map(|l| l.to_vec()));
            }
            i = j;
        } else {
            out.push(lines[i].to_vec());
            i += 1;
        }
    }
    if removed == 0 {
        return None;
    }
    // a removed section leaves its blank separator behind: no two blank lines in a row
    let mut tidy: Vec<Vec<u8>> = Vec::new();
    for l in out {
        let blank = l.iter().all(|b| b.is_ascii_whitespace());
        if blank && tidy.last().map(|p: &Vec<u8>| p.iter().all(|b| b.is_ascii_whitespace())).unwrap_or(false) { continue; }
        tidy.push(l);
    }
    Some(tidy.join(if crlf { &b"\r\n"[..] } else { &b"\n"[..] }))
}

/// Whether the open workspace differs from its file only by the agent's projects: the projects Altium has open
/// (`open`, absolute, from the agent) against the file's, both without the agent's and without Free Documents.
pub fn differs_only_by_agent(file_bytes: &[u8], file_dir: &str, open: &[String]) -> bool {
    let mut disk: Vec<String> = project_paths(file_bytes).iter().filter(|p| !is_agent_project(p)).map(|p| resolve(file_dir, p)).collect();
    let mut mem: Vec<String> = open.iter().filter(|p| p.contains('\\') && !is_agent_project(p)).map(|p| resolve(file_dir, p)).collect();
    disk.sort();
    disk.dedup();
    mem.sort();
    mem.dedup();
    disk == mem
}

/// Altium's automatic last-workspace files (`%APPDATA%\Altium\<install>\LastWorkspace\*.DsnWrk`).
pub fn last_workspace_files() -> Vec<std::path::PathBuf> {
    let Ok(appdata) = std::env::var("APPDATA") else { return Vec::new() };
    let mut out = Vec::new();
    if let Ok(rd) = std::fs::read_dir(std::path::Path::new(&appdata).join("Altium")) {
        for inst in rd.flatten() {
            if let Ok(files) = std::fs::read_dir(inst.path().join("LastWorkspace")) {
                out.extend(files.flatten().map(|f| f.path()).filter(|p| p.extension().map(|e| e.eq_ignore_ascii_case("dsnwrk")).unwrap_or(false)));
            }
        }
    }
    out
}

/// Remove the agent's projects from a workspace file on disk. Answers whether it changed the file.
pub fn scrub_file(path: &std::path::Path) -> bool {
    let Ok(bytes) = std::fs::read(path) else { return false };
    match without_agent_projects(&bytes) {
        Some(clean) => std::fs::write(path, clean).is_ok(),
        None => false,
    }
}

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

    const IVAN: &str = "[ProjectGroup]\r\nVersion=1.0\r\n\r\n[Project1]\r\nProjectPath=Board\\Board.PrjPcb\r\n\r\n[Project2]\r\nProjectPath=..\\..\\..\\Users\\u\\AppData\\Local\\Adom Bridge\\bridges-cache\\altium\\agent\\AD24\\AdomAgent_4005dc0085.PrjScr\r\n\r\n[Project3]\r\nProjectPath=Lib\\Lib.LibPkg\r\n";

    #[test]
    fn removes_only_the_agent_projects_and_renumbers() {
        let out = String::from_utf8(without_agent_projects(IVAN.as_bytes()).unwrap()).unwrap();
        assert_eq!(out, "[ProjectGroup]\r\nVersion=1.0\r\n\r\n[Project1]\r\nProjectPath=Board\\Board.PrjPcb\r\n\r\n[Project2]\r\nProjectPath=Lib\\Lib.LibPkg\r\n");
        // nothing of ours: the file is left alone
        assert!(without_agent_projects(out.as_bytes()).is_none());
        // a user's own script project is not ours
        assert!(!is_agent_project(r"C:\Scripts\MyTools.PrjScr"));
        assert!(is_agent_project(r"C:/x/agent/AD26/AdomAgent_a086cfbf3f.PrjScr"));
    }

    #[test]
    fn paths_compare_resolved_and_without_case() {
        assert_eq!(resolve(r"C:\Users\u\Documents\ws", r"..\Boards\B.PrjPcb"), r"c:\users\u\documents\boards\b.prjpcb");
        assert_eq!(resolve(r"C:\ws", r"D:\X\Y.PrjPcb"), r"d:\x\y.prjpcb");
    }

    #[test]
    fn only_the_agent_difference_counts_as_ours() {
        let dir = r"C:\Users\u\Documents\ws";
        let open = vec!["Free Documents".to_string(), r"C:\Users\u\Documents\ws\Board\Board.PrjPcb".to_string(),
            r"C:\Users\u\Documents\ws\Lib\Lib.LibPkg".to_string(),
            r"C:\Users\u\AppData\Local\Adom Bridge\bridges-cache\altium\agent\AD24\AdomAgent_a086cfbf3f.PrjScr".to_string()];
        assert!(differs_only_by_agent(IVAN.as_bytes(), dir, &open));
        // the user opened another project: their change, the workspace stays changed
        let mut more = open.clone();
        more.push(r"C:\Other\Other.PrjPcb".to_string());
        assert!(!differs_only_by_agent(IVAN.as_bytes(), dir, &more));
        // or closed one
        assert!(!differs_only_by_agent(IVAN.as_bytes(), dir, &open[..2]));
    }

    #[test]
    fn an_ansi_file_keeps_its_bytes() {
        let mut f = b"[ProjectGroup]\r\nVersion=1.0\r\n\r\n[Project1]\r\nProjectPath=C:\\Users\\Iv".to_vec();
        f.push(0xE1); // รก in Windows-1252
        f.extend_from_slice(b"n\\B.PrjPcb\r\n\r\n[Project2]\r\nProjectPath=C:\\x\\AdomAgent_1.PrjScr\r\n");
        let out = without_agent_projects(&f).unwrap();
        assert!(out.windows(3).any(|w| w == [b'v', 0xE1, b'n']));
        assert!(!String::from_utf8_lossy(&out).contains("AdomAgent"));
    }
}