main
Colby Knox altium-bridge 0.2.90: eleven new verbs, license never answers success for a press that didn't happen, update_pcb opens… dd28f04
//! preferences and extensions (EDA Bridge Standard #29, app tier).
//! - Altium keeps its preferences in the registry, HKCU\Software\Altium\<product>\DesignExplorer\Preferences\<server>\...
//!   (measured on Altium Designer Develop 26.9 and Altium Designer 26.11). They read any time. A set changes existing
//!   values only, with Altium closed: Altium writes its preferences back when it exits.
//! - Altium's installed extensions are folders of ...\ProgramData\Altium\<product>\Extensions, each with its .ins. They
//!   list from there. Altium's Extensions & Updates page is not in UI Automation, so install and remove are refused.
use serde_json::{json, Value};
use std::process::Command;

fn ps(script: &str) -> Option<String> {
    let full = format!("[Console]::OutputEncoding=[Text.Encoding]::UTF8; $ErrorActionPreference='Stop'; {script}");
    let o = Command::new("powershell").args(["-NoProfile", "-Command", &full]).output().ok()?;
    o.status.success().then(|| String::from_utf8_lossy(&o.stdout).to_string())
}

fn sq(s: &str) -> String { s.replace('\'', "''") }

/// The Altium products with preferences: (registry name, edition). Only the ones that hold any: an old install's key
/// may be empty.
fn products() -> Vec<(String, String)> {
    let out = ps("Get-ChildItem 'HKCU:\\Software\\Altium' | Where-Object { Test-Path (Join-Path $_.PSPath 'DesignExplorer\\Preferences\\Client') } | ForEach-Object { $_.PSChildName }").unwrap_or_default();
    out.lines().map(str::trim).filter(|l| l.starts_with("Altium Designer") && !l.ends_with("_Security"))
        .map(|l| (l.to_string(), edition_of(l).to_string())).collect()
}

/// The edition a product name is. Pure.
pub fn edition_of(product: &str) -> &'static str { if product.to_ascii_lowercase().contains("develop") { "Altium Designer Develop" } else { "Altium Designer" } }

/// Which product a call means: the edition asked for, else the one alone, else the one running. Pure over its inputs.
pub fn pick_product(all: &[(String, String)], want: Option<&str>, running: Option<&str>) -> Result<(String, String), String> {
    let names = || all.iter().map(|p| p.1.clone()).collect::<Vec<_>>().join(", ");
    if let Some(w) = want {
        let w = w.to_ascii_lowercase();
        let exact = all.iter().find(|p| p.1.to_ascii_lowercase() == w);
        let hit = exact.or_else(|| all.iter().find(|p| p.1.to_ascii_lowercase().contains(&w)));
        return hit.cloned().ok_or_else(|| format!("no Altium edition {w} here: {}", names()));
    }
    if all.len() == 1 { return Ok(all[0].clone()); }
    if let Some(r) = running { if let Some(p) = all.iter().find(|p| p.1 == r) { return Ok(p.clone()); } }
    if all.is_empty() { return Err("no Altium preferences on this machine: start Altium once".into()); }
    Err(format!("several Altiums here and none running: name one with edition ({})", names()))
}

/// A key the caller names to a registry path and value name: Server/Group/Name. Pure.
pub fn split_key(key: &str) -> Option<(String, String)> {
    // the standard's dotted path, or Altium's own Server/Group/Name
    let k = key.trim_matches('/').replace('\\', "/");
    let k = if k.contains('/') { k } else { k.replace('.', "/") };
    let (path, name) = k.rsplit_once('/')?;
    if path.is_empty() || name.is_empty() || k.contains("..") { return None; }
    Some((path.replace('/', "\\"), name.to_string()))
}

fn running_edition() -> Option<String> {
    let l = crate::instance::licence_state();
    l.get("running").and_then(|b| b.as_bool()).filter(|b| *b)?;
    Some(edition_of(l["edition"].as_str().unwrap_or("")).to_string())
}

/// altium_preferences {edition?, key?, under?, set?: {key: value}, dryRun?}
pub fn preferences(args: &Value) -> Value {
    let all = products();
    let want = args.get("edition").and_then(|v| v.as_str());
    let (product, edition) = match pick_product(&all, want, running_edition().as_deref()) {
        Ok(p) => p,
        Err(e) => return json!({"success": false, "errorCode": "no_edition", "error": e, "editions": all.iter().map(|p| p.1.clone()).collect::<Vec<_>>()}),
    };
    let root = format!("HKCU:\\Software\\Altium\\{}\\DesignExplorer\\Preferences", sq(&product));
    if let Some(set) = args.get("set").and_then(|v| v.as_object()) {
        if crate::health::is_running() {
            return json!({"success": false, "errorCode": "altium_running", "reason": "tool_running", "edition": edition, "error": "Altium writes its preferences back when it exits, so they are set with Altium closed", "_hint": "altium_close, then call again."});
        }
        let (mut before, mut applied, mut failed) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());
        for (k, v) in set {
            let Some((path, name)) = split_key(k) else { failed.push(json!({"key": k, "error": "a key is Server/Group/Name, as a read lists it"})); continue; };
            let reg = format!("'{root}\\{}'", sq(&path));
            let was = ps(&format!("(Get-ItemProperty -LiteralPath {reg} -Name '{}').'{}'", sq(&name), sq(&name)));
            let Some(was) = was else { failed.push(json!({"key": k, "error": "Altium has no such preference: a set changes existing ones only"})); continue; };
            before.insert(k.clone(), json!(was.trim()));
            if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) { continue; }
            let text = match v { Value::String(s) => s.clone(), Value::Bool(b) => if *b { "1".into() } else { "0".into() }, o => o.to_string() };
            let wrote = ps(&format!("Set-ItemProperty -LiteralPath {reg} -Name '{}' -Value '{}'; (Get-ItemProperty -LiteralPath {reg} -Name '{}').'{}'", sq(&name), sq(&text), sq(&name), sq(&name)));
            match wrote {
                Some(back) if back.trim() == text => { applied.insert(k.clone(), json!({"ok": true, "requested": v, "read": back.trim()})); }
                o => { applied.insert(k.clone(), json!({"ok": false, "requested": v, "read": o.as_deref().map(str::trim)})); failed.push(json!({"key": k, "error": "the value did not read back"})); }
            }
        }
        return json!({"success": failed.is_empty(), "edition": edition, "before": before, "applied": applied, "failed": failed, "mutated": !applied.is_empty(), "needsRestart": false,
            "_hint": "Altium reads its preferences when it starts. Each value is read back from where Altium keeps it."});
    }
    // a read: one key, or everything under a section; with neither, the sections
    if let Some(k) = args.get("key").and_then(|v| v.as_str()) {
        let Some((path, name)) = split_key(k) else { return json!({"success": false, "errorCode": "bad_args", "error": "key is Server/Group/Name"}) };
        return match ps(&format!("(Get-ItemProperty -LiteralPath '{root}\\{}' -Name '{}').'{}'", sq(&path), sq(&name), sq(&name))) {
            Some(v) => json!({"success": true, "edition": edition, "current": {k: v.trim()}}),
            None => json!({"success": false, "errorCode": "not_found", "edition": edition, "error": format!("Altium has no preference {k}")}),
        };
    }
    // the whole of Altium's preferences by default, or one section
    let under = args.get("under").and_then(|v| v.as_str()).map(|u| { let u = u.trim_matches('/').replace('/', "\\"); if u.contains('\\') { u } else { u.replace('.', "\\") } });
    if under.as_deref().map(|u| u.contains("..")).unwrap_or(false) { return json!({"success": false, "errorCode": "bad_args", "error": "under is a section such as ExtensionManager.AutoUpdatePrefs"}); }
    let start = match &under { Some(u) => format!("{root}\\{}", sq(u)), None => root.clone() };
    let script = format!(r#"$r='{start}'; $o=[ordered]@{{}}; foreach($k in @(Get-Item -LiteralPath $r)+@(Get-ChildItem -LiteralPath $r -Recurse)) {{ $i=$k.PSPath.IndexOf('Preferences\'); if($i -lt 0) {{ continue }}; $p=$k.PSPath.Substring($i+12).Replace('\','.'); foreach($n in $k.Property) {{ $v=$k.GetValue($n); if($v -is [byte[]]) {{ $v=[BitConverter]::ToString($v) }} $o["$p.$n"]="$v" }} }}; $o | ConvertTo-Json -Depth 2 -Compress"#);
    match ps(&script).and_then(|t| serde_json::from_str::<Value>(t.trim()).ok()) {
        Some(v) => {
            let n = v.as_object().map(|m| m.len()).unwrap_or(0);
            let sections: std::collections::BTreeSet<String> = v.as_object().map(|m| m.keys().filter_map(|k| k.split('.').next().map(str::to_string)).collect()).unwrap_or_default();
            json!({"success": true, "edition": edition, "under": under.map(|u| u.replace('\\', ".")), "count": n, "sections": sections, "current": v,
                "_hint": "Altium's preferences as dotted keys. key reads one, under reads a section, and set: {key: value} changes existing ones with Altium closed."})
        }
        None => json!({"success": false, "errorCode": "not_found", "edition": edition, "error": "no preferences there"}),
    }
}

/// An extension's name, description and version from its .ins text. Pure.
pub fn parse_ins(text: &str) -> (Option<String>, Option<String>, Option<String>) {
    let field = |k: &str| text.lines().find_map(|l| { let (a, b) = l.split_once('=')?; (a.trim().eq_ignore_ascii_case(k)).then(|| b.trim().trim_matches('\'').to_string()) });
    (field("EditorName"), field("EditorDescription"), field("Version"))
}

/// altium_extensions {action: list | install | remove, name?, edition?}
pub fn extensions(args: &Value) -> Value {
    let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("list").to_ascii_lowercase();
    if action == "install" || action == "remove" {
        return json!({"success": false, "errorCode": "not_supported", "action": action,
            "error": format!("the bridge cannot {action} an Altium extension: Altium does that on its Extensions & Updates page, which is not in UI Automation, and it restarts Altium to apply"),
            "_hint": "The user does it in Altium: Extensions & Updates. altium_install_extension is the separate one for Adom's own AdomBridge extension."});
    }
    if action != "list" { return json!({"success": false, "errorCode": "bad_args", "error": format!("action is list, install or remove (got {action})")}); }
    let want = args.get("edition").and_then(|v| v.as_str()).map(str::to_ascii_lowercase);
    let data = std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".into());
    let mut editions = Vec::new();
    for prod in std::fs::read_dir(std::path::Path::new(&data).join("Altium")).into_iter().flatten().flatten() {
        let name = prod.file_name().to_string_lossy().to_string();
        if !name.starts_with("Altium Designer") || name.ends_with("_Security") { continue; }
        let edition = edition_of(&name);
        if want.as_ref().map(|w| !edition.to_ascii_lowercase().contains(w.as_str())).unwrap_or(false) { continue; }
        let mut list = Vec::new();
        for ext in std::fs::read_dir(prod.path().join("Extensions")).into_iter().flatten().flatten() {
            if !ext.path().is_dir() { continue; }
            let folder = ext.file_name().to_string_lossy().to_string();
            let ins = std::fs::read_dir(ext.path()).into_iter().flatten().flatten().map(|f| f.path()).find(|p| p.extension().map(|x| x.eq_ignore_ascii_case("ins")).unwrap_or(false));
            let (server, desc, ver) = ins.and_then(|p| std::fs::read(p).ok()).map(|b| parse_ins(&String::from_utf8_lossy(&b))).unwrap_or((None, None, None));
            let version = ver.map(|v| v.trim_start_matches("Version ").to_string());
            list.push(json!({"id": folder, "name": desc.unwrap_or_else(|| folder.clone()), "server": server, "version": version, "kind": "altium"}));
        }
        list.sort_by_key(|e| e["id"].as_str().unwrap_or("").to_ascii_lowercase());
        if !list.is_empty() { editions.push(json!({"edition": edition, "count": list.len(), "extensions": list})); }
    }
    let flat: Vec<Value> = editions.first().and_then(|e| e["extensions"].as_array().cloned()).unwrap_or_default();
    json!({"success": true, "extensions": flat, "count": flat.len(), "editions": editions,
        "_hint": "Altium's optional extensions on this machine, by edition (extensions is the first edition's). Installing and removing them happens on Altium's Extensions & Updates page, not through the bridge."})
}

/// How the saved document holds each named model: Altium writes `EMBED=TRUE|MODEL.NAME=x.step` in its body records (true
/// when the model is inside the document, false when it only points at a file), and EMBED=FALSE with no name for an
/// extruded body (measured on Altium's example boards, 2026-11-03). Pure.
pub fn embed_flags(doc: &[u8]) -> std::collections::BTreeMap<String, bool> {
    const KEY: &[u8] = b"EMBED=";
    let mut out = std::collections::BTreeMap::new();
    let mut i = 0;
    while i + KEY.len() < doc.len() {
        if !doc[i..].starts_with(KEY) { i += 1; continue; }
        let rest = &doc[i + KEY.len()..];
        let end = rest.iter().position(|b| *b == 0).unwrap_or(rest.len()).min(400);
        let text = String::from_utf8_lossy(&rest[..end]);
        let mut f = text.split('|');
        let flag = f.next().unwrap_or("").eq_ignore_ascii_case("TRUE");
        if let Some(name) = f.next().and_then(|x| x.strip_prefix("MODEL.NAME=")).filter(|n| !n.is_empty()) {
            // inside the document wins if a name is recorded both ways
            let e = out.entry(name.to_string()).or_insert(flag);
            *e = *e || flag;
        }
        i += KEY.len() + end;
    }
    out
}

/// Can this name be looked up on disk at all? Altium usually records a bare file name. Pure.
fn is_full_path(f: &str) -> bool { f.contains(":\\") || f.contains(":/") || f.starts_with("\\\\") || f.starts_with('/') }

/// What one part's models say: the row is the agent's [ref, footprint, [[file, overall, standoff, w, h]]], `to_mm` turns
/// raw units to mm, `embedded` says how the saved document holds a named model, and `on_disk` whether a file exists. A
/// model embedded in the document is there whether or not the file it came from still is. Pure.
pub fn check_part(row: &Value, to_mm: f64, embedded: &dyn Fn(&str) -> Option<bool>, on_disk: &dyn Fn(&str) -> bool) -> Value {
    let models: Vec<Value> = row[2].as_array().cloned().unwrap_or_default().iter().map(|b| {
        let file = b[0].as_str().unwrap_or("");
        let n = |i: usize| b[i].as_f64().unwrap_or(0.0) * to_mm;
        let (h, s) = (n(1), n(2));
        let geometry = h > s && n(3) > 0.0 && n(4) > 0.0;
        let linked = !file.is_empty() && embedded(file) == Some(false);
        let source = if is_full_path(file) { json!(on_disk(file)) } else { Value::Null };
        json!({"path": if file.is_empty() { Value::Null } else { json!(file) }, "location": if linked { "file" } else { "embedded" }, "found": if linked { on_disk(file) } else { true }, "hasGeometry": geometry,
            "kind": if file.is_empty() { "extruded" } else { "model" }, "sourceFileFound": source, "heightMm": ((h - s) * 1000.0).round() / 1000.0})
    }).collect();
    let mut issues = Vec::new();
    if models.is_empty() { issues.push("no 3D model".to_string()); }
    if models.iter().any(|m| m["found"] != json!(true)) { issues.push("a linked model's file is not found".to_string()); }
    if models.iter().any(|m| m["hasGeometry"] != json!(true)) { issues.push("a model holds no geometry".to_string()); }
    json!({"name": row[0], "footprint": row[1], "models": models, "issues": issues})
}

/// altium_model_check {filePath? | library?, footprint?, refs?, limit?}
pub fn model_check(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let doc = crate::support::s(args, "filePath").or_else(|| crate::support::s(args, "library"));
    if let Some(p) = &doc { if let Some(e) = crate::support::must_open(p, 60) { return e; } }
    let r = crate::agent::call("model_check", &[], None, std::time::Duration::from_secs(180));
    let d = r.get("data").cloned().unwrap_or(Value::Null);
    if d["ok"] != json!(true) { return json!({"success": false, "errorCode": "no_document", "error": d.get("error").cloned().unwrap_or(json!("no board or footprint library is current")), "reply": r}); }
    let mut want: Vec<String> = args.get("refs").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_ascii_lowercase)).collect();
    if let Some(f) = crate::support::s(args, "footprint") { want.push(f.to_ascii_lowercase()); }
    let to_mm = 0.0254 / 10000.0;
    // how the document holds its models is in the saved file; a model added since the last save reads as embedded, as
    // Altium adds them. A linked model named without a folder is looked for beside the document.
    let doc_path = d["document"].as_str().unwrap_or("").to_string();
    let flags = std::fs::read(&doc_path).map(|b| embed_flags(&b)).unwrap_or_default();
    let embedded = |f: &str| flags.get(f).copied();
    let on_disk = |f: &str| std::path::Path::new(f).is_file() || std::path::Path::new(&doc_path).parent().map(|p| p.join(f).is_file()).unwrap_or(false);
    let parts: Vec<Value> = d["parts"].as_array().cloned().unwrap_or_default().iter()
        .filter(|p| want.is_empty() || p[0].as_str().map(|x| want.contains(&x.to_ascii_lowercase())).unwrap_or(false))
        .map(|p| check_part(p, to_mm, &embedded, &on_disk)).collect();
    if !want.is_empty() && parts.is_empty() { return json!({"success": false, "errorCode": "not_found", "error": format!("none of {want:?} is on this document"), "document": d["document"]}); }
    let names = |f: &dyn Fn(&Value) -> bool| parts.iter().filter(|p| f(p)).filter_map(|p| p["name"].as_str().map(str::to_string)).collect::<Vec<_>>();
    let no_model = names(&|p| p["models"].as_array().map(|b| b.is_empty()).unwrap_or(true));
    let not_found = names(&|p| p["models"].as_array().map(|b| b.iter().any(|x| x["found"] != json!(true))).unwrap_or(false));
    let no_geometry = names(&|p| p["models"].as_array().map(|b| !b.is_empty() && b.iter().any(|x| x["hasGeometry"] != json!(true))).unwrap_or(false));
    let lost_source = names(&|p| p["models"].as_array().map(|b| b.iter().any(|x| x["sourceFileFound"] == json!(false))).unwrap_or(false));
    // the report is capped, the answer is not: ok and checked speak for every part, with the worst ones listed first
    let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as usize;
    let mut shown = parts.clone();
    shown.sort_by_key(|p| p["issues"].as_array().map(|i| i.is_empty()).unwrap_or(true));
    shown.truncate(limit);
    json!({"success": true, "ok": no_model.is_empty() && no_geometry.is_empty() && not_found.is_empty(), "kind": d["kind"], "document": d["document"], "checked": parts.len(), "parts": shown, "noModel": no_model, "noGeometry": no_geometry, "notFound": not_found, "sourceFileMissing": lost_source,
        "_hint": "location is how the saved document holds each model: embedded models are inside it and draw whether or not their source file exists; a linked one (file) needs its file, and notFound names the parts whose file is gone. sourceFileFound is null when Altium recorded only a file name, which can't be looked up. noModel has no body at all; noGeometry has a body with no height or size. ok and checked cover every part; parts lists up to limit, those with issues first. altium_bodies says whether each body sits where the board puts the part."})
}

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

    #[test]
    fn a_parts_models() {
        let k = 10000.0 / 0.0254;
        let to_mm = 1.0 / k;
        let raw = |mm: f64| mm * k;
        let row = json!(["U1", "QFN", [["CAPC0603X03L.step", raw(1.0), 0.0, raw(4.0), raw(4.0)], ["", raw(0.5), 0.0, raw(2.0), raw(2.0)]]]);
        let r = check_part(&row, to_mm, &|_| Some(true), &|_| false);
        assert_eq!(r["name"], "U1");
        assert_eq!(r["issues"], json!([]), "an embedded model needs no file");
        assert_eq!(r["models"][0]["location"], "embedded");
        assert_eq!(r["models"][0]["found"], true);
        assert_eq!(r["models"][0]["sourceFileFound"], Value::Null, "a bare name can't be looked up");
        assert_eq!(r["models"][0]["heightMm"], 1.0);
        assert_eq!(r["models"][1]["kind"], "extruded");
        // a model that only points at a file needs that file
        let linked = json!(["U2", "QFN", [["C:/m/u2.step", raw(1.0), 0.0, raw(4.0), raw(4.0)]]]);
        let gone = check_part(&linked, to_mm, &|_| Some(false), &|_| false);
        assert_eq!(gone["models"][0]["location"], "file");
        assert_eq!(gone["models"][0]["found"], false);
        assert_eq!(gone["models"][0]["sourceFileFound"], false);
        assert_eq!(gone["issues"], json!(["a linked model's file is not found"]));
        assert_eq!(check_part(&linked, to_mm, &|_| Some(false), &|_| true)["issues"], json!([]));
        assert_eq!(check_part(&json!(["R1", "R", []]), to_mm, &|_| None, &|_| true)["issues"], json!(["no 3D model"]));
        assert_eq!(check_part(&json!(["R1", "R", [["x.step", 0.0, 0.0, 0.0, 0.0]]]), to_mm, &|_| None, &|_| true)["models"][0]["hasGeometry"], false);
    }

    #[test]
    fn the_saved_file_says_how_a_model_is_held() {
        let doc = b"xx\0EMBED=TRUE|MODEL.NAME=a.step|MODEL.2D.X=1mil\0yy\0EMBED=FALSE|MODEL.NAME=|MODEL.MODELTYPE=0\0EMBED=FALSE|MODEL.NAME=b.step|Z=1\0";
        let f = embed_flags(doc);
        assert_eq!(f.get("a.step"), Some(&true));
        assert_eq!(f.get("b.step"), Some(&false));
        assert_eq!(f.len(), 2, "an extruded body names no model");
    }

    #[test]
    fn a_key_is_its_section_and_name() {
        assert_eq!(split_key("ExtensionManager/AutoUpdatePrefs/UpdatesCheckFrequency"), Some(("ExtensionManager\\AutoUpdatePrefs".to_string(), "UpdatesCheckFrequency".to_string())));
        assert_eq!(split_key("ExtensionManager.AutoUpdatePrefs.UpdatesCheckFrequency"), Some(("ExtensionManager\\AutoUpdatePrefs".to_string(), "UpdatesCheckFrequency".to_string())), "the standard's dotted path");
        assert_eq!(split_key("Plain"), None);
        assert_eq!(split_key("../../Evil/Name"), None, "stays under Altium's preferences");
    }

    #[test]
    fn which_altium_a_call_means() {
        let a = |n: &str, e: &str| (n.to_string(), e.to_string());
        let two = vec![a("D {1}", "Altium Designer"), a("V {2}", "Altium Designer Develop")];
        assert_eq!(pick_product(&two, Some("develop"), None).unwrap().0, "V {2}");
        assert_eq!(pick_product(&two, Some("altium designer"), None).unwrap().0, "D {1}", "the exact edition, not the first that contains it");
        assert_eq!(pick_product(&two, None, Some("Altium Designer Develop")).unwrap().0, "V {2}");
        assert!(pick_product(&two, None, None).is_err());
        assert_eq!(pick_product(&two[..1], None, None).unwrap().0, "D {1}");
    }

    #[test]
    fn an_extensions_ins_file() {
        let (n, d, v) = parse_ins("ClientInsFile 1.0\n\nServer\n    EditorName        = 'PcbDrawing'\n    EditorDescription = 'Draftsman'\n    Version           = 'Version 1.0.0.0'\nEnd\n");
        assert_eq!((n.as_deref(), d.as_deref(), v.as_deref()), (Some("PcbDrawing"), Some("Draftsman"), Some("Version 1.0.0.0")));
    }
}