← Commit history

0.2.120 source: repair libraries with 1024 mechanical layers (#44): xcopy makes toLib and copies height, layer_map get reports libraryLayers

Colby Knox ·d910148f9b · ·parent 4127ad7
11 files changed +79−10
CHANGELOG.md+8
@@ -1,5 +1,13 @@ # Changelog +## 0.2.120++- **Repairing a library with 1024 mechanical layers** (#44):+  - `altium_xcopy_footprint` makes `toLib` when the file does not exist yet (`createdToLib`); it had to be made first.+  - `altium_xcopy_footprint` and `altium_copy_footprint` copy the footprint's height, which was left at 0. Everything else was already copied: pads with their own pad stacks, embedded STEP bodies, typed-layer graphics on the destination's layers of the same type, and the description.+  - `altium_layer_map {action: "get", libraryPath}` reports `libraryLayers` for a `.PcbLib` or `.PcbDoc`, read from the saved file: `layerRecords`, `mechanicalLayers`, `mechanicalLayersOn` and `bloated`.+- Tested on Altium Designer 26.11.1. A 1048-record library (a QFN-16 on typed layers, and an R0603 with a stacked through-hole pad, an embedded STEP body and a height) was copied footprint by footprint into a library that did not exist. The copy was identical primitive by primitive and had 56 layer records. Swapped in at the old path (Altium's documents closed first), it reopened with the STEP still embedded (the .step file moved away). An IntLib built from its LibPkg packed R0603 and the embedded model.+ ## 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.
bridge-rs/src/layermap_verb.rs+40
@@ -85,6 +85,28 @@ fn scope_file(args: &Value) -> Result<PathBuf, Value> {     } } +/// A PcbLib's layer records as saved (read from the file, no Altium): how many mechanical layers it defines and how+/// many are on. Up to 0.2.118 the footprint verbs left every library they touched with all 1024 mechanical layers+/// defined (#44); `bloated` says so (1000 or more defined, under half on). Copy such a library's footprints into a fresh+/// one (altium_xcopy_footprint) to repair it.+pub fn library_layers(bytes: &[u8]) -> Value {+    let t = String::from_utf8_lossy(bytes);+    let (mut records, mut mech, mut on) = (std::collections::BTreeSet::new(), 0usize, 0usize);+    for (i, _) in t.match_indices("LAYER_V8_") {+        let rest = &t[i + 9..];+        let n: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();+        if n.is_empty() { continue; }+        let after = &rest[n.len()..];+        if after.starts_with("NAME=") { records.insert(n.clone()); }+        if let Some(v) = after.strip_prefix("MECHENABLED=") {+            mech += 1;+            if v.starts_with("TRUE") { on += 1; }+        }+    }+    json!({"layerRecords": records.len(), "mechanicalLayers": mech, "mechanicalLayersOn": on, "bloated": mech >= 1000 && on < mech / 2,+        "_hint": if mech >= 1000 { "This file defines all 1024 mechanical layers (left by altium-bridge 0.2.118 and earlier, #44). A library: copy its footprints into a fresh one with altium_xcopy_footprint. A board: it still works, only larger." } else { "Counted from the saved file: save the library first for its current state." }})+}+ fn get(args: &Value) -> Value {     let lib = s(args, "libraryPath");     let e = effective(args, lib.as_deref());@@ -93,6 +115,9 @@ fn get(args: &Value) -> Value {     if let Some(f) = lf { r["files"]["library"] = json!({"path": f, "exists": f.is_file()}); }     let m = layermap::report(&e, &json!([]));     r["layerMap"] = m;+    if let Some(stats) = lib.as_deref().filter(|l| { let l = l.to_lowercase(); l.ends_with(".pcblib") || l.ends_with(".pcbdoc") }).and_then(|l| std::fs::read(l).ok()).map(|b| library_layers(&b)) {+        r["libraryLayers"] = stats;+    }     r["_hint"] = json!("Each key shows the layer asked for and where it comes from: the call, the library's adom-layer-map.json, your default, or the built-in layer. A typed layer (CourtyardTop) the library lacks is made, as a top/bottom pair, the first time a footprint uses it.");     r }@@ -244,3 +269,18 @@ mod tests {         assert_eq!(d["template"]["footprint"], "F");     } }++#[cfg(test)]+mod layer_count_tests {+    use super::*;++    #[test]+    fn a_library_with_every_mechanical_layer_reads_as_bloated() {+        let mut s = String::from("|LAYER_V8_0NAME=Top Paste|LAYER_V8_0LAYERID=35|");+        for i in 1..=1024 { s.push_str(&format!("|LAYER_V8_{}NAME=Mechanical {i}|LAYER_V8_{}MECHENABLED={}|", 10 + i, 10 + i, if i < 3 { "TRUE" } else { "FALSE" })); }+        let r = library_layers(s.as_bytes());+        assert_eq!((r["layerRecords"].as_u64(), r["mechanicalLayers"].as_u64(), r["mechanicalLayersOn"].as_u64(), r["bloated"].as_bool()), (Some(1025), Some(1024), Some(2), Some(true)));+        let small = library_layers(b"|LAYER_V8_11NAME=Mechanical 1|LAYER_V8_11MECHENABLED=TRUE|LAYER_V8_12MECHENABLED=FALSE|");+        assert_eq!(small["bloated"], json!(false));+    }+}
bridge-rs/src/library.rs+12−2
@@ -286,13 +286,23 @@ pub fn xcopy_footprint(args: &Value) -> Value {     if let Some(g) = support::need_licensed() {         return g;     }+    let mut created = false;     if let Some(p) = s(args, "toLib") {+        // a toLib that does not exist yet is made (an empty PcbLib; Altium's placeholder footprint goes with the first copy)+        if !std::path::Path::new(&p).exists() {+            if !p.to_lowercase().ends_with(".pcblib") { return json!({"success": false, "errorCode": "bad_args", "error": format!("{p} is not a .PcbLib")}); }+            let r = agent::call("ensure_lib", &[("kind", "PCBLIB".into()), ("path", p.replace('/', "\\"))], None, timeout_of(args, 90));+            if r.pointer("/data/ok") != Some(&json!(true)) { let mut e = r.clone(); e["success"] = json!(false); e["errorCode"] = json!("library_not_created"); return e; }+            created = true;+        }         if let Some(e) = support::must_open(&p, 60) { return e; }     }     let to = s(args, "to").or_else(|| s(args, "from")).unwrap_or_default();-    agent::call("xcopy_footprint",+    let mut r = agent::call("xcopy_footprint",         &[("fromLib", s_or(args, "fromLib", "")), ("from", s_or(args, "from", "")), ("to", to)],-        None, timeout_of(args, 120))+        None, timeout_of(args, 120));+    if created { r["createdToLib"] = json!(true); }+    r }  pub fn swap_footprint(args: &Value) -> Value {
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.119";+pub const BRIDGE_VERSION: &str = "0.2.120";  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/verbs.rs+2−2
@@ -605,7 +605,7 @@ fn describe() -> Value {             &["plan_route", "route_net", "routing_state", "repour", "routing_drc", "save"], &["Needs a board with routed tracks.", "Takes a few seconds per thousand tracks, plus a repour and two batch DRCs.", "The board is left unsaved."], json!({"nets": ["N1", "GND"]})),         verb_doc("layer_map", "Choose which Altium layer each kind of footprint graphic goes on (silkscreen, fab/assembly, courtyard, 3D body, centroid, designator, ...) and the template footprint new footprints start from, per call, per library folder (your organisation's default) or as your own default. Reads a template footprint and proposes the map from the typed layers it uses (Top Assembly, Top Courtyard, ...), and finds the PCB library template in Altium's Template Files setting.",             json!({"action": "get (default) | set | clear | from_template | find_template", "libraryPath": "the library (or its folder): get shows the map in effect there; set/clear scope:'library' write adom-layer-map.json beside it; from_template reads the template from it", "scope": "user | library (set, clear)", "layerMap": "{key: layer} (set, and the footprint verbs per call). Keys: overlay, fab, courtyard, body3d, comment, balls, centroid, designator, outline, dimensions. A layer is a type (CourtyardTop, AssemblyTop, 3DBodyTop, ...), a name (Top Courtyard, Mechanical 15) or an id; null removes a key", "template": "{libraryPath, footprint}: the footprint new footprints start from (set, and per call)", "replace": "bool (set): replace the scope's map instead of merging into it", "keys": "[key] (clear): only these keys ('template' for the template); all when omitted", "footprint": "the template footprint (from_template)", "save": "user | library (from_template): keep the proposal in that scope", "edition": "Altium Designer | Altium Designer Develop (find_template)"}),-            json!({"layerMap": "{keys: {key: {asked, source: call|library|user|built-in, layer?, layerId?, kind?, used?}}, template?, refused?}", "files": "{user, library}: {path, exists} (get)", "written": "path (set)", "proposal": "{layerMap, template} (from_template)", "templateCopy": "what a footprint keeps from the template (from_template)", "entries": "[{kind, value, itemGuid}] Altium's Template Files (find_template)", "cachedLibraries": "[{path, matchesPreference}] (find_template)", "template": "{libraryPath} when one cached copy matches (find_template)"}), 120,+            json!({"libraryLayers": "get, with libraryPath (a .PcbLib or .PcbDoc): {layerRecords, mechanicalLayers, mechanicalLayersOn, bloated}, read from the saved file. bloated: all 1024 mechanical layers defined, as 0.2.118 and earlier left files (#44)", "layerMap": "{keys: {key: {asked, source: call|library|user|built-in, layer?, layerId?, kind?, used?}}, template?, refused?}", "files": "{user, library}: {path, exists} (get)", "written": "path (set)", "proposal": "{layerMap, template} (from_template)", "templateCopy": "what a footprint keeps from the template (from_template)", "entries": "[{kind, value, itemGuid}] Altium's Template Files (find_template)", "cachedLibraries": "[{path, matchesPreference}] (find_template)", "template": "{libraryPath} when one cached copy matches (find_template)"}), 120,             "Precedence per key: the call's layerMap, then adom-layer-map.json beside the library, then your default, then the bridge's built-in layers (unchanged when nothing is set). A typed layer the library or board lacks is made as a top/bottom pair the first time it is used. The footprint verbs (build_footprint, footprint_from_land_pattern, import_part, add_body) take layerMap and template per call and report the map they used.",             &["read_footprint", "build_footprint", "import_part", "add_body", "list_library"], &["A layer type can be made only as a pair (Top and Bottom Courtyard): Altium's single-layer kinds (Board, Dimensions, V Cut, ...) are reached by name.", "outline and dimensions are accepted and reported but nothing the bridge draws goes there yet.", "From a template a footprint keeps its special strings (.Designator) and its Component Center graphics; the example pad, outline, courtyard, assembly drawing and dimensions stay behind."],             json!({"action": "from_template", "libraryPath": "C:/org/Templates.PcbLib", "footprint": "Default Footprint", "save": "library"})),@@ -1505,7 +1505,7 @@ fn describe() -> Value {             &["xcopy_footprint", "rename_footprint", "pcb_report"], &["'target already exists' - choose another name or altium_remove_footprint first."],             json!({"libraryPath": "C:/lib/Adom_ToF.PcbLib", "from": "VL53L5CX", "to": "VL53L5CX_HANDSOLDER"})),         verb_doc("xcopy_footprint", "Copy a footprint ACROSS libraries: from fromLib into toLib (opened and made current), optionally under a new name.",-            json!({"fromLib": "path to the source .PcbLib", "from": "string - footprint name in the source", "toLib": "path to the destination .PcbLib - optional; else the current PcbLib", "to": "string - default: same as from", "timeout": "seconds, default 120"}),+            json!({"fromLib": "path to the source .PcbLib", "from": "string - footprint name in the source", "toLib": "path to the destination .PcbLib - optional; else the current PcbLib. Made (empty) when it does not exist (0.2.120)", "to": "string - default: same as from", "timeout": "seconds, default 120"}),             json!({"data": "{to, primitives: int}", "roundtripMs": "int"}), 120,             "altium_pcb_report {path: toLib, name} to confirm pads and bodies arrived, then altium_save {filePath: toLib}.",             &["copy_footprint", "pcb_report", "save"], &["'open the destination PcbLib first' = pass toLib.", "'target already exists' in the destination: pass a different to."],
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.119",+  "version": "0.2.120",   "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.119",+  "version": "0.2.120",   "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+7
@@ -104,6 +104,13 @@ Footprints the bridge makes (`build_footprint`, `footprint_from_land_pattern`, `   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.+- **Check and repair** (0.2.120): `altium_layer_map {action:"get", libraryPath}` reports `libraryLayers` for a+  `.PcbLib` or `.PcbDoc` from the saved file (`bloated: true` when all 1024 mechanical layers are defined). To repair a+  library, close it in Altium, copy every footprint into a new library with+  `altium_xcopy_footprint {fromLib, from, toLib}` (toLib is made if missing; skip Altium's empty `PCBComponent_1`),+  save the new library, close everything, then swap the files on disk (old one renamed aside). The copy keeps pads and+  pad stacks, embedded STEP bodies, typed layers, the description and the height. Never swap a library's file while+  Altium has it open: close its documents first (`altium_close_all_documents {under, save}`).  ## Heatsink vias from an imported library: `altium_plate_vias` (from 0.2.20) 
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.119+0.2.120
src/agent/AdomAgent.pas.tmpl+4
@@ -4910,6 +4910,8 @@ Begin     Dst := PCBServer.CreatePCBLibComp;     Dst.Name := Param(Lines, 'to');     Dst.Description := Src.Description;+    { the footprint's height (3D clearance checks read it): it was left at 0 }+    Dst.Height := Src.Height;     NCopied := 0;     GIt := Src.GroupIterator_Create;     GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);@@ -5184,6 +5186,8 @@ Begin     Dst := PCBServer.CreatePCBLibComp;     Dst.Name := Param(Lines, 'to');     Dst.Description := Src.Description;+    { the footprint's height (3D clearance checks read it): it was left at 0 }+    Dst.Height := Src.Height;     NCopied := 0;     GIt := Src.GroupIterator_Create;     GIt.AddFilter_IPCB_LayerSet(LayerSetUtils.AllLayers);
src/bridge.json+1−1
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.119",+  "version": "0.2.120",   "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",