main
Colby Knox 0.2.79 source (unreleased): the board-file writers from the standard's engine 0.2.0 (standard 0.5.0); export_dxf draws… d915247
//! Board files Altium has no headless exporter for (DXF per layer, GenCAD), from the EDA Bridge Standard's shared
//! writers (adom-eda-checks `writers`, standard 0.5.0): the engine returns the file text from the board model, this
//! bridge reads the board (and its poured copper) and writes the files.

use serde_json::{json, Value};

/// The board model of the current (or named) board, or the refusal to answer with.
fn board(args: &Value) -> Result<(Value, String), Value> {
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return Err(e); } }
    let st = crate::routing::routing_state(&json!({}));
    match st["file"].as_str().filter(|f| !f.is_empty()).map(str::to_string) { Some(f) => Ok((st, f)), None => Err(st) }
}

fn stem(board: &str) -> String { std::path::Path::new(board).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into()) }

/// altium_export_dxf {filePath?, layers, outputDir?, units?, contours?, titleBlock?, excludeDesignators?, excludeValues?, useDrillOrigin?}
pub fn export_dxf(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    if args.get("layers").and_then(|v| v.as_array()).map(|a| a.is_empty()).unwrap_or(true) {
        return json!({"success": false, "errorCode": "bad_args", "error": "layers is required: [\"Edge.Cuts\", \"F.Cu\", ...]", "_hint": "Edge.Cuts with contours:true is the enclosure drawing."});
    }
    let (st, file) = match board(args) { Ok(x) => x, Err(e) => return e };
    // the copper actually poured, so a pour is drawn as filled and not as the outline it was drawn with
    let pours = crate::routing::pour_state(&json!({}));
    let r = adom_eda_checks::writers::dxf_layers(&json!({"board": st, "pours": pours, "args": args}));
    if r.get("files").is_none() { return r; }
    let dir = crate::support::s(args, "outputDir").map(std::path::PathBuf::from)
        .unwrap_or_else(|| std::path::Path::new(&file).parent().unwrap_or(std::path::Path::new(".")).join("DXF"));
    if let Err(e) = std::fs::create_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    let mut files = Vec::new();
    for f in r["files"].as_array().cloned().unwrap_or_default() {
        let path = dir.join(format!("{}-{}", stem(&file), f["name"].as_str().unwrap_or("layer.dxf")));
        if let Err(e) = std::fs::write(&path, f["text"].as_str().unwrap_or("")) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }
        files.push(json!({"layer": f["layer"], "path": path.to_string_lossy(), "entities": f["entities"]}));
    }
    // text is not drawn, so designators and values are left out whatever the flags say
    let not_applied: Vec<&str> = ["titleBlock", "useDrillOrigin"].into_iter().filter(|k| args.get(*k).and_then(|v| v.as_bool()) == Some(true)).collect();
    json!({"success": r["success"], "files": files, "unknownLayers": r["unknownLayers"], "poursAsDrawn": r["poursAsDrawn"], "outputDir": dir.to_string_lossy(),
        "units": r["units"], "writtenFrom": r["writtenFrom"], "optionsNotApplied": not_applied, "windowEtiquette": "background",
        "_hint": "Written from the board model by the standard's shared writer: the outline, tracks, arcs, pads, vias and the poured copper on each layer (texts are not drawn). Edge.Cuts with contours:true is one closed polyline, what CAM and laser tools want. Layers: Edge.Cuts, F.Cu, In<n>.Cu, B.Cu, F.SilkS, B.SilkS, F.Mask, B.Mask, F.Paste, B.Paste, Mechanical<n>, or Altium's L<id>."})
}

/// altium_export_gencad {filePath?, outputDir?, uniquePins?, flipBottomPads?, useDrillOrigin?}
pub fn export_gencad(args: &Value) -> Value {
    if let Some(g) = crate::support::need_licensed() { return g; }
    let (st, file) = match board(args) { Ok(x) => x, Err(e) => return e };
    let b = |k: &str| args.get(k).and_then(|v| v.as_bool()) == Some(true);
    let r = adom_eda_checks::writers::gencad(&json!({"board": st, "args": {"title": stem(&file), "uniquePins": b("uniquePins")}}));
    let Some(text) = r["text"].as_str() else { return r };
    let dir = crate::support::s(args, "outputDir").map(std::path::PathBuf::from)
        .unwrap_or_else(|| std::path::Path::new(&file).parent().unwrap_or(std::path::Path::new(".")).to_path_buf());
    if let Err(e) = std::fs::create_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }
    let path = dir.join(format!("{}.cad", stem(&file)));
    if let Err(e) = std::fs::write(&path, text) { return json!({"success": false, "errorCode": "write_failed", "error": format!("{}: {e}", path.display())}); }
    // a bottom part is written MIRRORX FLIP as KiCad writes it; separate flipped padstacks are not made
    let not_applied: Vec<&str> = ["useDrillOrigin", "flipBottomPads"].into_iter().filter(|k| b(k)).collect();
    json!({"success": true, "file": path.to_string_lossy(), "counts": r["counts"], "units": r["units"], "writtenFrom": r["writtenFrom"], "optionsNotApplied": not_applied, "windowEtiquette": "background",
        "_hint": "GenCAD 1.4 written from the board model by the standard's shared writer (Altium has no GenCAD exporter): outline, pads, padstacks, a shape per footprint, components, signals and routes, in inches. Ask the fixture or assembly house which options it needs; uniquePins is the common one."})
}