main
Colby Knox 0.2.65 source (not yet released, needs signing): coffeenmusic/altium-mcp parity (selection, move by offset, check_orien… 0daea09
//! Read-only inspection: an OutJob's containers and settings from its file, symbol and footprint search across
//! libraries, and the parameters a project's parts carry.
use crate::support::{self, s};
use crate::{agent, bom};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;

/// An OutJob file as sections of key=value lines.
fn ini(text: &str) -> Vec<(String, Vec<(String, String)>)> {
    let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new();
    for line in text.lines() {
        let l = line.trim();
        if l.starts_with('[') && l.ends_with(']') { out.push((l[1..l.len() - 1].to_string(), vec![])); continue; }
        if let (Some((k, v)), Some(sec)) = (l.split_once('='), out.last_mut()) { sec.1.push((k.to_string(), v.to_string())); }
    }
    out
}

/// The containers (output media), outputs and their settings of an OutJob file. Pure, for the tests.
pub fn outjob_summary(text: &str) -> Value {
    let mut groups = Vec::new();
    for (name, kv) in ini(text) {
        if !name.starts_with("OutputGroup") { continue; }
        let get = |k: &str| kv.iter().find(|(a, _)| a == k).map(|(_, b)| b.clone());
        let mut media: BTreeMap<usize, Value> = BTreeMap::new();
        let mut outputs: BTreeMap<usize, Value> = BTreeMap::new();
        for (k, v) in &kv {
            if let Some(n) = k.strip_prefix("OutputMedium").and_then(|r| r.parse::<usize>().ok()) {
                media.insert(n, json!({"index": n, "name": v, "type": get(&format!("OutputMedium{n}_Type")).unwrap_or_default()}));
            }
            if let Some(n) = k.strip_prefix("OutputType").and_then(|r| r.parse::<usize>().ok()) {
                let in_media: Vec<usize> = kv.iter().filter_map(|(a, b)| a.strip_prefix(&format!("OutputEnabled{n}_OutputMedium")).and_then(|m| m.parse::<usize>().ok()).filter(|_| b != "0")).collect();
                let config: Vec<String> = kv.iter().filter(|(a, _)| a.starts_with(&format!("Configuration{n}_Item"))).map(|(_, b)| b.clone()).collect();
                // the settings an engineer checks first, out of the configuration record
                let field = |key: &str| config.iter().flat_map(|c| c.split('|')).find_map(|f| f.strip_prefix(&format!("{key}="))).map(str::to_string);
                let mut settings = serde_json::Map::new();
                for key in ["GerberUnit", "NumberOfDecimals", "Units", "GenerateCSVFormat", "BatchMode", "OriginPosition", "PlotPositivePlaneLayers", "Record"] {
                    if let Some(v) = field(key) { settings.insert(key.to_string(), json!(v)); }
                }
                if let Some(ps) = field("Plot.Set") { settings.insert("plottedLayers".into(), json!(ps.split(',').filter(|x| x.ends_with("~1")).count())); }
                outputs.insert(n, json!({"index": n, "type": v, "name": get(&format!("OutputName{n}")).unwrap_or_default(),
                    "document": get(&format!("OutputDocumentPath{n}")).unwrap_or_default(), "enabled": get(&format!("OutputEnabled{n}")).as_deref() != Some("0"),
                    "inMedia": in_media, "settings": settings}));
            }
        }
        let media: Vec<Value> = media.into_values().map(|mut m| {
            let i = m["index"].as_u64().unwrap_or(0) as usize;
            m["outputs"] = json!(outputs.values().filter(|o| o["inMedia"].as_array().map(|a| a.iter().any(|x| x.as_u64() == Some(i as u64))).unwrap_or(false)).map(|o| o["name"].clone()).collect::<Vec<_>>());
            m
        }).collect();
        groups.push(json!({"group": name, "name": get("Name").unwrap_or_default(), "variant": get("VariantName").unwrap_or_default(),
            "containers": media, "outputs": outputs.into_values().collect::<Vec<_>>()}));
    }
    json!(groups)
}

/// altium_outjob_info {outjobPath}: an OutJob's containers, outputs and their key settings, read from the file
/// (Altium need not be running; unsaved edits in an open OutJob are not seen).
pub fn outjob_info(args: &Value) -> Value {
    let Some(p) = s(args, "outjobPath").or_else(|| s(args, "filePath")) else { return json!({"success": false, "errorCode": "bad_args", "error": "outjobPath (.OutJob) is required"}) };
    let text = match std::fs::read(&p) { Ok(b) => String::from_utf8_lossy(&b).to_string(), Err(e) => return json!({"success": false, "errorCode": "not_found", "error": format!("{p}: {e}")}) };
    let groups = outjob_summary(&text);
    json!({"success": true, "outjobPath": p, "groups": groups,
        "_hint": "Run one container with altium_run_outjob {outjobPath, projectPath, medium:'<container name>'}. This reads the saved file: save an OutJob open in Altium first."})
}

/// altium_find_symbol {query, libraries?, kind?}: symbols (or footprints, kind:'footprint') whose name contains the
/// query, across the given libraries or every installed .SchLib/.PcbLib.
pub fn find_symbol(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let Some(q) = s(args, "query").map(|q| q.to_lowercase()).filter(|q| !q.is_empty()) else { return json!({"success": false, "errorCode": "bad_args", "error": "query is required (part of the name)"}) };
    let footprints = s(args, "kind").map(|k| k.starts_with("foot")).unwrap_or(false);
    let ext = if footprints { ".pcblib" } else { ".schlib" };
    let libs: Vec<String> = match args.get("libraries").and_then(|v| v.as_array()) {
        Some(a) => a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect(),
        None => {
            let r = crate::library::list_installed_libraries(&json!({}));
            r["libraries"].as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(|p| p.replace('/', "\\"))).collect()
        }
    };
    let mut matches = Vec::new();
    let mut skipped = Vec::new();
    for lib in &libs {
        if !lib.to_lowercase().ends_with(ext) { skipped.push(lib.clone()); continue; }
        if support::agent_open(lib, 60).get("success").and_then(|b| b.as_bool()) != Some(true) { skipped.push(lib.clone()); continue; }
        let r = agent::call("lib_list", &[("kind", (if footprints { "pcb" } else { "sch" }).to_string()), ("limit", "5000".into())], None, Duration::from_secs(120));
        let names = r.get("data").and_then(|d| d.get("names")).and_then(|n| n.as_array()).cloned().unwrap_or_default();
        for n in names.iter().filter_map(|n| n.as_str()) {
            if n.to_lowercase().contains(&q) {
                matches.push(json!({"name": n, "library": lib, "exact": n.to_lowercase() == q}));
            }
        }
    }
    matches.sort_by_key(|m| (m["exact"] != json!(true), m["name"].as_str().map(|x| x.len()).unwrap_or(0)));
    let best = matches.first().cloned();
    json!({"success": true, "query": q, "matches": matches, "best": best, "searched": libs.len() - skipped.len(), "skipped": skipped,
        "_hint": if best.is_some() { if footprints { "altium_show_footprint {libraryPath, footprintName} shows the best match; altium_footprint_primitives / altium_read_symbol read geometry." } else { "altium_show_symbol {libraryPath, symbolName} shows the best match; altium_read_symbol / altium_symbol_prims read it as a style reference; altium_sch_place_part places it." } }
                 else { "No match. Integrated libraries (.IntLib) are not searched (altium_extract_intlib gives their sources); the Altium 365 workspace is searched with altium_workspace_search." }})
}

/// altium_part_parameters {projectPath, name?}: every parameter name the project's parts carry (with how many parts
/// carry it), or with name, that parameter's value on every part.
pub fn part_parameters(args: &Value) -> Value {
    if let Some(g) = support::need_licensed() { return g; }
    let Some(prj) = s(args, "projectPath") else { return json!({"success": false, "errorCode": "bad_args", "error": "projectPath (.PrjPcb) is required"}) };
    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();
    let project = bom::parse_project(&text, Path::new(&prj).parent().unwrap_or(Path::new(".")));
    if project.sheets.is_empty() { return json!({"success": false, "errorCode": "no_sheets", "error": "the project lists no sheet"}); }
    let want = s(args, "name");
    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
    let mut values = Vec::new();
    for sheet in &project.sheets {
        if let Some(e) = support::must_open(sheet, 60) { return e; }
        let mut p: Vec<(&str, String)> = vec![("pins", "0".into()), ("params", "1".into()), ("limit", "5000".into())];
        match &want { Some(n) => p.push(("paramFilter", format!("|{}|", n.to_ascii_uppercase()))), None => p.push(("paramNamesOnly", "1".into())) }
        let r = agent::call("schematic_data", &p, None, Duration::from_secs(180));
        for c in r.get("data").and_then(|d| d.get("components")).and_then(|c| c.as_array()).cloned().unwrap_or_default() {
            let des = c["designator"].as_str().unwrap_or("").to_string();
            for prm in c["params"].as_array().cloned().unwrap_or_default() {
                let n = prm["name"].as_str().unwrap_or("").to_string();
                if n.is_empty() { continue; }
                match &want {
                    Some(w) if n.eq_ignore_ascii_case(w) => values.push(json!({"designator": des, "value": prm["value"], "sheet": sheet})),
                    Some(_) => {}
                    None => *counts.entry(n).or_insert(0) += 1,
                }
            }
        }
    }
    match want {
        Some(n) => json!({"success": true, "name": n, "count": values.len(), "values": values, "_hint": "Change values with altium_sheet_params {projectPath, designators, params}."}),
        None => json!({"success": true, "names": counts.iter().map(|(k, v)| json!({"name": k, "parts": v})).collect::<Vec<_>>(),
            "_hint": "Pass name to get that parameter's value on every part. altium_bom groups parts by MPN with the purchasing parameters."}),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn outjob_containers_and_outputs() {
        let t = "[OutputJobFile]\r\nVersion=1.0\r\n\r\n[OutputGroup1]\r\nName=Fab\r\nVariantName=[No Variations]\r\nOutputMedium1=Gerbers\r\nOutputMedium1_Type=GeneratedFiles\r\nOutputMedium2=PDF\r\nOutputMedium2_Type=Publish\r\nOutputType1=Gerber\r\nOutputName1=Gerber Files\r\nOutputDocumentPath1=b.PcbDoc\r\nOutputEnabled1=1\r\nOutputEnabled1_OutputMedium1=1\r\nConfiguration1_Item1=GerberUnit=Imperial|NumberOfDecimals=5|Plot.Set=SerializeLayerHash.Version~2,ClassName~TLayerToBoolean,1~1,2~1|Record=GerberView\r\nOutputType2=Schematic Print\r\nOutputName2=Sheets\r\nOutputEnabled2=1\r\nOutputEnabled2_OutputMedium2=1\r\n";
        let g = outjob_summary(t);
        assert_eq!(g[0]["containers"][0]["name"], json!("Gerbers"));
        assert_eq!(g[0]["containers"][0]["outputs"], json!(["Gerber Files"]));
        assert_eq!(g[0]["containers"][1]["outputs"], json!(["Sheets"]));
        assert_eq!(g[0]["outputs"][0]["settings"]["GerberUnit"], json!("Imperial"));
        assert_eq!(g[0]["outputs"][0]["settings"]["plottedLayers"], json!(2));
    }
}