main
Colby Knox 0.2.116: export_3d runs Altium's Parasolid/VRML output through an OutJob, headless; File > Export only as a fallback 4b61622
//! The board's 3D outside the parts: import_step places a STEP with the board as free geometry (an enclosure, a
//! bracket) for fit checks, the standard's import_step (EDA Bridge Standard #29). It is a 3D body of the board itself,
//! on a mechanical layer, belonging to no part (add_body puts a model on one footprint instead), and the answer says at
//! once which parts' bodies it now meets.
use serde_json::{json, Value};
use std::time::Duration;

fn f(v: &Value) -> f64 { v.as_f64().unwrap_or(0.0) }
fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }

/// The parts' bodies a box meets: plan overlap more than 0.01 mm both ways and height overlap, on the same side. Pure.
pub fn meets(bx: [f64; 4], z: (f64, f64), side: &str, bodies: &[Value]) -> Vec<Value> {
    let mut out = Vec::new();
    for b in bodies {
        if b["side"].as_str().unwrap_or("top") != side || b["ref"].as_str().unwrap_or("").is_empty() { continue; }
        let (ox, oy) = (bx[2].min(f(&b["x1"])) - bx[0].max(f(&b["x0"])), bx[3].min(f(&b["y1"])) - bx[1].max(f(&b["y0"])));
        let oz = z.1.min(f(&b["z1"])) - z.0.max(f(&b["z0"]));
        if ox > 0.01 && oy > 0.01 && oz > 0.0 {
            out.push(json!({"ref": b["ref"], "overlapMm": [r3(ox), r3(oy), r3(oz)]}));
        }
    }
    out
}

/// altium_import_step {filePath, stepPath, at?: [x, y] mm, rotation?: [rx, ry, rz] degrees, standoffMm?, side?, layer?}
pub fn import_step(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let s = |k: &str| crate::support::s(args, k);
    let Some(board) = s("filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});
    };
    let Some(step) = s("stepPath").or_else(|| s("path")).filter(|p| { let l = p.to_lowercase(); l.ends_with(".step") || l.ends_with(".stp") }) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "stepPath (a .step or .stp file on this machine) is required"});
    };
    let side = s("side").unwrap_or_else(|| "top".into()).to_lowercase();
    if side != "top" && side != "bottom" { return json!({"success": false, "errorCode": "bad_args", "error": "side is top or bottom"}); }
    let mech = args.get("layer").and_then(|v| v.as_i64()).unwrap_or(1);
    if !(1..=16).contains(&mech) { return json!({"success": false, "errorCode": "bad_args", "error": "layer is a mechanical layer number, 1 to 16"}); }
    let num = |v: &Value, i: usize| v.get(i).and_then(|x| x.as_f64()).unwrap_or(0.0);
    let at = args.get("at").cloned().unwrap_or(json!([0, 0]));
    let rot = args.get("rotation").cloned().unwrap_or(json!([0, 0, 0]));
    if let Some(e) = crate::support::must_open(&board, 60) { return e; }
    let p = |v: f64| format!("{v}");
    let r = crate::agent::call("import_step", &[("path", step.clone()), ("x", p(num(&at, 0))), ("y", p(num(&at, 1))),
        ("rx", p(num(&rot, 0))), ("ry", p(num(&rot, 1))), ("rz", p(num(&rot, 2))), ("standoff", p(args.get("standoffMm").and_then(|v| v.as_f64()).unwrap_or(0.0))),
        ("side", side.clone()), ("layer", (56 + mech).to_string())], None, Duration::from_secs(120));
    let d = r.get("data").cloned().unwrap_or(Value::Null);
    if d["ok"] != json!(true) {
        return json!({"success": false, "errorCode": d.get("errorCode").cloned().unwrap_or(json!("import_failed")), "error": d.get("error").cloned().unwrap_or(r.get("error").cloned().unwrap_or(json!("the STEP was not placed"))), "reply": r});
    }
    let mm = |v: &Value| r3(f(v) / crate::routing::PER_MM);
    let bx = [mm(&d["box"][0]), mm(&d["box"][1]), mm(&d["box"][2]), mm(&d["box"][3])];
    let (standoff, height) = (mm(&d["standoff"]), mm(&d["height"]));
    // the parts' bodies it meets, from the same boxes height_check reads
    let bodies = crate::verbs::dispatch("bodies", &json!({}), &[]);
    let rows = bodies["bodies"].as_array().cloned().unwrap_or_default();
    let hits = meets(bx, (standoff, height.max(standoff)), &side, &rows);
    json!({"success": true, "mutated": true, "id": d["id"], "boxMm": bx, "standoffMm": standoff, "heightMm": height, "side": side, "layer": format!("Mechanical {mech}"),
        "meets": hits, "partsChecked": rows.len(),
        "_hint": "The STEP is a 3D body of the board (no part owns it), placed with its own origin at `at`. boxMm is its plan extent in the board model's frame; meets lists the parts' bodies it overlaps in plan and height. The board is not saved: altium_save keeps it, Edit > Undo takes it back. altium_render_board or altium_show_3d_board shows the fit."})
}

/// A format's exporter on Altium's File > Export menu: (label in its Save-as type, extension, index on Develop 26).
/// Measured 2026-10-30: the menu lists Ansoft Neutral .. PDF3D, and `PCB:Export Index=n` opens the n-th (1-based).
pub fn exporter(format: &str) -> Option<(&'static str, &'static str, u32)> {
    match format.to_ascii_lowercase().as_str() {
        "parasolid" | "x_t" | "xt" => Some(("PARASOLID", "x_t", 8)),
        "vrml" | "wrl" => Some(("VRML", "wrl", 16)),
        _ => None,
    }
}

/// An Altium dialog whose title holds `title`, within `secs`.
fn wait_dialog(title: &str, secs: u64) -> Option<i64> {
    let t0 = std::time::Instant::now();
    while t0.elapsed().as_secs() < secs {
        if let Some(h) = crate::dialogs::scan().iter().find(|d| d["title"].as_str().map(|t| t.contains(title)).unwrap_or(false)).and_then(|d| d["hwnd"].as_i64()) { return Some(h); }
        std::thread::sleep(Duration::from_millis(400));
    }
    None
}

/// Open exporter `index` through Altium's process launcher (outside the script engine: a RunProcess inside the agent
/// held it in the exporter's modal dialogs, and the next verb found it deaf, 2026-10-30) and answer its Export File
/// dialog when its Save-as type names `label`; cancel it otherwise. Answers the dialog and the launcher still running.
fn open_exporter(index: u32, label: &str) -> Result<(i64, std::process::Child), String> {
    let exe = crate::lifecycle::x2_exe_pub().ok_or("X2.exe not found")?;
    let mut child = crate::lifecycle::spawn_helper_pub(&exe, &format!("-RPCB:Export(Index={index})"))?;
    let Some(h) = wait_dialog("Export File", 15) else {
        crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(10));
        return Err(format!("exporter {index} opened no Export File dialog"));
    };
    // its Save-as type box names the format ("Export PARASOLID (*.x_t)"): reading the whole dialog's text walked the
    // file list and timed out (2026-10-30)
    let fc = crate::ab::call("desktop_find_controls", json!({"hwnd": h, "contains": "Save as type"}), &[], 15);
    let kind = fc["matches"].as_array().or(fc["output"]["matches"].as_array()).cloned().unwrap_or_default().iter()
        .filter_map(|m| m["value"].as_str().map(str::to_string)).collect::<Vec<_>>().join(" ").to_ascii_uppercase();
    if kind.contains(&label.to_ascii_uppercase()) { return Ok((h, child)); }
    crate::dialogs::press(h, "Cancel");
    crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(20));
    Err(format!("exporter {index} is not {label} ({kind})"))
}

/// altium_export_3d {filePath, format, output? | outputDir?}
pub fn export_3d(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let s = |k: &str| crate::support::s(args, k);
    let Some(board) = s("filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) else {
        return json!({"success": false, "errorCode": "bad_args", "error": "filePath (the .PcbDoc) is required"});
    };
    let format = s("format").unwrap_or_default().to_ascii_lowercase();
    let bpath = std::path::PathBuf::from(board.replace('\\', "/"));
    let stem = bpath.file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| "board".into());
    if format == "step" || format == "stp" {
        // STEP is the standard's export_step; answered here too, so one call covers every 3D format
        let out = s("output").unwrap_or_else(|| bpath.parent().unwrap_or(std::path::Path::new(".")).join(format!("{stem}.step")).to_string_lossy().to_string());
        let mut r = crate::outputs::export_step(&json!({"filePath": board, "output": out}));
        r["format"] = json!("step");
        return r;
    }
    let Some((label, ext, known)) = exporter(&format) else {
        return json!({"success": false, "errorCode": "unsupported", "format": format,
            "error": format!("Altium writes no {format}: its 3D exporters are STEP, Parasolid and VRML (and 3D PDF, which the bridge cannot drive without a window yet)"),
            "formats": ["step", "parasolid", "vrml"], "_hint": "Ask for step, parasolid or vrml; a mesh format (stl, obj, glb, 3mf, ply) can be made from the STEP outside Altium."});
    };
    let out = s("output").unwrap_or_else(|| {
        let dir = s("outputDir").map(std::path::PathBuf::from).unwrap_or_else(|| bpath.parent().unwrap_or(std::path::Path::new(".")).to_path_buf());
        dir.join(format!("{stem}.{ext}")).to_string_lossy().to_string()
    }).replace('/', "\\");
    // headless first: the OutJob output Altium's STEP generator also makes (ExportPARASOLID, ExportVRML). The File >
    // Export entries the menu route opens exist only once that menu has been opened in the session, so in a fresh
    // Altium the menu route opened nothing (#42 follow-up, 2026-12-01)
    if !std::path::Path::new(&board.replace('\\', "/")).is_file() && !std::path::Path::new(&board).is_file() {
        return json!({"success": false, "errorCode": "file_not_found", "error": format!("{board} is not on this machine")});
    }
    let output_type = if label == "PARASOLID" { "ExportPARASOLID" } else { "ExportVRML" };
    let outjob_err = match crate::outputs::export_3d_outjob(&board, output_type, ext, &out, Duration::from_secs(300)) {
        Ok(path) => {
            let bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
            return json!({"success": bytes > 0, "format": format, "path": path.replace('\\', "/"), "bytes": bytes, "lane": "outjob", "windowEtiquette": "background",
                "_hint": "Written by Altium's own Parasolid/VRML output (an OutJob on a throwaway project), with no window raised. A board open with unsaved changes exports its saved state: altium_save first."});
        }
        Err(e) => e,
    };
    if let Err(e) = crate::ab::need_input_approval("answer Altium's export dialogs (the file name and the export options)", 90) { return e; }
    if let Some(e) = crate::support::must_open(&board, 60) { return e; }
    // a file already there would raise Windows' overwrite question: the caller asked for this path. Its folder must
    // exist: Windows' "Path does not exist" box stopped the save when the battery had just emptied it (2026-10-30)
    let _ = std::fs::remove_file(&out);
    if let Some(dir) = std::path::Path::new(&out.replace('\\', "/")).parent() { let _ = std::fs::create_dir_all(dir); }
    // the exporter runs outside the script engine: the agent stops for it and starts again after
    let stop = crate::lifecycle::stop();
    if stop.get("success").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "agent_stop_failed", "stop": stop}); }
    let r = run_exporter(&out, label, known, args);
    let start = crate::lifecycle::start(Duration::from_secs(90));
    let mut r = r;
    r["agentRestarted"] = json!(start.get("success").and_then(|v| v.as_bool()) == Some(true));
    r["lane"] = json!("menu");
    r["outjobFirst"] = outjob_err;
    if r.get("success").and_then(|b| b.as_bool()) == Some(true) { r["format"] = json!(format); }
    r
}

/// The exporter's dialogs, answered, and the file waited for. The agent is stopped while this runs.
fn run_exporter(out: &str, label: &str, known: u32, args: &Value) -> Value {
    // the exporter's place on the menu: the measured one first, then every other one, each checked by its file type
    let mut tried = Vec::new();
    let mut hwnd = None;
    for i in std::iter::once(known).chain((1..=20).filter(|i| *i != known)) {
        match open_exporter(i, label) { Ok((h, c)) => { hwnd = Some((i, h, c)); break; } Err(e) => tried.push(e) }
        // no dialog at all is Altium not ready (no board in front, the agent busy), not a menu in another order
        if tried.last().map(|t| t.contains("opened no")).unwrap_or(false) { break; }
    }
    let Some((index, h, mut child)) = hwnd else { return json!({"success": false, "errorCode": "exporter_not_found", "error": format!("no {label} exporter on Altium's File > Export menu"), "tried": tried}) };
    // the file name, read back: right after the dialog opens a set can be lost, and Save then saved nothing the
    // battery could see (Export Options never came, 2026-10-30)
    let norm = |v: &str| v.replace('\\', "/").to_ascii_lowercase();
    let mut named = false;
    for _ in 0..3 {
        crate::ab::call("desktop_ui_set", json!({"hwnd": h, "automationId": "1001", "text": out}), &[], 15);
        std::thread::sleep(Duration::from_millis(300));
        let back = crate::ab::call("desktop_find_controls", json!({"hwnd": h, "automationId": "1001"}), &[], 15);
        let vals: Vec<String> = back["matches"].as_array().or(back["output"]["matches"].as_array()).cloned().unwrap_or_default().iter().filter_map(|m| m["value"].as_str().map(norm)).collect();
        if vals.iter().any(|v| *v == norm(out)) { named = true; break; }
    }
    let give_up = |child: &mut std::process::Child, why: &str| -> Value {
        // never leave a dialog behind: it blocks every verb after this one
        // a Windows message over the dialog (Path does not exist ...) first, then the dialogs themselves
        for d in crate::dialogs::scan() {
            let btns: Vec<String> = d["buttons"].as_array().cloned().unwrap_or_default().iter().filter_map(|b| b.as_str().map(str::to_string)).collect();
            if d["title"].as_str() == Some("Export File") && btns.iter().any(|b| b == "OK") && !btns.iter().any(|b| b == "Cancel") { if let Some(x) = d["hwnd"].as_i64() { crate::dialogs::press(x, "OK"); } }
        }
        for d in crate::dialogs::scan() {
            let t = d["title"].as_str().unwrap_or("");
            if t.contains("Export File") || t.contains("Export Options") { if let Some(x) = d["hwnd"].as_i64() { crate::dialogs::press(x, "Cancel"); } }
        }
        crate::lifecycle::wait_helper_pub(child, Duration::from_secs(20));
        json!({"success": false, "errorCode": "dialog_failed", "error": why})
    };
    if !named { return give_up(&mut child, "the file name could not be set in Altium's Export File dialog"); }
    let mut options = None;
    for _ in 0..3 {
        crate::dialogs::press(h, "Save");
        options = wait_dialog("Export Options", 10);
        if options.is_some() { break; }
    }
    match options {
        Some(o) => { crate::dialogs::press(o, "OK"); }
        None => return give_up(&mut child, "Altium showed no Export Options after Save"),
    }
    // done when the file is there and has stopped growing
    let t0 = std::time::Instant::now();
    let mut last = 0u64;
    let mut size = 0u64;
    while t0.elapsed().as_secs() < crate::support::timeout_of(args, 300).as_secs() {
        std::thread::sleep(Duration::from_millis(800));
        size = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
        if size > 0 && size == last { break; }
        last = size;
    }
    // the export ends on Altium's Information box ("export complete"): it is ours, so answer it, or the agent cannot
    // start again behind it (agentRestarted false, 2026-10-30); then the launcher ends
    // press and see it go: the box can outlast one press, and left up it refuses every verb behind this one
    if let Some(mut i) = wait_dialog("Information", 15) {
        let t0 = std::time::Instant::now();
        loop {
            crate::dialogs::press(i, "OK");
            std::thread::sleep(Duration::from_millis(700));
            match wait_dialog("Information", 1) { Some(next) if t0.elapsed().as_secs() <= 10 => i = next, _ => break }
        }
    }
    crate::lifecycle::wait_helper_pub(&mut child, Duration::from_secs(60));
    if size == 0 { return json!({"success": false, "errorCode": "not_written", "error": format!("{out} was not written"), "dialogs": crate::dialogs::scan()}); }
    json!({"success": true, "path": out, "bytes": size, "exporter": label, "exporterIndex": index, "windowEtiquette": "background",
        "_hint": "Written by Altium's own exporter (File > Export) with its default options: the whole board, components with their 3D bodies, pad holes. The file is of the board as it is open in Altium."})
}

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

    #[test]
    fn formats_altium_writes() {
        assert_eq!(exporter("Parasolid").map(|e| e.1), Some("x_t"));
        assert_eq!(exporter("wrl").map(|e| e.0), Some("VRML"));
        assert!(exporter("stl").is_none() && exporter("glb").is_none());
    }

    #[test]
    fn a_box_meets_the_bodies_it_overlaps() {
        let b = |r: &str, side: &str, x0: f64, x1: f64, z1: f64| json!({"ref": r, "side": side, "x0": x0, "x1": x1, "y0": 0.0, "y1": 10.0, "z0": 0.0, "z1": z1});
        let rows = vec![b("U1", "top", 0.0, 10.0, 2.0), b("J1", "top", 20.0, 30.0, 12.0), b("C9", "bottom", 0.0, 10.0, 1.0), b("", "top", 0.0, 50.0, 50.0)];
        // a lid 5 mm above the board, over U1 and J1: only the tall connector reaches it
        let hits = meets([0.0, 0.0, 40.0, 10.0], (5.0, 6.0), "top", &rows);
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0]["ref"], "J1");
        assert_eq!(hits[0]["overlapMm"], json!([10.0, 10.0, 1.0]));
        assert!(meets([0.0, 0.0, 40.0, 10.0], (0.0, 1.0), "bottom", &rows).iter().any(|h| h["ref"] == "C9"));
    }
}