← Commit history

0.2.119 source: footprint verbs stop creating 1024 mechanical layers (#44); layers only when used, edit_footprint widths and map-aware F.Fab (#43)

Colby Knox ·a86b045472 · ·parent 0dbc730
10 files changed +199−51
CHANGELOG.md+13
@@ -1,5 +1,18 @@ # Changelog +## 0.2.119++- **Footprint verbs no longer fill a library with 1024 mechanical layers** (#44). Looking a mechanical layer up by its number creates that layer in Altium, and the next save keeps it. The bridge searched for typed and named layers by looking up every number from 1 to 1024, so any library a footprint or layer-map verb touched came out with all 1024 mechanical layers. A fresh library's 56 layer records became 1048, its file grew from 108 KB to 1 MB, and the reporter saw Altium hang while attaching a STEP to such a library. The verbs now search only the library's enabled mechanical layers, which Altium lists without creating any, and make at most the one layer a graphic needs.+- A library that already has the extra layers can be repaired by copying its footprints into a fresh library (`altium_xcopy_footprint`): the copy carries only the layers its graphics use.+- **Mechanical 1, Mechanical 9 ("Adom.SolderBalls"), 13 and 15 are turned on only when a footprint draws on them** (#43). `altium_build_footprint` and the verbs built on it turned all four on for every footprint.+- **`altium_edit_footprint` graphics** (#43):+  - A shape's own `widthMm` is honoured; only the entry's was read.+  - `{type: "circle", filled: true}` draws a solid dot.+  - `F.Fab` and `F.CrtYd` follow the library's layer map (its `fab` and `courtyard` keys; `B.` takes the pair's bottom layer), as the footprint builders do. They always drew on Mechanical 13 and 15.+  - A layer can also be named by its kind (`AssemblyTop`, `DimensionsTop`, ...), made if the library has none.+  - The shape format is now in the altium-libraries skill.+- Tested on Altium Designer 26.11.1 and Develop. A QFN-16 from `altium_footprint_from_land_pattern` with a typed layer map leaves a fresh library at 56 layer records (0.2.118: 1048), with the same footprint. A library with Mechanical 1 turned off keeps it off. An `F.Fab` edit lands on Top Assembly with its own width.+ ## 0.2.118  - **Simulating no longer leaves your design asking to be saved** (reported by AI Flow). After `altium_sim_copy` and `altium_simulate`, closing Altium listed the original sheet and project as modified, though nothing in them had changed (the saved sheet was byte-for-byte the same). Three causes, each fixed:
bridge-rs/src/main.rs+1−1
@@ -89,7 +89,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.118";+pub const BRIDGE_VERSION: &str = "0.2.119";  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/project.rs+61−13
@@ -433,6 +433,25 @@ mod tests {     }  +    #[test]+    fn graphics_layers_follow_the_layer_map_and_shapes_keep_their_width() {+        // #43: with a map, F.Fab is the map's fab layer (B. the bottom of its pair); without one, Mechanical 13+        let map = vec![("fab".to_string(), "k1".to_string()), ("courtyard".to_string(), "k11".to_string())];+        assert_eq!(fp_graphics_layer("F.Fab", &map).as_deref(), Some("k1"));+        assert_eq!(fp_graphics_layer("B.Fab", &map).as_deref(), Some("k2"));+        assert_eq!(fp_graphics_layer("B.CrtYd", &map).as_deref(), Some("k12"));+        assert_eq!(fp_graphics_layer("F.Fab", &[]).as_deref(), Some("69"));+        assert_eq!(fp_graphics_layer("F.SilkS", &map).as_deref(), Some("33"));+        assert_eq!(fp_graphics_layer("AssemblyTop", &[]).as_deref(), Some("k1"));+        assert_eq!(fp_graphics_layer("Mechanical 13", &[]).as_deref(), Some("69"));+        assert_eq!(fp_graphics_layer("Mechanical20", &[]).as_deref(), Some("m20"));+        assert_eq!(fp_graphics_layer("L67108881", &[]).as_deref(), Some("67108881"));+        let (ops, _) = fp_ops(&json!({"graphics": [{"layer": "F.SilkS", "widthMm": 0.15, "shapes": [+            {"type": "line", "start": [0, 0], "end": [1, 0], "widthMm": 0.3}, {"type": "line", "start": [0, 1], "end": [1, 1]},+            {"type": "circle", "center": [0, 0], "radius": 0.2, "filled": true}]}]}), &[]).unwrap();+        assert_eq!(ops, ["GL|33|0|0|1|0|0.3", "GL|33|0|1|1|1|0.15", "GA|33|0|0|0.1|0.2|0|360"]);+    }+     #[test]     fn kinds_by_extension() {         assert_eq!(kind_of("a.PrjPcb"), "project");@@ -477,16 +496,36 @@ fn part_pieces(args: &Value) -> Result<(String, String, Option<String>, Option<S     Ok((part, lib, fp, fp_lib)) } -/// A footprint graphics layer by the standard's name: silkscreen, fab, courtyard, mask, paste, Mechanical<n> or L<id>.-fn fp_graphics_layer(l: &str) -> Option<i64> {-    Some(match l {-        "F.SilkS" | "F.Silkscreen" => 33, "B.SilkS" | "B.Silkscreen" => 34, "F.Paste" => 35, "B.Paste" => 36, "F.Mask" => 37, "B.Mask" => 38,-        // as this bridge builds footprints: Fab on Mechanical 13, Courtyard on Mechanical 15-        "F.Fab" | "B.Fab" => 69, "F.CrtYd" | "B.CrtYd" | "F.Courtyard" | "B.Courtyard" => 71,-        "F.Cu" => 1, "B.Cu" => 32,-        _ => return l.strip_prefix("Mechanical").and_then(|n| n.parse::<i64>().ok()).filter(|n| (1..=32).contains(n)).map(|n| 56 + n)-            .or_else(|| l.strip_prefix('L').and_then(|n| n.parse().ok())),-    })+/// A footprint graphics layer by the standard's name, as the agent's layer field: an Altium layer id, or a layer-map+/// code (`k1` a typed layer, made if the library has none). F.Fab and F.CrtYd follow the library's layer map (its+/// `fab` and `courtyard` keys, the B. side taking the bottom layer of a typed pair), as the footprint builders do;+/// without a map they stay on Mechanical 13 and 15, where this bridge builds them. A layer kind's name (AssemblyTop,+/// CourtyardTop) or a layer's name works too (#43: F.Fab drew on Mechanical 13 though the map said Top Assembly).+fn fp_graphics_layer(l: &str, map: &[(String, String)]) -> Option<String> {+    let mapped = |key: &str, bottom: bool| map.iter().find(|(k, _)| k == key).map(|(_, c)| {+        match c.strip_prefix('k').and_then(|k| k.parse::<i64>().ok()).and_then(crate::layermap::pair_of) {+            Some((_, top, bot)) if bottom => format!("k{}", if c == &format!("k{top}") { bot } else { top }),+            _ => c.clone(),+        }+    });+    let fixed = match l {+        "F.SilkS" | "F.Silkscreen" => Some(33), "B.SilkS" | "B.Silkscreen" => Some(34), "F.Paste" => Some(35), "B.Paste" => Some(36), "F.Mask" => Some(37), "B.Mask" => Some(38),+        "F.Cu" => Some(1), "B.Cu" => Some(32),+        _ => None,+    };+    if let Some(id) = fixed { return Some(id.to_string()); }+    match l {+        "F.Fab" => return Some(mapped("fab", false).unwrap_or_else(|| "69".into())),+        "B.Fab" => return Some(mapped("fab", true).unwrap_or_else(|| "69".into())),+        "F.CrtYd" | "F.Courtyard" => return Some(mapped("courtyard", false).unwrap_or_else(|| "71".into())),+        "B.CrtYd" | "B.Courtyard" => return Some(mapped("courtyard", true).unwrap_or_else(|| "71".into())),+        _ => {}+    }+    if let Some(n) = l.strip_prefix("Mechanical").and_then(|n| n.trim().parse::<i64>().ok()).filter(|n| (1..=1024).contains(n)) {+        return Some(if n <= 16 { (56 + n).to_string() } else { format!("m{n}") });+    }+    if let Some(id) = l.strip_prefix('L').and_then(|n| n.parse::<i64>().ok()) { return Some(id.to_string()); }+    crate::layermap::encode(&json!(l)).ok() }  fn xy(v: &Value) -> Option<(f64, f64)> { Some((v.get(0)?.as_f64()?, v.get(1)?.as_f64()?)) }@@ -540,9 +579,13 @@ pub(crate) fn fp_ops(args: &Value, pads_now: &[String]) -> Result<(Vec<String>,         for (i, (a, _)) in map.iter().enumerate() { ops.push(format!("PS|{a}|number|__adom{i}")); }         for (i, (_, b)) in map.iter().enumerate() { ops.push(format!("PS|__adom{i}|number|{b}")); }     }+    let lib = support::s(args, "libraryPath");+    let map: Vec<(String, String)> = if args.get("graphics").is_some() {+        crate::layermap_verb::effective(args, lib.as_deref()).entries.iter().map(|(k, _, c, _)| (k.clone(), c.clone())).collect()+    } else { Vec::new() };     for g in args.get("graphics").and_then(|v| v.as_array()).cloned().unwrap_or_default() {         let ln = g.get("layer").and_then(|v| v.as_str()).unwrap_or("");-        let lid = fp_graphics_layer(ln).ok_or_else(|| bad(format!("graphics layer {ln}: F.SilkS, F.Fab, F.CrtYd, F.Mask, F.Paste (or B.), Mechanical<n>, L<id>")))?;+        let lid = fp_graphics_layer(ln, &map).ok_or_else(|| bad(format!("graphics layer {ln}: F.SilkS, F.Fab, F.CrtYd, F.Mask, F.Paste (or B.), Mechanical<n>, L<id>, or a layer kind (AssemblyTop, CourtyardTop, ...)")))?;         let mode = g.get("mode").and_then(|v| v.as_str()).unwrap_or("append");         if !["append", "replace", "delete"].contains(&mode) { return Err(bad(format!("graphics mode {mode}: append, replace or delete"))); }         // shapes go in `shapes`: an entry with none drew nothing, and replace then only cleared the layer (#42)@@ -555,8 +598,10 @@ pub(crate) fn fp_ops(args: &Value, pads_now: &[String]) -> Result<(Vec<String>,         if !unknown.is_empty() { return Err(bad(format!("graphics on {ln}: {} not read; shapes go in shapes: [{{type, ...}}]; nothing was changed", unknown.join(", ")))); }         if mode == "replace" || mode == "delete" { ops.push(format!("GD|{lid}")); }         if mode == "delete" { continue; }-        let w = g.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(0.12);+        let gw = g.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(0.12);         for sh in g.get("shapes").and_then(|v| v.as_array()).cloned().unwrap_or_default() {+            // a shape's own widthMm beats the entry's (#43: it was ignored)+            let w = sh.get("widthMm").and_then(|v| v.as_f64()).unwrap_or(gw);             let line = |a: (f64, f64), b: (f64, f64)| format!("GL|{lid}|{}|{}|{}|{}|{w}", a.0, a.1, b.0, b.1);             match sh.get("type").and_then(|v| v.as_str()).unwrap_or("") {                 "line" => ops.push(line(sh.get("start").and_then(xy).ok_or_else(|| bad("a line needs start".into()))?, sh.get("end").and_then(xy).ok_or_else(|| bad("a line needs end".into()))?)),@@ -570,7 +615,10 @@ pub(crate) fn fp_ops(args: &Value, pads_now: &[String]) -> Result<(Vec<String>,                 }                 "circle" => {                     let c = sh.get("center").and_then(xy).ok_or_else(|| bad("a circle needs center".into()))?;-                    ops.push(format!("GA|{lid}|{}|{}|{}|{w}|0|360", c.0, c.1, f(sh.get("radius").unwrap_or(&json!(0)))));+                    let r = f(sh.get("radius").unwrap_or(&json!(0)));+                    // filled: a dot, drawn as a ring of half the radius as wide as the radius+                    if sh.get("filled").and_then(|v| v.as_bool()) == Some(true) { ops.push(format!("GA|{lid}|{}|{}|{}|{}|0|360", c.0, c.1, r / 2.0, r)); }+                    else { ops.push(format!("GA|{lid}|{}|{}|{}|{w}|0|360", c.0, c.1, r)); }                 }                 "arc" => {                     let c = sh.get("center").and_then(xy).ok_or_else(|| bad("an arc needs center, radius, startAngle, endAngle (degrees, counter-clockwise)".into()))?;
bridge-rs/src/verbs.rs+1−1
@@ -939,7 +939,7 @@ fn describe() -> Value {             json!({"stepPath": "path", "family": "string", "dimensionsMm": "{letter: mm}: every dimension used, defaults included", "bboxMm": "{x, y, z}", "solids": "int", "marking": "string | null", "families": "[string] (when family is unknown)"}), 60,             "The body is in the package's own frame (IPC-7351 zero orientation, pin 1 top-left, seated on z = 0), ready for add_body. Compare bboxMm with the datasheet's body size before attaching it.", &["add_body", "bodies", "export_step"], &["A wrong dimension gives a plausible but wrong body: nothing checks it against a datasheet.", "Written by the bridge, no CAD tool needed: plain prisms (round cans and balls are many-sided), a dark body and bright leads.", "A marking is real geometry in a segment font: very small text on a small package is unreadable, which is not an error; characters the font does not draw are listed under notApplied."], json!({"family": "soic", "dimensionsMm": {"pins": 8, "D": 4.9, "E1": 3.9, "E": 6.0, "A": 1.75, "e": 1.27}, "outputPath": "C:/lib/SOIC8.step"})),         verb_doc("edit_footprint", "Edit a library footprint in place: change, delete, add or renumber pads; add, replace or delete graphics on a layer; set its description; replace, add or delete 3D models. Everything not edited stays as it was.",-            json!({"libraryPath": "path to the footprint library (required)", "name": "the footprint's name (required)", "pads": "[{number, set?: {sizeMm, at, shape, drillMm, layers, rotation, type, newNumber}, delete?: true}]", "addPads": "[pad]: {number, at, sizeMm, shape, drillMm, layers, rotation, type}", "renumber": "{map: {\"1\": \"A1\"}} | {sequential: true, start?: 1}", "graphics": "[{layer, mode: append|replace|delete, widthMm?, shapes: [{type: line {start, end} | arc {center, radius, startAngle, endAngle} | rect {start, end} | circle {center, radius} | poly {points}}]}]", "metadata": "{description?, tags?, attributes?}", "models": "{mode: replace|append|delete, list: [{path, offset, scale, rotate}]}", "dryRun": "bool, default false: answer the plan and change nothing"}),+            json!({"libraryPath": "path to the footprint library (required)", "name": "the footprint's name (required)", "pads": "[{number, set?: {sizeMm, at, shape, drillMm, layers, rotation, type, newNumber}, delete?: true}]", "addPads": "[pad]: {number, at, sizeMm, shape, drillMm, layers, rotation, type}", "renumber": "{map: {\"1\": \"A1\"}} | {sequential: true, start?: 1}", "graphics": "[{layer: F.SilkS | F.Fab | F.CrtYd | F.Mask | F.Paste (or B.) | Mechanical<n> | L<id> | a layer kind (AssemblyTop, ...), mode: append|replace|delete, widthMm?, shapes: [{type: line {start, end} | arc {center, radius, startAngle, endAngle} | rect {start, end} | circle {center, radius, filled?} | poly {points}, widthMm? (beats the entry's)}]}]: F.Fab and F.CrtYd follow the layer map's fab and courtyard keys", "metadata": "{description?, tags?, attributes?}", "models": "{mode: replace|append|delete, list: [{path, offset, scale, rotate}]}", "dryRun": "bool, default false: answer the plan and change nothing"}),             json!({"changes": "[string]: what was done, in order (ok:... or err:...)", "notApplied": "[string]", "footprint": "{pads, graphics, courtyardMm} read back"}), 300,             "Operations run in the order pads, addPads, renumber, graphics, metadata, models. An edited pad keeps its id. Positions are mm from the footprint's origin, as read_footprint gives them.", &["read_footprint", "swap_footprint", "add_body"], &["Boards that already use the footprint keep their own copy: update them with swap_footprint.", "Graphics replace and delete touch shapes only, never text on that layer.", "An Altium footprint has no tags or BOM attributes (they belong to the placed part): those are reported under notApplied.", "Models are aligned onto the pads by add_body: offset, scale and rotate are reported under notApplied."], json!({"libraryPath": "C:/lib/Parts.PcbLib", "name": "SOIC8", "pads": [{"number": "1", "set": {"sizeMm": [1.6, 0.6]}}], "metadata": {"description": "SOIC-8, wider pads"}})),         verb_doc("import_svg", "Import SVG artwork (a logo, a label) as filled polygons on a silkscreen, copper, mask or user layer, at a position and size; curves flattened, holes kept. One undo step.",
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.118",+  "version": "0.2.119",   "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.118",+  "version": "0.2.119",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -159,4 +159,4 @@     "tools/symbol_modes.py",     "uninstall.sh"   ]-}\ No newline at end of file+}
skills/altium-libraries/SKILL.md+16
@@ -97,6 +97,13 @@ Footprints the bridge makes (`build_footprint`, `footprint_from_land_pattern`, ` - **Placing and copying** (`build_board`, `place_parts`, `swap_footprint`, `xcopy_footprint`, ...) put each typed   layer's graphics on the board's (or library's) layer of the same type, made with the source's numbers and names   when missing, so a part flipped to the bottom moves to Bottom Assembly, Bottom Courtyard and so on.+- **Layers are made only when used** (0.2.119, #43 and #44). The verbs find typed and named layers among the library's+  enabled mechanical layers (Altium's `Board.MechanicalLayerIterator`) and make at most the one layer a graphic needs.+  Looking a mechanical layer up by number (`MasterLayerStack.GetMechanicalLayer(N)`, `LayerObject_V7`) CREATES it, and+  the next save keeps it: up to 0.2.118 a 1..1024 lookup loop left every library it touched with all 1024 mechanical+  layers (a fresh library's 56 layer records became 1048, its file 108 KB became 1 MB, and Altium hung attaching a STEP+  to one). Your own scripts should never loop that call either. Mechanical 1, Mechanical 9 (Adom.SolderBalls), 13+  (Fab) and 15 (Courtyard) are turned on only when a footprint draws on them.  ## Heatsink vias from an imported library: `altium_plate_vias` (from 0.2.20) @@ -241,6 +248,15 @@ altium_footprint_from_land_pattern '{"libraryPath":"C:\\lib\\Parts.PcbLib","name   or delete a layer's graphics, set the description, and replace, append or delete 3D models, in that order. Positions   are mm from the footprint's origin, as altium_read_footprint gives them; read it back to check. Boards that already   use the footprint keep their copy (altium_swap_footprint).+- Graphics, each entry one layer: `{layer, mode: append|replace|delete, widthMm?, shapes: [...]}`. Shapes:+  `{type: "line", start: [x, y], end: [x, y]}`, `{type: "rect", start, end}`, `{type: "poly", points: [[x, y], ...]}`+  (closed), `{type: "arc", center, radius, startAngle, endAngle}` (degrees, counter-clockwise) and+  `{type: "circle", center, radius, filled?}`. A shape's own `widthMm` beats the entry's (0.12 mm when neither says);+  `filled: true` draws a solid dot (0.2.119, #43).+- Layers: `F.SilkS`, `F.Mask`, `F.Paste`, `F.Cu` (and `B.`), `F.Fab` and `F.CrtYd`, `Mechanical<n>`, `L<id>`, or a+  layer kind (`AssemblyTop`, `CourtyardTop`, `DimensionsTop`, ...; made if the library has none). `F.Fab` and+  `F.CrtYd` follow the layer map's `fab` and `courtyard` keys (the `B.` side takes the pair's bottom layer); with no+  map they are Mechanical 13 and 15, where the footprint builders put them (0.2.119, #43). - `altium_generate_body {family, dimensionsMm?, outputPath}`: a STEP body from the package family (chip, soic,   sot23, qfp, qfn, dfn, bga, melf, ecap, crystal, header) and the datasheet's JEDEC letters; missing letters take   the family's defaults, and `dimensionsMm` in the reply lists every one used. Compare `bboxMm` with the datasheet,
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.118+0.2.119
src/agent/AdomAgent.pas.tmpl+102−31
@@ -1699,20 +1699,57 @@ Begin     If Q > 0 Then Result := Copy(Rest, 1, Q - 1) Else Result := Rest; End; -{ The mechanical layer number holding kind K on Board, 0 when there is none. }+{ The mechanical layer numbers Board has turned on, as ',1,20,'. Read through Board.MechanicalLayerIterator, which+  lists the enabled mechanical layers and creates none. MasterLayerStack.GetMechanicalLayer(N) CREATES layer N in the+  document when it is missing, and the next save keeps it: looping it over 1..1024 left libraries with all 1024+  mechanical layers (#44, measured 2026-12-02 on AD 26.11: a fresh library's 56 layer records became 1048, its file+  108 KB became 1 MB, and an organisation reported Altium hanging on such a library). The stack's First/Next iterator+  lists only the physical stack, never a mechanical layer. }+Function EnabledMechNos(Board : IPCB_Board) : String;+Var+    It;+    N : Integer;+Begin+    Result := ',';+    It := Board.MechanicalLayerIterator;+    While It.Next Do+    Begin+        N := MechLayerNo(It.Layer);+        If N > 0 Then Result := Result + IntToStr(N) + ',';+    End;+End;++{ The first number in a ',1,20,' list, and the list without it in Rest; 0 when the list is empty. }+Function PopMechNo(Var Rest : String) : Integer;+Var+    P : Integer;+Begin+    Result := 0;+    If Copy(Rest, 1, 1) = ',' Then Rest := Copy(Rest, 2, Length(Rest));+    P := Pos(',', Rest);+    If P = 0 Then Exit;+    Result := StrToIntDef(Copy(Rest, 1, P - 1), 0);+    Rest := Copy(Rest, P + 1, Length(Rest));+End;++{ The enabled mechanical layer number holding kind K on Board, 0 when there is none. } Function MechNoOfKind(Board : IPCB_Board; K : Integer) : Integer; Var     N : Integer;+    Rest : String;     ML : IPCB_MechanicalLayer; Begin     Result := 0;     If K <= 0 Then Exit;-    For N := 1 To 1024 Do+    Rest := EnabledMechNos(Board);+    N := PopMechNo(Rest);+    While N > 0 Do     Begin         Try             ML := Board.MasterLayerStack.GetMechanicalLayer(N);             If ML <> Nil Then If ML.Kind = K Then Begin Result := N; Exit; End;         Except End;+        N := PopMechNo(Rest);     End; End; @@ -1720,34 +1757,41 @@ End; Function MechNoNamed(Board : IPCB_Board; Nm : String) : Integer; Var     N : Integer;+    Rest : String;     ML : IPCB_MechanicalLayer; Begin     Result := 0;-    For N := 1 To 1024 Do+    Rest := EnabledMechNos(Board);+    N := PopMechNo(Rest);+    While N > 0 Do     Begin         Try             ML := Board.MasterLayerStack.GetMechanicalLayer(N);-            If ML <> Nil Then If ML.MechanicalLayerEnabled And (UpperCase(ML.Name) = UpperCase(Nm)) Then Begin Result := N; Exit; End;+            If ML <> Nil Then If UpperCase(ML.Name) = UpperCase(Nm) Then Begin Result := N; Exit; End;         Except End;+        N := PopMechNo(Rest);     End; End;  { A mechanical layer free to become a typed layer: off and with no kind. Prefer when it is free, else the first free one-  above 16 (the old 16 are left to the user's own uses); never Avoid. 0 when none is free. }+  above 16 (the old 16 are left to the user's own uses); never Avoid. 0 when none is free. Only numbers that are not+  enabled are looked at, so normally exactly one layer is touched (looking one up creates it, #44). } Function FreeMechNo(Board : IPCB_Board; Prefer, Avoid : Integer) : Integer; Var     N : Integer;+    Ens : String;     ML : IPCB_MechanicalLayer; Begin     Result := 0;-    If (Prefer > 0) And (Prefer <= 1024) And (Prefer <> Avoid) Then+    Ens := EnabledMechNos(Board);+    If (Prefer > 0) And (Prefer <= 1024) And (Prefer <> Avoid) And (Pos(',' + IntToStr(Prefer) + ',', Ens) = 0) Then     Begin         ML := Board.MasterLayerStack.GetMechanicalLayer(Prefer);         If ML <> Nil Then If (Not ML.MechanicalLayerEnabled) And (ML.Kind = 0) Then Begin Result := Prefer; Exit; End;     End;     For N := 17 To 1024 Do     Begin-        If N <> Avoid Then+        If (N <> Avoid) And (Pos(',' + IntToStr(N) + ',', Ens) = 0) Then         Begin             ML := Board.MasterLayerStack.GetMechanicalLayer(N);             If ML <> Nil Then If (Not ML.MechanicalLayerEnabled) And (ML.Kind = 0) Then Begin Result := N; Exit; End;@@ -3406,6 +3450,31 @@ Begin     If Result <= 0 Then Result := SpecLayer(Tag); End; +{ Turn on (and name) the built-in mechanical layer a spec tag draws on: comment Mechanical 1, balls Mechanical 9+  (Adom.SolderBalls, hidden), fab Mechanical 13 (Fab), courtyard Mechanical 15 (Courtyard). Other tags need nothing. }+Procedure EnableSpecLayer(Board : IPCB_Board; Tag : String);+Begin+    If Tag = 'comment' Then Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True+    Else If Tag = 'balls' Then+    Begin+        Board.LayerStack.LayerObject[eMechanical9].MechanicalLayerEnabled := True;+        Board.LayerStack.LayerObject[eMechanical9].Name := 'Adom.SolderBalls';+        Board.LayerIsDisplayed[eMechanical9] := False;+    End+    Else If Tag = 'fab' Then+    Begin+        Board.LayerStack.LayerObject[eMechanical13].MechanicalLayerEnabled := True;+        Board.LayerStack.LayerObject[eMechanical13].Name := 'Fab';+        Board.LayerIsDisplayed[eMechanical13] := True;+    End+    Else If Tag = 'courtyard' Then+    Begin+        Board.LayerStack.LayerObject[eMechanical15].MechanicalLayerEnabled := True;+        Board.LayerStack.LayerObject[eMechanical15].Name := 'Courtyard';+        Board.LayerIsDisplayed[eMechanical15] := True;+    End;+End;+ { A template primitive the new footprint starts with: a special string (.Designator, .Comment) or a graphic on a   Component Center layer (the centroid marker). The example pad, outline, courtyard, assembly drawing, silkscreen and   dimensions are the template's own and stay behind. }@@ -3486,28 +3555,7 @@ Begin     Spec.LoadFromFile(SpecPath);     Name := ''; Desc := '';     NPads := 0; NTh := 0; NPrims := 0;-    { mech layers this spec may use: enable + name them once per library. A layer the map (#41) moves elsewhere is-      not touched: Mechanical 13 may be the organisation's own. }     LMap := Param(Lines, 'lmap'); TCache := ','; MCache := ','; Used := ','; UsedJ := '';-    If LMapCode(LMap, 'comment') = '' Then PLib.Board.LayerStack.LayerObject[eMechanical1].MechanicalLayerEnabled := True;-    If LMapCode(LMap, 'balls') = '' Then-    Begin-        PLib.Board.LayerStack.LayerObject[eMechanical9].MechanicalLayerEnabled := True;-        PLib.Board.LayerStack.LayerObject[eMechanical9].Name := 'Adom.SolderBalls';-        PLib.Board.LayerIsDisplayed[eMechanical9] := False;-    End;-    If LMapCode(LMap, 'fab') = '' Then-    Begin-        PLib.Board.LayerStack.LayerObject[eMechanical13].MechanicalLayerEnabled := True;-        PLib.Board.LayerStack.LayerObject[eMechanical13].Name := 'Fab';-        PLib.Board.LayerIsDisplayed[eMechanical13] := True;-    End;-    If LMapCode(LMap, 'courtyard') = '' Then-    Begin-        PLib.Board.LayerStack.LayerObject[eMechanical15].MechanicalLayerEnabled := True;-        PLib.Board.LayerStack.LayerObject[eMechanical15].Name := 'Courtyard';-        PLib.Board.LayerIsDisplayed[eMechanical15] := True;-    End;     { every layer the spec draws on, found (and a typed one made) before the edit begins }     For I := 0 To Spec.Count - 1 Do     Begin@@ -3518,6 +3566,9 @@ Begin             If Pos(',' + Tag + ',', Used) = 0 Then             Begin                 Used := Used + Tag + ',';+                { a built-in layer is turned on and named only when the spec draws on it (#43: Mechanical 1 and 9+                  appeared in libraries with nothing on them); a layer the map moves elsewhere is not touched }+                If LMapCode(LMap, Tag) = '' Then EnableSpecLayer(PLib.Board, Tag);                 TL := SpecLayerMapped(PLib.Board, LMap, Tag, TCache);                 If UsedJ <> '' Then UsedJ := UsedJ + ',';                 UsedJ := UsedJ + '["' + JsonEsc(Tag) + '","' + JsonEsc(LayerNameOf(PLib.Board, TL)) + '",' + IntToStr(TL) + ',' + IntToStr(LayerKindOf(PLib.Board, TL)) + ']';@@ -11217,6 +11268,15 @@ Begin     Else Result := eTopLayer; End; +{ A graphics op's layer field: an Altium layer id, or a layer-map code (k<kind>, m<n>, n<name>, i<id>) looked up in+  LCache (',code=id,'), which CmdEditFp fills before its edit begins (making a typed layer inside PreProcess is not+  safe). 0 when the code named no layer. }+Function FpLayerField(S : String; LCache : String) : Integer;+Begin+    If (S <> '') And (Pos(Copy(S, 1, 1), 'kmni') > 0) Then Result := StrToIntDef(CacheGet(LCache, S), 0)+    Else Result := AdomInt(S);+End;+ Function CmdEditFp(Lines : TStringList; Payload : String) : String; Var     LibErr : String;@@ -11231,6 +11291,7 @@ Var     Old   : IPCB_LibComponent;     GIt   : IPCB_GroupIterator;     I, K, OX, OY, Lay, Okay, Failed : Integer;+    LCache, Code : String; Begin     { the library the bridge names, as the open document: a library loaded by path is a separate copy (pads added or       deleted on it never reached the document, 2026-10-28), and open shows a document without making it current }@@ -11246,6 +11307,14 @@ Begin     Ops := TStringList.Create;     Ops.Text := Payload;     Results := ''; Okay := 0; Failed := 0;+    { layer-map codes resolved (a typed layer made if missing) before the edit begins }+    LCache := ',';+    For I := 0 To Ops.Count - 1 Do+    Begin+        Kind := FieldP(Ops[I], 1); Code := FieldP(Ops[I], 2);+        If ((Kind = 'GL') Or (Kind = 'GA') Or (Kind = 'GD')) And (Code <> '') And (Pos(Copy(Code, 1, 1), 'kmni') > 0) Then+            If CacheGet(LCache, Code) = '' Then LCache := LCache + Code + '=' + IntToStr(ResolveLayerCode(PLib.Board, Code)) + ',';+    End;     PCBServer.PreProcess;     { the edit is made on a copy that is then registered in the footprint's place: on a registered footprint, pads       and lines added or removed did not reach it (only changes to existing pads did, Develop 2026-10-28), while a@@ -11326,7 +11395,7 @@ Begin         End         Else If (Kind = 'GD') Or (Kind = 'BD') Then         Begin-            If Kind = 'BD' Then Lay := 0 Else Lay := AdomInt(FieldP(Op, 2));+            If Kind = 'BD' Then Lay := 0 Else Lay := FpLayerField(FieldP(Op, 2), LCache);             K := 0;             Prim := FpFirstOn(Fp, Lay);             While (Prim <> Nil) And (K < 5000) Do@@ -11338,10 +11407,12 @@ Begin             If Kind = 'BD' Then Res := 'ok:deleted ' + IntToStr(K) + ' 3D bodies'             Else Res := 'ok:deleted ' + IntToStr(K) + ' shapes on layer ' + FieldP(Op, 2);         End+        Else If ((Kind = 'GL') Or (Kind = 'GA')) And (FpLayerField(FieldP(Op, 2), LCache) = 0) Then+            Res := 'err:layer ' + FieldP(Op, 2) + ' could not be found or made'         Else If Kind = 'GL' Then         Begin             Trk := PCBServer.PCBObjectFactory(eTrackObject, eNoDimension, eCreate_Default);-            Trk.Layer := AdomInt(FieldP(Op, 2));+            Trk.Layer := FpLayerField(FieldP(Op, 2), LCache);             Trk.X1 := OX + MmC(FieldP(Op, 3)); Trk.Y1 := OY + MmC(FieldP(Op, 4));             Trk.X2 := OX + MmC(FieldP(Op, 5)); Trk.Y2 := OY + MmC(FieldP(Op, 6));             Trk.Width := MmC(FieldP(Op, 7));@@ -11351,7 +11422,7 @@ Begin         Else If Kind = 'GA' Then         Begin             Arc := PCBServer.PCBObjectFactory(eArcObject, eNoDimension, eCreate_Default);-            Arc.Layer := AdomInt(FieldP(Op, 2));+            Arc.Layer := FpLayerField(FieldP(Op, 2), LCache);             Arc.XCenter := OX + MmC(FieldP(Op, 3)); Arc.YCenter := OY + MmC(FieldP(Op, 4));             Arc.Radius := MmC(FieldP(Op, 5));             Arc.LineWidth := MmC(FieldP(Op, 6));
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.118",+  "version": "0.2.119",   "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",