← Commit history
CHANGELOG.md+20
@@ -1,5 +1,25 @@ # Changelog +## 0.2.121++- **New verb `altium_add_dimensions`: anchored dimensions on a library footprint** (#43). True Altium linear dimensions whose ends are bound to the footprint's pads (their centres) and its assembly-outline corners, so they follow them when they move: pitch, row span, body size.+  - The reply reads each dimension back after the library is saved, closed and reopened (`validAfterReopen`).+  - With `expect` (the datasheet's value) it says MATCH or MISMATCH.+  - Text, line, arrow and unit settings come from `format` (`units: auto` gives whole mils for a multiple of 5 mil, else mm).+  - The dimensions go on the layer map's `dimensions` layer.+  - How it works: Altium does not anchor a dimension a script makes. So the footprint is copied onto a work board saved as Altium's ASCII PcbDoc, the dimensions are written in bound to those primitives (the route the reporter proved), and the footprint is rebuilt from the work board's own instances.+  - The rebuilt footprint was identical, primitive by primitive, to a twin built without dimensions, with its description, height and 3D body.+  - A later call keeps the earlier dimensions and binds them again.+- **New verb `altium_check_silkscreen`**: the edge-to-edge clearance between a footprint's silkscreen (lines, arcs, texts, fills) and each pad's exposed copper, the pad grown by its mask expansion. It reports the closest pair, every pair under the minimum, and PASS or FAIL.+  - The footprint builders trim silkscreen 0.2 mm from bare copper. With Altium's default 4 mil mask opening, a built SOIC-8 measures 0.143 mm and fails a 0.15 mm rule.+- **`altium_footprint_from_land_pattern {fabOutline: "edges"}`** draws the assembly outline as four lines meeting at the body's corners, with the pin-1 chamfer as its own line, so dimensions can anchor to the corners. The reply gives the corners.+- The agent lint now checks every name in a declaration against the Pascal keywords (a variable named `AS` stopped the agent compiling during this work).+- Tested on Altium Designer 26.11.1 and on Develop:+  - a SOIC-8 with and without an organisation layer map (fab on Top Assembly, dimensions on Top Dimensions);+  - dimensions from pad 1 to 8 (5.40 mm), 1 to 2 (50 mil) and corner to corner (3.90 and 4.90 mm), all valid after reopen and MATCH;+  - pad 8 moved 0.5 mm: the row span read 5.90 mm;+  - two calls on one footprint: all four dimensions bound.+ ## 0.2.120  - **Repairing a library with 1024 mechanical layers** (#44):
README.md+6−4
@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files),   schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -285 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+287 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free desktop app, through Adom Bridge. You bring your own AI subscription and your own Altium licence.  ::youtube{id="dFecpcIzdSE" title="An AI designs a 12 V to 5 V buck converter in Altium Designer"}@@ -29,7 +29,7 @@ and the verb prefix `altium_`.  ## What it can do -Tested on Altium Designer 26.11.1 and Altium Designer Develop. 285 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 287 verbs; each row names the ones behind it (prefix `altium_`).  | Area | What the AI can do | Verbs |@@ -70,7 +70,7 @@ This bridge is the reference for the [EDA Bridge Standard](https://wiki.adom.inc  Altium Designer is the user's own **host app**. The bridge finds an installed Altium (`%ProgramFiles%\Altium\AD*\X2.EXE`, Designer or Develop), starts it in the background, runs a small-**DelphiScript agent** inside it, and gives the AI 285 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 287 `altium_*` verbs.  - **Page and docs:** https://wiki.adom.inc/adom/altium-bridge - **Bridge SDK:** https://wiki.adom.inc/adom/adom-bridge-sdk@@ -170,7 +170,7 @@ way to read it). A stopped engine is restarted with `altium_agent_recover`.  <!-- verbs:start (tools/readme_verbs.py writes this list) --> -All 285 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 287 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -457,6 +457,8 @@ All 285 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_set_models`: Replace every footprint model on a SchLib component with ONE PCBLIB model (set_params footprint and add_models APPEND, which is how a symbol ends up with two). - `altium_add_sim_model`: Put a SPICE model (.MODEL or .SUBCKT from a .mdl/.lib/.ckt file) on a SchLib symbol, as Altium's Sim Model dialog does, so the placed part simulates in Altium and the model goes into an IntLib. - `altium_sim_copy`: Make a simulation copy of a design's sheets and put sources and loads on it, so a schematic drawn for the board (no stimulus, no load) simulates in Altium while the design stays untouched: voltage and current sources (DC, AC, sine, pulse, piecewise linear) and R, C, L loads, each joined to its nets, and Altium's generic model on every R, C and L that has none.+- `altium_check_silkscreen`: Check a library footprint's silkscreen against its pads: the edge-to-edge clearance between every overlay line, arc, text and fill and each pad's exposed copper (the pad grown by its solder mask expansion), with the closest pair and PASS or FAIL against a minimum.+- `altium_add_dimensions`: Put anchored linear dimensions on a library footprint: true Altium dimensions whose ends are bound to the footprint's pads and assembly-outline corners and follow them when they move (pitch, row span, body size, hole positions). - `altium_selftest_script_error`: Regression test for the script-error safety net (from 0.2.23): makes the agent raise a REAL DelphiScript runtime error on purpose and checks that the bridge photographs Altium's Error box, stops the halted script itself and leaves no dialog behind. - `altium_install`: Install Altium Designer on this machine, STAGED, with the rules in the verb (from 0.2.29). 
bridge-rs/src/dimensions.rsadded+366
@@ -0,0 +1,366 @@+//! altium_add_dimensions (#43): anchored linear dimensions on a library footprint, whose ends are bound to the+//! footprint's pads and assembly-outline corners and follow them when they move. Altium will not anchor a dimension a+//! script makes (its reference setters do not stick), so this takes the route the reporter proved (2026-12-02): the+//! footprint is copied onto a work board saved as Altium's ASCII PcbDoc, the dimensions are written into that file+//! pointing at those primitives, Altium opens it and validates them, and the footprint is rebuilt from the work board's+//! own instances (agent dim_work / dim_apply). The library is then saved, closed and reopened, and every dimension's+//! references are read back: `validAfterReopen` is the proof.+use serde_json::{json, Map, Value};++const MIL_PER_MM: f64 = 1.0 / 0.0254;++/// A primitive of the work board a dimension can be bound to.+#[derive(Clone, Debug, PartialEq)]+pub struct Anchor { pub kind: &'static str, pub prim: i64, pub anchor: i64, pub x: f64, pub y: f64 }++/// The work board's pads and tracks (mil, from the board's origin), its dimension count and its layer names.+#[derive(Default, Debug)]+pub struct Work { pub pads: Vec<(i64, String, f64, f64)>, pub tracks: Vec<(i64, String, f64, f64, f64, f64)>, pub dims: usize }++fn fields(l: &str) -> Map<String, Value> {+    let mut m = Map::new();+    for part in l.split('|') {+        if let Some((k, v)) = part.split_once('=') { m.entry(k.to_string()).or_insert(json!(v)); }+    }+    m+}++fn mil(v: Option<&Value>) -> f64 { v.and_then(|v| v.as_str()).map(|s| s.trim().trim_end_matches("mil")).and_then(|s| s.trim().parse().ok()).unwrap_or(0.0) }++/// Reads the work board's ASCII text.+pub fn parse_work(text: &str) -> Work {+    let mut w = Work::default();+    for l in text.lines() {+        if l.starts_with("|RECORD=Pad|") {+            let f = fields(l);+            w.pads.push((f["INDEXFORSAVE"].as_str().and_then(|s| s.parse().ok()).unwrap_or(-1), f.get("NAME").and_then(|v| v.as_str()).unwrap_or("").to_string(), mil(f.get("X")), mil(f.get("Y"))));+        } else if l.starts_with("|RECORD=Track|") {+            let f = fields(l);+            // a layer above Mechanical 16 is in LAYER_V7; LAYER holds the old name, capped at MECHANICAL16+            let layer = f.get("LAYER_V7").or_else(|| f.get("LAYER")).and_then(|v| v.as_str()).unwrap_or("").to_string();+            w.tracks.push((f["INDEXFORSAVE"].as_str().and_then(|s| s.parse().ok()).unwrap_or(-1), layer,+                mil(f.get("X1")), mil(f.get("Y1")), mil(f.get("X2")), mil(f.get("Y2"))));+        } else if l.starts_with("|RECORD=Embedded|") && l.contains("DIMENSIONKIND=") {+            w.dims += 1;+        }+    }+    w+}++/// The bounding corners (TL, TR, BR, BL) of a layer's tracks.+fn corners(w: &Work, layer: &str) -> Option<[(f64, f64); 4]> {+    let t: Vec<_> = w.tracks.iter().filter(|t| t.1.eq_ignore_ascii_case(layer)).collect();+    if t.is_empty() { return None; }+    let xs = t.iter().flat_map(|t| [t.2, t.4]);+    let ys = t.iter().flat_map(|t| [t.3, t.5]);+    let (x0, x1) = xs.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));+    let (y0, y1) = ys.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));+    Some([(x0, y1), (x1, y1), (x1, y0), (x0, y0)])+}++/// A track end at (x, y) mil: (index, anchor 1 for X1/Y1 or 2 for X2/Y2), on `layer` when given.+fn track_end(w: &Work, x: f64, y: f64, layer: Option<&str>) -> Option<(i64, i64)> {+    let near = |a: f64, b: f64| (a - b).abs() < 0.02;+    w.tracks.iter().filter(|t| layer.is_none_or(|l| t.1.eq_ignore_ascii_case(l))).find_map(|t| {+        if near(t.2, x) && near(t.3, y) { Some((t.0, 1)) } else if near(t.4, x) && near(t.5, y) { Some((t.0, 2)) } else { None }+    })+}++/// One end of a dimension: a pad's number ("1"), an assembly-outline corner ("TL", "TR", "BR", "BL", or "corner:TL"),+/// or a point {x, y} (mm, from the footprint's origin) where a track ends.+pub fn resolve(w: &Work, v: &Value, fab_layer: &str) -> Result<Anchor, String> {+    if let Some(o) = v.as_object() {+        let (x, y) = (o.get("x").and_then(|v| v.as_f64()).ok_or("a point anchor is {x, y} in mm")? * MIL_PER_MM, o.get("y").and_then(|v| v.as_f64()).ok_or("a point anchor is {x, y} in mm")? * MIL_PER_MM);+        if let Some((i, a)) = track_end(w, x, y, None) { return Ok(Anchor { kind: "Track", prim: i, anchor: a, x, y }); }+        if let Some(p) = w.pads.iter().find(|p| (p.2 - x).abs() < 0.02 && (p.3 - y).abs() < 0.02) { return Ok(Anchor { kind: "Pad", prim: p.0, anchor: 1, x: p.2, y: p.3 }); }+        return Err(format!("no track end or pad centre at ({:.4}, {:.4}) mm", x / MIL_PER_MM, y / MIL_PER_MM));+    }+    let s = v.as_str().map(str::to_string).or_else(|| v.as_i64().map(|n| n.to_string())).ok_or("an anchor is a pad number, a corner (TL, TR, BR, BL) or {x, y}")?;+    let c = s.trim().trim_start_matches("corner:").to_ascii_uppercase();+    if let Some(k) = ["TL", "TR", "BR", "BL"].iter().position(|n| *n == c) {+        let cs = corners(w, fab_layer).ok_or_else(|| format!("{s}: the footprint has no outline on its assembly layer ({fab_layer}) to take a corner from"))?;+        let (x, y) = cs[k];+        let (i, a) = track_end(w, x, y, Some(fab_layer)).ok_or_else(|| format!("{s}: no outline line ends at that corner (a chamfered corner has none: build the footprint with fabOutline: \"edges\")"))?;+        return Ok(Anchor { kind: "Track", prim: i, anchor: a, x, y });+    }+    let p = w.pads.iter().find(|p| p.1 == s.trim()).ok_or_else(|| format!("{s}: no pad of that number, and not a corner (TL, TR, BR, BL)"))?;+    Ok(Anchor { kind: "Pad", prim: p.0, anchor: 1, x: p.2, y: p.3 })+}++/// How a dimension reads: millimetres to `precision` decimals, or with `units: auto` whole mils when the length is a+/// whole multiple of 5 mil (the reporter's house rule), else millimetres to 2 decimals.+pub fn units_for(length_mil: f64, units: &str, precision: Option<i64>) -> (&'static str, i64) {+    match units {+        "mil" => ("Mils", precision.unwrap_or(0)),+        "mm" => ("Millimeters", precision.unwrap_or(2)),+        _ => {+            let r = (length_mil / 5.0).round() * 5.0;+            if (length_mil - r).abs() < 0.01 { ("Mils", precision.unwrap_or(0)) } else { ("Millimeters", precision.unwrap_or(2)) }+        }+    }+}++/// The text a dimension shows for `length_mil` in those units.+pub fn label(length_mil: f64, unit: &str, precision: i64) -> String {+    if unit == "Mils" { format!("{:.*} mil", precision as usize, length_mil) } else { format!("{:.*} mm", precision as usize, length_mil / MIL_PER_MM) }+}++/// The dimension's record in Altium's ASCII PcbDoc, as Altium itself writes a linear dimension (AD 26.11), bound to+/// `a` and `b`.+#[allow(clippy::too_many_arguments)]+pub fn record(index: usize, mech: i64, horizontal: bool, at_mil: f64, a: &Anchor, b: &Anchor, f: &Format, unit: &str, precision: i64) -> String {+    // as Altium writes it: a layer above Mechanical 16 is LAYER_V7 / DIMENSIONLAYER_V7, the plain names capped at 16+    // (a plain MECHANICAL21 was read as Mechanical 16, measured 2026-12-02)+    let (layer, v7, dv7) = if mech > 16 { ("MECHANICAL16".to_string(), format!("|LAYER_V7=MECHANICAL{mech}"), format!("|DIMENSIONLAYER_V7=MECHANICAL{mech}")) }+        else { (format!("MECHANICAL{mech}"), String::new(), String::new()) };+    let m = |v: f64| format!("{v:.4}mil");+    let (x1, y1, x2, y2) = if horizontal { (a.x, at_mil, b.x, at_mil) } else { (at_mil, a.y, at_mil, b.y) };+    let angle = if horizontal { " 0.00000000000000E+0000" } else { " 9.00000000000000E+0001" };+    let oid = |k: &str| if k == "Pad" { 2 } else { 4 };+    let r = |n: usize, x: &Anchor| format!("REFERENCE{n}PRIM={}|REFERENCE{n}OBJECTID={}|REFERENCE{n}OBJECTSTRING={}|REFERENCE{n}POINTX={}|REFERENCE{n}POINTY={}|REFERENCE{n}ANCHOR={}",+        x.prim, oid(x.kind), x.kind, m(x.x), m(x.y), x.anchor);+    format!("|RECORD=Embedded|INDEXFORSAVE={index}|SELECTION=FALSE|LAYER={layer}|LOCKED=FALSE|POLYGONOUTLINE=FALSE|USERROUTED=TRUE|UNIONINDEX=0|NAME=|SELECTION=FALSE|LAYER={layer}|LOCKED=FALSE|POLYGONOUTLINE=FALSE|USERROUTED=TRUE|UNIONINDEX=0{v7}|PRIMITIVELOCK=TRUE{dv7}|DIMENSIONLAYER={layer}|DIMENSIONLOCKED=FALSE|OBJECTID=13|DIMENSIONKIND=1|DRCERROR=FALSE|VINDEXFORSAVE={index}|X1={}|Y1={}|X2={}|Y2={}|TEXTX={}|TEXTY={}|HEIGHT=0mil|LINEWIDTH={}|TEXTHEIGHT={}|TEXTWIDTH={}|FONT=DEFAULT|STYLE=None|TEXTLINEWIDTH={}|TEXTPOSITION=Auto|TEXTGAP={}|TEXTFORMAT=10|TEXTDIMENSIONUNIT={unit}|TEXTPRECISION={precision}|TEXTPREFIX=|TEXTSUFFIX=|TEXTPREFIXUNIV=|TEXTSUFFIXUNIV=|ARROWSIZE={}|ARROWLINEWIDTH={}|ARROWLENGTH={}|ARROWPOSITION=Inside|EXTENSIONOFFSET={}|EXTENSIONLINEWIDTH={}|EXTENSIONPICKGAP={}|REFERENCES_COUNT=2|{}|{}|TEXT1MIRROR=FALSE|USETTFONTS={}|BOLD=FALSE|ITALIC=FALSE|FONTNAME={}|ANGLE={angle}",+        m(x1), m(y1), m(x2), m(y2), m((x1 + x2) / 2.0), m((y1 + y2) / 2.0), m(f.line), m(f.text_height), m(f.line), m(f.text_line), m(f.text_gap),+        m(f.arrow_size), m(f.line), m(f.arrow_length), m(f.extension_offset), m(f.line), m(f.extension_offset), r(0, a), r(1, b),+        if f.font.is_some() { "TRUE" } else { "FALSE" }, f.font.as_deref().unwrap_or("Arial"))+}++/// The look of the dimensions (mil). Defaults are Altium's own for a new linear dimension, scaled to a footprint.+#[derive(Clone, Debug)]+pub struct Format { pub text_height: f64, pub text_line: f64, pub text_gap: f64, pub line: f64, pub arrow_size: f64, pub arrow_length: f64, pub extension_offset: f64, pub units: String, pub precision: Option<i64>, pub font: Option<String> }++pub fn format_of(v: Option<&Value>) -> Format {+    let mm = |k: &str, d: f64| v.and_then(|o| o.get(k)).and_then(|x| x.as_f64()).map(|x| x * MIL_PER_MM).unwrap_or(d);+    Format {+        text_height: mm("textHeightMm", 40.0), text_line: mm("textLineWidthMm", 4.0), text_gap: mm("textGapMm", 8.0), line: mm("lineWidthMm", 4.0),+        arrow_size: mm("arrowSizeMm", 20.0), arrow_length: mm("arrowLengthMm", 40.0), extension_offset: mm("extensionOffsetMm", 8.0),+        units: v.and_then(|o| o.get("units")).and_then(|x| x.as_str()).unwrap_or("auto").to_string(),+        precision: v.and_then(|o| o.get("precision")).and_then(|x| x.as_i64()),+        font: v.and_then(|o| o.get("font")).and_then(|x| x.as_str()).map(str::to_string),+    }+}++/// The footprint's existing dimensions, bound again: copying a dimension onto the work board drops its references to bare+/// points (a dimension added by an earlier call stopped following its pad after a second call, measured 2026-12-02), so+/// each reference point is looked up again, a pad centre first, else a track end, and written back bound. Returns the+/// text and how many references were bound.+pub fn rebind(text: &str, w: &Work, off: (f64, f64)) -> (String, usize) {+    let mut n = 0;+    let set = |l: &str, k: &str, v: &str| -> String {+        let key = format!("|{k}=");+        match l.find(&key) {+            Some(i) => { let rest = &l[i + key.len()..]; let end = rest.find('|').map(|e| i + key.len() + e).unwrap_or(l.len()); format!("{}{}{}", &l[..i + key.len()], v, &l[end..]) }+            None => format!("{l}|{k}={v}"),+        }+    };+    let lines: Vec<String> = text.split('\n').map(|l| {+        if !(l.starts_with("|RECORD=Embedded|") && l.contains("DIMENSIONKIND=")) { return l.to_string(); }+        let f = fields(l);+        let mut out = l.to_string();+        // a copied dimension keeps some of its points in the library's own coordinates, the library origin away (50000+        // mil): those are brought back from the work board's origin+        let far = |x: f64, y: f64| x.abs() > 25_000.0 || y.abs() > 25_000.0;+        let fix = |x: f64, y: f64| if far(x, y) { (x - off.0, y - off.1) } else { (x, y) };+        for (kx, ky) in [("X1", "Y1"), ("X2", "Y2")] {+            let (x, y) = (mil(f.get(kx)), mil(f.get(ky)));+            if far(x, 0.0) { out = set(&out, kx, &format!("{:.4}mil", x - off.0)); }+            if far(0.0, y) { out = set(&out, ky, &format!("{:.4}mil", y - off.1)); }+        }+        for r in 0..2 {+            let (x, y) = fix(mil(f.get(&format!("REFERENCE{r}POINTX"))), mil(f.get(&format!("REFERENCE{r}POINTY"))));+            let hit = w.pads.iter().find(|p| (p.2 - x).abs() < 0.02 && (p.3 - y).abs() < 0.02).map(|p| ("Pad", p.0, 1))+                .or_else(|| track_end(w, x, y, None).map(|(i, a)| ("Track", i, a)));+            out = set(&out, &format!("REFERENCE{r}POINTX"), &format!("{x:.4}mil"));+            out = set(&out, &format!("REFERENCE{r}POINTY"), &format!("{y:.4}mil"));+            if let Some((kind, prim, a)) = hit {+                out = set(&out, &format!("REFERENCE{r}PRIM"), &prim.to_string());+                out = set(&out, &format!("REFERENCE{r}OBJECTID"), if kind == "Pad" { "2" } else { "4" });+                out = set(&out, &format!("REFERENCE{r}OBJECTSTRING"), kind);+                out = set(&out, &format!("REFERENCE{r}ANCHOR"), &a.to_string());+                n += 1;+            }+        }+        out+    }).collect();+    (lines.join("\n"), n)+}++/// The work board's text with the dimension records added after its last primitive.+pub fn insert(text: &str, records: &[String]) -> String {+    let lines: Vec<&str> = text.split('\n').collect();+    let prim = |l: &str| ["|RECORD=Pad|", "|RECORD=Track|", "|RECORD=Arc|", "|RECORD=Text|", "|RECORD=Fill|", "|RECORD=Region|", "|RECORD=Embedded|", "|RECORD=ComponentBody|"].iter().any(|p| l.starts_with(p));+    let at = lines.iter().rposition(|l| prim(l)).map(|i| i + 1).unwrap_or(lines.len());+    let mut out: Vec<String> = lines[..at].iter().map(|s| s.to_string()).collect();+    out.extend(records.iter().cloned());+    out.extend(lines[at..].iter().map(|s| s.to_string()));+    out.join("\n")+}++fn fail(code: &str, m: String) -> Value { json!({"success": false, "errorCode": code, "error": m}) }++/// altium_add_dimensions {libraryPath, footprint, dimensions: [{a, b, dir: H|V, at, expect?, toleranceMm?}], format?, layerMap?}+pub fn add_dimensions(args: &Value) -> Value {+    let s = |k: &str| crate::support::s(args, k);+    let Some(lib) = s("libraryPath").filter(|l| l.to_lowercase().ends_with(".pcblib")) else { return fail("bad_args", "libraryPath (.PcbLib) is required".into()) };+    let Some(name) = s("footprint").or_else(|| s("name")) else { return fail("bad_args", "footprint is required".into()) };+    let Some(list) = args.get("dimensions").and_then(|v| v.as_array()).filter(|a| !a.is_empty()).cloned() else {+        return fail("bad_args", "dimensions is required: [{a, b, dir: H|V, at}] (a, b: a pad number, a corner TL/TR/BR/BL, or {x, y}; at: the dimension line's y (H) or x (V), mm)".into());+    };+    for (i, d) in list.iter().enumerate() {+        let dir = d.get("dir").and_then(|v| v.as_str()).unwrap_or("").to_ascii_uppercase();+        if dir != "H" && dir != "V" { return fail("bad_args", format!("dimensions[{i}].dir: H (measures along x) or V (along y)")); }+        if d.get("at").and_then(|v| v.as_f64()).is_none() { return fail("bad_args", format!("dimensions[{i}].at: where the dimension line runs, mm (its y for H, its x for V)")); }+        if d.get("a").is_none() || d.get("b").is_none() { return fail("bad_args", format!("dimensions[{i}]: a and b are required")); }+    }+    let fmt = format_of(args.get("format"));+    if let Some(g) = crate::support::need_licensed() { return g; }+    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }+    let map = crate::layermap_verb::effective(args, Some(&lib));+    let code = |k: &str| map.entries.iter().find(|e| e.0 == k).map(|e| e.2.clone()).unwrap_or_default();+    let dir = crate::agent::cache_dir().join("dimensions");+    let _ = std::fs::create_dir_all(&dir);+    let safe: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();+    let work = dir.join(format!("{safe}.PcbDoc")).to_string_lossy().replace('/', "\\");+    let dur = std::time::Duration::from_secs(120);+    let w = crate::agent::call("dim_work", &[("path", lib.replace('/', "\\")), ("name", name.clone()), ("work", work.clone()), ("lcode", code("dimensions")), ("fcode", code("fab"))], None, dur);+    let wd = match crate::sch::agent_data(&w) { Ok(d) => d, Err(e) => return e };+    let text = match std::fs::read(&work) { Ok(b) => String::from_utf8_lossy(&b).to_string(), Err(e) => return fail("work_board_unreadable", format!("{work}: {e}")) };+    let wb = parse_work(&text);+    let dim_mech = wd["dimMech"].as_i64().unwrap_or(13);+    let dim_layer = format!("MECHANICAL{dim_mech}");+    let fab_layer = format!("MECHANICAL{}", wd["fabMech"].as_i64().unwrap_or(13));+    let mut records = Vec::new();+    let mut planned = Vec::new();+    for (i, d) in list.iter().enumerate() {+        let a = match resolve(&wb, &d["a"], &fab_layer) { Ok(x) => x, Err(m) => return fail("anchor_not_found", format!("dimensions[{i}].a: {m}")) };+        let b = match resolve(&wb, &d["b"], &fab_layer) { Ok(x) => x, Err(m) => return fail("anchor_not_found", format!("dimensions[{i}].b: {m}")) };+        let h = d["dir"].as_str().unwrap_or("H").eq_ignore_ascii_case("H");+        let at = d["at"].as_f64().unwrap_or(0.0) * MIL_PER_MM;+        let len = if h { (b.x - a.x).abs() } else { (b.y - a.y).abs() };+        if len < 0.01 { return fail("bad_args", format!("dimensions[{i}]: a and b are level along {} (nothing to measure)", if h { "x" } else { "y" })); }+        let (unit, prec) = units_for(len, &fmt.units, fmt.precision);+        records.push(record(wb.dims + i, dim_mech, h, at, &a, &b, &fmt, unit, prec));+        planned.push(json!({"a": d["a"], "b": d["b"], "dir": if h { "H" } else { "V" }, "lengthMm": (len / MIL_PER_MM * 10000.0).round() / 10000.0, "text": label(len, unit, prec),+            "anchors": [format!("{} {} (anchor {})", a.kind, a.prim, a.anchor), format!("{} {} (anchor {})", b.kind, b.prim, b.anchor)], "expect": d.get("expect"), "toleranceMm": d.get("toleranceMm").and_then(|v| v.as_f64()).unwrap_or(0.01)}));+    }+    if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {+        return json!({"success": true, "dryRun": true, "dimensions": planned, "layer": dim_layer, "outlineLayer": fab_layer, "_hint": "Nothing changed. Call again without dryRun to add them."});+    }+    let off = wd["offsetMil"].as_array().map(|a| (a.first().and_then(|v| v.as_f64()).unwrap_or(0.0), a.get(1).and_then(|v| v.as_f64()).unwrap_or(0.0))).unwrap_or((0.0, 0.0));+    let (text, rebound) = rebind(&text, &wb, off);+    if let Err(e) = std::fs::write(&work, insert(&text, &records)) { return fail("write_failed", format!("{work}: {e}")); }+    let a = crate::agent::call("dim_apply", &[("path", lib.replace('/', "\\")), ("name", name.clone()), ("work", work.clone()), ("skip", wd["skip"].as_str().unwrap_or("").to_string()),+        ("multiRegions", if text.lines().any(|l| l.starts_with("|RECORD=Region|") && l.contains("|LAYER=MULTILAYER|")) { "1".into() } else { "0".into() })], None, dur);+    let ad = match crate::sch::agent_data(&a) { Ok(d) => d, Err(e) => return e };+    // the proof: saved, closed and reopened, every dimension's references read back+    let saved = crate::surfaces::save(&json!({"filePath": lib}));+    if saved.get("success").and_then(|b| b.as_bool()) == Some(false) { let mut e = saved.clone(); e["errorCode"] = json!("save_failed"); return e; }+    let _ = crate::agent::call("close_document", &[("path", lib.replace('/', "\\"))], None, dur);+    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }+    let r = crate::agent::call("dim_read", &[("path", lib.replace('/', "\\")), ("name", name.clone())], None, dur);+    let rd = match crate::sch::agent_data(&r) { Ok(d) => d, Err(e) => return e };+    let k = rd["k"].as_f64().unwrap_or(10_000_000.0) / 25.4;+    let found: Vec<(bool, f64)> = rd["dims"].as_array().cloned().unwrap_or_default().iter().map(|d| (d[0].as_bool().unwrap_or(false), d[1].as_f64().unwrap_or(0.0) / k)).collect();+    let mech_of = |id: i64| if (57..=72).contains(&id) { id - 56 } else if id > 67_108_864 { id - 67_108_864 } else { 0 };+    let layers: Vec<i64> = rd["dims"].as_array().cloned().unwrap_or_default().iter().map(|d| mech_of(d[2].as_i64().unwrap_or(0))).collect();+    let mut used = vec![false; found.len()];+    let mut out = Vec::new();+    let mut ok = true;+    for p in planned {+        let want = p["lengthMm"].as_f64().unwrap_or(0.0);+        let hit = found.iter().enumerate().filter(|(i, _)| !used[*i]).min_by(|x, y| (x.1 .1 - want).abs().partial_cmp(&(y.1 .1 - want).abs()).unwrap()).map(|(i, f)| (i, *f));+        let mut q = p.clone();+        match hit {+            Some((i, (valid, v))) if (v - want).abs() < 0.001 => {+                used[i] = true;+                q["valueMm"] = json!((v * 10000.0).round() / 10000.0);+                q["validAfterReopen"] = json!(valid);+                q["onLayer"] = json!(format!("Mechanical {}", layers[i]));+                if !valid { ok = false; }+                if layers[i] != dim_mech { ok = false; q["error"] = json!(format!("landed on Mechanical {}, not {}", layers[i], dim_mech)); }+                if let Some(e) = p["expect"].as_f64() {+                    let tol = p["toleranceMm"].as_f64().unwrap_or(0.01);+                    q["check"] = json!(if (v - e).abs() <= tol { "MATCH" } else { "MISMATCH" });+                    q["deltaMm"] = json!(((v - e) * 10000.0).round() / 10000.0);+                }+            }+            _ => { ok = false; q["validAfterReopen"] = json!(false); q["error"] = json!("not found after the library was reopened"); }+        }+        out.push(q);+    }+    let mismatch = out.iter().any(|d| d["check"] == "MISMATCH");+    json!({"success": ok, "errorCode": if ok { Value::Null } else { json!("not_anchored") }, "footprint": name, "library": lib, "layer": dim_layer, "outlineLayer": fab_layer,+        "dimensions": out, "allDimensions": found.len(), "rebuilt": {"moved": ad["moved"], "bodies": ad["bodies"], "existingDimensions": wb.dims, "referencesRebound": rebound}, "anyMismatch": mismatch, "saved": true,+        "_hint": if ok { "Each dimension is bound to its pads or corners (validAfterReopen: read back after the library was saved, closed and reopened) and follows them when they move. check compares the measured length with expect." }+            else { "A dimension did not validate after the reopen: its anchor may be a corner shared by a chamfer, or a pad Altium could not rebind. Read the footprint (altium_read_footprint) and call again; a chamfered outline needs fabOutline: edges." }})+}++#[cfg(test)]+mod tests {+    use super::*;++    const WORK: &str = "|RECORD=Board|X=0\n|RECORD=Track|INDEXFORSAVE=4|LAYER=MECHANICAL16|LAYER_V7=MECHANICAL19|X1=0mil|Y1=0mil|X2=10mil|Y2=0mil\n|RECORD=Pad|INDEXFORSAVE=0|LAYER=TOP|NAME=1|X=-106.2992mil|Y=75mil|XSIZE=10mil\n|RECORD=Pad|INDEXFORSAVE=1|LAYER=TOP|NAME=8|X=106.2992mil|Y=75mil\n|RECORD=Track|INDEXFORSAVE=0|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=96.4567mil|X2=76.7717mil|Y2=96.4567mil|WIDTH=3.937mil\n|RECORD=Track|INDEXFORSAVE=1|LAYER=MECHANICAL13|X1=76.7717mil|Y1=-96.4567mil|X2=76.7717mil|Y2=96.4567mil\n|RECORD=Track|INDEXFORSAVE=2|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=-96.4567mil|X2=76.7717mil|Y2=-96.4567mil\n|RECORD=Track|INDEXFORSAVE=3|LAYER=MECHANICAL13|X1=-76.7717mil|Y1=-96.4567mil|X2=-76.7717mil|Y2=96.4567mil\n|RECORD=Rule|NAME=x";++    #[test]+    fn anchors_are_pads_corners_and_track_ends() {+        let w = parse_work(WORK);+        assert_eq!((w.pads.len(), w.tracks.len(), w.dims), (2, 5, 0));+        assert_eq!(w.tracks[0].1, "MECHANICAL19", "LAYER_V7 is the real layer");+        assert_eq!(resolve(&w, &json!("8"), "MECHANICAL13").unwrap(), Anchor { kind: "Pad", prim: 1, anchor: 1, x: 106.2992, y: 75.0 });+        // TL is the top edge's start; TR its end; BR is where the right edge starts as Altium saved it (its X1/Y1)+        let tl = resolve(&w, &json!("TL"), "MECHANICAL13").unwrap();+        assert_eq!((tl.prim, tl.anchor), (0, 1));+        let tr = resolve(&w, &json!("corner:TR"), "MECHANICAL13").unwrap();+        assert_eq!((tr.prim, tr.anchor), (0, 2));+        let br = resolve(&w, &json!("BR"), "MECHANICAL13").unwrap();+        assert!((br.prim == 1 && br.anchor == 1) || (br.prim == 2 && br.anchor == 2), "{br:?}");+        let p = resolve(&w, &json!({"x": -1.95, "y": -2.45}), "MECHANICAL13").unwrap();+        assert_eq!(p.kind, "Track");+        assert!(resolve(&w, &json!("9"), "MECHANICAL13").is_err());+        assert!(resolve(&w, &json!("TL"), "MECHANICAL15").is_err(), "no outline on that layer");+    }++    #[test]+    fn an_existing_dimension_is_bound_again() {+        let dim = "|RECORD=Embedded|INDEXFORSAVE=0|DIMENSIONKIND=1|REFERENCE0PRIM=-1|REFERENCE0OBJECTID=-1|REFERENCE0OBJECTSTRING=NoObject|REFERENCE0POINTX=-106.2992mil|REFERENCE0POINTY=75mil|REFERENCE0ANCHOR=-1|REFERENCE1PRIM=-1|REFERENCE1OBJECTID=-1|REFERENCE1OBJECTSTRING=NoObject|REFERENCE1POINTX=76.7717mil|REFERENCE1POINTY=96.4567mil|REFERENCE1ANCHOR=-1|ANGLE=0";+        let text = format!("{WORK}\n{dim}");+        let w = parse_work(&text);+        assert_eq!(w.dims, 1);+        let (out, n) = rebind(&text, &w, (50000.0, 50000.0));+        assert_eq!(n, 2);+        let l = out.lines().last().unwrap();+        assert!(l.contains("|REFERENCE0PRIM=0|REFERENCE0OBJECTID=2|REFERENCE0OBJECTSTRING=Pad|") && l.contains("|REFERENCE0ANCHOR=1|"), "{l}");+        assert!(l.contains("|REFERENCE1OBJECTSTRING=Track|") && l.contains("|REFERENCE1ANCHOR=2|"), "the top edge's X2/Y2 end: {l}");+        // a point still in the library's coordinates (50000 mil out) is brought back+        let far = dim.replace("REFERENCE0POINTX=-106.2992mil|REFERENCE0POINTY=75mil", "REFERENCE0POINTX=49893.7008mil|REFERENCE0POINTY=50075mil");+        let (out2, n2) = rebind(&format!("{WORK}\n{far}"), &w, (50000.0, 50000.0));+        assert_eq!(n2, 2, "{out2}");+        assert!(out2.lines().last().unwrap().contains("|REFERENCE0POINTX=-106.2992mil|"));+    }++    #[test]+    fn units_follow_the_house_rule() {+        assert_eq!(units_for(50.0, "auto", None), ("Mils", 0));+        assert_eq!(units_for(212.5984, "auto", None), ("Millimeters", 2));+        assert_eq!(label(212.5984, "Millimeters", 2), "5.40 mm");+        assert_eq!(label(50.0, "Mils", 0), "50 mil");+        assert_eq!(units_for(50.0, "mm", None), ("Millimeters", 2));+    }++    #[test]+    fn the_record_binds_both_ends() {+        let w = parse_work(WORK);+        let a = resolve(&w, &json!("1"), "MECHANICAL13").unwrap();+        let b = resolve(&w, &json!("8"), "MECHANICAL13").unwrap();+        let r = record(0, 13, true, 150.0, &a, &b, &format_of(None), "Millimeters", 2);+        assert!(r.starts_with("|RECORD=Embedded|INDEXFORSAVE=0|"));+        assert!(r.contains("|REFERENCE0PRIM=0|REFERENCE0OBJECTID=2|REFERENCE0OBJECTSTRING=Pad|") && r.contains("|REFERENCE1PRIM=1|"), "{r}");+        assert!(r.contains("|X1=-106.2992mil|Y1=150.0000mil|X2=106.2992mil|Y2=150.0000mil|"), "{r}");+        assert!(r.contains("|DIMENSIONLAYER=MECHANICAL13|") && r.contains("|TEXTDIMENSIONUNIT=Millimeters|"));+        let typed = record(1, 21, true, 150.0, &a, &b, &format_of(None), "Millimeters", 2);+        assert!(typed.contains("|LAYER=MECHANICAL16|") && typed.contains("|LAYER_V7=MECHANICAL21|") && typed.contains("|DIMENSIONLAYER_V7=MECHANICAL21|") && typed.contains("|DIMENSIONLAYER=MECHANICAL16|"), "{typed}");+        let out = insert(WORK, &[r.clone()]);+        let lines: Vec<&str> = out.lines().collect();+        assert_eq!(lines[lines.len() - 2], r, "after the last primitive, before the rules");+    }+}
bridge-rs/src/footprint.rs+44−2
@@ -21,6 +21,27 @@ pub fn spec(name: &str, desc: &str, fp: &Fp) -> String {     s } +/// `fabOutline: "edges"` (#43): the assembly outline as exactly four lines, one per body edge, meeting at the body's+/// corners (TL, TR, BR, BL), and the pin-1 chamfer as a line of its own across the top-left corner. The layout draws+/// the outline as one polyline with that corner cut off, so the corner was no line's end and a dimension could not+/// attach to it. Returns the corners (mm), or None when the layout drew no fab outline.+pub fn fab_edges(fp: &mut Fp) -> Option<Value> {+    let fab: Vec<_> = fp.lines.iter().filter(|l| l.0 == "fab").cloned().collect();+    if fab.is_empty() { return None; }+    let xs = fab.iter().flat_map(|l| [l.1, l.3]);+    let ys = fab.iter().flat_map(|l| [l.2, l.4]);+    let (x0, x1) = xs.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));+    let (y0, y1) = ys.clone().fold((f64::MAX, f64::MIN), |(a, b), v| (a.min(v), b.max(v)));+    let w = fab[0].5;+    let ch = ((x1 - x0).min(y1 - y0) * 0.25).min(1.0);+    let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+    fp.lines.retain(|l| l.0 != "fab");+    for (a, b, c, d) in [(x0, y1, x1, y1), (x1, y1, x1, y0), (x1, y0, x0, y0), (x0, y0, x0, y1)] { fp.lines.push(("fab", r3(a), r3(b), r3(c), r3(d), w)); }+    fp.lines.push(("fab", r3(x0), r3(y1 - ch), r3(x0 + ch), r3(y1), w));+    Some(json!({"mode": "edges", "corners": {"TL": [r3(x0), r3(y1)], "TR": [r3(x1), r3(y1)], "BR": [r3(x1), r3(y0)], "BL": [r3(x0), r3(y0)]},+        "edges": ["top TL-TR", "right TR-BR", "bottom BR-BL", "left BL-TL"], "pin1Chamfer": [[r3(x0), r3(y1 - ch)], [r3(x0 + ch), r3(y1)]]}))+}+ /// A plain description: "SOIC-8, 1.27 mm pitch, 8 pads". fn describe(a: &Value, fp: &Fp) -> String {     let fam = a.get("family").and_then(|f| f.as_str()).unwrap_or("dual");@@ -31,11 +52,16 @@ fn describe(a: &Value, fp: &Fp) -> String { /// altium_footprint_from_land_pattern {libraryPath, name, family, ..., dryRun?} pub fn from_land_pattern(args: &Value) -> Value {     let Some(name) = crate::support::s(args, "name").filter(|n| !n.is_empty()) else { return json!({"success": false, "errorCode": "bad_args", "error": "name is required"}) };-    let fp = match layout(args) { Ok(f) => f, Err(e) => return json!({"success": false, "errorCode": "bad_args", "error": e,+    let mut fp = match layout(args) { Ok(f) => f, Err(e) => return json!({"success": false, "errorCode": "bad_args", "error": e,         "_hint": "Give the datasheet's RECOMMENDED LAND PATTERN numbers (mm): chip {span, padLength, padWidth}; dual/sot {pins | leftPins+rightPins, pitch, span (pad centre to pad centre across), padLength, padWidth}; quad {pins | pinsPerSideX+pinsPerSideY, pitch, span, spanY?, padLength, padWidth}; bga {rows, cols, pitch, ballPad, missing?}; plus exposedPad {w, h} and body {w, l, height?}."}) };+    let fab_outline = match crate::support::s(args, "fabOutline").as_deref() {+        None | Some("chamfer") => None,+        Some("edges") => fab_edges(&mut fp),+        Some(o) => return json!({"success": false, "errorCode": "bad_args", "error": format!("fabOutline {o}: chamfer (the default: one outline with the pin-1 corner cut) or edges (four edges meeting at the corners, for dimensions)")}),+    };     let desc = crate::support::s(args, "description").unwrap_or_else(|| describe(args, &fp));     let text = spec(&name, &desc, &fp);-    let summary = json!({"pads": fp.pads.len(), "courtyardMm": [fp.courtyard.0, fp.courtyard.1, fp.courtyard.2, fp.courtyard.3],+    let summary = json!({"pads": fp.pads.len(), "courtyardMm": [fp.courtyard.0, fp.courtyard.1, fp.courtyard.2, fp.courtyard.3], "fabOutline": fab_outline,         "silkLines": fp.lines.iter().filter(|l| l.0 == "overlay").count(),         "padTable": fp.pads.iter().take(12).map(|p| json!([p.name, p.x, p.y, p.w, p.h])).collect::<Vec<_>>()});     if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) {@@ -85,6 +111,22 @@ mod tests {         assert!(t.lines().any(|l| l.starts_with("LINE|courtyard|")));     } +    #[test]+    fn the_edges_outline_meets_at_the_body_corners() {+        let mut fp = layout(&json!({"family": "dual", "pins": 8, "pitch": 1.27, "span": 5.4, "padLength": 1.55, "padWidth": 0.6, "body": {"w": 3.9, "l": 4.9}})).unwrap();+        let before = fp.lines.iter().filter(|l| l.0 != "fab").count();+        let c = fab_edges(&mut fp).unwrap();+        let fab: Vec<_> = fp.lines.iter().filter(|l| l.0 == "fab").collect();+        assert_eq!(fab.len(), 5, "four edges and the chamfer");+        assert_eq!(fp.lines.iter().filter(|l| l.0 != "fab").count(), before, "other layers untouched");+        let tl = (c["corners"]["TL"][0].as_f64().unwrap(), c["corners"]["TL"][1].as_f64().unwrap());+        // the top edge starts at TL and the left edge ends there: a corner is an end of two lines+        assert_eq!((fab[0].1, fab[0].2), tl);+        assert_eq!((fab[3].3, fab[3].4), tl);+        let br = (c["corners"]["BR"][0].as_f64().unwrap(), c["corners"]["BR"][1].as_f64().unwrap());+        assert!((br.0 - tl.0 - 3.9).abs() < 1e-6 || (br.0 - tl.0 - 4.9).abs() < 1e-6, "{c}");+    }+     #[test]     fn a_sot23_5s_short_column_spans_the_long_one() {         // EDA Bridge Standard #25: pins 4 and 5 level with 3 and 1, the courtyard round the pads and body only
bridge-rs/src/main.rs+3−1
@@ -14,6 +14,8 @@ mod layermap; mod layermap_verb; mod simmodel; mod simcopy;+mod silkcheck;+mod dimensions; mod autoclass; mod board; mod bodies;@@ -89,7 +91,7 @@ use tiny_http::{Header, Method, Response, Server}; /// Attached to every failed reply (see the /command handler). const REPORT_ISSUES: &str = "If this looks like an altium-bridge BUG (not a refusal you expected), report it: check for a duplicate with `adom-wiki issue list adom/altium-bridge`, then `adom-wiki issue create adom/altium-bridge --title \"<verb>: <one-line symptom>\" --category bug-report --body \"<what you ran, what you expected, what happened, the VERBATIM response JSON (and errorShot if present), bridgeVersion, the Altium version from altium_status, the OS>\"`. A relay, routing, toast or lifecycle problem belongs on adom/adom-bridge instead. Reports from real machines are how this bridge gets correct: three different Altium builds behaved three different ways in one weekend."; -pub const BRIDGE_VERSION: &str = "0.2.120";+pub const BRIDGE_VERSION: &str = "0.2.121";  fn json_response(status: u16, body: &serde_json::Value) -> Response<std::io::Cursor<Vec<u8>>> {     let data = serde_json::to_vec(body).unwrap_or_else(|_| b"{}".to_vec());
bridge-rs/src/silkcheck.rsadded+305
@@ -0,0 +1,305 @@+//! altium_check_silkscreen (#43): edge-to-edge clearance between a footprint's silkscreen (overlay lines, arcs, texts,+//! fills) and each pad's exposed copper (the pad grown by its solder mask expansion), measured on the footprint as+//! Altium holds it. Every shape is a core (a point, a polyline or a filled polygon) with a radius around it: a round+//! pad is a point with half its diameter, an oval a segment with half its width, a rounded rectangle its inner+//! rectangle with the corner radius, a silk line its centre line with half its width. The mask expansion and the stroke+//! width only add to the radius, so one distance function covers every pair.+use serde_json::{json, Value};++pub type P = (f64, f64);++#[derive(Clone, Debug)]+pub enum Core {+    /// a point or an open polyline (an arc is flattened into one)+    Line(Vec<P>),+    /// a filled convex polygon+    Poly(Vec<P>),+}++#[derive(Clone, Debug)]+pub struct Shape { pub core: Core, pub r: f64 }++fn rot(p: P, deg: f64) -> P { let (s, c) = deg.to_radians().sin_cos(); (p.0 * c - p.1 * s, p.0 * s + p.1 * c) }+fn add(a: P, b: P) -> P { (a.0 + b.0, a.1 + b.1) }+fn sub(a: P, b: P) -> P { (a.0 - b.0, a.1 - b.1) }+fn dot(a: P, b: P) -> f64 { a.0 * b.0 + a.1 * b.1 }+fn cross(a: P, b: P) -> f64 { a.0 * b.1 - a.1 * b.0 }+fn len(a: P) -> f64 { dot(a, a).sqrt() }++fn point_seg(p: P, a: P, b: P) -> f64 {+    let ab = sub(b, a);+    let l2 = dot(ab, ab);+    if l2 == 0.0 { return len(sub(p, a)); }+    let t = (dot(sub(p, a), ab) / l2).clamp(0.0, 1.0);+    len(sub(p, add(a, (ab.0 * t, ab.1 * t))))+}++fn segs_cross(a: P, b: P, c: P, d: P) -> bool {+    let (d1, d2) = (cross(sub(b, a), sub(c, a)), cross(sub(b, a), sub(d, a)));+    let (d3, d4) = (cross(sub(d, c), sub(a, c)), cross(sub(d, c), sub(b, c)));+    ((d1 > 0.0 && d2 < 0.0) || (d1 < 0.0 && d2 > 0.0)) && ((d3 > 0.0 && d4 < 0.0) || (d3 < 0.0 && d4 > 0.0))+}++fn seg_seg(a: P, b: P, c: P, d: P) -> f64 {+    if segs_cross(a, b, c, d) { return 0.0; }+    point_seg(a, c, d).min(point_seg(b, c, d)).min(point_seg(c, a, b)).min(point_seg(d, a, b))+}++/// Inside a convex polygon (either winding), edges included.+fn inside(p: P, poly: &[P]) -> bool {+    let n = poly.len();+    if n < 3 { return false; }+    let mut sign = 0.0;+    for i in 0..n {+        let c = cross(sub(poly[(i + 1) % n], poly[i]), sub(p, poly[i]));+        if c.abs() < 1e-12 { continue; }+        if sign == 0.0 { sign = c.signum(); } else if c.signum() != sign { return false; }+    }+    true+}++fn edges(c: &Core) -> Vec<(P, P)> {+    match c {+        Core::Line(v) if v.len() == 1 => vec![(v[0], v[0])],+        Core::Line(v) => v.windows(2).map(|w| (w[0], w[1])).collect(),+        Core::Poly(v) => (0..v.len()).map(|i| (v[i], v[(i + 1) % v.len()])).collect(),+    }+}++fn points(c: &Core) -> &Vec<P> { match c { Core::Line(v) | Core::Poly(v) => v } }++/// The distance between two cores: 0 when they touch or one holds the other.+pub fn core_dist(a: &Core, b: &Core) -> f64 {+    if let Core::Poly(pa) = a { if points(b).iter().any(|p| inside(*p, pa)) { return 0.0; } }+    if let Core::Poly(pb) = b { if points(a).iter().any(|p| inside(*p, pb)) { return 0.0; } }+    let (ea, eb) = (edges(a), edges(b));+    let mut m = f64::MAX;+    for (p, q) in &ea { for (r, s) in &eb { m = m.min(seg_seg(*p, *q, *r, *s)); } }+    m+}++/// Edge-to-edge clearance: 0 or less when the shapes touch or overlap.+pub fn clearance(a: &Shape, b: &Shape) -> f64 { core_dist(&a.core, &b.core) - a.r - b.r }++fn rect(c: P, w: f64, h: f64, deg: f64) -> Vec<P> {+    [(-w / 2.0, -h / 2.0), (w / 2.0, -h / 2.0), (w / 2.0, h / 2.0), (-w / 2.0, h / 2.0)].iter().map(|p| add(c, rot(*p, deg))).collect()+}++/// A pad's exposed copper on one side: Altium's shape code (1 round, 2 rectangle, 3 octagon, 9 rounded rectangle),+/// size, corner radius (% of half the short side), rotation and the mask expansion `e`. An octagon is taken as its+/// rectangle (the clearance read is then never larger than the real one).+pub fn pad_shape(c: P, shape: i64, sx: f64, sy: f64, cr_pct: f64, deg: f64, e: f64) -> Shape {+    match shape {+        1 if (sx - sy).abs() < 1e-9 => Shape { core: Core::Line(vec![c]), r: sx / 2.0 + e },+        1 => {+            let (l, w) = (sx.max(sy), sx.min(sy));+            let half = (l - w) / 2.0;+            let (a, b) = if sx >= sy { ((-half, 0.0), (half, 0.0)) } else { ((0.0, -half), (0.0, half)) };+            Shape { core: Core::Line(vec![add(c, rot(a, deg)), add(c, rot(b, deg))]), r: w / 2.0 + e }+        }+        9 => {+            let cr = (cr_pct / 100.0) * sx.min(sy) / 2.0;+            let (iw, ih) = ((sx - 2.0 * cr).max(0.0), (sy - 2.0 * cr).max(0.0));+            let core = if iw == 0.0 && ih == 0.0 { Core::Line(vec![c]) } else if iw == 0.0 || ih == 0.0 {+                Core::Line(vec![add(c, rot((-iw / 2.0, -ih / 2.0), deg)), add(c, rot((iw / 2.0, ih / 2.0), deg))])+            } else { Core::Poly(rect(c, iw, ih, deg)) };+            Shape { core, r: cr + e }+        }+        _ => Shape { core: Core::Poly(rect(c, sx, sy, deg)), r: e },+    }+}++/// An arc (degrees, counter-clockwise from start to end) as a polyline whose chords stay within 1 um of the curve.+pub fn arc_points(c: P, r: f64, a0: f64, a1: f64) -> Vec<P> {+    let mut sweep = a1 - a0;+    while sweep <= 0.0 { sweep += 360.0; }+    let step = if r > 0.0 { (2.0 * (1.0 - 0.001 / r).clamp(-1.0, 1.0).acos()).to_degrees().max(0.5) } else { 360.0 };+    let n = ((sweep / step).ceil() as usize).clamp(1, 720);+    (0..=n).map(|i| { let a = (a0 + sweep * i as f64 / n as f64).to_radians(); (c.0 + r * a.cos(), c.1 + r * a.sin()) }).collect()+}++/// One silkscreen item: its layer, shape and what to call it in a reply.+pub struct Silk { pub layer: i64, pub shape: Shape, pub what: Value }+/// One pad's exposed copper on one side.+pub struct Copper { pub side: i64, pub shape: Shape, pub pad: String }++/// The footprint geometry the agent read (fp_geometry), as silk items and exposed copper. `mask`: the mask expansion+/// to use (mm), else each pad's own manual one, else `default_mask`.+pub fn parse(d: &Value, mask: Option<f64>, default_mask: f64) -> (Vec<Silk>, Vec<Copper>, Vec<String>) {+    let k = d["k"].as_f64().unwrap_or(10_000_000.0) / 25.4; // internal units per mm+    let mm = |v: &Value| v.as_f64().unwrap_or(0.0) / k;+    let arr = |key: &str| d[key].as_array().cloned().unwrap_or_default();+    let mut silk = Vec::new();+    let mut notes = Vec::new();+    let r4 = |v: f64| (v * 10000.0).round() / 10000.0;+    for t in arr("tracks") {+        let l = t[0].as_i64().unwrap_or(0);+        if l != 33 && l != 34 { continue; }+        let (a, b) = ((mm(&t[1]), mm(&t[2])), (mm(&t[3]), mm(&t[4])));+        silk.push(Silk { layer: l, shape: Shape { core: Core::Line(vec![a, b]), r: mm(&t[5]) / 2.0 }, what: json!({"kind": "line", "from": [r4(a.0), r4(a.1)], "to": [r4(b.0), r4(b.1)], "widthMm": r4(mm(&t[5]))}) });+    }+    for t in arr("arcs") {+        let l = t[0].as_i64().unwrap_or(0);+        if l != 33 && l != 34 { continue; }+        let (c, r) = ((mm(&t[1]), mm(&t[2])), mm(&t[3]));+        let (a0, a1) = (t[4].as_f64().unwrap_or(0.0) / 1000.0, t[5].as_f64().unwrap_or(0.0) / 1000.0);+        silk.push(Silk { layer: l, shape: Shape { core: Core::Line(arc_points(c, r, a0, a1)), r: mm(&t[6]) / 2.0 },+            what: json!({"kind": "arc", "center": [r4(c.0), r4(c.1)], "radiusMm": r4(r), "startAngle": a0, "endAngle": a1, "widthMm": r4(mm(&t[6]))}) });+    }+    for t in arr("texts") {+        let l = t[0].as_i64().unwrap_or(0);+        if l != 33 && l != 34 { continue; }+        let (x0, y0, x1, y1) = (mm(&t[1]), mm(&t[2]), mm(&t[3]), mm(&t[4]));+        silk.push(Silk { layer: l, shape: Shape { core: Core::Poly(vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]), r: 0.0 },+            what: json!({"kind": "text", "text": t[5], "box": [r4(x0), r4(y0), r4(x1), r4(y1)]}) });+    }+    for t in arr("fills") {+        let l = t[0].as_i64().unwrap_or(0);+        if l != 33 && l != 34 { continue; }+        let (x0, y0, x1, y1) = (mm(&t[1]), mm(&t[2]), mm(&t[3]), mm(&t[4]));+        let deg = t[5].as_f64().unwrap_or(0.0) / 1000.0;+        let c = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);+        silk.push(Silk { layer: l, shape: Shape { core: Core::Poly(rect(c, (x1 - x0).abs(), (y1 - y0).abs(), deg)), r: 0.0 }, what: json!({"kind": "fill", "box": [r4(x0), r4(y0), r4(x1), r4(y1)]}) });+    }+    if !arr("texts").iter().all(|t| t[0].as_i64() != Some(33) && t[0].as_i64() != Some(34)) {+        notes.push("A text is measured by its bounding box: a rotated string reads closer than its strokes are.".into());+    }+    let mut copper = Vec::new();+    let mut octagon = false;+    for p in arr("pads") {+        let name = p[0].as_str().unwrap_or("").to_string();+        let c = (mm(&p[1]), mm(&p[2]));+        let deg = p[3].as_f64().unwrap_or(0.0) / 1000.0;+        let layer = p[4].as_i64().unwrap_or(1);+        let e = mask.unwrap_or(if p[15].as_i64() == Some(1) { mm(&p[14]) } else { default_mask });+        let sides: &[(i64, usize)] = match layer { 1 => &[(33, 5)], 32 => &[(34, 8)], _ => &[(33, 5), (34, 8)] };+        for (side, at) in sides {+            let shape = p[*at].as_i64().unwrap_or(2);+            if shape == 3 { octagon = true; }+            let cr = p[if *at == 5 { 11 } else { 12 }].as_f64().unwrap_or(0.0);+            copper.push(Copper { side: *side, shape: pad_shape(c, shape, mm(&p[at + 1]), mm(&p[at + 2]), cr, deg, e), pad: name.clone() });+        }+    }+    if octagon { notes.push("An octagonal pad is measured as its rectangle.".into()); }+    (silk, copper, notes)+}++/// Every silk-to-copper pair on the same side: (clearance mm, silk index, copper index), closest first.+pub fn pairs(silk: &[Silk], copper: &[Copper]) -> Vec<(f64, usize, usize)> {+    let mut v = Vec::new();+    for (i, s) in silk.iter().enumerate() {+        for (j, c) in copper.iter().enumerate() {+            if s.layer == c.side { v.push((clearance(&s.shape, &c.shape), i, j)); }+        }+    }+    v.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));+    v+}++/// Altium's default solder mask expansion rule: 4 mil.+pub const DEFAULT_MASK_MM: f64 = 0.1016;++/// altium_check_silkscreen {libraryPath, footprint | footprints, minMm?, maskExpansionMm?}+pub fn check_silkscreen(args: &Value) -> Value {+    let bad = |m: &str| json!({"success": false, "errorCode": "bad_args", "error": m});+    let Some(lib) = crate::support::s(args, "libraryPath").filter(|l| l.to_lowercase().ends_with(".pcblib")) else { return bad("libraryPath (.PcbLib) is required") };+    let mut names: Vec<String> = args.get("footprints").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+    if let Some(f) = crate::support::s(args, "footprint").or_else(|| crate::support::s(args, "name")) { names.insert(0, f); }+    if names.is_empty() { return bad("footprint (or footprints: [...]) is required"); }+    let min = args.get("minMm").and_then(|v| v.as_f64()).unwrap_or(0.15);+    let mask = args.get("maskExpansionMm").and_then(|v| v.as_f64());+    if let Some(g) = crate::support::need_licensed() { return g; }+    if let Some(e) = crate::support::must_open(&lib, 60) { return e; }+    let mut results = Vec::new();+    let mut all_pass = true;+    let mut notes: Vec<String> = Vec::new();+    for name in &names {+        let r = crate::agent::call("fp_geometry", &[("path", lib.replace('/', "\\")), ("name", name.clone())], None, std::time::Duration::from_secs(90));+        let d = match crate::sch::agent_data(&r) { Ok(d) => d, Err(e) => { results.push(json!({"footprint": name, "error": e["error"], "errorCode": e["errorCode"]})); all_pass = false; continue; } };+        let (silk, copper, n) = parse(&d, mask, DEFAULT_MASK_MM);+        for x in n { if !notes.contains(&x) { notes.push(x); } }+        let pr = pairs(&silk, &copper);+        let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+        let item = |(c, i, j): &(f64, usize, usize)| {+            let side = if silk[*i].layer == 34 { "bottom" } else { "top" };+            json!({"clearanceMm": r3(*c), "silk": silk[*i].what, "side": side, "pad": copper[*j].pad, "overlaps": *c <= 1e-9})+        };+        let under: Vec<Value> = pr.iter().filter(|p| p.0 < min - 1e-9).map(item).collect();+        // one line per silk item and pad: its closest approach+        let mut seen = std::collections::HashSet::new();+        let under: Vec<Value> = under.into_iter().filter(|v| seen.insert((v["silk"].to_string(), v["pad"].to_string()))).collect();+        let pass = under.is_empty();+        if !pass { all_pass = false; }+        results.push(json!({"footprint": name, "result": if pass { "PASS" } else { "FAIL" }, "closest": pr.first().map(item), "under": under,+            "silkItems": silk.len(), "pads": copper.iter().map(|c| c.pad.clone()).collect::<std::collections::BTreeSet<_>>().len()}));+    }+    let unsaved = crate::project::has_changes(&lib) == Some(true);+    json!({"success": true, "result": if all_pass { "PASS" } else { "FAIL" }, "minMm": min,+        "maskExpansion": match mask { Some(m) => json!({"mm": m, "from": "the call"}), None => json!({"mm": DEFAULT_MASK_MM, "from": "each pad's own manual expansion, else Altium's default rule (4 mil)"}) },+        "footprints": results, "notes": notes, "unsavedChanges": unsaved,+        "_hint": if all_pass { "Every silkscreen item clears every pad's exposed copper by at least minMm." } else {+            "under lists each silkscreen item closer than minMm to a pad (its closest approach), overlaps when it touches the copper. Move or trim it (altium_edit_footprint graphics), then check again." }})+}++#[cfg(test)]+mod tests {+    use super::*;++    fn close(a: f64, b: f64) -> bool { (a - b).abs() < 1e-3 }++    #[test]+    fn a_line_beside_a_rectangular_pad() {+        // pad 1 x 1 at the origin; a 0.2 mm line 1 mm above its centre: 1 - 0.5 - 0.1 = 0.4+        let pad = pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.0);+        let line = Shape { core: Core::Line(vec![(-2.0, 1.0), (2.0, 1.0)]), r: 0.1 };+        assert!(close(clearance(&line, &pad), 0.4), "{}", clearance(&line, &pad));+        // the mask grows the copper by 0.05+        let masked = pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.05);+        assert!(close(clearance(&line, &masked), 0.35));+        // a line across the pad overlaps it+        let across = Shape { core: Core::Line(vec![(-2.0, 0.0), (2.0, 0.0)]), r: 0.1 };+        assert!(clearance(&across, &pad) < 0.0);+    }++    #[test]+    fn round_oval_and_rounded_pads() {+        // a 1 mm round pad, a point 1.5 mm away: 1.5 - 0.5 = 1.0+        let dot = Shape { core: Core::Line(vec![(1.5, 0.0)]), r: 0.0 };+        assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 1.0, 1.0, 0.0, 0.0, 0.0)), 1.0));+        // a 2 x 1 oval: its end is 1 mm out along x+        assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 2.0, 1.0, 0.0, 0.0, 0.0)), 0.5));+        // turned 90 degrees, the same point is 1.5 - 0.5 = 1.0 from the side+        assert!(close(clearance(&dot, &pad_shape((0.0, 0.0), 1, 2.0, 1.0, 0.0, 90.0, 0.0)), 1.0));+        // a 1 x 1 rounded rectangle at 50 %: corner radius 0.25; diagonally the corner is rounded, not square+        let diag = Shape { core: Core::Line(vec![(1.0, 1.0)]), r: 0.0 };+        let rr = clearance(&diag, &pad_shape((0.0, 0.0), 9, 1.0, 1.0, 50.0, 0.0, 0.0));+        let sq = clearance(&diag, &pad_shape((0.0, 0.0), 2, 1.0, 1.0, 0.0, 0.0, 0.0));+        assert!(close(sq, (0.5f64 * 0.5 * 2.0).sqrt()), "{sq}");+        assert!(close(rr, (0.75f64 * 0.75 * 2.0).sqrt() - 0.25), "{rr}");+    }++    #[test]+    fn arcs_and_texts() {+        // a 0.1 mm wide arc of radius 2 round a 1 mm round pad: 2 - 0.05 - 0.5 = 1.45+        let arc = Shape { core: Core::Line(arc_points((0.0, 0.0), 2.0, 0.0, 90.0)), r: 0.05 };+        assert!(close(clearance(&arc, &pad_shape((0.0, 0.0), 1, 1.0, 1.0, 0.0, 0.0, 0.0)), 1.45));+        // a text box holding the pad reads as overlapping+        let boxed = Shape { core: Core::Poly(vec![(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)]), r: 0.0 };+        assert!(clearance(&boxed, &pad_shape((0.0, 0.0), 2, 0.5, 0.5, 0.0, 0.0, 0.0)) <= 0.0, "touching or inside reads as no clearance");+    }++    #[test]+    fn geometry_from_the_agent() {+        // k = internal units per 1000 mil: 10_000_000 per inch+        let k = 10_000_000.0;+        let u = |mm: f64| (mm / 25.4 * k).round();+        let d = json!({"k": k, "pads": [["1", u(0.0), u(0.0), 0, 1, 2, u(1.0), u(1.0), 2, u(1.0), u(1.0), 0, 0, 0, 0, 0]],+            "tracks": [[33, u(-2.0), u(1.0), u(2.0), u(1.0), u(0.2)], [57, u(-2.0), u(0.6), u(2.0), u(0.6), u(0.2)]], "arcs": [], "texts": [], "fills": []});+        let (s, c, _) = parse(&d, Some(0.0), 0.1016);+        assert_eq!((s.len(), c.len()), (1, 1), "the mechanical line is not silkscreen");+        let p = pairs(&s, &c);+        assert!(close(p[0].0, 0.4), "{:?}", p[0].0);+        let (_, c2, _) = parse(&d, None, 0.1016);+        assert!(close(pairs(&s, &c2)[0].0, 0.4 - 0.1016), "the default mask expansion applies");+    }+}
bridge-rs/src/verbs.rs+17−2
@@ -37,7 +37,7 @@ pub const KNOWN: &[&str] = &[     "clone_symbol", "rename_symbol", "rename_footprint", "remove_symbol", "remove_footprint",     "copy_footprint", "xcopy_footprint", "swap_footprint", "symbol_mode", "cleanup_libs",     "install_library", "install_library_bundle", "install_receipt", "compile_intlib", "extract_intlib",-    "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "add_sim_model", "sim_copy", "selftest_script_error", "install",+    "place_on_sch", "place_on_pcb", "import_part", "add_symbol_art", "symbol_prims", "set_models", "add_sim_model", "sim_copy", "check_silkscreen", "add_dimensions", "selftest_script_error", "install",     // licence / account     "license", "license_status", "ensure_licensed", "setup_trial", "signin", "signin_status",     "connect_workspace",@@ -155,6 +155,19 @@ fn describe() -> Value {             &["set_models", "sch_place_part", "simulate", "sim_copy", "export_spice", "compile_intlib", "read_symbol"],             &["An encrypted model ($CDNENCSTART, as many PSpice packages are) is refused: only PSpice runs it.", "A vendor file's uncommented title line is dropped from the clean copy (SPICE reads a first line as a title).", "generic covers resistors, capacitors and inductors; switches and other passives are not attached.", "A generic part with no Value parameter cannot netlist: give it one.", "A MOSFET symbol with three pins ties the body to the source."],             json!({"libraryPath": "C:/lib/Diodes.SchLib", "symbolName": "1N4148WS", "modelPath": "C:/vendor/1N4148WS.lib"})),+        verb_doc("add_dimensions", "Put anchored linear dimensions on a library footprint: true Altium dimensions whose ends are bound to the footprint's pads and assembly-outline corners and follow them when they move (pitch, row span, body size, hole positions). Checked after the library is saved and reopened, and against the datasheet's value when given.",+            json!({"libraryPath": "the .PcbLib (required)", "footprint": "the footprint (required)", "dimensions": "[{a, b, dir: H (along x) | V (along y), at: the dimension line's y (H) or x (V) in mm from the origin, expect?: the datasheet's value in mm, toleranceMm?: default 0.01}] (required). a and b: a pad number (its centre), an assembly-outline corner TL, TR, BR, BL (a footprint made with fabOutline: edges has one), or {x, y} in mm where an outline line ends", "format": "{textHeightMm, textLineWidthMm, lineWidthMm, arrowSizeMm, arrowLengthMm, extensionOffsetMm, units: auto (whole mils when a multiple of 5 mil, else mm) | mm | mil, precision, font (a TrueType font name)}", "layerMap": "{dimensions: DimensionsTop, fab: AssemblyTop} optional: the dimensions' layer and the outline's; else the library's or your map, else Mechanical 13", "dryRun": "bool: resolve the anchors and the texts, change nothing"}),+            json!({"dimensions": "[{a, b, dir, lengthMm, text, anchors, valueMm, validAfterReopen, check: MATCH | MISMATCH (with expect), deltaMm}]", "layer": "the dimensions' layer", "outlineLayer": "where corners were looked for", "allDimensions": "int: dimensions on the footprint now", "rebuilt": "{moved, bodies}", "anyMismatch": "bool", "saved": "true: the library is saved"}), 300,+            "Altium will not anchor a dimension a script makes, so the footprint is copied onto a work board saved as ASCII, the dimensions are written in bound to those primitives, Altium validates them, and the footprint is rebuilt from the work board's own instances (pads, tracks and dimensions together), then saved, closed and reopened to read the references back. The footprint keeps its name, description, height, 3D bodies and every primitive.",+            &["footprint_from_land_pattern", "read_footprint", "layer_map", "check_silkscreen"],+            &["A chamfered outline corner is not the end of a line: build the footprint with fabOutline: edges to dimension its corners.", "Boards that already use the footprint keep their copy: update them with swap_footprint.", "The footprint's primitives get new unique ids (it is rebuilt)."],+            json!({"libraryPath": "C:/lib/Parts.PcbLib", "footprint": "SOIC8", "dimensions": [{"a": "1", "b": "8", "dir": "H", "at": 3.5, "expect": 5.4}, {"a": "1", "b": "2", "dir": "V", "at": -4.0, "expect": 1.27}, {"a": "TL", "b": "TR", "dir": "H", "at": 3.0, "expect": 3.9}]})),+        verb_doc("check_silkscreen", "Check a library footprint's silkscreen against its pads: the edge-to-edge clearance between every overlay line, arc, text and fill and each pad's exposed copper (the pad grown by its solder mask expansion), with the closest pair and PASS or FAIL against a minimum.",+            json!({"libraryPath": "the .PcbLib (required)", "footprint": "the footprint (or footprints: [names]) (required)", "minMm": "the minimum clearance, default 0.15", "maskExpansionMm": "the mask expansion to grow every pad by; default each pad's own manual expansion, else Altium's default rule (0.1016 mm, 4 mil)"}),+            json!({"result": "PASS | FAIL", "footprints": "[{footprint, result, closest: {clearanceMm, silk, side, pad, overlaps}, under: [the same, for every silkscreen item closer than minMm to a pad], silkItems, pads}]", "maskExpansion": "{mm, from}", "notes": "[how a shape was measured]", "unsavedChanges": "bool: the library has changes not yet saved (they are measured too)"}), 120,+            "Top overlay is checked against copper on the top (top and through-hole pads), bottom overlay against the bottom. Round, oval, rectangular and rounded-rectangle pads are measured exactly; an octagon as its rectangle; a text by its bounding box. Fix a FAIL with altium_edit_footprint graphics and check again.",+            &["read_footprint", "edit_footprint", "footprint_from_land_pattern"], &["The footprint builders trim silkscreen while drawing; this verb checks the result as it is, after any edits."],+            json!({"libraryPath": "C:/lib/Parts.PcbLib", "footprint": "SOIC8", "minMm": 0.15})),         verb_doc("sim_copy", "Make a simulation copy of a design's sheets and put sources and loads on it, so a schematic drawn for the board (no stimulus, no load) simulates in Altium while the design stays untouched: voltage and current sources (DC, AC, sine, pulse, piecewise linear) and R, C, L loads, each joined to its nets, and Altium's generic model on every R, C and L that has none. The copy's netlist is read back to prove each source sits on its net.",             json!({"schematic": "the .SchDoc to simulate (filePath works too); it must belong to a .PrjPcb beside it (required)", "sources": "[{type?: voltage|current (default voltage), plus: net or Ref.Pin (R1.2), minus?: net (default GND), dc?, ac?: magnitude | {magnitude, phase}, sin?: {offset?, amplitude, frequency, delay?, damping?, phase?} | pulse?: {initial?, pulsed, delay?, rise?, fall?, width, period} | pwl?: [[time, value], ...], designator?: V.../I... (default VSIM1, ISIM1, ...)}]: values are numbers or SPICE values (10k, 4.7u)", "loads": "[{type?: resistor|capacitor|inductor (default resistor), value, plus, minus?: GND, ic?, designator? (default RSIM1, CSIM1, ...)}]", "genericPassives": "bool, default true: every R, C and L of the copy with no simulation model gets Altium's generic one (its Value parameter, else its comment)", "copyDir": "folder for the copy (default AdomSim\\<project> beside the project); rebuilt on every call, and refused when it holds files this verb did not make"}),             json!({"copy": "{project, schematic, dir}: simulate copy.schematic (the sheets are renamed <name>_sim.SchDoc)", "closedCopies": "[other simulation copies this verb made that Altium still held, saved and closed]", "parts": "[{designator, kind, subKind, plus, minus, spice: the SPICE element as Altium netlists it (VVSIM1 IN 0 DC 12: the prefix before the designator, GND as node 0), atMil}]", "checks": "[{pin, want, net, otherPins, ok}]: each source and load pin in the compiled netlist", "genericPassives": "[{designator, kind, value, from: value|comment, result: ok|has_model|no_value|not_two_pins}]", "passivesWithoutValue": "[the R, C, L that could not get a model]"}), 300,@@ -1409,7 +1422,7 @@ fn describe() -> Value {                    "pitch": "mm", "span": "mm, pad centre to pad centre across the rows (quad: left-right)", "spanY": "quad, top-bottom (default span)",                    "padLength": "mm, along the lead (across the row)", "padWidth": "mm, along the row", "ballPad": "bga pad diameter mm", "rows": "bga", "cols": "bga", "missing": "bga ['B2', ...]",                    "exposedPad": "{w, h, x?, y?, number?}", "body": "{w, l, height?, standoff?} mm - silkscreen, fab, courtyard, 3D",-                   "padShape": "roundrect (default) | rect | round | oval", "polarized": "chip: add the pin-1 dot", "courtyard": "margin mm, default 0.25", "silkWidth": "default 0.15", "silkClearance": "default 0.2", "description": "optional", "dryRun": "bool - return the pad table and spec only"}),+                   "padShape": "roundrect (default) | rect | round | oval", "fabOutline": "chamfer (default: one outline with the pin-1 corner cut) | edges (four lines meeting at the body corners and the chamfer as its own line, so altium_add_dimensions can anchor to the corners; the reply's summary.fabOutline gives the corners)", "polarized": "chip: add the pin-1 dot", "courtyard": "margin mm, default 0.25", "silkWidth": "default 0.15", "silkClearance": "default 0.2", "description": "optional", "dryRun": "bool - return the pad table and spec only"}),             json!({"summary": "{pads, courtyardMm, silkLines, padTable:[[name, x, y, w, h]]}", "spec": "the staged spec path", "body3d": "{success}", "shot": "{image}"}), 300,             "dryRun first and compare padTable with the datasheet drawing; then build, check shot.image, altium_save the library and link it with altium_set_models.",             &["build_footprint", "create_footprint", "add_body", "set_models", "save", "show_footprint"],@@ -2401,6 +2414,8 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "set_models" => library::set_models(args),         "add_sim_model" => crate::simmodel::add_sim_model(args),         "sim_copy" => crate::simcopy::sim_copy(args),+        "check_silkscreen" => crate::silkcheck::check_silkscreen(args),+        "add_dimensions" => crate::dimensions::add_dimensions(args),         "place_on_pcb" => library::place_on_pcb(args),         "import_part" => library::import_part(args),         // ---- licence / account ----
dev-skills/altium-bridge-test/run_verb_tests.py+6
@@ -172,6 +172,12 @@ def matrix(w):     M["footprint_from_land_pattern"] = dict(phase=2, timeout=320, **ok(libraryPath=PL, name="BAT_QFN16", family="quad", pins=16, pitch=0.5, span=3.0,                                                                         padLength=0.8, padWidth=0.25, exposedPad={"w": 1.7, "h": 1.7}, body={"w": 3, "l": 3, "height": 0.9}),                                             check=lambda d: (d.get("summary") or {}).get("pads") == 17 and (d.get("body3d") or {}).get("success") is not False)+    # 0.2.121 (#43): the QFN's silkscreen measured against its pads (the builder trims to 0.2 mm from bare copper), and an+    # anchored dimension across pins 1 to 4 (3 x 0.5 mm pitch) that must validate after the library is reopened+    M["check_silkscreen"] = dict(phase=2, **ok(libraryPath=PL, footprint="BAT_QFN16", minMm=0.15, maskExpansionMm=0),+                                 check=lambda d: d.get("result") == "PASS" and abs(((d.get("footprints") or [{}])[0].get("closest") or {}).get("clearanceMm", 0) - 0.2) < 0.01)+    M["add_dimensions"] = dict(phase=2, timeout=400, **ok(libraryPath=PL, footprint="BAT_QFN16", dimensions=[{"a": "1", "b": "4", "dir": "V", "at": -3.0, "expect": 1.5}]),+                               check=lambda d: all(x.get("validAfterReopen") and x.get("check") == "MATCH" for x in d.get("dimensions") or [{}]))     M["copy_footprint"] = dict(phase=2, **ok(libraryPath=PL, **{"from": "BAT_FP", "to": "BAT_FP_COPY"}))     M["rename_footprint"] = dict(phase=2, **ok(libraryPath=PL, **{"from": "BAT_FP_COPY", "to": "BAT_FP_RENAMED"}))     M["remove_footprint"] = dict(phase=2, **ok(libraryPath=PL, footprintName="BAT_FP_RENAMED"))
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.120",+  "version": "0.2.121",   "type": "app",   "description": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",   "tags": [
page.json+2−2
@@ -4,7 +4,7 @@   "type": "app",   "title": "Altium Bridge: AI for Altium Designer",   "brief": "Let an AI (Claude, ChatGPT, Codex or any agent) run Altium Designer for you: create symbols and footprints, place parts (also from Altium 365), wire and annotate schematics, Update PCB, set the stack-up and rules, route, pour copper, add mounting holes and stitching vias, run ERC and DRC, and make Gerbers, BOMs and STEP. Free in Hydrogen; bring your own AI and Altium licence.",-  "version": "0.2.120",+  "version": "0.2.121",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -159,4 +159,4 @@     "tools/symbol_modes.py",     "uninstall.sh"   ]-}\ No newline at end of file+}
scripts/release.py+8−2
@@ -230,8 +230,14 @@ def lint_agent_script():     # (2026-11-30, #41). Out is a parameter modifier in DelphiScript.     for m in re.finditer(r"(?:\(|;)\s*(?:Var\s+|Const\s+)?(Out|Type|Label)\s*:\s*[A-Za-z]", code, flags=re.I):         hits.append(f"reserved word {m.group(1)} named as a parameter  ->  ...{code[max(0, m.start() - 40):m.end() + 20].strip()}...")-    for m in re.finditer(r"^\s+(Out|Type|Label)\s*(?:,[^:\n]*)?:\s*[A-Za-z]", code, flags=re.M | re.I):-        hits.append(f"reserved word {m.group(1)} named as a variable  ->  ...{code[max(0, m.start() - 10):m.end() + 20].strip()}...")+    # every name of a declaration line (A, B, AS : String;), not only the first: a variable named AS (the as operator)+    # stopped the agent compiling (2026-12-02, #43)+    reserved = {"out", "type", "label", "as", "is", "in", "of", "do", "to", "or", "and", "not", "div", "mod", "shl", "shr", "xor",+                "set", "file", "array", "record", "with", "case", "var", "const", "nil", "repeat", "until", "downto", "goto", "object", "class"}+    for m in re.finditer(r"^\s+([A-Za-z_][A-Za-z0-9_]*(?:\s*,\s*[A-Za-z_][A-Za-z0-9_]*)*)\s*:\s*[A-Za-z]", code, flags=re.M):+        for name in [n.strip() for n in m.group(1).split(",")]:+            if name.lower() in reserved:+                hits.append(f"reserved word {name} named as a variable  ->  ...{code[max(0, m.start() - 10):m.end() + 20].strip()}...")     if hits:         raise SystemExit("agent template uses engine-halting identifiers (see ENGINE_HALTING):\n  " + "\n  ".join(hits)) 
skills/altium-libraries/SKILL.md+34
@@ -230,6 +230,40 @@ altium_footprint_from_land_pattern '{"libraryPath":"C:\\lib\\Parts.PcbLib","name - `dryRun:true` returns the pad table (name, x, y, w, h) and the spec without Altium: compare it with the datasheet   drawing first. +## Dimensions, silkscreen clearance and the edges outline (0.2.121, #43)++```bash+altium_footprint_from_land_pattern '{"libraryPath":"C:/lib/Parts.PcbLib","name":"SOIC8","family":"dual","pins":8,"pitch":1.27,"span":5.4,"padLength":1.55,"padWidth":0.6,"body":{"w":3.9,"l":4.9},"fabOutline":"edges"}'+altium_add_dimensions '{"libraryPath":"C:/lib/Parts.PcbLib","footprint":"SOIC8","dimensions":[{"a":"1","b":"8","dir":"H","at":3.5,"expect":5.4},{"a":"1","b":"2","dir":"V","at":-4.2,"expect":1.27},{"a":"TL","b":"TR","dir":"H","at":3.0,"expect":3.9}]}'+altium_check_silkscreen '{"libraryPath":"C:/lib/Parts.PcbLib","footprint":"SOIC8","minMm":0.15}'+```++- **`fabOutline: "edges"`** draws the assembly outline as four lines meeting at the body's corners (TL, TR, BR, BL;+  the reply's `summary.fabOutline` gives them) with the pin-1 chamfer as a line of its own. The default outline is one+  polyline with the pin-1 corner cut off, so that corner is no line's end and nothing can be anchored to it.+- **`altium_add_dimensions`** puts true anchored linear dimensions on a library footprint: each end is bound to a pad+  (its centre), an outline corner (`TL` ... `BL`) or `{x, y}` where an outline line ends, and follows it when it+  moves (measured: pad 8 moved 0.5 mm, the 5.40 mm dimension read 5.90). `dir` H measures along x and V along y; `at`+  is where the dimension line runs (its y for H, its x for V, mm). `expect` (the datasheet's value) answers MATCH or+  MISMATCH within `toleranceMm` (0.01). `format`: text height, line widths, arrows, extension offset, `units: auto`+  (whole mils when the length is a multiple of 5 mil, else mm to 2 decimals), `mm` or `mil`. The dimensions go on the+  layer map's `dimensions` layer (a typed DimensionsTop is made if missing), else Mechanical 13; corners are looked for+  on the map's `fab` layer.+- How: Altium will not anchor a dimension a script makes. The footprint is copied onto a work board saved as Altium's+  ASCII PcbDoc, the dimensions are written in bound to those primitives (as the issue's reporter proved), Altium+  validates them, and the footprint is rebuilt from the work board's own instances (pads, lines and dimensions together:+  dimensions moved alone were saved as bare points that did not follow a pad). The library is saved, closed and+  reopened, and `validAfterReopen` is read back. The footprint keeps every primitive, its name, description, height and+  3D bodies (compared primitive by primitive with a twin). A second call keeps the earlier dimensions and binds them+  again. Boards that use the footprint keep their copy until `altium_swap_footprint`.+- **`altium_check_silkscreen`** measures, on the footprint as Altium holds it, the edge-to-edge clearance between every+  overlay line, arc, text and fill and each pad's exposed copper: the pad grown by `maskExpansionMm`, else its own+  manual expansion, else Altium's default rule (4 mil). Round, oval, rectangular and rounded-rectangle pads are exact;+  an octagon is taken as its rectangle and a text as its box. It answers the closest pair, every pair under `minMm`+  and PASS/FAIL. The footprint builders trim silkscreen 0.2 mm from the bare copper, so with the default 4 mil mask+  opening a built SOIC-8 reads 0.143 mm and fails a 0.15 mm rule: pass `silkClearance` wider when your rule counts+  the mask.+ ## A part on its own: read, show, export, a demo project (0.2.77)  - `altium_read_footprint {libraryPath, name}`: pads (number, position, size, shape, layers, hole), the layers used and
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.120+0.2.121
src/agent/AdomAgent.pas.tmpl+307
@@ -12104,6 +12104,309 @@ Begin     Result := '{' + JRaw('ok','true') + ',' + JRaw('renamed', IntToStr(N)) + '}'; End; +{ fp_geometry (#43): a library footprint's exact geometry, from its origin, internal units: pads [name, x, y,+  rotation*1000, layer, topShape, topX, topY, botShape, botX, botY, topCR%, botCR%, hole, maskExpansion, maskManual],+  tracks [layer, x1, y1, x2, y2, width], arcs [layer, cx, cy, r, startDeg*1000, endDeg*1000, width], texts [layer,+  left, bottom, right, top, "text"] (the bounding box) and fills [layer, x1, y1, x2, y2, rotation*1000].+  altium_check_silkscreen measures from it. }+Function CmdFpGeometry(Lines : TStringList) : String;+Var+    LibErr, Nm, PS, TS, ArS, XS, FS : String;+    PLib  : IPCB_Library;+    Fp    : IPCB_LibComponent;+    GIt   : IPCB_GroupIterator;+    Prim  : IPCB_Primitive;+    Pad   : IPCB_Pad;+    PC    : TPadCache;+    I, OX, OY, Man, CRT, CRB : Integer;+    R : TCoordRect;+Begin+    LibErr := CurrentLibAt(Param(Lines, 'path'));+    If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End;+    PLib := PCBServer.GetCurrentPCBLibrary;+    If PLib = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_a_pcblib') + ',' + JStr('error','the current document is not a PCB library') + '}'; Exit; End;+    Nm := Param(Lines, 'name'); Fp := Nil;+    For I := 0 To PLib.ComponentCount - 1 Do+        If UpperCase(PLib.GetComponent(I).Name) = UpperCase(Nm) Then Begin Fp := PLib.GetComponent(I); Break; End;+    If Fp = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Nm + ' in this library') + '}'; Exit; End;+    If PLib.CurrentComponent <> Fp Then Begin PLib.CurrentComponent := Fp; PLib.Board.ViewManager_FullUpdate; End;+    OX := PLib.Board.XOrigin; OY := PLib.Board.YOrigin;+    PS := ''; TS := ''; ArS := ''; XS := ''; FS := '';+    GIt := Fp.GroupIterator_Create;+    GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    Prim := GIt.FirstPCBObject;+    While Prim <> Nil Do+    Begin+        If Prim.ObjectId = ePadObject Then+        Begin+            Pad := Prim;+            Man := 0;+            Try PC := Pad.GetState_Cache; If PC.SolderMaskExpansionValid = eCacheManual Then Man := 1; Except End;+            CRT := 0; CRB := 0;+            Try CRT := Pad.GetState_StackCRPctOnLayer(eTopLayer); Except End;+            Try CRB := Pad.GetState_StackCRPctOnLayer(eBottomLayer); Except End;+            If PS <> '' Then PS := PS + ',';+            PS := PS + '["' + JsonEsc(Pad.Name) + '",' + IntToStr(Pad.x - OX) + ',' + IntToStr(Pad.y - OY) + ',' + IntToStr(Round(Pad.Rotation * 1000)) + ',' ++                IntToStr(Pad.Layer) + ',' + IntToStr(Pad.TopShape) + ',' + IntToStr(Pad.TopXSize) + ',' + IntToStr(Pad.TopYSize) + ',' ++                IntToStr(Pad.BotShape) + ',' + IntToStr(Pad.BotXSize) + ',' + IntToStr(Pad.BotYSize) + ',' + IntToStr(CRT) + ',' + IntToStr(CRB) + ',' ++                IntToStr(Pad.HoleSize) + ',' + IntToStr(Pad.SolderMaskExpansion) + ',' + IntToStr(Man) + ']';+        End+        Else If Prim.ObjectId = eTrackObject Then+        Begin+            If TS <> '' Then TS := TS + ',';+            TS := TS + '[' + IntToStr(Prim.Layer) + ',' + IntToStr(Prim.X1 - OX) + ',' + IntToStr(Prim.Y1 - OY) + ',' + IntToStr(Prim.X2 - OX) + ',' + IntToStr(Prim.Y2 - OY) + ',' + IntToStr(Prim.Width) + ']';+        End+        Else If Prim.ObjectId = eArcObject Then+        Begin+            If ArS <> '' Then ArS := ArS + ',';+            ArS := ArS + '[' + IntToStr(Prim.Layer) + ',' + IntToStr(Prim.XCenter - OX) + ',' + IntToStr(Prim.YCenter - OY) + ',' + IntToStr(Prim.Radius) + ',' ++                IntToStr(Round(Prim.StartAngle * 1000)) + ',' + IntToStr(Round(Prim.EndAngle * 1000)) + ',' + IntToStr(Prim.LineWidth) + ']';+        End+        Else If Prim.ObjectId = eTextObject Then+        Begin+            R := Prim.BoundingRectangle;+            If XS <> '' Then XS := XS + ',';+            XS := XS + '[' + IntToStr(Prim.Layer) + ',' + IntToStr(R.Left - OX) + ',' + IntToStr(R.Bottom - OY) + ',' + IntToStr(R.Right - OX) + ',' + IntToStr(R.Top - OY) + ',"' + JsonEsc(Prim.Text) + '"]';+        End+        Else If Prim.ObjectId = eFillObject Then+        Begin+            If FS <> '' Then FS := FS + ',';+            FS := FS + '[' + IntToStr(Prim.Layer) + ',' + IntToStr(Prim.X1Location - OX) + ',' + IntToStr(Prim.Y1Location - OY) + ',' + IntToStr(Prim.X2Location - OX) + ',' + IntToStr(Prim.Y2Location - OY) + ',' + IntToStr(Round(Prim.Rotation * 1000)) + ']';+        End;+        Prim := GIt.NextPCBObject;+    End;+    Fp.GroupIterator_Destroy(GIt);+    Result := '{' + JRaw('ok','true') + ',' + JStr('name', Fp.Name) + ',' + JRaw('k', IntToStr(MilsToCoord(1000))) + ',' ++        JRaw('pads', '[' + PS + ']') + ',' + JRaw('tracks', '[' + TS + ']') + ',' + JRaw('arcs', '[' + ArS + ']') + ',' + JRaw('texts', '[' + XS + ']') + ',' + JRaw('fills', '[' + FS + ']') + '}';+End;++{ ---- altium_add_dimensions (#43): anchored dimensions on a library footprint, the route the reporter proved.+  A dimension made by script comes out unanchored (its reference setters do not stick), so: the footprint's primitives+  are copied onto a work board saved as ASCII (dim_work); the bridge writes the dimensions into that file pointing at+  those primitives (PRIM = their INDEXFORSAVE, ANCHOR 1 a pad's centre or a track's X1/Y1 end, 2 its X2/Y2 end);+  Altium opens it and validates them; then the footprint is rebuilt from the work board's own instances, moved through+  the library's board (dim_apply): pads, tracks and the dimensions travel together, so the references stay bound+  (moving only the dimensions saved them as bare points that did not follow a pad, measured 2026-12-02). A registered+  footprint ignores primitives removed from it, so a new one is made and takes the old one's name. }++{ An object's key for dim_work's skip list: type, layer and box from the board's origin. }+Function DimObjKey(B : IPCB_Board; P : IPCB_Primitive) : String;+Var+    R : TCoordRect;+Begin+    R := P.BoundingRectangle;+    Result := IntToStr(P.ObjectId) + ':' + IntToStr(P.Layer) + ':' + IntToStr(R.Left - B.XOrigin) + ',' + IntToStr(R.Bottom - B.YOrigin) + ',' + IntToStr(R.Right - B.XOrigin) + ',' + IntToStr(R.Top - B.YOrigin);+End;++{ dim_work: path= the PcbLib, name= the footprint, work= the ASCII board to write, lcode= the dimensions layer's map+  code (resolved in the library: a typed layer made if missing). Every primitive but 3D bodies is copied onto a new+  board from the board's origin, with the footprint's existing dimensions; the board is saved as ASCII and closed. }+Function CmdDimWork(Lines : TStringList) : String;+Var+    LibErr, Work : String;+    PLib : IPCB_Library;+    Fp : IPCB_LibComponent;+    Doc : IServerDocument;+    W : IPCB_Board;+    GI : IPCB_GroupIterator;+    BI : IPCB_BoardIterator;+    P, C : IPCB_Primitive;+    Skip : String;+    DX, DY, N, ND, DimL, FabL : Integer;+Begin+    LibErr := CurrentLibAt(Param(Lines, 'path'));+    If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End;+    PLib := PCBServer.GetCurrentPCBLibrary;+    Fp := FindFp(PLib, Param(Lines, 'name'));+    If Fp = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Param(Lines, 'name')) + '}'; Exit; End;+    { the dimensions' layer, made in the library first: the work board's dimensions carry its id }+    DimL := 0;+    If Param(Lines, 'lcode') <> '' Then DimL := ResolveLayerCode(PLib.Board, Param(Lines, 'lcode'));+    If DimL <= 0 Then DimL := eMechanical13;+    { the assembly outline's layer, where corner anchors are looked for }+    FabL := 0;+    If Param(Lines, 'fcode') <> '' Then FabL := ResolveLayerCode(PLib.Board, Param(Lines, 'fcode'));+    If FabL <= 0 Then FabL := eMechanical13;+    If DimL = eMechanical13 Then PLib.Board.LayerStack.LayerObject[eMechanical13].MechanicalLayerEnabled := True;+    If PLib.CurrentComponent <> Fp Then Begin PLib.CurrentComponent := Fp; PLib.Board.ViewManager_FullUpdate; End;+    Work := Param(Lines, 'work');+    Doc := CreateNewDocumentFromDocumentKind('PCB');+    Client.ShowDocument(Doc);+    W := PCBServer.GetCurrentPCBBoard;+    DX := W.XOrigin - PLib.Board.XOrigin; DY := W.YOrigin - PLib.Board.YOrigin;+    PCBServer.PreProcess;+    { a new board starts with objects of its own (its board-shape region, a small one at the origin) that Altium will+      not remove: they are listed (skip), and dim_apply leaves them behind (the rebuild carried them into the footprint,+      measured 2026-12-02) }+    Skip := '';+    BI := W.BoardIterator_Create;+    BI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    BI.AddFilter_Method(eProcessAll);+    P := BI.FirstPCBObject;+    While P <> Nil Do Begin Skip := Skip + DimObjKey(W, P) + ';'; P := BI.NextPCBObject; End;+    W.BoardIterator_Destroy(BI);+    N := 0;+    GI := Fp.GroupIterator_Create;+    GI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    P := GI.FirstPCBObject;+    While P <> Nil Do+    Begin+        If P.ObjectId <> eComponentBodyObject Then+        Begin+            C := P.Replicate;+            C.MoveByXY(DX, DY);+            W.AddPCBObject(C);+            N := N + 1;+        End;+        P := GI.NextPCBObject;+    End;+    Fp.GroupIterator_Destroy(GI);+    { the footprint's own dimensions live on the library's board while it is shown }+    ND := 0;+    BI := PLib.Board.BoardIterator_Create;+    BI.AddFilter_ObjectSet(MkSet(eDimensionObject));+    BI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    P := BI.FirstPCBObject;+    While P <> Nil Do+    Begin+        C := P.Replicate;+        C.MoveByXY(DX, DY);+        W.AddPCBObject(C);+        ND := ND + 1;+        P := BI.NextPCBObject;+    End;+    PLib.Board.BoardIterator_Destroy(BI);+    PCBServer.PostProcess;+    FreePath(Work);+    Doc.SetFileName(Work);+    Doc.DoFileSave('PCB ASCII File');+    If Not FileExists(Work) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_saved') + ',' + JStr('error','the work board did not save as ASCII to ' + Work) + '}'; Exit; End;+    Client.CloseDocument(Doc);+    Result := '{' + JRaw('ok','true') + ',' + JRaw('primitives', IntToStr(N)) + ',' + JRaw('existingDimensions', IntToStr(ND)) + ',' + JRaw('dimLayer', IntToStr(DimL)) + ',' ++        JRaw('dimMech', IntToStr(MechLayerNo(DimL))) + ',' + JRaw('fabMech', IntToStr(MechLayerNo(FabL))) + ',' + JStr('skip', Skip) + ',' + JRaw('offsetMil', '[' + IntToStr(Round(CoordToMils(-DX))) + ',' + IntToStr(Round(CoordToMils(-DY))) + ']') + ',' + JStr('work', Work) + '}';+End;++{ The dimensions on a footprint, read while it is shown: [valid, value (internal units), layer, refs]. }+Function FpDimsJson(PLib : IPCB_Library) : String;+Var+    BI : IPCB_BoardIterator;+    D : IPCB_Primitive;+Begin+    Result := '';+    BI := PLib.Board.BoardIterator_Create;+    BI.AddFilter_ObjectSet(MkSet(eDimensionObject));+    BI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    D := BI.FirstPCBObject;+    While D <> Nil Do+    Begin+        If Result <> '' Then Result := Result + ',';+        Result := Result + '[' + JBool(D.References_Validate) + ',' + FloatToStr(D.TextValue) + ',' + IntToStr(D.Layer) + ',' + IntToStr(D.References_Count) + ']';+        D := BI.NextPCBObject;+    End;+    PLib.Board.BoardIterator_Destroy(BI);+    Result := '[' + Result + ']';+End;++{ dim_apply: path=, name=, work= (the ASCII board with the dimensions written in). The footprint is rebuilt from the work+  board's instances: a new footprint is registered and shown, every top-level object of the work board (a dimension's+  own lines and texts travel inside it) is moved onto the library's board, the old footprint's 3D bodies are copied+  over, its description and height kept; then the old footprint goes and the new one takes its name. }+Function CmdDimApply(Lines : TStringList) : String;+Var+    LibErr, Nm : String;+    PLib : IPCB_Library;+    Old, NewC : IPCB_LibComponent;+    WDoc : IServerDocument;+    W : IPCB_Board;+    BI : IPCB_BoardIterator;+    GI : IPCB_GroupIterator;+    P : IPCB_Primitive;+    Ps, Bodies : TInterfaceList;+    I, DX, DY, NM2 : Integer;+Begin+    LibErr := CurrentLibAt(Param(Lines, 'path'));+    If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End;+    PLib := PCBServer.GetCurrentPCBLibrary;+    Nm := Param(Lines, 'name');+    Old := FindFp(PLib, Nm);+    If Old = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Nm) + '}'; Exit; End;+    WDoc := Client.OpenDocument('PCB', Param(Lines, 'work'));+    W := PCBServer.GetPCBBoardByPath(Param(Lines, 'work'));+    If W = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','work_board_unreadable') + ',' + JStr('error','Altium could not open the work board ' + Param(Lines, 'work')) + '}'; Exit; End;+    { the old footprint's 3D bodies, replicated while it is shown (they are not on the work board) }+    If PLib.CurrentComponent <> Old Then Begin PLib.CurrentComponent := Old; PLib.Board.ViewManager_FullUpdate; End;+    Bodies := TInterfaceList.Create;+    GI := Old.GroupIterator_Create;+    GI.AddFilter_ObjectSet(MkSet(eComponentBodyObject));+    GI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    P := GI.FirstPCBObject;+    While P <> Nil Do Begin Bodies.Add(P.Replicate); P := GI.NextPCBObject; End;+    Old.GroupIterator_Destroy(GI);+    Ps := TInterfaceList.Create;+    BI := W.BoardIterator_Create;+    BI.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);+    BI.AddFilter_Method(eProcessAll);+    P := BI.FirstPCBObject;+    While P <> Nil Do+    Begin+        { a board's own regions on the multi-layer (its shape, a small one at the origin) are made when it opens and are+          in no record: one goes only when the file holds such a region (multiRegions=1, the footprint's own) }+        If (Not P.InDimension) And (Pos(';' + DimObjKey(W, P) + ';', ';' + Param(Lines, 'skip')) = 0) And+           Not ((P.ObjectId = eRegionObject) And (P.Layer = eMultiLayer) And (Param(Lines, 'multiRegions') <> '1')) Then Ps.Add(P);+        P := BI.NextPCBObject;+    End;+    W.BoardIterator_Destroy(BI);+    NewC := PCBServer.CreatePCBLibComp;+    NewC.Name := Nm + '__adom_dim';+    NewC.Description := Old.Description;+    NewC.Height := Old.Height;+    PLib.RegisterComponent(NewC);+    PLib.CurrentComponent := NewC; PLib.Board.ViewManager_FullUpdate;+    DX := PLib.Board.XOrigin - W.XOrigin; DY := PLib.Board.YOrigin - W.YOrigin;+    PCBServer.PreProcess;+    NM2 := 0;+    For I := 0 To Ps.Count - 1 Do+    Begin+        P := Ps[I];+        W.RemovePCBObject(P);+        P.MoveByXY(DX, DY);+        PLib.Board.AddPCBObject(P);+        PCBServer.SendMessageToRobots(PLib.Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, P.I_ObjectAddress);+        NM2 := NM2 + 1;+    End;+    For I := 0 To Bodies.Count - 1 Do+    Begin+        P := Bodies[I];+        PLib.Board.AddPCBObject(P);+        PCBServer.SendMessageToRobots(PLib.Board.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, P.I_ObjectAddress);+    End;+    PCBServer.PostProcess;+    PLib.Board.ViewManager_FullUpdate;+    PLib.RemoveComponent(Old);+    NewC.Name := Nm;+    PLib.CurrentComponent := NewC; PLib.Board.ViewManager_FullUpdate;+    { the emptied work board is scratch: saved before it closes, so no save prompt comes up }+    WDoc.DoFileSave('PCB ASCII File');+    Client.CloseDocument(WDoc);+    Result := '{' + JRaw('ok','true') + ',' + JRaw('moved', IntToStr(NM2)) + ',' + JRaw('bodies', IntToStr(Bodies.Count)) + ',' + JRaw('dims', FpDimsJson(PLib)) + '}';+End;++{ dim_read: path=, name=: the footprint's dimensions as Altium holds them (after a reopen: the proof). }+Function CmdDimRead(Lines : TStringList) : String;+Var+    LibErr : String;+    PLib : IPCB_Library;+    Fp : IPCB_LibComponent;+Begin+    LibErr := CurrentLibAt(Param(Lines, 'path'));+    If LibErr <> '' Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','library_not_current') + ',' + JStr('error', LibErr) + '}'; Exit; End;+    PLib := PCBServer.GetCurrentPCBLibrary;+    Fp := FindFp(PLib, Param(Lines, 'name'));+    If Fp = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','no footprint ' + Param(Lines, 'name')) + '}'; Exit; End;+    PLib.CurrentComponent := Fp; PLib.Board.ViewManager_FullUpdate;+    Result := '{' + JRaw('ok','true') + ',' + JRaw('k', IntToStr(MilsToCoord(1000))) + ',' + JRaw('dims', FpDimsJson(PLib)) + '}';+End;+ Function Dispatch(Cmd : String; Lines : TStringList; Payload : String) : String; Begin     If Cmd = 'ping' Then Result := CmdPing(Lines)@@ -12147,6 +12450,10 @@ Begin     Else If Cmd = 'sim_part' Then Result := CmdSimPart(Lines)     Else If Cmd = 'sim_generic' Then Result := CmdSimGeneric(Lines)     Else If Cmd = 'sim_refs' Then Result := CmdSimRefs(Lines, Payload)+    Else If Cmd = 'fp_geometry' Then Result := CmdFpGeometry(Lines)+    Else If Cmd = 'dim_work' Then Result := CmdDimWork(Lines)+    Else If Cmd = 'dim_apply' Then Result := CmdDimApply(Lines)+    Else If Cmd = 'dim_read' Then Result := CmdDimRead(Lines)     Else If Cmd = 'place_on_pcb' Then Result := CmdPlaceOnPcb(Lines)     Else If Cmd = 'pcb_report' Then Result := CmdPcbReport(Lines)     Else If Cmd = 'list_designators' Then Result := CmdListDesignators(Lines)
src/bridge.json+4−2
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.120",+  "version": "0.2.121",   "description": "Drive Altium Designer from Adom: a resident DelphiScript agent (eval + the 1,100-command process launcher), the X2 -R command line, UIA over the VCL shell, dialogs by PID, screenshots of every Altium window, and Altium 365.",   "homepage": "https://wiki.adom.inc/adom/altium-bridge",   "docs": "https://wiki.adom.inc/adom/altium-bridge",@@ -269,6 +269,8 @@     "altium_set_models",     "altium_add_sim_model",     "altium_sim_copy",+    "altium_add_dimensions",+    "altium_check_silkscreen",     "altium_set_outline",     "altium_set_params",     "altium_set_track_width",@@ -318,7 +320,7 @@       "eval": 600,       "panelize": 240,       "impedance": 120,-      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "sim_copy": 600, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600,+      "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "sim_copy": 600, "add_dimensions": 420, "check_silkscreen": 200, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600,       "height_check": 150,       "copper_balance": 240,       "return_path": 240,