main
Colby Knox 0.2.113: altium_layer_map (organisation layers, template footprints), typed layers kept when placing and copying, every… 1d98bc4
//! The footprint layer map (#41): which Altium layer each kind of footprint graphic goes on, so footprints the bridge
//! makes land on an organisation's own layers. Keys are Adom's logical layers; a value names an Altium layer by type
//! (a typed component layer of AD 24+, "CourtyardTop"), by name ("Top Courtyard", "Mechanical 15") or by number.
//!
//! Precedence, per key: the call's `layerMap`, then `adom-layer-map.json` beside the library (the organisation's
//! default), then the user's default, then the bridge's built-in layers (unchanged since before the map). Pure: the
//! files are read in layermap_verb.
use serde_json::{json, Map, Value};

/// The logical layers, with what the bridge draws on each and its built-in Altium layer.
pub const KEYS: &[(&str, &str, &str)] = &[
    ("overlay", "silkscreen (KiCad F.SilkS)", "Top Overlay"),
    ("fab", "fabrication / assembly outline (KiCad F.Fab)", "Mechanical 13"),
    ("courtyard", "courtyard (KiCad F.CrtYd)", "Mechanical 15"),
    ("body3d", "3D body (altium_add_body)", "Mechanical 1"),
    ("comment", "comments (KiCad Cmts.User)", "Mechanical 1"),
    ("balls", "BGA solder balls (KiCad User.9)", "Mechanical 9"),
    ("centroid", "the centre marker a template carries", "the template's own layer"),
    ("designator", "the .Designator string a template carries", "the template's own layer"),
    ("outline", "component outline (nothing the bridge draws yet)", "-"),
    ("dimensions", "dimensions (nothing the bridge draws yet)", "-"),
];

/// Keys the bridge draws on today. The rest are accepted, so one map serves a whole organisation, and reported unused.
pub const DRAWN: &[&str] = &["overlay", "fab", "courtyard", "body3d", "comment", "balls", "centroid", "designator"];

/// A typed component layer's kind number by its type name (as Altium's layer type, "CourtyardTop"; spaces, dots and
/// case ignored, so "Top Courtyard" is not a type but "courtyard top" is).
pub fn kind_of(name: &str) -> Option<i64> {
    let n: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
    (1..=30).find(|k| crate::fplayers::kind_name(*k).map(|t| t.to_ascii_lowercase()) == Some(n.clone()))
}

/// The top/bottom pair a kind belongs to: (pair kind, top kind, bottom kind), as Altium sets them (AD 26.11, read
/// 2026-11-30). Only a pair can be given a type from a script.
pub fn pair_of(kind: i64) -> Option<(i64, i64, i64)> {
    Some(match kind {
        1 | 2 => (1, 1, 2), 5 | 6 => (2, 5, 6), 7 | 8 => (3, 7, 8), 9 | 10 => (4, 9, 10), 11 | 12 => (5, 11, 12),
        13 | 14 => (6, 13, 14), 16 | 17 => (7, 16, 17), 19 | 20 => (8, 19, 20), 21 | 22 => (9, 21, 22),
        23 | 24 => (10, 23, 24), 26 | 27 => (11, 26, 27),
        _ => return None,
    })
}

/// A mechanical layer's id: Mechanical 1-16 keep their old ids, the rest are 67108864 + n.
pub fn is_mech(id: i64) -> bool { (57..=72).contains(&id) || (67_108_865..=67_109_888).contains(&id) }

/// Standard layer names the bridge knows by id (non-mechanical).
fn named_id(name: &str) -> Option<i64> {
    Some(match name.trim().to_ascii_lowercase().as_str() {
        "top overlay" | "f.silks" | "f.silkscreen" => 33, "bottom overlay" | "b.silks" | "b.silkscreen" => 34,
        "top paste" | "f.paste" => 35, "bottom paste" | "b.paste" => 36, "top solder" | "f.mask" => 37, "bottom solder" | "b.mask" => 38,
        "top layer" | "f.cu" => 1, "bottom layer" | "b.cu" => 32, "keep-out layer" => 56, "multi-layer" => 74,
        _ => return None,
    })
}

/// One value as the agent's code: `k<kind>` a typed layer (made if the library has none), `m<n>` Mechanical n,
/// `i<id>` an Altium layer id, `n<name>` a mechanical layer by its name. Err names what was wrong.
pub fn encode(v: &Value) -> Result<String, String> {
    if let Some(i) = v.as_i64() {
        return if i > 0 { Ok(format!("i{i}")) } else { Err(format!("{i} is not a layer id")) };
    }
    if let Some(o) = v.as_object() {
        if let Some(k) = o.get("kind").and_then(|x| x.as_str()) { return encode(&json!(k)).and_then(|c| if c.starts_with('k') { Ok(c) } else { Err(format!("{k} is not a layer type")) }); }
        if let Some(n) = o.get("mechanical").and_then(|x| x.as_i64()) { return if (1..=1024).contains(&n) { Ok(format!("m{n}")) } else { Err(format!("Mechanical {n} is out of 1..1024")) }; }
        if let Some(n) = o.get("name").and_then(|x| x.as_str()) { return Ok(format!("n{}", n.trim())); }
        if let Some(i) = o.get("id").and_then(|x| x.as_i64()) { return encode(&json!(i)); }
        return Err("an object value takes kind, name, mechanical or id".into());
    }
    let Some(s) = v.as_str().map(str::trim).filter(|s| !s.is_empty()) else { return Err("a layer is a type, a name or a number".into()) };
    if s.contains(';') || s.contains('>') || s.contains('|') { return Err(format!("{s}: a layer name cannot hold ; > or |")); }
    if let Some(k) = kind_of(s) { return Ok(format!("k{k}")); }
    if let Some(i) = named_id(s) { return Ok(format!("i{i}")); }
    let low = s.to_ascii_lowercase();
    if let Some(rest) = low.strip_prefix("mechanical") {
        if let Ok(n) = rest.trim().parse::<i64>() {
            return if (1..=1024).contains(&n) { Ok(format!("m{n}")) } else { Err(format!("Mechanical {n} is out of 1..1024")) };
        }
    }
    Ok(format!("n{s}"))
}

/// Where an entry came from.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Source { Call, Library, User }

impl Source {
    pub fn word(self) -> &'static str { match self { Source::Call => "call", Source::Library => "library", Source::User => "user" } }
}

/// The map in effect: each key's given value, its agent code and its source; the template; and what was refused.
#[derive(Clone, Debug, Default)]
pub struct Effective {
    pub entries: Vec<(String, Value, String, Source)>,
    pub template: Option<(String, String, Source)>,
    pub errors: Vec<String>,
}

/// A map document as stored or passed: `{layerMap: {key: value}, template: {libraryPath, footprint}}`, or the bare
/// `{key: value}` map.
fn split(doc: &Value) -> (Map<String, Value>, Option<(String, String)>) {
    let map = doc.get("layerMap").and_then(|m| m.as_object()).cloned()
        .unwrap_or_else(|| doc.as_object().cloned().unwrap_or_default().into_iter().filter(|(k, _)| KEYS.iter().any(|(n, _, _)| n == k)).collect());
    let t = doc.get("template").and_then(|t| Some((t.get("libraryPath")?.as_str()?.to_string(), t.get("footprint")?.as_str()?.to_string())));
    (map, t)
}

/// Merges the call's, the library's and the user's maps, key by key, the call first.
pub fn merge(call: Option<&Value>, library: Option<&Value>, user: Option<&Value>) -> Effective {
    let mut e = Effective::default();
    for (doc, src) in [(call, Source::Call), (library, Source::Library), (user, Source::User)] {
        let Some(doc) = doc else { continue };
        let (map, t) = split(doc);
        for (k, v) in map {
            if !KEYS.iter().any(|(n, _, _)| *n == k) { e.errors.push(format!("{k} ({}): not a layer key; the keys are {}", src.word(), KEYS.iter().map(|k| k.0).collect::<Vec<_>>().join(", "))); continue; }
            if e.entries.iter().any(|x| x.0 == k) { continue; }
            match encode(&v) {
                Ok(c) => e.entries.push((k, v, c, src)),
                Err(m) => e.errors.push(format!("{k} ({}): {m}", src.word())),
            }
        }
        if e.template.is_none() { if let Some((l, f)) = t { e.template = Some((l, f, src)); } }
    }
    e
}

/// The agent's `lmap` parameter: `;key>code;key>code;`, only the keys that were set (an unset key keeps the
/// built-in layer, and its naming, exactly as before).
pub fn agent_param(e: &Effective) -> String {
    if e.entries.is_empty() { return String::new(); }
    format!(";{};", e.entries.iter().map(|(k, _, c, _)| format!("{k}>{c}")).collect::<Vec<_>>().join(";"))
}

/// The map a reply reports: for every key, the layer asked for (or the built-in one) and where it came from, merged
/// with what the agent resolved (`[[key, id, name, kind]]`).
pub fn report(e: &Effective, resolved: &Value) -> Value {
    let mut out = Map::new();
    for (k, _, builtin) in KEYS {
        let entry = e.entries.iter().find(|x| x.0 == *k);
        let mut v = match entry {
            Some((_, given, _, src)) => json!({"asked": given, "source": src.word()}),
            None => json!({"asked": builtin, "source": "built-in"}),
        };
        if let Some(r) = resolved.as_array().and_then(|a| a.iter().find(|r| r[0] == *k)) {
            v["layer"] = r[1].clone();
            v["layerId"] = r[2].clone();
            if let Some(kn) = r[3].as_i64().and_then(crate::fplayers::kind_name) { v["kind"] = json!(kn); }
        }
        if !DRAWN.contains(k) { v["used"] = json!(false); }
        out.insert(k.to_string(), v);
    }
    let mut r = json!({"keys": out});
    if let Some((l, f, s)) = &e.template { r["template"] = json!({"libraryPath": l, "footprint": f, "source": s.word()}); }
    if !e.errors.is_empty() { r["refused"] = json!(e.errors); }
    r
}

/// The map a template footprint suggests, from its layers as altium_read_footprint gives them (`layerDetails`):
/// each typed layer it uses becomes the key of that kind, by type, so the map works in any library. Silkscreen stays
/// on Top Overlay.
pub fn propose(details: &[Value]) -> (Map<String, Value>, Vec<String>) {
    let by_kind = [("AssemblyTop", "fab"), ("CourtyardTop", "courtyard"), ("ComponentOutlineTop", "outline"), ("ComponentCenterTop", "centroid"),
                   ("DesignatorTop", "designator"), ("DimensionsTop", "dimensions"), ("3DBodyTop", "body3d")];
    let mut map = Map::new();
    let mut notes = Vec::new();
    for (kind, key) in by_kind {
        if details.iter().any(|d| d["kind"] == kind) { map.insert(key.into(), json!(kind)); }
    }
    if details.iter().any(|d| d["id"] == 33) { map.insert("overlay".into(), json!("Top Overlay")); }
    for d in details {
        if d.get("kind").is_none() && d["id"].as_i64().is_some_and(|i| is_mech(i)) {
            notes.push(format!("{} has no layer type: map a key to it by name if the template means it", d["altiumName"].as_str().unwrap_or("?")));
        }
    }
    if !map.contains_key("body3d") { notes.push("the template has no 3D body layer in use: body3d keeps Mechanical 1 unless you set it".into()); }
    (map, notes)
}

/// The entries of Altium's Template Files preference (`PCBLIB=dxp://...ItemGUID=...;...`): (document kind, value,
/// the item GUID when it names a Workspace item).
pub fn template_entries(pref: &str) -> Vec<(String, String, Option<String>)> {
    pref.split(['\n', '\r', '|']).flat_map(|chunk| chunk.split(';').map(str::to_string).collect::<Vec<_>>()).filter_map(|e| {
        let e = e.trim();
        let (k, v) = e.split_once('=')?;
        if k.trim().is_empty() || v.trim().is_empty() { return None; }
        let guid = v.split(['?', '&']).find_map(|p| p.strip_prefix("ItemGUID=").map(str::to_string));
        Some((k.trim().to_string(), v.trim().to_string(), guid))
    }).collect()
}

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

    #[test]
    fn values_name_a_layer_by_type_name_or_number() {
        assert_eq!(encode(&json!("CourtyardTop")).unwrap(), "k11");
        assert_eq!(encode(&json!("courtyard top")).unwrap(), "k11");
        assert_eq!(encode(&json!("3DBodyTop")).unwrap(), "k26");
        assert_eq!(encode(&json!("Top Courtyard")).unwrap(), "nTop Courtyard", "a layer's name, not its type");
        assert_eq!(encode(&json!("Mechanical 15")).unwrap(), "m15");
        assert_eq!(encode(&json!("Mechanical13")).unwrap(), "m13");
        assert_eq!(encode(&json!("Top Overlay")).unwrap(), "i33");
        assert_eq!(encode(&json!(69)).unwrap(), "i69");
        assert_eq!(encode(&json!({"kind": "AssemblyTop"})).unwrap(), "k1");
        assert_eq!(encode(&json!({"mechanical": 57})).unwrap(), "m57");
        assert!(encode(&json!({"kind": "Top Assembly"})).is_err(), "kind must be a type");
        assert!(encode(&json!("Mechanical 2000")).is_err());
        assert!(encode(&json!("a;b")).is_err());
    }

    #[test]
    fn the_call_wins_then_the_library_then_the_user() {
        let e = merge(Some(&json!({"courtyard": "CourtyardTop"})), Some(&json!({"layerMap": {"courtyard": "Mechanical 15", "fab": "AssemblyTop"},
            "template": {"libraryPath": "C:/org/Templates.PcbLib", "footprint": "Default Footprint"}})), Some(&json!({"fab": "Mechanical 13", "body3d": "3DBodyTop"})));
        let get = |k: &str| e.entries.iter().find(|x| x.0 == k).map(|x| (x.2.clone(), x.3));
        assert_eq!(get("courtyard"), Some(("k11".into(), Source::Call)));
        assert_eq!(get("fab"), Some(("k1".into(), Source::Library)));
        assert_eq!(get("body3d"), Some(("k26".into(), Source::User)));
        assert_eq!(e.template.as_ref().map(|t| t.2), Some(Source::Library));
        assert_eq!(agent_param(&e), ";courtyard>k11;fab>k1;body3d>k26;");
    }

    #[test]
    fn no_map_sends_nothing_so_footprints_stay_as_they_were() {
        let e = merge(None, None, None);
        assert_eq!(agent_param(&e), "");
        let r = report(&e, &json!([]));
        assert_eq!(r["keys"]["fab"]["asked"], "Mechanical 13");
        assert_eq!(r["keys"]["fab"]["source"], "built-in");
        assert_eq!(r["keys"]["outline"]["used"], false);
    }

    #[test]
    fn unknown_keys_and_bad_values_are_refused_by_name() {
        let e = merge(Some(&json!({"layerMap": {"silk": "Top Overlay", "fab": "Mechanical 9999"}})), None, None);
        assert!(e.entries.is_empty());
        assert_eq!(e.errors.len(), 2);
        assert!(e.errors.iter().any(|m| m.contains("silk")) && e.errors.iter().any(|m| m.contains("9999")), "{:?}", e.errors);
    }

    #[test]
    fn a_template_proposes_its_typed_layers_by_type() {
        let d = vec![json!({"id": 33, "name": "F.SilkS"}), json!({"id": 67108917, "kind": "AssemblyTop", "altiumName": "Top Assembly"}),
                     json!({"id": 67108925, "kind": "CourtyardTop"}), json!({"id": 67108921, "kind": "ComponentCenterTop"}),
                     json!({"id": 67108927, "kind": "DesignatorTop"}), json!({"id": 69, "altiumName": "Mechanical 13"})];
        let (m, notes) = propose(&d);
        assert_eq!(m["fab"], "AssemblyTop");
        assert_eq!(m["courtyard"], "CourtyardTop");
        assert_eq!(m["centroid"], "ComponentCenterTop");
        assert_eq!(m["designator"], "DesignatorTop");
        assert_eq!(m["overlay"], "Top Overlay");
        assert!(notes.iter().any(|n| n.contains("Mechanical 13")));
    }

    #[test]
    fn pairs_follow_altiums_kinds() {
        assert_eq!(pair_of(11), Some((5, 11, 12)));
        assert_eq!(pair_of(27), Some((11, 26, 27)));
        assert_eq!(pair_of(15), None, "an unpaired kind cannot be made from a script");
    }

    #[test]
    fn the_template_preference_gives_each_kind_and_item() {
        let p = "PCBLIB=dxp://VaultExplorer:Navigate_URL?ItemGUID=ABC-123&RevisionMode=Last&FileExt=PcbLib;SCHLIB=C:\\t\\a.SchLib";
        let e = template_entries(p);
        assert_eq!(e[0].0, "PCBLIB");
        assert_eq!(e[0].2.as_deref(), Some("ABC-123"));
        assert_eq!(e[1].2, None);
    }
}