main
Colby Knox lint_library on the standard's engine (adom-eda-checks 0.21.1, vendored as published); open finds a document under any… 7a1ea1f
//! lint_library: is a library fit to ship? The rules are the standard's (EDA Bridge Standard #28), run by the shared
//! engine (adom-eda-checks `lint_library`); this module reads the library from Altium and hands it over. KiCad's lint
//! adds its tool's verdict on the file; an Altium library always parses, so Altium sends content only.
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }

/// One footprint as read_footprint answers it, in the engine's terms. A key is sent only when it was read: an empty
/// one is a finding (no courtyard on Mechanical 15, nothing on the overlays, no 3D body). Pure.
pub fn engine_footprint(name: &str, fp: &Value) -> Value {
    let pads: Vec<Value> = fp["pads"].as_array().cloned().unwrap_or_default().iter().map(|p| {
        let (mut w, mut h) = (f(&p["sizeMm"][0]), f(&p["sizeMm"][1]));
        // the copper's box in the footprint's frame: a quarter turn swaps the sides, any other turn takes the larger
        let rot = f(&p["rotation"]).rem_euclid(180.0);
        if (rot - 90.0).abs() < 0.01 { std::mem::swap(&mut w, &mut h); } else if rot > 0.01 && (rot - 180.0).abs() > 0.01 { let m = w.max(h); w = m; h = m; }
        json!({"number": p["number"], "x": p["at"][0], "y": p["at"][1], "w": w, "h": h, "hole": p["drillMm"], "plated": p["type"] != "npth"})
    }).collect();
    let ids = &fp["graphicsLayerIds"];
    let on = |id: &str| ids.get(id).and_then(|v| v.as_i64()).unwrap_or(0) > 0;
    json!({"name": name, "pads": pads,
        "courtyard": if on("71") { fp["courtyardMm"].clone() } else { Value::Null },
        "silk": if on("33") || on("34") { json!([[0, 0]]) } else { json!([]) },
        "bodies": fp["models"].as_array().cloned().unwrap_or_default(),
        "description": fp["description"].as_str().unwrap_or("")})
}

/// The footprint a symbol links: its current PCBLIB model, else its first.
fn linked_footprint(sym: &Value) -> Option<String> {
    let models: Vec<&Value> = sym["models"].as_array().map(|a| a.iter().filter(|m| m["type"].as_str().map(|t| t.eq_ignore_ascii_case("PCBLIB")).unwrap_or(false)).collect()).unwrap_or_default();
    models.iter().find(|m| m["isCurrent"] == json!(true)).or(models.first()).and_then(|m| m["name"].as_str()).map(str::to_string)
}

/// One symbol as read_symbol answers it, in the engine's terms. Pure.
pub fn engine_symbol(name: &str, sym: &Value) -> Value {
    let pins: Vec<Value> = sym["pins"].as_array().cloned().unwrap_or_default().iter().map(|p| json!({"number": p["des"], "name": p["name"]})).collect();
    let param = |n: &str| sym["params"].as_array().and_then(|a| a.iter().find(|p| p["name"].as_str().map(|x| x.eq_ignore_ascii_case(n)).unwrap_or(false)))
        .and_then(|p| p["value"].as_str()).map(str::trim).filter(|v| !v.is_empty()).map(str::to_string);
    json!({"name": name, "pins": pins, "footprint": linked_footprint(sym).unwrap_or_default(),
        "partNumber": param("MPN").or_else(|| param("Manufacturer Part Number")).unwrap_or_default()})
}

fn data(r: &Value) -> Value { if r["data"].is_object() { r["data"].clone() } else { r.clone() } }
fn ok(r: &Value) -> bool { r.get("success").and_then(|v| v.as_bool()) == Some(true) && data(r)["ok"] != json!(false) }
fn names_of(lib: &str) -> Result<Vec<String>, Value> {
    let r = crate::surfaces::list_library(&json!({"libraryPath": lib}));
    if !ok(&r) { return Err(r); }
    Ok(data(&r)["names"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default())
}

/// altium_lint_library {libraryPath | filePath, names?, footprintLibraries? | footprintLibrary?}
pub fn lint_library(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let Some(lib) = crate::support::s(args, "libraryPath").or_else(|| crate::support::s(args, "filePath")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "libraryPath (a .PcbLib or .SchLib) is required"});
    };
    let low = lib.to_lowercase();
    let kind = if low.ends_with(".pcblib") { "pcb" } else if low.ends_with(".schlib") { "sch" } else {
        return json!({"success": false, "errorCode": "bad_args", "error": "libraryPath must be a .PcbLib or .SchLib"});
    };
    let all = match names_of(&lib) { Ok(n) => n, Err(e) => return e };
    let want: Vec<String> = args.get("names").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(|s| s.to_lowercase())).collect()).unwrap_or_default();
    let names: Vec<String> = all.into_iter().filter(|n| want.is_empty() || want.contains(&n.to_lowercase())).collect();
    let mut unread = Vec::new();
    if kind == "pcb" {
        let mut fps = Vec::new();
        for n in &names {
            let fp = crate::project::read_footprint(&json!({"libraryPath": lib, "name": n}));
            if ok(&fp) { fps.push(engine_footprint(n, &fp)); } else { unread.push(json!({"name": n, "error": fp.get("error")})); }
        }
        let mut r = adom_eda_checks::liblint::lint_library(&json!({"library": {"footprints": fps, "unread": unread}}));
        r["library"] = json!(lib); r["kind"] = json!(kind);
        return r;
    }
    // a SchLib: its symbols, checked against the footprints they link, from the libraries named or the PcbLibs beside it
    let mut fp_libs: Vec<String> = args.get("footprintLibraries").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
    if let Some(l) = crate::support::s(args, "footprintLibrary") { fp_libs.push(l); }
    if fp_libs.is_empty() { fp_libs = sibling_pcblibs(Path::new(&lib.replace('\\', "/"))).iter().map(|p| p.to_string_lossy().to_string()).collect(); }
    let mut syms = Vec::new();
    for n in &names {
        let r = crate::library::read_symbol(&json!({"libraryPath": lib, "symbolName": n}));
        if ok(&r) { syms.push(engine_symbol(n, &data(&r))); } else { unread.push(json!({"name": n, "error": r.get("error").or(data(&r).get("error"))})); }
    }
    let lib_names: Vec<(String, Vec<String>)> = fp_libs.iter().map(|l| (l.clone(), names_of(l).unwrap_or_default())).collect();
    // each linked footprint read once, from the first library that has it; one not found is left out, so the
    // engine names it footprint_not_found
    let mut fps: BTreeMap<String, Value> = BTreeMap::new();
    for s in &syms {
        let Some(fpn) = s["footprint"].as_str().filter(|n| !n.is_empty()).map(str::to_string) else { continue };
        if fps.contains_key(&fpn) { continue; }
        let hit = lib_names.iter().find_map(|(l, ns)| ns.iter().find(|n| n.eq_ignore_ascii_case(&fpn)).map(|n| (l, n.clone())));
        if let Some((l, n)) = hit {
            let fp = crate::project::read_footprint(&json!({"libraryPath": l, "name": n}));
            if ok(&fp) { fps.insert(fpn.clone(), engine_footprint(&fpn, &fp)); }
        }
    }
    let findings: Vec<Value> = syms.iter().flat_map(|s| adom_eda_checks::liblint::lint_symbol(s, Some(&fps))).collect();
    // the engine's reply, with the symbol findings as ours: the footprints were read to check pins, not to lint them
    let mut r = adom_eda_checks::liblint::lint_library(&json!({"library": {"findings": findings, "unread": unread}}));
    r["checked"] = json!(syms.len());
    r["library"] = json!(lib); r["kind"] = json!(kind); r["footprintLibraries"] = json!(fp_libs);
    r
}

fn sibling_pcblibs(schlib: &Path) -> Vec<PathBuf> {
    let dir = schlib.parent().unwrap_or(Path::new("."));
    let mut out: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path())
        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("PcbLib")).unwrap_or(false)).collect();
    out.sort();
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use adom_eda_checks::liblint::{lint_footprint, lint_symbol};

    fn pad(n: &str, x: f64, y: f64) -> Value { json!({"number": n, "type": "smd", "at": [x, y], "sizeMm": [1.0, 0.6], "drillMm": 0.0, "rotation": 0.0}) }
    fn rules(v: &[Value]) -> Vec<String> { v.iter().map(|f| f["rule"].as_str().unwrap().to_string()).collect() }

    #[test]
    fn a_good_footprint_is_clean() {
        let fp = json!({"pads": [pad("1", -1.0, 0.0), pad("2", 1.0, 0.0)], "graphicsLayerIds": {"33": 4, "71": 4}, "courtyardMm": [-1.6, -0.5, 1.6, 0.5], "models": [{}], "description": "0603"});
        assert_eq!(rules(&lint_footprint(&engine_footprint("R0603", &fp))), Vec::<String>::new());
    }

    #[test]
    fn what_altium_did_not_draw_is_a_finding() {
        // BAT_FP_X as the battery's xcopy left it (#29): 1270 mm off, nothing on the overlays or Mechanical 15, no body
        let fp = json!({"pads": [pad("1", -1271.016, -1270.0), pad("2", -1268.984, -1270.0)], "graphicsLayerIds": {}, "courtyardMm": [0, 0, 0, 0], "models": [], "description": "battery"});
        let r = rules(&lint_footprint(&engine_footprint("BAT_FP_X", &fp)));
        assert_eq!(r, ["no_courtyard", "origin_off_part", "no_silkscreen", "no_3d_body"]);
    }

    #[test]
    fn a_turned_pad_is_measured_turned() {
        let mut p = pad("1", 0.0, 0.0); p["rotation"] = json!(90.0);
        assert_eq!(engine_footprint("X", &json!({"pads": [p]}))["pads"][0]["w"], json!(0.6));
    }

    #[test]
    fn symbol_pins_against_footprint_pads() {
        let sym = json!({"pins": [{"des": "1"}, {"des": "2"}, {"des": "3"}], "params": [{"name": "Manufacturer Part Number", "value": "X1"}],
                         "models": [{"type": "PCBLIB", "name": "SOT23", "isCurrent": true}]});
        let mut fps = BTreeMap::new();
        fps.insert("SOT23".to_string(), engine_footprint("SOT23", &json!({"pads": [pad("1", 0.0, 0.0), pad("2", 2.0, 0.0), pad("4", 4.0, 0.0)]})));
        assert_eq!(rules(&lint_symbol(&engine_symbol("Q1", &sym), Some(&fps))), ["pin_without_pad", "pad_without_pin"]);
        assert_eq!(rules(&lint_symbol(&engine_symbol("Q1", &sym), Some(&BTreeMap::new()))), ["footprint_not_found"]);
        assert_eq!(rules(&lint_symbol(&engine_symbol("B", &json!({"pins": []})), Some(&fps))), ["no_pins", "no_footprint", "no_part_number"]);
    }
}