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
//! import_svg: SVG artwork (a logo, a label) as filled regions on a board layer, through the EDA Bridge Standard's shared
//! writer (adom-eda-checks `writers::svg_to_regions`, standard 0.5.0), applied here as one undo step of edit_board.

use serde_json::{json, Value};

/// altium_import_svg {filePath?, expectedRevision?, svgPath | svg, at, widthMm?, scale?, anchor?, layer?, mirror?, net?, toleranceMm?, dryRun?}
pub fn import_svg(args: &Value) -> Value {
    let bad = |m: &str| json!({"success": false, "errorCode": "bad_args", "error": m});
    let text = match (crate::support::s(args, "svg"), crate::support::s(args, "svgPath")) {
        (Some(t), _) => t,
        (None, Some(p)) => match std::fs::read_to_string(&p) { Ok(t) => t, Err(e) => return json!({"success": false, "errorCode": "file_not_found", "error": format!("{p}: {e}")}) },
        _ => return bad("svgPath or svg is required"),
    };
    let Some(at) = args.get("at").and_then(|v| v.as_array()).filter(|a| a.len() == 2).and_then(|a| Some((a[0].as_f64()?, a[1].as_f64()?))) else { return bad("at [x, y] in mm is required") };
    let layer = crate::support::s(args, "layer").unwrap_or_else(|| "F.SilkS".into());
    // the standard's shared writer (adom-eda-checks `writers`): the SVG's filled shapes as regions in board mm, each one
    // contour with its holes slit in (Altium printed a separate hole contour filled)
    let mut eargs = args.clone();
    eargs["at"] = json!([at.0, at.1]);
    eargs["layer"] = json!(layer);
    let er = adom_eda_checks::writers::svg_to_regions(&json!({"svg": text, "args": eargs}));
    if er.get("success").and_then(|v| v.as_bool()) != Some(true) { return er; }
    let shapes: Vec<Vec<(f64, f64)>> = er["regions"].as_array().cloned().unwrap_or_default().iter()
        .map(|r| r["points"].as_array().cloned().unwrap_or_default().iter().map(|p| (p[0].as_f64().unwrap_or(0.0), p[1].as_f64().unwrap_or(0.0))).collect()).collect();
    let plan = json!({"polygons": er["polygons"], "holes": er["holes"], "points": er["points"], "sizeMm": er["sizeMm"], "layer": layer, "mirror": er["mirror"], "skipped": er["skipped"]});
    if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {
        let mut p = plan; p["success"] = json!(true); p["dryRun"] = json!(true);
        p["_hint"] = json!("Nothing changed. Call again without dryRun to place it.");
        return p;
    }
    if let Some(g) = crate::support::need_licensed() { return g; }
    if let Some(p) = crate::support::s(args, "filePath") { if let Some(e) = crate::support::must_open(&p, 60) { return e; } }
    let before = match crate::routing::guarded(args) { Ok(s) => s, Err(e) => return e };
    let lid = match layer.as_str() {
        "F.SilkS" => Some(33), "B.SilkS" => Some(34), "F.Paste" => Some(35), "B.Paste" => Some(36), "F.Mask" => Some(37), "B.Mask" => Some(38),
        l => l.strip_prefix('L').and_then(|n| n.parse::<i64>().ok()).or_else(|| crate::routing::layer_id(&json!(l))),
    };
    let Some(lid) = lid else {
        return bad(&format!("layer {layer}: F.SilkS, B.SilkS, F.Mask, B.Mask, a copper layer (F.Cu, In1.Cu, B.Cu) or Altium's L<id>"));
    };
    let net = crate::support::s(args, "net").unwrap_or_default();
    let per = crate::routing::PER_MM;
    let ops: Vec<String> = shapes.iter().map(|s| format!("Y|{lid}|{net}|{}", s.iter().map(|p| format!("{},{}", (p.0 * per).round() as i64, (p.1 * per).round() as i64)).collect::<Vec<_>>().join(";"))).collect();
    let mut r = crate::routing::apply(&ops, &before, "import_svg");
    let ids: Vec<Value> = r["results"].as_array().map(|a| a.iter().filter_map(|x| x.as_str()).filter_map(|x| x.strip_prefix("ok:")).map(|k| json!(k)).collect()).unwrap_or_default();
    for (k, v) in plan.as_object().unwrap() { r[k] = v.clone(); }
    r["ids"] = json!(ids);
    if !net.is_empty() || lid <= 32 { r["_hint"] = json!("On copper the artwork is graphics on the net given: run altium_run_drc."); }
    r
}