main
Colby Knox 0.2.60 source (not yet released, needs signing): layer_stack editing, net_classes, diff_pairs, set_track_width, variant… e42e78c
//! Assembly variants (which parts are fitted on which build) written into the project file, since Altium's
//! script API reads variants but cannot make them. Only the [ProjectVariantN] sections change; Altium reloads
//! the project and the bridge reads back what Altium holds.
use crate::support::{self, s};
use crate::{agent, bom};
use serde_json::{json, Value};
use std::collections::HashMap;
use std::path::Path;
use std::time::Duration;

/// One [ProjectVariantN] block: its key=value lines in file order.
#[derive(Debug, Clone, PartialEq)]
pub struct Block { pub lines: Vec<(String, String)> }

impl Block {
    fn get(&self, k: &str) -> Option<&str> { self.lines.iter().find(|(a, _)| a == k).map(|(_, b)| b.as_str()) }
    pub fn name(&self) -> String { self.get("Description").unwrap_or("").to_string() }
    /// designator (upper case) -> the whole Variation value, in order
    pub fn variations(&self) -> Vec<(String, String)> {
        self.lines.iter().filter(|(k, _)| k.starts_with("Variation") && k.len() > 9 && k[9..].chars().all(|c| c.is_ascii_digit()))
            .filter_map(|(_, v)| {
                let f: HashMap<&str, &str> = v.split('|').filter_map(|x| x.split_once('=')).collect();
                f.get("Designator").map(|d| (d.to_ascii_uppercase(), v.clone()))
            }).collect()
    }
    fn has_param_variations(&self) -> bool { self.lines.iter().any(|(k, v)| k.starts_with("ParamVariation") && v != "0" || k == "ParameterCount" && v != "0") }
}

/// The file split around its variant blocks: (text before the first, the blocks, text after them with any
/// non-variant sections that sat between). Line endings are kept as CRLF on output.
pub fn split(text: &str) -> (Vec<String>, Vec<Block>, Vec<String>) {
    let mut before = Vec::new();
    let mut after = Vec::new();
    let mut blocks: Vec<Block> = Vec::new();
    let mut in_variant = false;
    let mut seen = false;
    for raw in text.lines() {
        let line = raw.trim_end_matches('\r');
        let t = line.trim();
        if t.starts_with('[') && t.ends_with(']') {
            in_variant = t[1..t.len() - 1].starts_with("ProjectVariant");
            if in_variant { blocks.push(Block { lines: vec![] }); seen = true; continue; }
        }
        if in_variant {
            if let Some((k, v)) = line.split_once('=') { blocks.last_mut().unwrap().lines.push((k.to_string(), v.to_string())); }
            continue;
        }
        if seen { after.push(line.to_string()) } else { before.push(line.to_string()) }
    }
    (before, blocks, after)
}

pub fn join(before: &[String], blocks: &[Block], after: &[String]) -> String {
    let mut out: Vec<String> = before.to_vec();
    while out.last().map(|l| l.trim().is_empty()).unwrap_or(false) { out.pop(); }
    for (i, b) in blocks.iter().enumerate() {
        out.push(String::new());
        out.push(format!("[ProjectVariant{}]", i + 1));
        for (k, v) in &b.lines { out.push(format!("{k}={v}")); }
    }
    let mut tail = after.to_vec();
    while tail.first().map(|l| l.trim().is_empty()).unwrap_or(false) { tail.remove(0); }
    if !tail.is_empty() { out.push(String::new()); out.extend(tail); }
    let mut s = out.join("\r\n");
    s.push_str("\r\n");
    s
}

/// A variant with these variations (designator, uniqueId path, kind, alternate part), keeping the block's
/// other keys when it already exists.
pub fn with_variations(existing: Option<&Block>, name: &str, vars: &[(String, String, i64, String)]) -> Block {
    let mut lines: Vec<(String, String)> = match existing {
        Some(b) => b.lines.iter().filter(|(k, _)| !(k.starts_with("Variation"))).cloned().collect(),
        None => vec![("Description".into(), name.into()), ("AllowFabrication".into(), "0".into()), ("ParameterCount".into(), "0".into())],
    };
    lines.push(("VariationCount".into(), vars.len().to_string()));
    for (i, (d, u, k, alt)) in vars.iter().enumerate() {
        lines.push((format!("Variation{}", i + 1), format!("Designator={d}|UniqueId={u}|Kind={k}|AlternatePart={alt}")));
    }
    Block { lines }
}

fn list_of(v: Option<&Value>) -> Vec<String> {
    match v {
        Some(Value::Array(a)) => a.iter().filter_map(|x| x.as_str()).map(|x| x.trim().to_ascii_uppercase()).filter(|x| !x.is_empty()).collect(),
        Some(Value::String(t)) => t.split(',').map(|x| x.trim().to_ascii_uppercase()).filter(|x| !x.is_empty()).collect(),
        _ => vec![],
    }
}

fn summary(blocks: &[Block]) -> Vec<Value> {
    blocks.iter().map(|b| {
        let vars = b.variations();
        let kind_of = |v: &str| v.split('|').find_map(|x| x.strip_prefix("Kind=")).and_then(|k| k.parse::<i64>().ok()).unwrap_or(0);
        json!({"name": b.name(),
               "notFitted": vars.iter().filter(|(_, v)| kind_of(v) == 1).map(|(d, _)| d.clone()).collect::<Vec<_>>(),
               "alternates": vars.iter().filter(|(_, v)| kind_of(v) == 2).map(|(d, v)| json!({"designator": d, "part": v.split('|').find_map(|x| x.strip_prefix("AlternatePart=")).unwrap_or("")})).collect::<Vec<_>>()})
    }).collect()
}

fn read_back(prj: &str) -> Value {
    let r = agent::call("project_variants", &[("path", prj.to_string())], None, Duration::from_secs(60));
    r.get("data").cloned().unwrap_or(r)
}

/// altium_variants {projectPath, name?, notFitted?, fitted?, remove?}
pub fn variants(args: &Value) -> Value {
    let Some(prj) = s(args, "projectPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"}) };
    let Ok(bytes) = std::fs::read(&prj) else { return json!({"success": false, "errorCode": "not_found", "error": format!("cannot read {prj}")}) };
    let text = String::from_utf8_lossy(&bytes).to_string();
    let (before, mut blocks, after) = split(&text);
    let Some(name) = s(args, "name") else {
        return json!({"success": true, "projectPath": prj, "variants": summary(&blocks),
            "_hint": "Make or change one with {name, notFitted:[designators], fitted:[designators]}; altium_bom {variant} gives that build's BOM."});
    };
    if name.contains(['\n', '[', ']']) { return json!({"success": false, "errorCode": "bad_args", "error": "a variant name cannot hold brackets or newlines"}); }
    if let Some(g) = support::need_licensed() { return g; }
    let idx = blocks.iter().position(|b| b.name().eq_ignore_ascii_case(&name));
    let remove = args.get("remove").and_then(|b| b.as_bool()) == Some(true);
    let not_fitted = list_of(args.get("notFitted").or_else(|| args.get("dnp")));
    let fitted = list_of(args.get("fitted"));
    if !remove && not_fitted.is_empty() && fitted.is_empty() {
        return json!({"success": false, "errorCode": "bad_args", "error": "give notFitted and/or fitted designators, or remove:true"});
    }
    if let Some(i) = idx { if blocks[i].has_param_variations() && !remove {
        return json!({"success": false, "errorCode": "has_parameter_variations", "error": format!("variant {name} carries parameter variations; edit it in Altium's Variant Management"), "variants": summary(&blocks)});
    } }
    let project = bom::parse_project(&text, Path::new(&prj).parent().unwrap_or(Path::new(".")));
    // each part's unique id from its sheet (a variation names the part by it)
    let mut uid: HashMap<String, String> = HashMap::new();
    if !not_fitted.is_empty() {
        for sheet in &project.sheets {
            if let Some(e) = support::must_open(sheet, 60) { return e; }
            let r = agent::call("schematic_data", &[("pins", "0".into()), ("params", "0".into()), ("limit", "5000".into())], None, Duration::from_secs(120));
            for c in r.get("data").and_then(|d| d.get("components")).and_then(|c| c.as_array()).cloned().unwrap_or_default() {
                if let (Some(d), Some(u)) = (c["designator"].as_str(), c["uniqueId"].as_str()) { uid.entry(d.to_ascii_uppercase()).or_insert(u.to_string()); }
            }
        }
        let missing: Vec<&String> = not_fitted.iter().filter(|d| !uid.contains_key(*d)).collect();
        if !missing.is_empty() { return json!({"success": false, "errorCode": "designator_not_found", "notOnSheets": missing, "_hint": "Designators must be on the project's sheets (annotate '?' parts first)."}); }
    }
    if remove {
        if let Some(i) = idx { blocks.remove(i); } else { return json!({"success": true, "removed": false, "variants": summary(&blocks)}); }
    } else {
        let mut vars: Vec<(String, String, i64, String)> = idx.map(|i| blocks[i].variations()).unwrap_or_default().into_iter()
            .filter(|(d, _)| !fitted.contains(d) && !not_fitted.contains(d))
            .map(|(_, v)| {
                let f: HashMap<&str, &str> = v.split('|').filter_map(|x| x.split_once('=')).collect();
                (f.get("Designator").unwrap_or(&"").to_string(), f.get("UniqueId").unwrap_or(&"").to_string(), f.get("Kind").and_then(|k| k.parse().ok()).unwrap_or(1), f.get("AlternatePart").unwrap_or(&"").to_string())
            }).collect();
        for d in &not_fitted { vars.push((d.clone(), format!("\\{}", uid[d]), 1, String::new())); }
        let b = with_variations(idx.map(|i| &blocks[i]), &name, &vars);
        match idx { Some(i) => blocks[i] = b, None => blocks.push(b) }
    }
    // Altium keeps the project in memory: save its documents and the project, close it, write, reopen
    for d in project.sheets.iter().chain(project.boards.iter()) { let _ = crate::surfaces::save(&json!({"filePath": d})); }
    let _ = crate::surfaces::save(&json!({"filePath": prj}));
    let _ = agent::call("close_document", &[("path", prj.clone())], None, Duration::from_secs(30));
    if let Err(e) = std::fs::write(&prj, join(&before, &blocks, &after)) {
        return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()});
    }
    let reopened = crate::surfaces::open_document(&json!({"filePath": prj}));
    let altium = read_back(&prj);
    let took = altium.get("variants").and_then(|v| v.as_array()).map(|v| {
        let have = v.iter().any(|x| x["name"].as_str().map(|n| n.eq_ignore_ascii_case(&name)).unwrap_or(false));
        have != remove
    }).unwrap_or(false);
    json!({"success": took, "projectPath": prj, "variant": name, "removed": remove, "variants": summary(&blocks), "altium": altium,
        "reopened": reopened.get("success"), "errorCode": if took { Value::Null } else { json!("not_read_back") },
        "_hint": if took { "Altium holds the variant. altium_bom {variant} gives that build's BOM; pick it in an OutJob's variant to build its outputs. The board marks not-fitted parts when the variant is current (View > Variant in Altium)." }
                 else { "The project file was written but Altium did not report the change: open the project in Altium (altium_open_project) and check Project > Variants." }})
}

#[cfg(test)]
mod tests {
    use super::*;
    const PRJ: &str = "[Design]\r\nVersion=1.0\r\n\r\n[Document1]\r\nDocumentPath=A.SchDoc\r\n\r\n[ProjectVariant1]\r\nDescription=Lite\r\nAllowFabrication=0\r\nParameterCount=0\r\nVariationCount=1\r\nVariation1=Designator=R2|UniqueId=\\ABC|Kind=1|AlternatePart=\r\n\r\n[Parameter1]\r\nName=Rev\r\nValue=A\r\n";

    #[test]
    fn variant_blocks_round_trip_and_the_rest_is_kept() {
        let (b, v, a) = split(PRJ);
        assert_eq!(v.len(), 1);
        assert_eq!(v[0].name(), "Lite");
        assert_eq!(join(&b, &v, &a), PRJ);
    }

    #[test]
    fn a_new_variant_is_numbered_after_the_others() {
        let (b, mut v, a) = split(PRJ);
        v.push(with_variations(None, "Full", &[("C1".into(), "\\XYZ".into(), 1, String::new())]));
        let out = join(&b, &v, &a);
        assert!(out.contains("[ProjectVariant2]\r\nDescription=Full\r\nAllowFabrication=0\r\nParameterCount=0\r\nVariationCount=1\r\nVariation1=Designator=C1|UniqueId=\\XYZ|Kind=1|AlternatePart=\r\n"));
        assert!(out.ends_with("[Parameter1]\r\nName=Rev\r\nValue=A\r\n"));
        let p = bom::parse_project(&out, Path::new("."));
        assert_eq!(p.variants.len(), 2);
        assert_eq!(p.variants[1].1["C1"].0, 1);
    }

    #[test]
    fn editing_keeps_the_variant_keys_and_renumbers_variations() {
        let (_, v, _) = split(PRJ);
        let b = with_variations(Some(&v[0]), "Lite", &[("R2".into(), "\\ABC".into(), 1, String::new()), ("R3".into(), "\\DEF".into(), 1, String::new())]);
        assert_eq!(b.name(), "Lite");
        assert_eq!(b.variations().len(), 2);
        assert_eq!(b.get("VariationCount"), Some("2"));
    }
}