← Commit history
CHANGELOG.md+35
@@ -1,5 +1,40 @@ # Changelog +## 0.2.77 (2026-10-27)++The EDA Bridge Standard's project, library-part and render verbs (13 new, 245 in all), all tried live on Altium Develop.++- **Documents and projects:** `document_info` (the document in front and every open one, with whether each has+  unsaved changes), `close_all_documents` (no save dialog; a changed document stays open unless `save` or+  `discardUnsaved` says otherwise; `under` limits it to one folder; never closes the bridge's own agent),+  `project_info` (files, sheet tree, board layers, parts, nets and size, text variables), `project_create` (a sheet+  from Altium's ANSI B template and a board of 2 to 8 layers), `project_rename` (refused while the project is open),+  `project_snapshot` (a dated copy with a board PDF), `cross_probe` (a sheet symbol to its board part and back, by+  Altium's own unique id, with both positions).+- **Library parts:** `read_footprint` (pads, shapes, layers and the courtyard in mm from the footprint's origin),+  `library_views` (the symbol, footprint and 3D images of a part), `export_library_part` (a part's symbol and+  footprint in libraries of their own, and its STEP when the file still exists), `create_part_project` (a one-part+  project: the symbol on a sheet as U1, the footprint on the board by Altium's change order, a board 5 mm round the+  part with its corner at the origin).+- **Renders:** `render_board_3d` (top or bottom, from Altium's 3D print) and `render_board_layers` (14 presets or any+  layers, mirror). The board print now covers the outline plus 1 mm (`area: "extent"` for every object): the design+  extent took in the change order's room and parts left off the board.+- **The shared checks engine** is adom-eda-checks 0.1.4 (standard 0.4.5), vendored as published with no local patch:+  `min_clearance` counts only copper-to-copper rules, and `current_capacity` lists each pour layer once.+- **Fixes:**+  - `altium_save {filePath}` saves that document by its path. It used to save whatever had focus, and opening a+    document does not focus it, so a save meant for a new board rewrote a source library.+  - Adding a document to a project no longer re-saves the project's unchanged libraries.+  - A footprint copied between libraries moves by the difference of their origins (a new library's origin is at+    50000 mil), so it sits on its own origin in the copy.+  - A new library made for one symbol no longer keeps Altium's empty Component_1.+  - A new board, sheet or panel saved onto a path closes an unchanged document already open there first. AD 26+    reopens its last session, so the battery's `test_board` left two documents at one path, and DRC on the board+    crashed inside ADVPCB.DLL (twice, once in 0.2.76's battery). A copy with changes is left alone.+  - `document_info` gives each open document's path, so two documents of one name can be told apart.+  - Schematic edits made through the agent mark the sheet as changed, and the bridge tracks its own unsaved edits,+    since Altium reads that flag back as false.+ ## 0.2.76 (2026-10-27)  - `altium_move_parts`: flips parts. `side: "top" | "bottom"` puts a part on that side and `flip: true` turns it
README.md+18−5
@@ -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 -232 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+245 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. 232 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 245 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 232 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 245 `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 232 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 245 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.  ### Running Altium: launch, close, health, dialogs @@ -245,6 +245,19 @@ All 232 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_routing_state`: The WHOLE current board as data, in mm: tracks, arcs, vias, pads (with owner and net), components (ref, x, y, rotation, side), polygon pours, the outline, the unrouted (ratsnest) count, and a revision hash. - `altium_route_net`: Route one net as tracks, segment by segment; a waypoint on another layer drops a via there. - `altium_move_parts`: Move, rotate and flip placed components (side top or bottom; flip:true turns a part over); each part is read back to 0.001 mm, the exact rotation and its side.+- `altium_export_library_part`: Export one library part into its own small library files: a symbol library with only its symbol, a footprint library with only its footprint, and its 3D model file.+- `altium_create_part_project`: Generate a small real project (schematic and board) around one library part, so the part can be shown and tested in every view: schematic, 2D board and 3D board.+- `altium_library_views`: Pictures of library parts for review, each as an image file: the schematic symbol, the footprint (pads and layers), the 3D body seated on the footprint, and the device view that maps symbol pins to pads.+- `altium_render_board_3d`: Render a 3D picture of the board from one side to an image file, through the tool's own renderer, without opening a window.+- `altium_render_board_layers`: Render chosen board layers to an image file without opening a window: a preset view (copper, silkscreen, solder mask, paste, outline, drill, assembly or fabrication, of either side) or a list of layers, as png or svg.+- `altium_document_info`: The active document: its name, what kind it is, whether it has unsaved changes, where it is saved and which version it is.+- `altium_close_all_documents`: Close every open document without a save dialog.+- `altium_project_info`: A project at a glance: name, files with sizes and dates, the sheet tree, the board (layers, parts, nets, size), text variables, net classes, last change, and whether the tool has it open.+- `altium_project_create`: Create a new project folder with a project file, an empty schematic and an empty board (2 to 32 copper layers), with a title and text variables.+- `altium_project_rename`: Rename a project: the project file, the root sheet, the board and the tool's side files, with the references inside them updated.+- `altium_project_snapshot`: A dated copy of the project's documents into <project>/snapshots/<stamp>[-label]/, with PDFs of the schematic and the board made by the tool.+- `altium_cross_probe`: From a schematic part to the board part linked to it, and back, by designator, the schematic symbol's id or its sheet path; optionally select them in the tool.+- `altium_read_footprint`: Every detail of one library footprint: pads (number, type, shape, position, size, drill, layers), the layers it uses, its courtyard box, graphics per layer, attributes, properties and 3D models. - `altium_export_odb`: Export the board as ODB++ (copper, drill, stack-up, netlist and parts in one archive) through the tool's own exporter. - `altium_export_ipc2581`: Export the board as IPC-2581: one XML file with copper, drill, stack-up, netlist and BOM, through the tool's own exporter. - `altium_remove_parts`: Remove placed parts from the board by designator, as one undo step.@@ -361,7 +374,7 @@ All 232 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca - `altium_export_pdf`: Every sheet of a project as one PDF, plus on request the board's composite print, Altium's assembly drawings (top and bottom, designators on the parts) and its fabrication print, from an OutJob in a throwaway project; the user's project is not touched. - `altium_sch_zoom`: Find parts on a sheet: select them (everything else deselected), frame the view on them and return a proof frame. - `altium_autoroute`: Altium's own autorouter (Situs) on the current board: picks a strategy, keeps existing routing locked by default, routes, and answers the unconnected count and DRC errors before and after.-- `altium_save`: Save the focused document, or open filePath first and save that (WorkspaceManager:SaveObject on the focused document).+- `altium_save`: Save the focused document, or the document at filePath (opened first if need be, saved by its path, never whatever happens to have focus). - `altium_test_board`: Place one footprint, or a ';' list, from the open PcbLib on ONE board: a NEW board (wMm x hMm outline) when pcbPath is new or omitted, APPENDED to the existing board when pcbPath already exists (issue 11). - `altium_board_shape`: Redefine the CURRENT board's outline as a wMm x hMm rectangle at (x0Mm, y0Mm) by rewriting the board outline's segments. - `altium_pcb_report`: Numbers instead of pixels: for a PcbLib, every footprint's pads, pad bounding box, primitive census and 3D bodies; for a board, outline, components with nets and bodies, census and tracks.
SKILL.md+5
@@ -43,6 +43,11 @@ Say **altium** to reach this bridge. Every verb returns `success`, a stable `err | Rotations, channel copies, a precise clearance check | `altium_check_orientation`, `altium_replicate_layout`, `altium_find_space {check, precise}` (**altium-boards**) | | A footprint from a datasheet's land pattern (SOIC, QFN, SOT, BGA, chips) | `altium_footprint_from_land_pattern {family, pins, pitch, span, padLength, padWidth, exposedPad, body}` (**altium-libraries**) | | Find a symbol or footprint by name; multi-part symbols; batches | `altium_find_symbol`, `altium_create_symbol {pins with part}`, `{symbols:[..]}` (**altium-libraries**) |+| What is open, a project at a glance, close everything | `altium_document_info`, `altium_project_info {project}`, `altium_close_all_documents {save?, discardUnsaved?, under?}` (a changed document stays open unless told) |+| A new project, rename one, a dated copy | `altium_project_create {parentDir, name, layers?}`, `altium_project_rename` (refused while open), `altium_project_snapshot {project, label?}` |+| A sheet symbol to its board part and back | `altium_cross_probe {ref}` (both positions; Altium's unique id, not the designator, links them) |+| A part as its own library, or as a one-part demo project | `altium_export_library_part {part, libraryPath}`, `altium_create_part_project {part, libraryPath}` (**altium-libraries**) |+| A picture of the board without a window | `altium_render_board_layers {preset \| layers, mirror?}`, `altium_render_board_3d {side}`, `altium_render_schematic` (**altium-outputs**) | | A project's parameters | `altium_part_parameters {projectPath, name?}` | | Manufacturing files, STEP, PDF | `altium_export_manufacturing` (checks the outline and copper layers in its Gerbers: `fabChecks`), `altium_board_outline`, `altium_export_step`, `altium_export_pdf`, `altium_run_outjob`, `altium_outjob_info` (read an OutJob's containers without running it) (**altium-outputs**) | | Make or fix library parts | `altium_import_part`, `altium_build_symbol_modes`, `altium_build_footprint`, `altium_add_body`, `altium_set_params` (**altium-libraries**, **altium-part-import**) |
bridge-rs/Cargo.lock+1−1
@@ -10,7 +10,7 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"  [[package]] name = "adom-eda-checks"-version = "0.1.0"+version = "0.1.4" dependencies = [  "serde_json", ]
bridge-rs/src/a365.rs+1−1
@@ -56,7 +56,7 @@ fn b64url(raw: &[u8]) -> String {     out } -fn b64url_decode(s: &str) -> Option<Vec<u8>> {+pub(crate) fn b64url_decode(s: &str) -> Option<Vec<u8>> {     let val = |c: u8| -> Option<u32> {         Some(match c {             b'A'..=b'Z' => (c - b'A') as u32,
bridge-rs/src/checks.rs+1−1
@@ -6,7 +6,7 @@ use serde_json::{json, Value}; use std::time::Duration;  /// The vendored engine, as vendor/README.md records it.-const ENGINE: &str = "adom-eda-checks 0.1.0 (EDA Bridge Standard 0.4.0)";+const ENGINE: &str = "adom-eda-checks 0.1.4 (EDA Bridge Standard 0.4.5)";  /// adom/pcb-design-rules' vendor records, bundled at build time (vendor/README.md). const RECORDS: &[(&str, &str)] = &[
bridge-rs/src/library.rs+2−4
@@ -693,10 +693,8 @@ pub fn import_part(args: &Value) -> Value {     }     for lib in [&pcb_lib, &sch_lib] {         if !lib.is_empty() {-            support::agent_open(lib, 60);-            agent::call("run_process",-                &[("process", "WorkspaceManager:SaveObject".into()), ("params", "ObjectKind=FocusedDocument".into())],-                None, Duration::from_secs(60));+            // by path: open shows a library without focusing it, and a focused save could write another document+            let _ = crate::surfaces::save(&json!({"filePath": lib}));         }     }     json!({"success": true, "symbol": sym_name, "footprint": fp_name, "steps": steps,
bridge-rs/src/main.rs+3−1
@@ -16,6 +16,8 @@ mod schwire; mod schsheet; mod boardedit; mod checks;+mod project;+mod render; mod design; mod dialogs; mod health;@@ -62,7 +64,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.76";+pub const BRIDGE_VERSION: &str = "0.2.77";  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/manufacturing.rs+1−1
@@ -49,7 +49,7 @@ fn set(kv: &mut Vec<(String, String)>, k: &str, v: &str) { }  /// a `|`-separated record with one field replaced or added-fn field(rec: &str, k: &str, v: &str) -> String {+pub(crate) fn field(rec: &str, k: &str, v: &str) -> String {     let mut parts: Vec<String> = rec.split('|').map(String::from).collect();     match parts.iter_mut().find(|p| p.split_once('=').map(|(a, _)| a == k).unwrap_or(false)) {         Some(p) => *p = format!("{k}={v}"),
bridge-rs/src/project.rsadded+532
@@ -0,0 +1,532 @@+//! Documents and projects, the EDA Bridge Standard's batch 4 and Fusion's app verbs on Altium: the document in front,+//! closing everything without a save dialog, a project at a glance, creating, renaming and snapshotting a project,+//! cross-probing between sheet and board, and one library footprint in full. Millimetres.+use crate::sch::{agent_data, st};+use crate::{agent, support};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::time::Duration;++fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }+fn dry(args: &Value) -> bool { args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++/// What a document is, from its file name. Pure.+pub fn kind_of(file: &str) -> &'static str {+    let l = file.to_lowercase();+    if l.ends_with(".prjpcb") || l.ends_with(".prjscr") || l.ends_with(".prjmbd") || l.ends_with(".prjhar") || l.ends_with(".libpkg") { "project" }+    else if l.ends_with(".schdoc") { "schematic" } else if l.ends_with(".pcbdoc") { "board" }+    else if l.ends_with(".schlib") || l.ends_with(".pcblib") || l.ends_with(".intlib") { "library" }+    else if l.ends_with(".step") || l.ends_with(".stp") { "model" } else { "other" }+}++/// The project beside a document that lists it.+pub fn project_of(doc: &str) -> Option<String> {+    let dir = Path::new(doc).parent()?;+    let name = Path::new(doc).file_name()?.to_string_lossy().to_lowercase();+    std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path())+        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))+        .find(|p| std::fs::read_to_string(p).map(|t| t.lines().any(|l| l.to_lowercase().starts_with("documentpath=") && l.to_lowercase().replace('/', "\\").ends_with(&name))).unwrap_or(false))+        .map(|p| p.to_string_lossy().to_string())+}++/// Documents this bridge changed and has not saved since. Altium's scripting API reads a document's changed flag back+/// as false even while its title shows the * (measured 2026-10-27), so the bridge remembers its own unsaved edits.+static UNSAVED: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());++fn norm(p: &str) -> String { p.replace('/', "\\").to_lowercase() }++/// A bridge edit left this document changed and unsaved.+pub fn mark_unsaved(path: &str) { if !path.is_empty() { if let Ok(mut g) = UNSAVED.lock() { g.insert(norm(path)); } } }++/// The document was saved or closed: nothing of ours is pending on it.+pub fn mark_clean(path: &str) { if let Ok(mut g) = UNSAVED.lock() { g.remove(&norm(path)); } }++fn unsaved(path: &str) -> bool { UNSAVED.lock().map(|g| g.contains(&norm(path))).unwrap_or(false) }++fn docs() -> Result<Value, Value> { agent_data(&agent::call("docs", &[], None, Duration::from_secs(30))) }++/// Whether a document has changes not yet saved: changed by this bridge, or flagged by Altium (which misses scripted+/// schematic edits, hence the bridge's own record). None when Altium could not be asked.+pub(crate) fn has_changes(path: &str) -> Option<bool> {+    if unsaved(path) { return Some(true); }+    let d = docs().ok()?;+    Some(d["documents"].as_array()?.iter().any(|x| norm(&st(&x["file"])) == norm(path) && x["modified"].as_bool() == Some(true)))+}++/// altium_document_info {}+pub fn document_info(_args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let d = match docs() { Ok(d) => d, Err(e) => return e };+    let cur = st(&d["current"]);+    if cur.is_empty() { return json!({"success": false, "errorCode": "no_document", "error": "no document is in front in Altium"}); }+    let entry = d["documents"].as_array().cloned().unwrap_or_default().into_iter().find(|x| st(&x["file"]).eq_ignore_ascii_case(&cur)).unwrap_or(Value::Null);+    let saved = Path::new(&cur).is_file();+    json!({"success": true, "name": Path::new(&cur).file_name().map(|n| n.to_string_lossy().to_string()), "kind": kind_of(&cur), "saved": saved,+        "modified": entry["modified"].as_bool().unwrap_or(false) || unsaved(&cur), "path": if saved { json!(cur) } else { Value::Null }, "version": Value::Null,+        "project": project_of(&cur), "openDocuments": d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| json!({"name": Path::new(&st(&x["file"])).file_name().map(|n| n.to_string_lossy().to_string()), "path": x["file"], "kind": kind_of(&st(&x["file"])), "modified": x["modified"].as_bool().unwrap_or(false) || unsaved(&st(&x["file"])), "altiumKind": x["kind"]})).collect::<Vec<_>>(),+        "_hint": "Altium keeps no version numbers for local files (version is null); Altium 365 items have revisions (altium_a365_*)."})+}++/// altium_close_all_documents {save?, discardUnsaved?, includeScratch?}+pub fn close_all_documents(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let d = match docs() { Ok(d) => d, Err(e) => return e };+    let b = |k: &str| args.get(k).and_then(|v| v.as_bool()) == Some(true);+    let (save, discard, scratch) = (b("save"), b("discardUnsaved"), b("includeScratch"));+    // under: only the documents in that folder (a project folder about to be replaced, say)+    let under = support::s(args, "under").map(|u| u.replace('/', "\\").trim_end_matches('\\').to_lowercase() + "\\");+    let (mut closed, mut saved, mut kept) = (vec![], vec![], vec![]);+    // projects last: closing a project first can take its documents with it+    let mut list = d["documents"].as_array().cloned().unwrap_or_default();+    list.sort_by_key(|x| kind_of(&st(&x["file"])) == "project");+    for x in list {+        let f = st(&x["file"]);+        if f.is_empty() { continue; }+        if let Some(u) = &under { if !f.replace('/', "\\").to_lowercase().starts_with(u.as_str()) { continue; } }+        // the bridge's own agent (its script project and script) stays: closing it stops the agent mid-verb+        if Path::new(&f).file_name().map(|n| n.to_string_lossy().starts_with("AdomAgent_")).unwrap_or(false) { continue; }+        let name = Path::new(&f).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or(f.clone());+        let on_disk = Path::new(&f).is_file();+        let modified = x["modified"].as_bool() == Some(true) || unsaved(&f);+        if !on_disk && !scratch { kept.push(json!({"name": name, "why": "scratch"})); continue; }+        if modified && on_disk && save {+            let r = crate::surfaces::save(&json!({"filePath": f}));+            if r.get("success").and_then(|v| v.as_bool()) == Some(false) { kept.push(json!({"name": name, "why": "save failed", "detail": r.get("error")})); continue; }+            saved.push(json!(name));+        } else if modified && !discard {+            kept.push(json!({"name": name, "why": "unsaved changes"}));+            continue;+        }+        let r = agent::call("close_document", &[("path", f.replace('/', "\\"))], None, Duration::from_secs(30));+        if r.get("data").and_then(|v| v.get("closed")).and_then(|v| v.as_bool()) == Some(true) { mark_clean(&f); closed.push(json!(name)); }+    }+    json!({"success": true, "closed": closed, "saved": saved, "keptOpen": kept,+        "_hint": "Altium closes a document without asking: a changed document stays open unless save:true (saved first) or discardUnsaved:true (its changes are lost: ask the person first). Changed means changed by this bridge and not saved since, or flagged by Altium: Altium's API does not always report edits made by hand, so ask the person before closing their work."})+}++/// A project from a path to the project, its folder or any of its documents.+fn find_project(p: &str) -> Option<String> {+    let path = Path::new(p);+    if p.to_lowercase().ends_with(".prjpcb") && path.is_file() { return Some(p.to_string()); }+    if path.is_dir() {+        return std::fs::read_dir(path).ok()?.filter_map(|e| e.ok()).map(|e| e.path())+            .find(|x| x.extension().map(|e| e.eq_ignore_ascii_case("prjpcb")).unwrap_or(false)).map(|x| x.to_string_lossy().to_string());+    }+    project_of(p)+}++fn project_docs(prj: &str) -> Vec<String> {+    let dir = Path::new(prj).parent().unwrap_or(Path::new(".")).to_path_buf();+    let text = std::fs::read(prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+    text.lines().filter_map(|l| l.trim().strip_prefix("DocumentPath=")).map(|d| {+        let p = Path::new(d);+        if p.is_absolute() || d.contains(':') { d.to_string() } else { dir.join(d.replace('\\', "/").replace('/', std::path::MAIN_SEPARATOR_STR)).to_string_lossy().to_string() }+    }).collect()+}++fn modified_of(p: &Path) -> Value {+    std::fs::metadata(p).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+        .map(|d| json!(crate::report::iso_utc(d.as_secs() as i64))).unwrap_or(Value::Null)+}++/// The project file's [Parameter] text variables: Name=, Value= pairs. Pure.+pub fn text_variables(prj_text: &str) -> serde_json::Map<String, Value> {+    let mut out = serde_json::Map::new();+    let mut name: Option<String> = None;+    let mut in_param = false;+    for l in prj_text.lines().map(str::trim) {+        if l.starts_with('[') { in_param = l.to_lowercase().starts_with("[parameter"); name = None; continue; }+        if !in_param { continue; }+        if let Some(n) = l.strip_prefix("Name=") { name = Some(n.to_string()); }+        if let (Some(v), Some(n)) = (l.strip_prefix("Value="), name.as_ref()) { out.insert(n.clone(), json!(v)); }+    }+    out+}++/// altium_project_info {project}+pub fn project_info(args: &Value) -> Value {+    let Some(p) = support::s(args, "project").or_else(|| support::s(args, "projectPath")) else { return bad("project: the project file, its folder or any of its documents") };+    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };+    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+    let docs_list = project_docs(&prj);+    let mut files = vec![json!({"path": prj, "bytes": std::fs::metadata(&prj).map(|m| m.len()).unwrap_or(0), "modified": modified_of(Path::new(&prj))})];+    for d in &docs_list { files.push(json!({"path": d, "bytes": std::fs::metadata(d).map(|m| m.len()).ok(), "modified": modified_of(Path::new(d)), "kind": kind_of(d), "exists": Path::new(d).is_file()})); }+    let sheets = crate::schsheet::hierarchy(&json!({"project": prj}));+    // the board: from Altium when it has it open, else its file size only+    let mut open = false;+    let mut board = Value::Null;+    if support::need_licensed().is_none() {+        if let Ok(d) = docs() {+            let open_files: Vec<String> = d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| st(&x["file"]).to_lowercase()).collect();+            open = docs_list.iter().chain(std::iter::once(&prj)).any(|f| open_files.contains(&f.to_lowercase()));+            if let Some(pcb) = docs_list.iter().find(|f| kind_of(f) == "board" && open_files.contains(&f.to_lowercase())) {+                if support::must_open(pcb, 30).is_none() {+                    let s = crate::routing::routing_state(&json!({}));+                    let bb = crate::fab::outline_bbox(&s);+                    let stack = agent::call("layer_stack", &[], None, Duration::from_secs(60));+                    board = json!({"file": pcb, "layers": stack.get("data").and_then(|d| d["copperLayers"].as_i64()), "parts": s["components"].as_array().map(|a| a.len()),+                        "nets": s["nets"].as_array().map(|a| a.len()), "sizeMm": bb.map(|b| json!([r3(b.2 - b.0), r3(b.3 - b.1)]))});+                }+            }+        }+    }+    if board.is_null() { if let Some(pcb) = docs_list.iter().find(|f| kind_of(f) == "board") { board = json!({"file": pcb, "note": "not open in Altium: open it for layers, parts, nets and size"}); } }+    let classes: Vec<Value> = Vec::new();+    json!({"success": true, "name": Path::new(&prj).file_stem().map(|s| s.to_string_lossy().to_string()), "project": prj, "files": files, "sheets": sheets["tree"], "sheetProblems": sheets["problems"],+        "board": board, "textVariables": text_variables(&text), "netClasses": classes, "modified": modified_of(Path::new(&prj)), "open": open,+        "_hint": "Read from the files, plus the board from Altium when it has it open. Net classes live in the board: altium_net_classes lists them."})+}++/// A new project's .PrjPcb text: the sheet and the board, and text variables as project parameters. Pure.+pub fn project_text(name: &str, vars: &serde_json::Map<String, Value>) -> String {+    let mut t = String::from("[Design]\r\nVersion=1.0\r\nHierarchyMode=0\r\nChannelRoomNamingStyle=0\r\nOutputPath=Project Outputs for ");+    t.push_str(name);+    t.push_str("\r\n\r\n");+    t.push_str(&format!("[Document1]\r\nDocumentPath={name}.SchDoc\r\nAnnotationEnabled=1\r\n\r\n[Document2]\r\nDocumentPath={name}.PcbDoc\r\nAnnotationEnabled=1\r\n\r\n"));+    for (i, (k, v)) in vars.iter().enumerate() { t.push_str(&format!("[Parameter{}]\r\nName={k}\r\nValue={}\r\n\r\n", i + 1, st(v))); }+    t+}++/// altium_project_create {parentDir, name, title?, layers?, fabRules?, textVariables?, dryRun?}+pub fn project_create(args: &Value) -> Value {+    let (Some(parent), Some(name)) = (support::s(args, "parentDir"), support::s(args, "name")) else { return bad("parentDir and name are required") };+    if name.contains(['\\', '/', ':', '*', '?', '"', '<', '>', '|']) { return bad(format!("{name} is not a usable file name")); }+    let dir = PathBuf::from(&parent).join(&name);+    if dir.is_dir() && std::fs::read_dir(&dir).map(|rd| rd.filter_map(|e| e.ok()).any(|e| e.path().extension().map(|x| x.eq_ignore_ascii_case("prjpcb")).unwrap_or(false))).unwrap_or(false) {+        return json!({"success": false, "errorCode": "exists", "error": format!("{} already holds a project", dir.display())});+    }+    let mut vars = args.get("textVariables").and_then(|v| v.as_object()).cloned().unwrap_or_default();+    if let Some(f) = support::s(args, "fabRules") { vars.insert("FabRules".into(), json!(f)); }+    let prj = dir.join(format!("{name}.PrjPcb"));+    let (sch, pcb) = (dir.join(format!("{name}.SchDoc")), dir.join(format!("{name}.PcbDoc")));+    let layers = args.get("layers").and_then(|v| v.as_i64()).unwrap_or(2);+    if ![2, 4, 6, 8].contains(&layers) { return bad("layers: 2, 4, 6 or 8"); }+    let files = vec![prj.to_string_lossy().to_string(), sch.to_string_lossy().to_string(), pcb.to_string_lossy().to_string()];+    if dry(args) { return json!({"success": true, "dryRun": true, "project": files[0], "files": files, "layers": layers, "textVariables": vars}); }+    if let Some(g) = support::need_licensed() { return g; }+    if let Err(e) = std::fs::create_dir_all(&dir).and_then(|_| std::fs::write(&prj, project_text(&name, &vars))) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    // the sheet from Altium's template, titled; the board as Altium makes a new one, with its layer count+    let tpl = match support::altium_public_file(r"Templates\ANSI B Landscape.SchDot") { Ok(p) => p, Err(e) => return json!({"success": false, "errorCode": "template_missing", "error": e}) };+    if let Err(e) = std::fs::copy(&tpl, &sch) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    let mut steps = Vec::new();+    if let Some(t) = support::s(args, "title") {+        let r = crate::schsheet::page(&json!({"sheet": sch.to_string_lossy(), "title": t}));+        steps.push(json!({"title": r.get("success")}));+    }+    let nb = agent::call("new_pcb", &[("path", pcb.to_string_lossy().to_string())], None, Duration::from_secs(90));+    if let Err(e) = agent_data(&nb) { return json!({"success": false, "errorCode": "board_failed", "error": "Altium did not make the board", "reply": e, "project": files[0]}); }+    if layers > 2 {+        let r = crate::boardedit::set_layer_count(&json!({"filePath": pcb.to_string_lossy(), "count": layers}));+        steps.push(json!({"layers": r.get("layers"), "success": r.get("success")}));+        let _ = crate::surfaces::save(&json!({"filePath": pcb.to_string_lossy()}));+    }+    // the new documents leave Altium: Altium may have attached the new board to whatever project was in front+    for f in [&pcb, &sch] { let _ = agent::call("close_document", &[("path", f.to_string_lossy().to_string())], None, Duration::from_secs(30)); }+    json!({"success": true, "project": files[0], "files": files, "layers": layers, "textVariables": vars, "steps": steps,+        "_hint": "Altium's new board has its default shape: set the outline (altium_set_outline) before routing or exporting. Open the project with altium_open_project."})+}++/// The renames for a project: the documents named after it. Pure: (from, to) file names.+pub fn rename_plan(old: &str, new: &str, docs: &[String]) -> Vec<(String, String)> {+    let mut out = Vec::new();+    for d in docs {+        let f = Path::new(d).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();+        let (stem, ext) = f.rsplit_once('.').map(|(a, b)| (a.to_string(), format!(".{b}"))).unwrap_or((f.clone(), String::new()));+        if stem.eq_ignore_ascii_case(old) { out.push((f.clone(), format!("{new}{ext}"))); }+        else if let Some(rest) = stem.strip_prefix(&format!("{old}.")) { out.push((f.clone(), format!("{new}.{rest}{ext}"))); } // lane.Manufacturing.OutJob+    }+    out+}++/// altium_project_rename {project, newName, dryRun?}+pub fn project_rename(args: &Value) -> Value {+    let (Some(p), Some(new)) = (support::s(args, "project").or_else(|| support::s(args, "projectPath")), support::s(args, "newName")) else { return bad("project and newName are required") };+    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };+    let old = Path::new(&prj).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default();+    let dir = Path::new(&prj).parent().unwrap_or(Path::new(".")).to_path_buf();+    let docs_list = project_docs(&prj);+    let mut plan = rename_plan(&old, &new, &docs_list);+    plan.insert(0, (format!("{old}.PrjPcb"), format!("{new}.PrjPcb")));+    for (_, to) in &plan { if dir.join(to).exists() { return json!({"success": false, "errorCode": "exists", "error": format!("{to} exists already")}); } }+    if support::need_licensed().is_none() {+        if let Ok(d) = docs() {+            let open: Vec<String> = d["documents"].as_array().cloned().unwrap_or_default().iter().map(|x| st(&x["file"]).to_lowercase()).collect();+            if docs_list.iter().chain(std::iter::once(&prj)).any(|f| open.contains(&f.to_lowercase())) {+                return json!({"success": false, "errorCode": "project_open", "error": "Altium has this project open: close it first (altium_close_all_documents or altium_close_document)"});+            }+        }+    }+    let renamed: Vec<Value> = plan.iter().map(|(a, b)| json!({"from": a, "to": b})).collect();+    // inside the project file: each renamed document's DocumentPath, and the output folder's name+    let text = std::fs::read(&prj).map(|b| String::from_utf8_lossy(&b).to_string()).unwrap_or_default();+    let mut new_text = text.clone();+    let mut changed = Vec::new();+    for (a, b) in plan.iter().skip(1) {+        let before = new_text.clone();+        new_text = new_text.lines().map(|l| if l.trim().strip_prefix("DocumentPath=").map(|d| d.eq_ignore_ascii_case(a)).unwrap_or(false) { format!("DocumentPath={b}") } else { l.to_string() }).collect::<Vec<_>>().join("\r\n");+        if new_text != before { changed.push(json!({"file": format!("{new}.PrjPcb"), "what": format!("DocumentPath {a} -> {b}")})); }+    }+    if new_text.contains(&format!("Project Outputs for {old}")) { new_text = new_text.replace(&format!("Project Outputs for {old}"), &format!("Project Outputs for {new}")); changed.push(json!({"file": format!("{new}.PrjPcb"), "what": "OutputPath"})); }+    if dry(args) { return json!({"success": true, "dryRun": true, "renamed": renamed, "changed": changed}); }+    if let Err(e) = std::fs::write(&prj, new_text.as_bytes()) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    for (a, b) in &plan { if let Err(e) = std::fs::rename(dir.join(a), dir.join(b)) { return json!({"success": false, "errorCode": "rename_failed", "error": format!("{a} -> {b}: {e}"), "renamed": renamed}); } }+    json!({"success": true, "renamed": renamed, "changed": changed, "project": dir.join(format!("{new}.PrjPcb")).to_string_lossy(),+        "_hint": "Child sheets keep their names; the folder keeps its name. Open the renamed project with altium_open_project."})+}++/// altium_project_snapshot {project, label?, pdfs?}+pub fn project_snapshot(args: &Value) -> Value {+    let Some(p) = support::s(args, "project").or_else(|| support::s(args, "projectPath")) else { return bad("project is required") };+    let Some(prj) = find_project(&p) else { return json!({"success": false, "errorCode": "project_not_found", "error": format!("no .PrjPcb found for {p}")}) };+    let dir = Path::new(&prj).parent().unwrap_or(Path::new(".")).to_path_buf();+    let stamp = crate::report::iso_utc(support::now() as i64).replace([':', '-'], "").replace('T', "-").trim_end_matches('Z').to_string();+    let label = support::s(args, "label").map(|l| format!("-{}", l.replace(['\\', '/', ':', '*', '?', '"', '<', '>', '|', ' '], "_"))).unwrap_or_default();+    let folder = dir.join("snapshots").join(format!("{stamp}{label}"));+    if let Err(e) = std::fs::create_dir_all(&folder) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    let mut files = Vec::new();+    for f in std::iter::once(prj.clone()).chain(project_docs(&prj)) {+        let src = Path::new(&f);+        if !src.is_file() { continue; }+        let to = folder.join(src.file_name().unwrap_or_default());+        if std::fs::copy(src, &to).is_ok() { files.push(to.to_string_lossy().to_string()); }+    }+    let mut pdfs = json!({"made": [], "skipped": Value::Null});+    if args.get("pdfs").and_then(|v| v.as_bool()) != Some(false) {+        if support::need_licensed().is_some() { pdfs["skipped"] = json!("Altium is not running with a licence: the files are copied, no PDFs"); }+        else {+            let out = folder.join("schematic-and-board.pdf");+            let r = crate::sch::export_pdf(&json!({"projectPath": prj, "output": out.to_string_lossy(), "board": true}));+            if r.get("success").and_then(|v| v.as_bool()) == Some(true) { pdfs["made"] = json!([out.to_string_lossy()]); } else { pdfs["skipped"] = json!(format!("the PDF failed: {}", r.get("error").map(|e| e.to_string()).unwrap_or_default())); }+        }+    }+    json!({"success": true, "folder": folder.to_string_lossy(), "files": files, "pdfs": pdfs,+        "_hint": "A copy of what is saved on disk: unsaved edits in Altium are not in it (save first). The PDF holds every sheet and the board's composite print."})+}++/// altium_cross_probe {filePath?, ref?, symbolId?, schematic?, select?}+pub fn cross_probe(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    if let Some(p) = support::s(args, "filePath") { if let Some(e) = support::must_open(&p, 60) { return e; } }+    let st_board = crate::routing::routing_state(&json!({}));+    if st_board.get("success").and_then(|b| b.as_bool()) != Some(true) { return st_board; }+    let pcb = st(&st_board["file"]);+    let cd = agent::call("component_data", &[("designator", String::new()), ("limit", "2000".into())], None, Duration::from_secs(90));+    let parts = cd.get("data").and_then(|d| d["components"].as_array().cloned()).unwrap_or_default();+    // the project's sheets, read from their files+    let sheets: Vec<String> = match support::s(args, "schematic") { Some(s) => vec![s], None => project_of(&pcb).map(|p| project_docs(&p).into_iter().filter(|d| kind_of(d) == "schematic").collect()).unwrap_or_default() };+    let mut syms = Vec::new();+    for sh in &sheets {+        let r = crate::schdoc::read_sheet_file(&json!({"path": sh, "pins": false}));+        for c in r["components"].as_array().cloned().unwrap_or_default() { syms.push((sh.clone(), c)); }+    }+    let want_ref = support::s(args, "ref").map(|r| r.to_uppercase());+    let want_id = support::s(args, "symbolId");+    let mut matches = Vec::new();+    for p in &parts {+        let r = st(&p["designator"]);+        let src = st(&p["sourceUniqueId"]);+        let id_tail = src.rsplit('\\').next().unwrap_or("").to_string();+        let sym = syms.iter().find(|(_, c)| !id_tail.is_empty() && st(&c["uniqueId"]) == id_tail).or_else(|| syms.iter().find(|(_, c)| st(&c["designator"]).eq_ignore_ascii_case(&r)));+        let hit = want_ref.as_ref().map(|w| r.to_uppercase() == *w).unwrap_or(true) && want_id.as_ref().map(|w| sym.map(|(_, c)| st(&c["uniqueId"]) == *w).unwrap_or(false)).unwrap_or(true);+        if !hit { continue; }+        // the exact placement from the board model (component_data rounds to whole mils)+        let c = st_board["components"].as_array().and_then(|a| a.iter().find(|c| st(&c["ref"]).eq_ignore_ascii_case(&r)).cloned()).unwrap_or(Value::Null);+        matches.push(json!({"board": {"ref": r, "id": src, "side": c["side"], "x": c["x"], "y": c["y"], "rotation": c["rotation"]},+            "schematic": sym.map(|(sh, c)| json!({"sheet": sh, "id": c["uniqueId"], "ref": c["designator"], "symbol": c["libReference"], "value": c["comment"]})),+            "linked": !id_tail.is_empty() && sym.map(|(_, c)| st(&c["uniqueId"]) == id_tail).unwrap_or(false)}));+    }+    let board_refs: Vec<String> = parts.iter().map(|p| st(&p["designator"]).to_uppercase()).collect();+    let orphans: Vec<Value> = syms.iter().filter(|(_, c)| !board_refs.contains(&st(&c["designator"]).to_uppercase()) && want_ref.as_ref().map(|w| st(&c["designator"]).to_uppercase() == *w).unwrap_or(true)).map(|(_, c)| c["designator"].clone()).collect();+    if args.get("select").and_then(|v| v.as_bool()) == Some(true) && !matches.is_empty() {+        let refs: Vec<Value> = matches.iter().map(|m| m["board"]["ref"].clone()).collect();+        let _ = crate::design::selection(&json!({"select": refs}));+    }+    if matches.is_empty() && want_ref.is_some() { return json!({"success": false, "errorCode": "part_not_found", "error": "no board part matches", "symbolWithoutPart": orphans}); }+    json!({"success": true, "matches": matches, "symbolWithoutPart": orphans, "sheets": sheets,+        "_hint": "linked:true means the board part carries its symbol's UniqueId (update_pcb put it there); a match by designator alone is linked:false. Sheets are read from their saved files."})+}++/// altium_read_footprint {libraryPath, name}+pub fn read_footprint(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let (Some(lib), Some(name)) = (support::s(args, "libraryPath"), support::s(args, "name")) else { return bad("libraryPath (.PcbLib) and name are required (Altium has no library table: libId is not used)") };+    if let Some(e) = support::must_open(&lib, 60) { return e; }+    let d = match agent_data(&agent::call("lib_fp", &[("name", name.clone())], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };+    let k = d["k"].as_f64().filter(|k| *k > 0.0).unwrap_or(10_000_000.0);+    let mm = |v: &Value| r3(v.as_f64().unwrap_or(0.0) * 25.4 / k);+    // Altium's pad shapes (TShape): 9 is the rounded rectangle of newer libraries+    let shape = |s: i64| match s { 1 => "round", 2 => "rect", 3 => "octagonal", 4 => "circle", 7 | 9 => "roundrect", 8 => "rotated-rect", _ => "other" };+    let pads: Vec<Value> = d["pads"].as_array().cloned().unwrap_or_default().iter().map(|p| {+        let hole = mm(&p[5]);+        let layer = crate::routing::layer_name(p[6].as_i64().unwrap_or(0));+        json!({"number": p[0], "type": if hole > 0.0 { if p[9].as_bool() == Some(false) { "npth" } else { "pth" } } else { "smd" }, "shape": shape(p[7].as_i64().unwrap_or(0)),+            "at": [mm(&p[1]), mm(&p[2])], "sizeMm": [mm(&p[3]), mm(&p[4])], "drillMm": hole, "layers": [layer], "rotation": p[8].as_f64().unwrap_or(0.0) / 1000.0})+    }).collect();+    let mut graphics = serde_json::Map::new();+    for o in d["other"].as_array().cloned().unwrap_or_default() { let l = crate::routing::layer_name(o[1].as_i64().unwrap_or(0)); *graphics.entry(l).or_insert(json!(0)) = json!(graphics.get(&crate::routing::layer_name(o[1].as_i64().unwrap_or(0))).and_then(|v| v.as_i64()).unwrap_or(0) + 1); }+    let mut layers: Vec<String> = pads.iter().filter_map(|p| p["layers"][0].as_str().map(str::to_string)).chain(graphics.keys().cloned()).collect();+    layers.sort(); layers.dedup();+    // the courtyard: the extent of the Courtyard layer's graphics (Mechanical 15, layer 71, as this bridge's footprints+    // and IPC wizards put it), else of everything but the pads; the library footprint itself has no extent in Altium+    let others = d["other"].as_array().cloned().unwrap_or_default();+    let ext = |rows: Vec<&Value>| -> Option<[f64; 4]> {+        let mut b = [f64::MAX, f64::MAX, f64::MIN, f64::MIN];+        for o in rows { if o.as_array().map(|a| a.len() >= 6).unwrap_or(false) { b[0] = b[0].min(mm(&o[2])); b[1] = b[1].min(mm(&o[3])); b[2] = b[2].max(mm(&o[4])); b[3] = b[3].max(mm(&o[5])); } }+        if b[0] <= b[2] { Some(b) } else { None }+    };+    let court = ext(others.iter().filter(|o| o[1].as_i64() == Some(71)).collect()).or_else(|| ext(others.iter().collect()));+    let b = court.map(|c| json!(c)).unwrap_or(d["box"].clone());+    let models: Vec<Value> = d["bodies"].as_array().cloned().unwrap_or_default().iter().map(|x| json!({"path": x["model"], "heightMm": mm(&x["overallHeight"]), "standoffMm": mm(&x["standoff"])})).collect();+    json!({"success": true, "name": d["name"], "library": lib, "pads": pads, "layers": layers, "courtyardMm": if court.is_some() { b.clone() } else { json!([mm(&b[0]), mm(&b[1]), mm(&b[2]), mm(&b[3])]) },+        "graphics": graphics, "attributes": {"mount": if pads.iter().any(|p| p["type"] == "pth") { "through_hole" } else { "smd" }},+        "properties": {"description": d["description"], "heightMm": mm(&d["height"])}, "models": models,+        "_hint": "Positions from the footprint's origin, mm. courtyardMm is the footprint's bounding box (Altium courtyards are a mechanical layer's graphics). altium_footprint_primitives reads a placed part."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn kinds_by_extension() {+        assert_eq!(kind_of("a.PrjPcb"), "project");+        assert_eq!(kind_of("C:/x/Main.SchDoc"), "schematic");+        assert_eq!(kind_of("b.PcbDoc"), "board");+        assert_eq!(kind_of("l.PcbLib"), "library");+        assert_eq!(kind_of("n.txt"), "other");+    }++    #[test]+    fn renaming_takes_the_documents_named_after_the_project() {+        let docs = vec!["C:/p/lane.SchDoc".to_string(), "C:/p/LaneSub.SchDoc".to_string(), "C:/p/lane.PcbDoc".to_string(), "C:/p/lane.Manufacturing.OutJob".to_string()];+        let plan = rename_plan("lane", "road", &docs);+        assert_eq!(plan, vec![("lane.SchDoc".into(), "road.SchDoc".into()), ("lane.PcbDoc".into(), "road.PcbDoc".into()), ("lane.Manufacturing.OutJob".into(), "road.Manufacturing.OutJob".into())]);+    }++    #[test]+    fn a_new_project_lists_its_sheet_board_and_variables() {+        let mut v = serde_json::Map::new();+        v.insert("REV".into(), json!("A"));+        let t = project_text("Buck", &v);+        assert!(t.contains("DocumentPath=Buck.SchDoc") && t.contains("DocumentPath=Buck.PcbDoc"));+        assert_eq!(text_variables(&t).get("REV"), Some(&json!("A")));+    }+}++/// The library part's pieces: its symbol library, the footprint name and the footprint library. From a .SchLib, the+/// footprint is the symbol's PCB model, found in a .PcbLib beside it (or the ones named).+fn part_pieces(args: &Value) -> Result<(String, String, Option<String>, Option<String>), Value> {+    let Some(part) = support::s(args, "part") else { return Err(bad("part (the symbol's name) is required")) };+    let Some(lib) = support::s(args, "libraryPath").filter(|l| l.to_lowercase().ends_with(".schlib")) else {+        return Err(bad("libraryPath (the .SchLib that holds the part) is required: Altium has no global library table to resolve a library id"));+    };+    let streams = std::fs::read(&lib).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok());+    let Some(st) = streams else { return Err(json!({"success": false, "errorCode": "library_unreadable", "error": format!("{lib} could not be read")})) };+    if !st.iter().any(|(n, d)| n.ends_with("Data") && crate::schdoc::records(d).iter().any(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1") && r.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(&part)).unwrap_or(false))) {+        return Err(json!({"success": false, "errorCode": "symbol_not_found", "error": format!("{part} is not in {lib}")}));+    }+    let fp = support::s(args, "footprint").or_else(|| crate::render::symbol_footprint(&st, &part));+    let dir = Path::new(&lib).parent().unwrap_or(Path::new(".")).to_path_buf();+    let fp_lib = support::s(args, "footprintLibrary").or_else(|| fp.as_ref().and_then(|f| crate::render::pcblib_with(&dir, f)));+    Ok((part, lib, fp, fp_lib))+}++/// altium_export_library_part {part, libraryPath, footprint?, footprintLibrary?, what?, outputDir?}+pub fn export_library_part(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let (part, lib, fp, fp_lib) = match part_pieces(args) { Ok(x) => x, Err(e) => return e };+    let what: Vec<String> = args.get("what").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or(vec!["symbol".into(), "footprint".into(), "model".into()]);+    let out = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(&lib).parent().unwrap_or(Path::new(".")).join("exports").join(&part));+    if let Err(e) = std::fs::create_dir_all(&out) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    let mut exports = serde_json::Map::new();+    let mut missing = Vec::new();+    if what.iter().any(|w| w == "symbol") {+        let dst = out.join(format!("{part}.SchLib"));+        let _ = std::fs::remove_file(&dst);+        let ok = agent_data(&agent::call("ensure_lib", &[("kind", "SCHLIB".into()), ("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(90)))+            .and_then(|_| agent_data(&agent::call("xcopy_symbol", &[("fromLib", lib.clone()), ("from", part.clone())], None, Duration::from_secs(90))));+        match ok {+            Ok(_) => { let _ = crate::surfaces::save(&json!({"filePath": dst.to_string_lossy()})); let _ = agent::call("close_document", &[("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(30)); exports.insert("symbol".into(), json!(dst.to_string_lossy())); }+            Err(e) => missing.push(json!({"what": "symbol", "why": e.get("error").cloned().unwrap_or(e)})),+        }+    }+    if what.iter().any(|w| w == "footprint") {+        match (&fp, &fp_lib) {+            (Some(f), Some(l)) => {+                let dst = out.join(format!("{f}.PcbLib"));+                let _ = std::fs::remove_file(&dst);+                let ok = agent_data(&agent::call("ensure_lib", &[("kind", "PCBLIB".into()), ("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(90)))+                    .and_then(|_| agent_data(&agent::call("xcopy_footprint", &[("fromLib", l.clone()), ("from", f.clone()), ("to", f.clone())], None, Duration::from_secs(90))));+                match ok {+                    Ok(_) => { let _ = crate::surfaces::save(&json!({"filePath": dst.to_string_lossy()})); let _ = agent::call("close_document", &[("path", dst.to_string_lossy().to_string())], None, Duration::from_secs(30)); exports.insert("footprint".into(), json!(dst.to_string_lossy())); }+                    Err(e) => missing.push(json!({"what": "footprint", "why": e.get("error").cloned().unwrap_or(e)})),+                }+            }+            _ => missing.push(json!({"what": "footprint", "why": "no footprint: the symbol has no PCB model, or no .PcbLib beside the library holds it (name footprint and footprintLibrary)"})),+        }+    }+    if what.iter().any(|w| w == "model") {+        let model = match (&fp, &fp_lib) {+            (Some(f), Some(l)) => read_footprint(&json!({"libraryPath": l, "name": f}))["models"].as_array().and_then(|m| m.first()).and_then(|m| m["path"].as_str().map(str::to_string)),+            _ => None,+        };+        match model.filter(|m| Path::new(m).is_file()) {+            Some(m) => { let dst = out.join(Path::new(&m).file_name().unwrap_or_default()); match std::fs::copy(&m, &dst) { Ok(_) => { exports.insert("model".into(), json!(dst.to_string_lossy())); } Err(e) => missing.push(json!({"what": "model", "why": e.to_string()})) } }+            None => missing.push(json!({"what": "model", "why": "no 3D model file: the footprint has no body, or its STEP is embedded in the library and its source file is gone (export the board with altium_export_step for a STEP)"})),+        }+    }+    // a footprint with no body has no model to give: that fails the export only when the caller asked for the model+    let asked_model = args.get("what").is_some();+    let ok = missing.iter().all(|m| m["what"] == "model" && !asked_model);+    json!({"success": ok, "complete": missing.is_empty(), "exports": exports, "missing": missing, "outputDir": out.to_string_lossy(), "footprint": fp,+        "_hint": "Each library holds only this part. The footprint library carries the 3D body too (Altium embeds it); model is the STEP file the body came from, when it still exists."})+}++/// altium_create_part_project {part, libraryPath, footprint?, footprintLibrary?, projectName?, outputDir?, overwrite?}+pub fn create_part_project(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let (part, lib, fp, fp_lib) = match part_pieces(args) { Ok(x) => x, Err(e) => return e };+    let (Some(fp), Some(fp_lib)) = (fp, fp_lib) else { return json!({"success": false, "errorCode": "no_footprint", "error": "the part needs a footprint: name footprint and footprintLibrary, or give the symbol a PCB model"}) };+    let name = support::s(args, "projectName").unwrap_or_else(|| format!("{}-demo", part.replace([' ', '/', '\\'], "_")));+    let parent = support::s(args, "outputDir").unwrap_or_else(|| Path::new(&lib).parent().unwrap_or(Path::new(".")).join("part-projects").to_string_lossy().to_string());+    let dir = Path::new(&parent).join(&name);+    if dir.exists() {+        if args.get("overwrite").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "exists", "error": format!("{} exists: overwrite:true replaces it", dir.display())}); }+        // only the documents of the project being replaced: anything else open may be someone's work+        let _ = close_all_documents(&json!({"under": dir.to_string_lossy(), "discardUnsaved": true}));+        if let Err(e) = std::fs::remove_dir_all(&dir) { return json!({"success": false, "errorCode": "write_failed", "error": e.to_string()}); }+    }+    let _ = std::fs::create_dir_all(&parent);+    let pc = project_create(&json!({"parentDir": parent, "name": name, "title": format!("{part} demo")}));+    if pc.get("success").and_then(|b| b.as_bool()) != Some(true) { return pc; }+    let prj = st(&pc["project"]);+    let sch = dir.join(format!("{name}.SchDoc")).to_string_lossy().to_string();+    let pcb = dir.join(format!("{name}.PcbDoc")).to_string_lossy().to_string();+    let mut steps = vec![json!({"project": prj})];+    // the libraries join the project, so the change order finds the footprint+    for l in [&lib, &fp_lib] { if let Err(e) = crate::hier::add_to_project(&prj, l) { return e; } }+    let _ = crate::surfaces::open_document(&json!({"filePath": prj}));+    let placed = crate::sch::place_part(&json!({"sheet": sch, "library": lib, "symbol": part, "designator": "U1", "x": 4000, "y": 4000, "footprint": fp, "pcbLib": fp_lib}));+    steps.push(json!({"symbolPlaced": placed.get("success"), "detail": placed.get("error")}));+    if placed.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "place_failed", "error": "the symbol could not be placed", "reply": placed, "project": prj}); }+    let up = crate::sch::update_pcb(&json!({"projectPath": prj, "execute": true}));+    steps.push(json!({"updatePcb": up.get("executed"), "detail": up.get("error")}));+    // a board just big enough: the part with a 5 mm margin+    if crate::support::must_open(&pcb, 60).is_none() {+        let s2 = crate::routing::routing_state(&json!({}));+        let pads = s2["pads"].as_array().cloned().unwrap_or_default();+        if !pads.is_empty() {+            let f = |p: &Value, k: &str| p[k].as_f64().unwrap_or(0.0);+            let (x0, y0, x1, y1) = pads.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(f(p, "x") - f(p, "sizeX")), b.1.min(f(p, "y") - f(p, "sizeY")), b.2.max(f(p, "x") + f(p, "sizeX")), b.3.max(f(p, "y") + f(p, "sizeY"))));+            // the change order drops a new part beside Altium's default board: it moves so the board's corner is the origin+            let m = crate::routing::move_parts(&json!({"parts": [{"ref": "U1", "dx": r3(5.0 - x0), "dy": r3(5.0 - y0)}]}));+            steps.push(json!({"moved": m.get("success")}));+            let r = crate::routing::set_outline(&json!({"outline": {"rect": [0.0, 0.0, r3(x1 - x0 + 10.0), r3(y1 - y0 + 10.0)], "cornerRadius": 1.0}}));+            steps.push(json!({"outline": r.get("success")}));+        }+        let _ = crate::surfaces::save(&json!({"filePath": pcb}));+    }+    json!({"success": up.get("success").and_then(|b| b.as_bool()) != Some(false), "project": prj, "schematic": sch, "board": pcb, "steps": steps,+        "_hint": "A real project: the symbol on the sheet as U1, the footprint on the board by Altium's own change order, a board 5 mm round the part. Show it with altium_show_schematic, altium_show_2d_board and altium_show_3d_board."})+}
bridge-rs/src/render.rsadded+234
@@ -0,0 +1,234 @@+//! Board pictures without a window, the EDA Bridge Standard's render_board_3d and render_board_layers on Altium:+//! Altium's own prints (the PCB 3D Print, the composite print of chosen layers) to PDF through the board's project,+//! then rendered to PNG by Windows' PDF renderer, as render_schematic does for a sheet.+use crate::{routing, support};+use serde_json::{json, Value};+use std::path::{Path, PathBuf};++fn bad(msg: impl Into<String>) -> Value { json!({"success": false, "errorCode": "bad_args", "error": msg.into()}) }++/// Page `page` (negative counts from the end) of a PDF as a PNG `width` px wide.+pub fn pdf_png(pdf: &Path, png: &Path, width: i64, page: i64) -> Result<Value, String> {+    let tmp = std::env::temp_dir().join("adom-altium-render").join(format!("{}", (support::now() * 1000.0) as u64));+    std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?;+    let script = tmp.join("render.ps1");+    std::fs::write(&script, crate::schsheet::RENDER_PS).map_err(|e| e.to_string())?;+    let r = crate::schsheet::powershell(&script, &["-Pdf".into(), pdf.to_string_lossy().to_string(), "-Png".into(), png.to_string_lossy().to_string(), "-Width".into(), width.to_string(), "-PageIndex".into(), page.to_string()]);+    let _ = std::fs::remove_dir_all(&tmp);+    r+}++/// The board to draw and its project: filePath, or the board open in Altium.+fn board_and_project(args: &Value) -> Result<(String, String), Value> {+    if let Some(g) = support::need_licensed() { return Err(g); }+    let pcb = match support::s(args, "filePath") {+        Some(p) => p,+        None => { let st = routing::routing_state(&json!({})); match st["file"].as_str() { Some(f) if !f.is_empty() => f.to_string(), _ => return Err(st) } }+    };+    let Some(prj) = crate::project::project_of(&pcb) else {+        return Err(json!({"success": false, "errorCode": "no_project", "error": format!("{pcb} is in no project beside it: Altium prints a project's documents"), "_hint": "Add the board to a .PrjPcb in its folder, then run this again."}));+    };+    Ok((pcb, prj))+}++fn out_dir(args: &Value, pcb: &str) -> PathBuf {+    support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| Path::new(pcb).parent().unwrap_or(Path::new(".")).join("render"))+}++/// altium_render_board_3d {filePath?, side?, width?, outputDir?}+pub fn render_board_3d(args: &Value) -> Value {+    let (pcb, prj) = match board_and_project(args) { Ok(x) => x, Err(e) => return e };+    let side = args.get("side").and_then(|v| v.as_str()).unwrap_or("top");+    if side != "top" && side != "bottom" { return json!({"success": false, "errorCode": "not_supported", "error": format!("side {side}: Altium's 3D print looks straight down at the top or up at the bottom; left, right, front and back need a window (altium_show_3d_board)")}); }+    let width = args.get("width").and_then(|v| v.as_i64()).unwrap_or(1600).clamp(200, 8000);+    let dir = out_dir(args, &pcb);+    let _ = std::fs::create_dir_all(&dir);+    let stem = Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());+    let pdf = dir.join(format!("{stem}-3d-{side}.pdf"));+    let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy(), "board3d": side}));+    if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "print_failed", "error": "Altium's 3D print wrote no PDF", "reply": ex}); }+    let png = dir.join(format!("{stem}-3d-{side}.png"));+    let r = match pdf_png(&pdf, &png, width, -1) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };+    let ignored: Vec<&str> = ["height", "quality", "background", "zoom", "perspective", "format"].into_iter().filter(|k| args.get(*k).is_some()).collect();+    json!({"success": true, "image": png.to_string_lossy(), "width": r["width"], "height": r["height"], "side": side, "pdf": pdf.to_string_lossy(), "optionsNotApplied": ignored, "windowEtiquette": "background",+        "_hint": "Altium's own PCB 3D Print (its Assembly template's settings, looking straight down or up), printed to PDF and rendered by Windows: no window opens. Parts with no 3D body show as bare pads (altium_bodies lists them)."})+}++/// The presets: name, what it shows, and Altium's print layers. Pure.+pub fn presets() -> Vec<(&'static str, &'static str, Vec<&'static str>)> {+    vec![+        ("all", "every outer layer: silkscreen, copper and the outline", vec!["TopOverlay", "TopLayer", "BottomLayer", "BottomOverlay", "MultiLayer", "Mechanical1"]),+        ("top_copper", "top copper and pads", vec!["TopLayer", "MultiLayer", "Mechanical1"]),+        ("bottom_copper", "bottom copper and pads", vec!["BottomLayer", "MultiLayer", "Mechanical1"]),+        ("top_silkscreen", "top silkscreen", vec!["TopOverlay", "Mechanical1"]),+        ("bottom_silkscreen", "bottom silkscreen", vec!["BottomOverlay", "Mechanical1"]),+        ("top_soldermask", "top solder mask openings", vec!["TopSolder", "Mechanical1"]),+        ("bottom_soldermask", "bottom solder mask openings", vec!["BottomSolder", "Mechanical1"]),+        ("top_paste", "top paste (the stencil)", vec!["TopPaste", "Mechanical1"]),+        ("bottom_paste", "bottom paste", vec!["BottomPaste", "Mechanical1"]),+        ("outline", "the board outline", vec!["Mechanical1", "KeepOutLayer"]),+        ("drill", "the drill drawing", vec!["DrillDrawing", "Mechanical1"]),+        ("assembly_top", "top assembly: silkscreen, pads and outline", vec!["TopOverlay", "MultiLayer", "Mechanical1"]),+        ("assembly_bottom", "bottom assembly", vec!["BottomOverlay", "MultiLayer", "Mechanical1"]),+        ("fabrication", "outline, drill drawing and pads", vec!["Mechanical1", "DrillDrawing", "MultiLayer"]),+    ]+}++/// Altium's print layer name for a layer id (as routing_state names them, or the tool's own L<n>). Pure.+pub fn print_layer(id: i64) -> Option<String> {+    Some(match id {+        1 => "TopLayer".into(), 32 => "BottomLayer".into(), 2..=31 => format!("MidLayer{}", id - 1), 39..=54 => format!("InternalPlane{}", id - 38),+        33 => "TopOverlay".into(), 34 => "BottomOverlay".into(), 35 => "TopPaste".into(), 36 => "BottomPaste".into(), 37 => "TopSolder".into(), 38 => "BottomSolder".into(),+        55 => "DrillGuide".into(), 56 => "KeepOutLayer".into(), 57..=72 => format!("Mechanical{}", id - 56), 73 => "DrillDrawing".into(), 74 => "MultiLayer".into(),+        _ => return None,+    })+}++/// altium_render_board_layers {filePath?, preset? | layers?, format?, dpi?, mirror?, outputPath?, listPresets?}+/// The box round a board's outline plus 1 mm, in Altium's internal units (10000 to the mil), from routing_state's mm.+fn outline_area(state: &Value) -> Option<[i64; 4]> {+    let pts = state["outline"].as_array()?;+    let xy: Vec<(f64, f64)> = pts.iter().filter_map(|p| Some((p[0].as_f64()?, p[1].as_f64()?))).collect();+    if xy.len() < 3 { return None; }+    let (x0, y0, x1, y1) = xy.iter().fold((f64::MAX, f64::MAX, f64::MIN, f64::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));+    let u = |mm: f64| (mm / 25.4 * 1000.0 * 10000.0).round() as i64;+    Some([u(x0 - 1.0), u(y0 - 1.0), u(x1 + 1.0), u(y1 + 1.0)])+}++pub fn render_board_layers(args: &Value) -> Value {+    if args.get("listPresets").and_then(|v| v.as_bool()) == Some(true) {+        let p: serde_json::Map<String, Value> = presets().into_iter().map(|(n, d, l)| (n.to_string(), json!({"description": d, "altiumLayers": l}))).collect();+        return json!({"success": true, "presets": p});+    }+    if args.get("format").and_then(|v| v.as_str()) == Some("svg") { return json!({"success": false, "errorCode": "not_supported", "error": "Altium prints to PDF here and Windows renders it to PNG: svg is not made (format png)"}); }+    let (pcb, prj) = match board_and_project(args) { Ok(x) => x, Err(e) => return e };+    let (name, layers): (String, Vec<String>) = match args.get("layers").and_then(|v| v.as_array()) {+        Some(ls) => {+            // standard copper names through this board's stack (In2.Cu may be a plane), or the tool's own L<n>+            if support::must_open(&pcb, 60).is_none() { let _ = routing::routing_state(&json!({})); }+            let mut out = Vec::new();+            for l in ls {+                let id = routing::layer_id(l).or_else(|| l.as_str().and_then(|x| x.strip_prefix('L')).and_then(|n| n.parse().ok()));+                match id.and_then(print_layer) { Some(n) => out.push(n), None => return bad(format!("layer {l}: a copper name (F.Cu, In1.Cu, B.Cu) or Altium's own id (L33 is the top silkscreen)")) }+            }+            ("custom".into(), out)+        }+        None => {+            let p = args.get("preset").and_then(|v| v.as_str()).unwrap_or("all");+            match presets().into_iter().find(|x| x.0 == p) { Some((n, _, l)) => (n.into(), l.into_iter().map(str::to_string).collect()), None => return bad(format!("preset {p}: listPresets:true names them")) }+        }+    };+    let dpi = args.get("dpi").and_then(|v| v.as_i64()).unwrap_or(300).clamp(50, 1200);+    // the print fills an A4 landscape page (11.69 in wide)+    let width = ((11.69 * dpi as f64).round() as i64).clamp(200, 12000);+    let stem = Path::new(&pcb).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or("board".into());+    let png = support::s(args, "outputPath").map(PathBuf::from).unwrap_or_else(|| out_dir(args, &pcb).join(format!("{stem}-{name}.png")));+    if let Some(d) = png.parent() { let _ = std::fs::create_dir_all(d); }+    let pdf = png.with_extension("pdf");+    let mirror = args.get("mirror").and_then(|v| v.as_bool()) == Some(true);+    // the board's own box, 1 mm round its outline: the design extent takes in rooms and parts left off the board+    // (a change order's room beside the default board made a one-part board a speck on the page, 2026-10-27)+    let whole = args.get("area").and_then(|v| v.as_str()) == Some("extent");+    let area = if whole || support::must_open(&pcb, 60).is_some() { None } else { outline_area(&routing::routing_state(&json!({}))) };+    let ex = crate::sch::export_pdf(&json!({"projectPath": prj, "output": pdf.to_string_lossy(), "board": true, "boardLayers": layers, "mirror": mirror, "boardArea": area}));+    if ex.get("success").and_then(|b| b.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "print_failed", "error": "Altium's board print wrote no PDF", "reply": ex}); }+    let r = match pdf_png(&pdf, &png, width, -1) { Ok(r) => r, Err(e) => return json!({"success": false, "errorCode": "render_failed", "error": e}) };+    json!({"success": true, "path": png.to_string_lossy(), "format": "png", "widthPx": r["width"], "heightPx": r["height"], "dpi": dpi, "preset": name, "layers": layers, "mirror": mirror, "pdf": pdf.to_string_lossy(), "windowEtiquette": "background",+        "area": if area.is_some() { "board" } else { "extent" }, "_hint": "Altium's composite print of these layers, the board's outline plus 1 mm (area:\"extent\" prints every object), fitted to an A4 landscape page and rendered by Windows: no window opens. Inner layers appear only when listed in layers; mirror draws the board as seen from below."})+}++#[cfg(test)]+mod tests {+    use super::*;++    #[test]+    fn the_print_area_is_the_outline_plus_a_millimetre() {+        let a = outline_area(&json!({"outline": [[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [0.0, 5.0]]})).unwrap();+        assert_eq!(a, [-393701, -393701, 4330709, 2362205]);+        assert!(outline_area(&json!({"outline": []})).is_none());+    }++    #[test]+    fn layer_ids_map_to_print_layers() {+        assert_eq!(print_layer(1).as_deref(), Some("TopLayer"));+        assert_eq!(print_layer(3).as_deref(), Some("MidLayer2"));+        assert_eq!(print_layer(39).as_deref(), Some("InternalPlane1"));+        assert_eq!(print_layer(57).as_deref(), Some("Mechanical1"));+        assert_eq!(print_layer(33).as_deref(), Some("TopOverlay"));+        assert!(print_layer(999).is_none());+        assert!(presets().iter().any(|p| p.0 == "top_paste"));+    }+}++/// A SchLib symbol's footprint model name (its PCBLIB implementation), read from the library file. Pure over the streams.+pub fn symbol_footprint(streams: &std::collections::BTreeMap<String, Vec<u8>>, libref: &str) -> Option<String> {+    for (name, data) in streams {+        if !name.ends_with("Data") { continue; }+        let recs = crate::schdoc::records(data);+        if !recs.iter().any(|r| r.get("RECORD").map(|v| v.as_str()) == Some("1") && r.get("LIBREFERENCE").map(|l| l.eq_ignore_ascii_case(libref)).unwrap_or(false)) { continue; }+        return recs.iter().find(|r| r.get("RECORD").map(|v| v.as_str()) == Some("45") && r.get("MODELTYPE").map(|t| t.eq_ignore_ascii_case("PCBLIB")).unwrap_or(false))+            .and_then(|r| r.get("MODELNAME").cloned());+    }+    None+}++/// The .PcbLib beside `dir` that holds a footprint of that name (its storage is named after it).+pub(crate) fn pcblib_with(dir: &Path, footprint: &str) -> Option<String> {+    std::fs::read_dir(dir).ok()?.filter_map(|e| e.ok()).map(|e| e.path())+        .filter(|p| p.extension().map(|x| x.eq_ignore_ascii_case("pcblib")).unwrap_or(false))+        .find(|p| std::fs::read(p).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok()).map(|s| s.keys().any(|k| k.split('/').next().map(|t| t.eq_ignore_ascii_case(footprint)).unwrap_or(false))).unwrap_or(false))+        .map(|p| p.to_string_lossy().to_string())+}++fn save_shot(r: &Value, path: &Path) -> Result<(i64, i64), String> {+    let img = r["shot"]["image"].as_str().ok_or_else(|| r.get("error").map(|e| e.to_string()).unwrap_or_else(|| "no picture in the reply".into()))?;+    let bytes = crate::a365::b64url_decode(img).ok_or("the picture did not decode")?;+    std::fs::write(path, bytes).map_err(|e| e.to_string())?;+    Ok((r["shot"]["width"].as_i64().unwrap_or(0), r["shot"]["height"].as_i64().unwrap_or(0)))+}++/// altium_library_views {libraryPath, parts, views?, outputDir?}+pub fn library_views(args: &Value) -> Value {+    if let Some(g) = support::need_licensed() { return g; }+    let Some(lib) = support::s(args, "libraryPath") else { return bad("libraryPath (.SchLib or .PcbLib) is required") };+    let parts: Vec<String> = args.get("parts").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 parts.is_empty() { return bad("parts: [part name] is required"); }+    let views: Vec<String> = args.get("views").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or(vec!["symbol".into(), "footprint".into(), "3d".into(), "device".into()]);+    let dir = Path::new(&lib).parent().unwrap_or(Path::new(".")).to_path_buf();+    let out = support::s(args, "outputDir").map(PathBuf::from).unwrap_or_else(|| dir.join("views"));+    let _ = std::fs::create_dir_all(&out);+    let is_sch = lib.to_lowercase().ends_with(".schlib");+    let sch_streams = if is_sch { std::fs::read(&lib).ok().and_then(|b| crate::schdoc::cfb_streams(&b).ok()) } else { None };+    let mut captured = Vec::new();+    for part in &parts {+        // the footprint: the part itself in a PcbLib, the symbol's footprint model from a SchLib+        let fp = if is_sch { sch_streams.as_ref().and_then(|s| symbol_footprint(s, part)) } else { Some(part.clone()) };+        let fp_lib = if is_sch { fp.as_ref().and_then(|f| pcblib_with(&dir, f)) } else { Some(lib.clone()) };+        for view in &views {+            let path = out.join(format!("{part}-{view}.png"));+            let mut row = json!({"part": part, "view": view, "path": path.to_string_lossy(), "ok": false});+            let r = match view.as_str() {+                "symbol" if is_sch => crate::surfaces::show_symbol(&json!({"libraryPath": lib, "symbolName": part})),+                "symbol" => { row["error"] = json!("a .PcbLib holds footprints only: give the .SchLib for the symbol"); captured.push(row); continue; }+                "footprint" | "3d" => {+                    let (Some(f), Some(l)) = (fp.as_ref(), fp_lib.as_ref()) else { row["error"] = json!("no footprint found for the part (its model link, or a .PcbLib beside the library that holds it)"); captured.push(row); continue; };+                    if view == "3d" {+                        let rf = crate::project::read_footprint(&json!({"libraryPath": l, "name": f}));+                        if rf["models"].as_array().map(|m| m.is_empty()).unwrap_or(true) { row["error"] = json!(format!("{f} has no 3D body: add one (altium_add_body)")); captured.push(row); continue; }+                        crate::surfaces::show_3d_chip(&json!({"libraryPath": l, "footprintName": f}))+                    } else { crate::surfaces::show_footprint(&json!({"libraryPath": l, "footprintName": f})) }+                }+                "device" => { row["error"] = json!("Altium has no device view: the symbol-pin to footprint-pad map is altium_pin_pad_check"); captured.push(row); continue; }+                o => { row["error"] = json!(format!("view {o}: symbol, footprint, 3d or device")); captured.push(row); continue; }+            };+            match save_shot(&r, &path) {+                Ok((w, h)) => { row["ok"] = json!(true); row["width"] = json!(w); row["height"] = json!(h); if view != "symbol" { row["footprint"] = json!(fp); } }+                Err(e) => { row["error"] = json!(e); }+            }+            captured.push(row);+        }+    }+    let all_ok = captured.iter().all(|c| c["ok"] == json!(true) || c["view"] == "device");+    json!({"success": all_ok, "captured": captured, "outputDir": out.to_string_lossy(), "windowEtiquette": "background",+        "_hint": "Each picture is Altium's own editor captured in the background (no foreground). The device view (symbol pins mapped to pads) is altium_pin_pad_check on Altium."})+}
bridge-rs/src/report.rs+21
@@ -95,6 +95,21 @@ table{{width:100%;border-collapse:collapse;font-size:13px}} th,td{{text-align:le         esc(board), esc(when), pass, work, esc(version), img, body) } +/// "YYYY-MM-DDTHH:MM:SSZ" for seconds since 1970 (civil-from-days, no date crate). Pure.+pub fn iso_utc(secs: i64) -> String {+    let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));+    let z = days + 719468;+    let era = z.div_euclid(146097);+    let doe = z - era * 146097;+    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+    let mp = (5 * doy + 2) / 153;+    let d = doy - (153 * mp + 2) / 5 + 1;+    let m = if mp < 10 { mp + 3 } else { mp - 9 };+    let y = yoe + era * 400 + if m <= 2 { 1 } else { 0 };+    format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, (rem % 3600) / 60, rem % 60)+}+ /// "YYYY-MM-DD HH:MM UTC" now (civil-from-days, no date crate). Pure but for the clock. fn utc_now() -> String {     let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);@@ -155,6 +170,12 @@ pub fn board_report(args: &Value) -> Value { mod tests {     use super::*; +    #[test]+    fn iso_dates() {+        assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");+        assert_eq!(iso_utc(1793134800), "2026-10-27T21:00:00Z");+    }+     #[test]     fn sections_read_every_check_and_the_page_escapes() {         let c = json!({"drc": {"success": true, "errors": 0, "unconnected": 0, "violations": []},
bridge-rs/src/routing.rs+11−3
@@ -26,9 +26,10 @@ fn deg(v: &Value) -> Value {     json!(v.as_f64().unwrap_or(0.0) / 1000.0) } -/// This board's copper layers as the board model names them, by their place in the stack (F.Cu, In1.Cu .., B.Cu;-/// an internal plane too, the EDA Bridge Standard's rule): Altium layer id and name. Set from the stack on every read-/// of the board and of the stack, so names and ids agree with the board the caller last read.+// This board's copper layers as the board model names them, by their place in the stack (F.Cu, In1.Cu .., B.Cu; an+// internal plane too, the EDA Bridge Standard's rule): Altium layer id and name. Set from the stack on every read of+// the board and of the stack, so names and ids agree with the board the caller last read. Per thread: one verb runs+// on one thread from its first read to its last edit. thread_local! { static LAYER_MAP: std::cell::RefCell<Vec<(i64, String)>> = const { std::cell::RefCell::new(Vec::new()) }; }  /// The stack's copper layers named by place: the first is F.Cu, the last B.Cu, the ones between In1.Cu, In2.Cu ..@@ -374,6 +375,8 @@ pub(crate) fn apply(ops: &[String], before: &Value, what: &str) -> Value {         _ => return r,     };     let after = routing_state(&json!({}));+    // a board edit is never saved here: the board has unsaved changes until altium_save+    if d["applied"].as_i64().unwrap_or(0) > 0 { crate::project::mark_unsaved(after["file"].as_str().unwrap_or("")); }     let failed = d.get("failed").and_then(|v| v.as_i64()).unwrap_or(0);     let mut out = json!({         "success": failed == 0, "applied": d["applied"], "failed": failed, "results": d["results"],@@ -916,6 +919,11 @@ pub(crate) fn project_members(prj: &std::path::Path) -> (Vec<String>, Vec<String /// Save every open member of a project, then close them and the project: no prompt, nothing lost. pub(crate) fn close_project_saved(prj: &str, open: &[String]) {     for d in open {+        // a library the project lists is often someone's shared source: saved only when it has changes (one that+        // merely joined the project was rewritten by this save, measured 2026-10-27). Sheets and boards are saved+        // as before, since hand edits are not always flagged.+        let lib = { let l = d.to_lowercase(); l.ends_with(".schlib") || l.ends_with(".pcblib") };+        if lib && crate::project::has_changes(d) == Some(false) { continue; }         let _ = crate::surfaces::save(&json!({"filePath": d}));     }     for d in open.iter().map(|s| s.as_str()).chain(std::iter::once(prj)) {
bridge-rs/src/sch.rs+30−10
@@ -24,9 +24,11 @@ pub(crate) fn need_sheet(args: &Value) -> Result<String, Value> {  /// Save the sheet unless save:false; the reply says which. pub(crate) fn maybe_save(args: &Value, sheet: &str) -> Value {-    if args.get("save").and_then(|b| b.as_bool()) == Some(false) { return json!(false); }+    if args.get("save").and_then(|b| b.as_bool()) == Some(false) { crate::project::mark_unsaved(sheet); return json!(false); }     let r = crate::surfaces::save(&json!({"filePath": sheet}));-    json!(r.get("success").and_then(|b| b.as_bool()) != Some(false))+    let ok = r.get("success").and_then(|b| b.as_bool()) != Some(false);+    if ok { crate::project::mark_clean(sheet); } else { crate::project::mark_unsaved(sheet); }+    json!(ok) }  pub(crate) fn agent_data(r: &Value) -> Result<Value, Value> {@@ -535,7 +537,13 @@ fn eco_rows(tree: &Value) -> Vec<String> { pub fn pdf_outjob(file_name: &str, board: bool) -> String { pdf_outjob_with(file_name, board, &[]) }  /// The PDF OutJob, with more outputs (already numbered from 3) appended: Altium's own Assembly and PCB Print outputs.-pub fn pdf_outjob_with(file_name: &str, board: bool, extra: &[Vec<(String, String)>]) -> String {+pub fn pdf_outjob_with(file_name: &str, board: bool, extra: &[Vec<(String, String)>]) -> String { pdf_outjob_layers(file_name, board, None, false, None, extra) }++/// The PDF OutJob with the board's composite print on chosen Altium layers (default overlay, top, bottom, multi-layer,+/// Mechanical 1), mirrored when asked.+/// area: the board print's box in Altium's internal units (x0, y0, x1, y1), else the design extent (every object,+/// rooms and parts off the board included).+pub fn pdf_outjob_layers(file_name: &str, board: bool, layers: Option<&[String]>, mirror: bool, area: Option<[i64; 4]>, extra: &[Vec<(String, String)>]) -> String {     let page = "Record=PageOptions|CenterHorizontal=True|CenterVertical=True|PrintScale=1.00|XCorrection=1.00|YCorrection=1.00|PrintKind=0|BorderSize=5000000|LeftOffset=0|BottomOffset=0|Orientation=2|PaperLength=1000|PaperWidth=1000|Scale=100|PaperSource=7|PrintQuality=-4|MediaType=1|DitherType=10|PaperKind=A4|PrintScaleMode=1";     let sch_view = "Record=SchPrintView|ShowNoERC=True|ShowParamSet=True|ShowProbe=True|ShowBlanket=True|ShowNote=True|ShowNoteCollapsed=True|ExpandDesignator=True|ExpandNetLabel=False|ExpandPort=False|ExpandSheetNum=False|ExpandDocNum=False|PrintArea=0";     let mut l: Vec<String> = ["[OutputJobFile]", "Version=1.0", "Caption=", "Description=Adom altium_export_pdf", "",@@ -552,10 +560,12 @@ pub fn pdf_outjob_with(file_name: &str, board: bool, extra: &[Vec<(String, Strin             "OutputEnabled2=1", "OutputEnabled2_OutputMedium1=2", "OutputDefault2=0"].iter().map(|x| x.to_string()));         l.push(format!("PageOptions2={page}"));         l.push("Configuration2_Name1=OutputConfigurationParameter1".into());-        l.push("Configuration2_Item1=DesignatorDisplayMode=Physical|PrintArea=DesignExtent|PrintAreaLowerLeftCornerX=0|PrintAreaLowerLeftCornerY=0|PrintAreaUpperRightCornerX=0|PrintAreaUpperRightCornerY=0|Record=PcbPrintView".into());+        let (kind, [x0, y0, x1, y1]) = match area { Some(a) => ("SpecificArea", a), None => ("DesignExtent", [0; 4]) };+        l.push(format!("Configuration2_Item1=DesignatorDisplayMode=Physical|PrintArea={kind}|PrintAreaLowerLeftCornerX={x0}|PrintAreaLowerLeftCornerY={y0}|PrintAreaUpperRightCornerX={x1}|PrintAreaUpperRightCornerY={y1}|Record=PcbPrintView"));         l.push("Configuration2_Name2=OutputConfigurationParameter2".into());-        l.push("Configuration2_Item2=IncludeBottomLayerComponents=True|IncludeMultiLayerComponents=True|IncludeTopLayerComponents=True|IncludeViewports=True|Index=0|Mirror=False|Name=Multilayer Composite Print|PadNumberFontSize=14|Record=PcbPrintOut|ShowHoles=False|ShowPadNets=False|ShowPadNumbers=False|SubstituteFonts=False".into());-        for (i, layer) in ["TopOverlay", "TopLayer", "BottomLayer", "MultiLayer", "Mechanical1"].iter().enumerate() {+        l.push(format!("Configuration2_Item2=IncludeBottomLayerComponents=True|IncludeMultiLayerComponents=True|IncludeTopLayerComponents=True|IncludeViewports=True|Index=0|Mirror={}|Name=Multilayer Composite Print|PadNumberFontSize=14|Record=PcbPrintOut|ShowHoles=False|ShowPadNets=False|ShowPadNumbers=False|SubstituteFonts=False", if mirror { "True" } else { "False" }));+        let default_layers: Vec<String> = ["TopOverlay", "TopLayer", "BottomLayer", "MultiLayer", "Mechanical1"].iter().map(|x| x.to_string()).collect();+        for (i, layer) in layers.unwrap_or(&default_layers).iter().enumerate() {             l.push(format!("Configuration2_Name{}=OutputConfigurationParameter{}", i + 3, i + 3));             l.push(format!("Configuration2_Item{}=CArc=Full|CFill=Full|Comment=Full|Coordinate=Full|CPad=Full|CRegion=Full|CText=Full|CTrack=Full|CVia=Full|DDSymbolKind=0|DDSymbolSize=500000|DDSymbolSortKind=0|Designator=Full|Dimension=Full|DLayer1=TopLayer|DLayer2=BottomLayer|FArc=Full|FFill=Full|FPad=Full|FRegion=Full|FText=Full|FTrack=Full|FVia=Full|Layer={layer}|Polygon=Full|PrintOutIndex=0|Record=PcbPrintLayer", i + 3));         }@@ -583,15 +593,17 @@ pub fn export_pdf(args: &Value) -> Value {     let stem = Path::new(&prj).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or("schematic".into());     let out = s(args, "output").unwrap_or_else(|| dir.join(format!("{stem}.pdf")).to_string_lossy().to_string());     let want = |k: &str| args.get(k).and_then(|b| b.as_bool()) == Some(true);-    let drawings = want("assembly") || want("fabrication");+    let board3d = s(args, "board3d");+    let board_layers: Option<Vec<String>> = args.get("boardLayers").and_then(|v| v.as_array()).map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect());+    let drawings = want("assembly") || want("fabrication") || board3d.is_some();     if drawings && project.boards.is_empty() { return json!({"success": false, "errorCode": "no_board", "error": "assembly and fabrication drawings need a board in the project"}); }     let with_board = (want("board") || drawings) && !project.boards.is_empty();     // Altium's own drawing outputs, from its OutJob templates: Assembly (top and bottom assembly drawings) and PCB     // Print (the fabrication print), numbered after the schematic (1) and the composite (2)     let board_name = project.boards.first().map(|b| Path::new(b).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default()).unwrap_or_default();     let mut extra: Vec<Vec<(String, String)>> = Vec::new();-    for (flag, tpl, kind) in [("assembly", "Assembly.OutJob", "Assembly"), ("fabrication", "Fabrication.OutJob", "PCB Print")] {-        if !want(flag) { continue; }+    for (flag, tpl, kind) in [("assembly", "Assembly.OutJob", "Assembly"), ("fabrication", "Fabrication.OutJob", "PCB Print"), ("board3d", "Assembly.OutJob", "PCB 3D Print")] {+        if flag == "board3d" { if board3d.is_none() { continue; } } else if !want(flag) { continue; }         let ini = match support::altium_public_file(&format!(r"OutputJobs\{tpl}")).and_then(|p| std::fs::read_to_string(&p).map_err(|e| format!("{p}: {e}"))) {             Ok(t) => crate::manufacturing::parse_ini(&t),             Err(e) => return json!({"success": false, "errorCode": "no_templates", "error": e}),@@ -603,6 +615,11 @@ pub fn export_pdf(args: &Value) -> Value {         for (k, v) in o.iter_mut() {             if k == &format!("OutputDocumentPath{n}") { *v = board_name.clone(); }             if k == &format!("OutputEnabled{n}") { *v = "1".into(); }+            // the 3D print straight down at the top or up at the bottom, not the template's tilted camera+            if flag == "board3d" && k.starts_with(&format!("Configuration{n}_Item")) && v.contains("Record=Pcb3DPrintView") {+                let top = board3d.as_deref() != Some("bottom");+                *v = crate::manufacturing::field(&crate::manufacturing::field(v, "ViewFromTop", if top { "True" } else { "False" }), "CustomCamera", "False");+            }         }         o.push((format!("OutputEnabled{n}_OutputMedium1"), n.to_string()));         extra.push(o);@@ -617,7 +634,10 @@ pub fn export_pdf(args: &Value) -> Value {     for (i, d) in docs.iter().enumerate() { prj_text.push_str(&format!("[Document{}]\r\nDocumentPath={}\r\nAnnotationEnabled=1\r\n\r\n", i + 1, d)); }     prj_text.push_str(&format!("[Document{}]\r\nDocumentPath=AdomPdf.OutJob\r\n\r\n", docs.len() + 1));     let file_name = "AdomExport.pdf";-    if let Err(e) = std::fs::create_dir_all(&tmp).and_then(|_| std::fs::write(&oj, pdf_outjob_with(file_name, with_board, &extra))).and_then(|_| std::fs::write(&proj, prj_text)) {+    // boardArea [x0, y0, x1, y1]: Altium internal units, the box to print+    let board_area = args.get("boardArea").and_then(|v| v.as_array()).filter(|a| a.len() == 4)+        .and_then(|a| Some([a[0].as_i64()?, a[1].as_i64()?, a[2].as_i64()?, a[3].as_i64()?]));+    if let Err(e) = std::fs::create_dir_all(&tmp).and_then(|_| std::fs::write(&oj, pdf_outjob_layers(file_name, with_board, board_layers.as_deref(), want("mirror"), board_area, &extra))).and_then(|_| std::fs::write(&proj, prj_text)) {         return json!({"success": false, "errorCode": "temp_write_failed", "error": e.to_string()});     }     let proj_s = proj.to_string_lossy().to_string();
bridge-rs/src/schsheet.rs+4−3
@@ -592,7 +592,7 @@ pub fn create(args: &Value) -> Value {  /// PowerShell: render page 1 of a PDF to a PNG with Windows' own PDF renderer (Windows.Data.Pdf), then optionally /// compare it with a baseline PNG pixel by pixel. Prints one JSON line.-const RENDER_PS: &str = r#"param([string]$Pdf, [string]$Png, [int]$Width, [int]$PageIndex = 0, [string]$Baseline = "", [string]$Diff = "")+pub(crate) const RENDER_PS: &str = r#"param([string]$Pdf, [string]$Png, [int]$Width, [int]$PageIndex = 0, [string]$Baseline = "", [string]$Diff = "") $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.Runtime.WindowsRuntime $m = [System.WindowsRuntimeSystemExtensions].GetMethods()@@ -605,7 +605,8 @@ function AwaitAct($op) { $k = $asAct.Invoke($null, @($op)); $k.Wait(-1) | Out-Nu [Windows.Data.Pdf.PdfDocument, Windows.Data.Pdf, ContentType = WindowsRuntime] | Out-Null $f = Await ([Windows.Storage.StorageFile]::GetFileFromPathAsync($Pdf)) ([Windows.Storage.StorageFile]) $doc = Await ([Windows.Data.Pdf.PdfDocument]::LoadFromFileAsync($f)) ([Windows.Data.Pdf.PdfDocument])-$pg = $doc.GetPage([Math]::Min($PageIndex, $doc.PageCount - 1))+$ix = if ($PageIndex -lt 0) { [Math]::Max(0, $doc.PageCount + $PageIndex) } else { [Math]::Min($PageIndex, $doc.PageCount - 1) }+$pg = $doc.GetPage($ix) $dir = Await ([Windows.Storage.StorageFolder]::GetFolderFromPathAsync([IO.Path]::GetDirectoryName($Png))) ([Windows.Storage.StorageFolder]) $out = Await ($dir.CreateFileAsync([IO.Path]::GetFileName($Png), [Windows.Storage.CreationCollisionOption]::ReplaceExisting)) ([Windows.Storage.StorageFile]) Add-Type -AssemblyName System.Drawing@@ -656,7 +657,7 @@ $r = [AdomPxDiff]::Run($Png, $Baseline, $Diff) $r.TrimEnd('}') + ",""renderer"":""$renderer""}" "#; -fn powershell(script: &Path, args: &[String]) -> Result<Value, String> {+pub(crate) fn powershell(script: &Path, args: &[String]) -> Result<Value, String> {     let mut cmd = std::process::Command::new("powershell");     cmd.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]).arg(script).args(args);     #[cfg(windows)]
bridge-rs/src/surfaces.rs+11−1
@@ -305,13 +305,23 @@ pub fn save(args: &Value) -> Value {     }     if let Some(p) = s(args, "filePath") {         if let Some(e) = support::must_open(&p, 60) { return e; }+        // the document itself, not the focused one: open shows a document without focusing it+        let before = std::fs::metadata(&p).and_then(|m| m.modified()).ok();+        let mut r = agent::call("save_doc", &[("path", p.replace('/', "\\"))], None, Duration::from_secs(60));+        let after = std::fs::metadata(&p).and_then(|m| m.modified()).ok();+        let ok = r.get("data").and_then(|d| d.get("ok")).and_then(|b| b.as_bool()) == Some(true);+        if ok { crate::project::mark_clean(&p); }+        r["success"] = json!(ok);+        r["saved"] = json!(ok && after.is_some() && after != before);+        r["_hint"] = json!("Saved this document. saved:false with ok means Altium found nothing to write, or the file did not change on disk.");+        return r;     }     // pre-empts "a command is currently active" (save-a-copy Warning)     agent::call("tx_clear", &[], None, Duration::from_secs(30));     let mut r = agent::call("run_process",         &[("process", "WorkspaceManager:SaveObject".into()), ("params", "ObjectKind=FocusedDocument".into())],         None, Duration::from_secs(60));-    r["_hint"] = json!("Saved the focused document. A 'Save As' dialog means the document never had a path — altium_check_dialogs.");+    r["_hint"] = json!("Saved the focused document (filePath names one). A 'Save As' dialog means the document never had a path — altium_check_dialogs.");     r } 
bridge-rs/src/verbs.rs+67−2
@@ -22,7 +22,7 @@ pub const KNOWN: &[&str] = &[     "list_nets", "net_connections", "layers", "copper_layers", "read_rules",     "set_layer_visibility", "footprint_primitives", "schematic_data", "layer_stack", "net_classes", "diff_pairs", "board_outline", "set_track_width", "find_space", "selection", "check_orientation", "replicate_layout", "outjob_info", "find_symbol", "part_parameters",     // the live-board lane AI Flow drives-    "routing_state", "route_net", "move_parts", "export_odb", "export_ipc2581", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",+    "routing_state", "route_net", "move_parts", "export_library_part", "create_part_project", "library_views", "render_board_3d", "render_board_layers", "document_info", "close_all_documents", "project_info", "project_create", "project_rename", "project_snapshot", "cross_probe", "read_footprint", "export_odb", "export_ipc2581", "remove_parts", "edit_parts", "align_parts", "set_layer_count", "copy_routing", "check_clearance", "remove_graphics", "place_vias", "board_features", "sch_sheet_symbol", "netlist", "silkscreen_prep", "net_lengths", "teardrops", "component_classes", "read_sheet_file", "fab_check", "panelize", "impedance", "current_capacity", "height_check", "bodies", "copper_balance", "return_path", "silk_designators", "via_fence", "assembly_check", "jlcpcb_order", "schematic_review", "pin_pad_check", "route_pair", "thermal_vias", "board_report", "placement_check", "auto_classes", "length_tune", "remove_items", "ripup_nets", "apply_pours", "pour_state", "remove_pours", "repour", "routing_drc", "build_board", "set_outline", "set_design_rules", "zoom_to", "add_rule", "build_schematic", "export_manufacturing", "select_net", "silk_state", "apply_silkscreen",     // surfaces     "show_project", "show_schematic", "show_2d_board", "show_3d_board", "show_library",     "show_symbol", "show_footprint", "show_3d_chip", "list_library", "demo",@@ -575,7 +575,7 @@ fn describe() -> Value {             json!({"data": "{kind: sch|pcb, count, names: [string]}", "path": "string", "kind": "sch | pcb", "roundtripMs": "int"}), 60,             "Use the exact names with altium_show_symbol / altium_read_symbol / altium_show_footprint / altium_pcb_report.",             &["show_library", "read_symbol", "pcb_report"], &["It makes the library the current document.", "count is the true total; names[] stops at limit."], json!({"libraryPath": "C:/lib/Adom_ToF.PcbLib"})),-        verb_doc("save", "Save the focused document, or open filePath first and save that (WorkspaceManager:SaveObject on the focused document).",+        verb_doc("save", "Save the focused document, or the document at filePath (opened first if need be, saved by its path, never whatever happens to have focus).",             json!({"filePath": "path - optional; opened and made current before the save"}),             json!({"data": "{process, params}", "roundtripMs": "int"}), 60,             "Pass filePath every time: every library authoring verb leaves the library UNSAVED. Then altium_check_dialogs - a 'Save As' box means the document never had a path.",@@ -764,6 +764,58 @@ fn describe() -> Value {             json!({"filePath": "path to the board file (default: the board open in the tool)", "outputDir": "folder for the output (default beside the board)", "version": "B|C, default C", "units": "mm|in, default mm", "compress": "bool, default false: zip the XML", "bomFields": "{mpn, manufacturer, distributorPn, distributor}: the part field names that carry these, so the embedded BOM is useful to the fab"}),             json!({"file": "path"}), 600,             "Name the part fields with bomFields, or the BOM inside the file carries no part numbers.", &["export_manufacturing", "run_drc"], &["Run run_drc first: the file carries the board's errors with it.", "Altium writes it with its manufacturing template's settings: units, compression and version options are reported under optionsNotApplied.", "The board must be a document of a .PrjPcb in its folder."], json!({"filePath": "C:/proj/Board.PcbDoc", "bomFields": {"mpn": "MPN"}})),+        verb_doc("document_info", "The active document: its name, what kind it is, whether it has unsaved changes, where it is saved and which version it is. Read only; opens nothing.",+            json!({}),+            json!({"name": "string", "kind": "project | schematic | board | library | model | other", "saved": "bool: it exists as a file or a cloud item", "modified": "bool: it has unsaved changes", "path": "file path or cloud location | null", "version": "int | null: the saved version, where the tool keeps versions", "project": "string | null"}), 300,+            "Cheap. Call it before an edit verb to make sure the right document is in front.", &[], &["A schematic and a board of one design are separate documents in some tools: kind says which one is in front.", "Altium keeps no version numbers for local files: version is null."], json!({})),+        verb_doc("close_all_documents", "Close every open document without a save dialog. Unsaved work is never lost by default: a document with unsaved changes stays open and is listed, unless save or discardUnsaved says what to do with it.",+            json!({"save": "bool, default false: save each changed document, then close it", "discardUnsaved": "bool, default false: close changed documents without saving (their changes are lost)", "includeScratch": "bool, default false: also close never-saved scratch documents", "under": "folder: only the documents in it (a project folder)"}),+            json!({"closed": "[name]", "saved": "[name]", "keptOpen": "[{name, why: unsaved changes | scratch}]"}), 300,+            "Use it to start from a clean editor. keptOpen tells you what still needs a decision.", &[], &["discardUnsaved loses changes that exist nowhere else: ask the person first.", "A scratch document was never saved, so closing one with unsaved changes loses it entirely.", "Altium closes a document without a dialog: a changed one stays open unless save or discardUnsaved says otherwise."], json!({"save": true})),+        verb_doc("project_info", "A project at a glance: name, files with sizes and dates, the sheet tree, the board (layers, parts, nets, size), text variables, net classes, last change, and whether the tool has it open. Read only.",+            json!({"project": "path to the project file, its folder or any of its documents (required)"}),+            json!({"name": "string", "files": "[{path, bytes, modified}]", "sheets": "the sheet tree, as sch_hierarchy answers it", "board": "{layers, parts, nets, sizeMm}", "textVariables": "{name: value}", "netClasses": "[string]", "modified": "date", "open": "bool: the tool has a document of this project open"}), 300,+            "Read this before renaming, snapshotting or editing a project.", &[], &["The board's layers, parts, nets and size come from Altium when it has the board open; net classes are listed by altium_net_classes."], json!({"project": "C:/proj/Board.PrjPcb"})),+        verb_doc("project_create", "Create a new project folder with a project file, an empty schematic and an empty board (2 to 32 copper layers), with a title and text variables.",+            json!({"parentDir": "folder to create the project in (required)", "name": "string (required): the project and folder name", "title": "string", "layers": "int, default 2", "fabRules": "a fab name from adom/pcb-design-rules, recorded to apply once the board has content", "textVariables": "{\"REV\": \"A\"}", "dryRun": "bool, default false: answer the plan and change nothing"}),+            json!({"project": "path", "files": "[path]"}), 300,+            "Next: draw the outline (set_outline), then place and route. fabRules is recorded, not applied.", &[], &["A folder that already holds a project is refused.", "The board has no outline yet: set it before routing or exporting.", "The sheet comes from Altium's ANSI B template, the board is Altium's default new board with its layer count set; text variables are project parameters."], json!({"parentDir": "C:/Users/me/Documents/Projects", "name": "widget", "layers": 4})),+        verb_doc("project_rename", "Rename a project: the project file, the root sheet, the board and the tool's side files, with the references inside them updated. Refused while the tool has the project open.",+            json!({"project": "path to the project file (required)", "newName": "string (required)", "dryRun": "bool, default false: answer the plan and change nothing"}),+            json!({"renamed": "[{from, to}]", "changed": "[{file, what}]"}), 300,+            "Dry-run first: the plan lists every file renamed and what changes inside each. Close the project in the tool first.", &[], &["Child sheet files keep their names; only the documents named after the project are renamed.", "The folder keeps its name.", "Take a project_snapshot first if the project is not under version control.", "Refused while Altium has any document of the project open."], json!({"project": "C:/proj/Old.PrjPcb", "newName": "widget-v2", "dryRun": true})),+        verb_doc("project_snapshot", "A dated copy of the project's documents into <project>/snapshots/<stamp>[-label]/, with PDFs of the schematic and the board made by the tool.",+            json!({"project": "path to the project file (required)", "label": "string: added to the folder name", "pdfs": "bool, default true"}),+            json!({"folder": "path", "files": "[path]", "pdfs": "{made: [path], skipped: why}"}), 300,+            "Take one before a risky edit (a rename, a big re-route). Libraries in sub-folders are referenced, not copied.", &[], &["A snapshot of an open project holds what is saved on disk, not unsaved edits: save first.", "The PDF holds every sheet and the board's composite print (altium_export_pdf)."], json!({"project": "C:/proj/Board.PrjPcb", "label": "before-routing"})),+        verb_doc("cross_probe", "From a schematic part to the board part linked to it, and back, by designator, the schematic symbol's id or its sheet path; optionally select them in the tool.",+            json!({"filePath": "path to the board file (default: the board open in the tool)", "ref": "\"U1\"", "symbolId": "the schematic symbol's id", "path": "the symbol's sheet path", "schematic": "path to a sheet of the project (default the project's)", "select": "bool, default false: also select the matches in the tool"}),+            json!({"matches": "[{board: {ref, id, side, x, y, rotation}, schematic: {sheet, id, ref, symbol, value}, linked: bool}]", "symbolWithoutPart": "[ref]"}), 300,+            "Reads the open board when the tool serves it, else the file.", &[], &["linked:false means the board part has no link to a symbol: placed by hand, or update_pcb never ran.", "Sheets are read from their saved files; a part matched by designator alone is linked:false."], json!({"filePath": "C:/proj/Board.PcbDoc", "ref": "U3"})),+        verb_doc("read_footprint", "Every detail of one library footprint: pads (number, type, shape, position, size, drill, layers), the layers it uses, its courtyard box, graphics per layer, attributes, properties and 3D models. The library mirror of read_symbol; footprint_primitives reads a part placed on the board.",+            json!({"libraryPath": "path to the footprint library", "name": "the footprint's name (with libraryPath)", "libId": "\"Lib:Name\": resolved through the project's and then the global library table", "project": "path to the project, for libId"}),+            json!({"name": "string", "pads": "[{number, type, shape, at, sizeMm, drillMm, layers, rotation}]", "layers": "[string]", "courtyardMm": "[x1, y1, x2, y2]", "graphics": "{layer: count}", "attributes": "{mount, excludeFromBom, excludeFromPos, dnp}", "properties": "{name: value}", "models": "[{path, offset, scale, rotate}]"}), 300,+            "Read before edit_footprint, and to check pin 1 and the pad numbers against the symbol.", &[], &["Altium has no library table: give libraryPath and name (libId is not used). courtyardMm is the footprint's bounding box."], json!({"libId": "Package_SO:SOIC-8_3.9x4.9mm_P1.27mm"})),+        verb_doc("render_board_3d", "Render a 3D picture of the board from one side to an image file, through the tool's own renderer, without opening a window.",+            json!({"filePath": "path to the board file (default: the board open in the tool)", "side": "top|bottom|left|right|front|back, default top", "width": "int px, default 1600", "height": "int px, default 900", "quality": "basic|high, default basic (high raytraces and is much slower)", "background": "default|transparent|opaque", "zoom": "number, default 1.0", "perspective": "bool, default false", "format": "png|jpg, default png", "outputDir": "folder for the output (default beside the board)"}),+            json!({"image": "path", "width": "int", "height": "int", "side": "string"}), 600,+            "One call per side: top and bottom for a review. A flat image of chosen layers is render_board_layers; show_3d_board opens a window instead.", &["show_3d_board", "export_pdf"], &["Parts without a 3D model render as bare pads: check them with bodies first.", "Altium's PCB 3D Print looks straight down at the top or up at the bottom: other sides need a window (altium_show_3d_board). height, quality, background, zoom, perspective and format are reported under optionsNotApplied.", "The board must be a document of a .PrjPcb in its folder."], json!({"filePath": "C:/proj/Board.PcbDoc", "side": "top"})),+        verb_doc("render_board_layers", "Render chosen board layers to an image file without opening a window: a preset view (copper, silkscreen, solder mask, paste, outline, drill, assembly or fabrication, of either side) or a list of layers, as png or svg.",+            json!({"filePath": "path to the board (optional; default the open board)", "preset": "all | top_copper | bottom_copper | top_silkscreen | bottom_silkscreen | top_soldermask | bottom_soldermask | top_paste | bottom_paste | outline | drill | assembly_top | assembly_bottom | fabrication (default all)", "layers": "[layer]: copper by its standard name (F.Cu, In1.Cu, B.Cu) or any layer by the tool's own id; overrides preset", "format": "png | svg (default png)", "dpi": "int, default 300 (png)", "mirror": "bool, default false: draw the board as seen from below", "monochrome": "bool, default false", "area": "board | extent (default board: the outline plus 1 mm; extent prints every object, rooms and parts off the board too)", "outputPath": "the image file to write (default beside the board)", "listPresets": "bool: answer the presets and their layers, and make no image"}),+            json!({"path": "path", "format": "png | svg", "widthPx": "int (png)", "heightPx": "int (png)", "preset": "string, or custom when layers was given", "layers": "[layer]: what was drawn", "presets": "{name: description} (listPresets)"}), 600,+            "Each preset is a fixed set of layers, so two bridges draw the same view. For a 3D picture use render_board_3d. The show_* verbs open a window; this one does not.", &["show_3d_board", "export_pdf"], &["Mirroring is never automatic: a bottom preset is drawn as seen from the top unless mirror is true.", "Inner copper layers appear only when listed in layers.", "PNG only (svg is refused): Altium prints to PDF and Windows renders it. The print fills an A4 landscape page; dpi sets the image width from that page.", "The board must be a document of a .PrjPcb in its folder."], json!({"preset": "assembly_top", "format": "png", "dpi": 300})),+        verb_doc("library_views", "Pictures of library parts for review, each as an image file: the schematic symbol, the footprint (pads and layers), the 3D body seated on the footprint, and the device view that maps symbol pins to pads.",+            json!({"libraryPath": "path to the library (required)", "parts": "[part name] (required)", "views": "[symbol, footprint, 3d, device] (default all four)", "outputDir": "folder for the images (default beside the library)"}),+            json!({"captured": "[{part, view, path, ok, error?}]"}), 900,+            "The four pictures a reviewer checks before a part is used: the pin names on the symbol, the pad shapes, the body on its pads, and every pin mapped to a pad.", &["show_symbol", "show_footprint", "show_3d_chip"], &["The 3d view needs a body on the part (add_body): a part without one is reported with ok false, not drawn empty.", "Altium has no device view: it is reported ok false and points to altium_pin_pad_check.", "From a .SchLib, the footprint is the symbol's PCB model, found in a .PcbLib beside the library."], json!({"libraryPath": "C:/libs/power.lbr", "parts": ["TPS54202"], "views": ["symbol", "footprint", "3d"]})),+        verb_doc("export_library_part", "Export one library part into its own small library files: a symbol library with only its symbol, a footprint library with only its footprint, and its 3D model file.",+            json!({"part": "the part's symbol name or library id (required)", "footprint": "a footprint name (default the symbol's own)", "what": "[symbol, footprint, model] (default all three)", "outputDir": "folder for the files", "libraryPath": "path to the .SchLib that holds the part (required on Altium)", "footprintLibrary": "the .PcbLib that holds the footprint (default: one beside libraryPath that has it)"}),+            json!({"exports": "{symbol: path, footprint: path, model: path}", "missing": "[what]"}), 900,+            "Use it to hand one part to another project or another tool.", &["xcopy_footprint", "sch_place_part", "update_pcb"], &["success is false when any piece asked for is missing; exports still carries what was written.", "Altium has no global library table: libraryPath (the .SchLib) is required; the footprint is the symbol's PCB model, from a .PcbLib beside it unless footprintLibrary names one.", "model is the STEP file the 3D body came from: a body embedded with no source file left is reported missing (the .PcbLib still carries it)."], json!({"part": "IN-S42ATA"})),+        verb_doc("create_part_project", "Generate a small real project (schematic and board) around one library part, so the part can be shown and tested in every view: schematic, 2D board and 3D board.",+            json!({"part": "the part's symbol name or library id (required)", "footprint": "a footprint name (default the symbol's own)", "projectName": "string (default from the part)", "outputDir": "folder (default the user's projects folder)", "overwrite": "bool, default false: replace a project of that name", "libraryPath": "path to the .SchLib that holds the part (required on Altium)", "footprintLibrary": "the .PcbLib that holds the footprint (default: one beside libraryPath that has it)"}),+            json!({"project": "path", "schematic": "path", "board": "path"}), 900,+            "The board keeps the footprint's 3D model, so render_board_3d and show_3d_board show the real part. One part by design.", &["xcopy_footprint", "sch_place_part", "update_pcb"], &["The part's symbol and footprint must both be in a library the tool can find.", "An existing project of that name is refused unless overwrite:true.", "Altium has no global library table: libraryPath (the .SchLib) is required; both libraries are added to the new project so its change order finds the footprint.", "The default folder is part-projects beside the library."], json!({"part": "IN-S42ATR"})),         verb_doc("sch_connect", "Connect pins of placed parts: a wire stub from each pin's outer end plus a net label (kind label), a power port (kind power: GND-like nets get a ground symbol) or the stub alone (kind wire); or mark a pin left open on purpose with a No ERC marker (kind noerc, no net). One undo step.",             json!({"sheet": "path to the .SchDoc (required)", "connections": "[{designator, pin (number or name), net, kind: label|power|wire|noerc|port (default label), io?: input|output|bidirectional (port), stubMil (default 200)}] (required)", "save": "bool, default true"}),             json!({"connected": "int", "results": "[{designator, pin, net, kind, result, endMil}]", "failed": "[..]", "saved": "bool"}), 90,@@ -1921,6 +1973,19 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) ->         "sheet_params" => crate::bom::sheet_params(args),         "sch_place_part" => crate::sch::place_part(args),         "sch_connect" => crate::sch::connect(args),+        "export_library_part" => crate::project::export_library_part(args),+        "create_part_project" => crate::project::create_part_project(args),+        "library_views" => crate::render::library_views(args),+        "render_board_3d" => crate::render::render_board_3d(args),+        "render_board_layers" => crate::render::render_board_layers(args),+        "document_info" => crate::project::document_info(args),+        "close_all_documents" => crate::project::close_all_documents(args),+        "project_info" => crate::project::project_info(args),+        "project_create" => crate::project::project_create(args),+        "project_rename" => crate::project::project_rename(args),+        "project_snapshot" => crate::project::project_snapshot(args),+        "cross_probe" => crate::project::cross_probe(args),+        "read_footprint" => crate::project::read_footprint(args),         "export_odb" => crate::manufacturing::export_format(args, "odb"),         "export_ipc2581" => crate::manufacturing::export_format(args, "ipc2581"),         "remove_parts" => crate::boardedit::remove_parts(args),
bridge-rs/vendor/README.md+2−4
@@ -2,11 +2,9 @@  | Folder | From | Version | |---|---|---|-| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.4.0, engine 0.1.0 |+| `adom-eda-checks/` | adom/eda-bridge-standard `engine/` (the shared checks engine) | standard 0.4.5, engine 0.1.4 | | `pcb-design-rules/records/` | adom/pcb-design-rules `rules/records/` (each fab's published limits, with sources and dates) | head of 2026-10-27 |  The wiki has no git protocol, so these are copied at a version: refresh both from their pages, then run the tests. -Local change, sent upstream on adom/eda-bridge-standard#8: `adom-eda-checks/src/coppermap.rs` `stack_layers` takes each-copper layer's board-model name from the stack's `layer` (the standard's plane rule), else names it by its place in-the stack, so an internal plane is `In<n>.Cu`, not `L<38+n>`.+No local changes: the copy is the standard's `engine/` as published.
bridge-rs/vendor/adom-eda-checks/Cargo.toml+1−1
@@ -1,6 +1,6 @@ [package] name = "adom-eda-checks"-version = "0.1.0"+version = "0.1.4" edition = "2021" description = "The EDA Bridge Standard's checks, computed from the board model JSON: no bridge calls, no tool." license = "MIT"
bridge-rs/vendor/adom-eda-checks/README.md+1−1
@@ -33,7 +33,7 @@ Every check takes one JSON object: | `board` | the board model, `<prefix>_routing_state` (`schema/board.schema.json`) | | `stack` | the stack-up companion, `<prefix>_layer_stack` | | `pours` | poured copper, `<prefix>_pour_state` (its `zones`) |-| `rules` | the board's rules, `<prefix>_read_rules`: a clearance rule as `{kind: "clearance", clearanceMm}` |+| `rules` | the board's rules, `<prefix>_read_rules`: a clearance rule as `{kind: "clearance", clearanceMm}` (a `value` with its unit, `"0.1mm"`, works too). Only copper-to-copper clearance counts: a rule whose kind or name names the board edge, mask, silk, paste, holes, a keepout or restrict area, the courtyard or the same net is skipped | | `silk` | `<prefix>_silk_state` | | `fab` | one record from adom/pcb-design-rules `rules/records/<vendor>.json`, with `vendor` | | `args` | the check's own arguments, as the standard verb documents them |
bridge-rs/vendor/adom-eda-checks/src/coppermap.rs+6−2
@@ -84,13 +84,14 @@ impl Raster {     pub fn count(&self) -> usize { self.cells.iter().filter(|c| **c).count() } } -/// The stack's copper layers in order as (routing_state name, plane?, plane net).+/// The stack's copper layers in order as (board model name, plane?, plane net). The name is the stack entry's `layer`+/// when the bridge gives it, else its place in the copper stack (F.Cu, In<n>.Cu, B.Cu): a plane is named like any other+/// inner layer (standard 0.3.1), never by a tool's id. pub fn stack_layers(stack: &Value) -> Vec<(String, bool, String)> {     let ls: Vec<Value> = stack["layers"].as_array().cloned().unwrap_or_default();     let n = ls.len();     ls.iter().enumerate().map(|(i, l)| {         let plane = l["kind"] == "plane";-        // the board model's name when the stack gives it (`layer`); else by place in the stack, a plane included         let name = l["layer"].as_str().map(str::to_string).unwrap_or_else(|| if i == 0 { "F.Cu".to_string() } else if i + 1 == n { "B.Cu".to_string() } else { format!("In{i}.Cu") });         (name, plane, if plane { l["net"].as_str().unwrap_or("").to_string() } else { String::new() })     }).collect()@@ -421,6 +422,9 @@ mod tests {         let l = stack_layers(&s);         assert_eq!(l.iter().map(|x| x.0.as_str()).collect::<Vec<_>>(), vec!["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"]);         assert!(l[1].1 && l[1].2 == "GND");+        // the bridge's own name wins when it gives one+        let named = json!({"layers": [{"layer": "F.Cu"}, {"layer": "In1.Cu", "kind": "plane", "net": "GND", "layerId": 39}, {"layer": "B.Cu"}]});+        assert_eq!(stack_layers(&named)[1], ("In1.Cu".to_string(), true, "GND".to_string()));     }     #[test]     fn gap_runs_group_and_the_fix_patches_the_neighbour() {
bridge-rs/vendor/adom-eda-checks/src/current.rs+4−2
@@ -69,7 +69,9 @@ pub fn check(state: &Value, copper_um: &[f64], nets: &Map<String, Value>, rise:             let each = via_amps(smallest, plating_um, rise);             json!({"count": net_vias.len(), "smallestDrillMm": r3(smallest), "ampsEach": r2(each), "neededPerLayerChange": (amps / each).ceil() as i64})         };-        let pours: Vec<Value> = polys.iter().filter(|p| same(&p["net"])).map(|p| p["layer"].clone()).collect();+        // each layer once, however many pours of the net it holds (#15)+        let mut pours: Vec<Value> = Vec::new();+        for l in polys.iter().filter(|p| same(&p["net"])).map(|p| p["layer"].clone()) { if !pours.contains(&l) { pours.push(l); } }         json!({"net": net, "amps": amps, "layers": layers, "shortOn": short, "ok": short.is_empty(), "vias": via, "poursOn": pours})     }).collect() }@@ -118,7 +120,7 @@ mod tests {     #[test]     fn check_finds_the_narrow_layer() {         let st = json!({"tracks": [{"net": "VIN", "layer": "F.Cu", "width": 1.5, "start": {"x": 0.0, "y": 0.0}}, {"net": "VIN", "layer": "B.Cu", "width": 0.3, "start": {"x": 4.0, "y": 1.0}}],-                        "vias": [{"net": "VIN", "drill": 0.3}, {"net": "VIN", "drill": 0.4}], "polygons": [{"net": "VIN", "layer": "B.Cu"}]});+                        "vias": [{"net": "VIN", "drill": 0.3}, {"net": "VIN", "drill": 0.4}], "polygons": [{"net": "VIN", "layer": "B.Cu"}, {"net": "VIN", "layer": "B.Cu"}]});         let nets = json!({"VIN": 3.0}).as_object().unwrap().clone();         let r = &check(&st, &[35.0, 35.0], &nets, 10.0, 25.0)[0];         assert_eq!(r["shortOn"], json!(["B.Cu"]));
bridge-rs/vendor/adom-eda-checks/src/fab.rs+52−4
@@ -118,14 +118,37 @@ pub fn compare(meas: &Map<String, Value>, limits: &Map<String, Value>, clearance     out } -/// The smallest clearance among the board's enabled clearance rules, in mm. A rule gives it as a number-/// (`clearanceMm`, `gapMm` or `minMm`) or in a descriptor the tool wrote ("Gap=10mil", "Gap=0.2mm": Altium's form).+/// A length written with its unit ("0.1mm", "4 mil", "0.004in", "100um") in mm; None without a known unit.+fn length_mm(text: &str) -> Option<f64> {+    let t = text.trim();+    let num: String = t.chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();+    let v: f64 = num.parse().ok()?;+    match t[num.len()..].trim().to_ascii_lowercase().as_str() {+        "mm" => Some(v),+        "mil" | "mils" | "th" => Some(v * 0.0254),+        "in" | "inch" => Some(v * 25.4),+        "um" | "\u{b5}m" => Some(v / 1000.0),+        _ => None,+    }+}++/// A clearance rule that names another object than copper of another net: the board edge, solder mask, silkscreen,+/// holes, keepouts, the courtyard, or the same net (Fusion's Solder-Mask Clearance is a mask expansion, often 0.05 mm).+const NOT_COPPER_CLEARANCE: &[&str] = &["dimension", "edge", "board", "mask", "silk", "paste", "hole", "restrict", "keepout", "keep-out",+                                        "courtyard", "component", "body", "same net", "samenet", "same-net"];++/// The smallest copper-to-copper clearance among the board's enabled rules, in mm. A rule gives it as a number+/// (`clearanceMm`, `gapMm` or `minMm`), as a `value` with its unit ("0.1mm": Fusion's form), or in a descriptor the tool+/// wrote ("Gap=10mil", "Gap=0.2mm": Altium's form). Clearance rules about anything but copper of another net are left out. pub fn min_clearance(rules: &[Value]) -> Option<f64> {-    rules.iter().filter(|r| r["kind"].as_i64() == Some(0) || r["kind"].as_str().map(|k| k.eq_ignore_ascii_case("clearance")).unwrap_or(false)-            || r["kindName"].as_str() == Some("Clearance") || r["name"].as_str().map(|n| n.to_lowercase().contains("clearance")).unwrap_or(false))+    let text = |r: &Value, k: &str| r[k].as_str().map(|s| s.to_lowercase()).unwrap_or_default();+    rules.iter().filter(|r| r["kind"].as_i64() == Some(0) || text(r, "kind").contains("clearance")+            || r["kindName"].as_str() == Some("Clearance") || text(r, "name").contains("clearance"))+        .filter(|r| !["kind", "name", "kindName"].iter().any(|k| { let t = text(r, k); NOT_COPPER_CLEARANCE.iter().any(|w| t.contains(w)) }))         .filter(|r| r["enabled"].as_bool() != Some(false))         .filter_map(|r| {             if let Some(v) = ["clearanceMm", "gapMm", "minMm"].iter().find_map(|k| r[*k].as_f64()) { return Some(v); }+            if let Some(v) = r["value"].as_str().and_then(length_mm) { return Some(v); }             let d = r["descriptor"].as_str()?;             let i = d.find("Gap=")? + 4;             let num: String = d[i..].chars().take_while(|c| c.is_ascii_digit() || *c == '.').collect();@@ -291,4 +314,29 @@ mod tests {     fn clearance_from_a_standard_rule() {         assert_eq!(min_clearance(&[json!({"kind": "clearance", "clearanceMm": 0.127}), json!({"kind": "clearance", "gapMm": 0.2})]), Some(0.127));     }++    #[test]+    fn clearance_from_a_value_with_its_unit_and_never_same_net() {+        // Fusion writes rules as a kind name and a value with its unit+        let rules = vec![json!({"kind": "Copper Clearance", "value": "0.15mm"}), json!({"kind": "Copper Clearance", "value": "5mil"}),+                         json!({"kind": "Same Net Clearance", "value": "0.05mm"}), json!({"kind": "Copper Clearance", "value": "0.2"})];+        assert_eq!(min_clearance(&rules), Some(0.127));+        assert_eq!(length_mm("0.004in"), Some(0.1016));+        assert_eq!(length_mm("100um"), Some(0.1));+        assert_eq!(length_mm("0.2"), None, "a bare number has no unit: never guessed");+    }++    #[test]+    fn only_copper_to_copper_clearance_counts() {+        // Fusion's rule set (#13): only Copper Clearance is the clearance between nets+        let fusion = vec![json!({"kind": "Copper Clearance", "value": "0.1mm"}), json!({"kind": "Dimension Clearance", "value": "0.3mm"}),+                          json!({"kind": "Solder-Mask Clearance", "value": "0.05mm"}), json!({"kind": "Restrict Clearance", "value": "0.02mm"}),+                          json!({"kind": "Via Restrict Clearance", "value": "0.02mm"}), json!({"kind": "Keepout Clearance", "value": "0.01mm"})];+        assert_eq!(min_clearance(&fusion), Some(0.1));+        // Altium names its other clearances by object too+        let altium = vec![json!({"kind": 0, "name": "Clearance", "descriptor": "Clearance Constraint (Gap=0.2mm) (All),(All)"}),+                          json!({"kind": 17, "name": "HoleToHoleClearance", "descriptor": "Gap=0.1mm"}),+                          json!({"kind": 20, "name": "SilkToSolderMaskClearance", "descriptor": "Gap=0.05mm"})];+        assert_eq!(min_clearance(&altium), Some(0.2));+    } }
dev-skills/altium-bridge-test/run_verb_tests.py+14
@@ -399,6 +399,20 @@ def matrix(w):     M["copy_routing"] = dict(phase=3.5, **anyo("planned, or nothing in the box", filePath=LB, box=[0, 0, 40, 20], offset=[0, 30], keepUnmappedNets=True, dryRun=True))     M["check_clearance"] = dict(phase=3.5, **ok(filePath=LB, thresholdMm=20), check=lambda d: isinstance(d.get("pairs"), list))     M["remove_graphics"] = dict(phase=3.5, **ok(filePath=LB), check=lambda d: (d.get("count") or 0) > 0)+    # 0.2.77: documents, projects, renders and library parts (reads, a new scratch project, dry runs)+    M["document_info"] = dict(phase=3.5, **ok(), check=lambda d: d.get("kind") in ("board", "schematic", "library", "project", "other") and isinstance(d.get("openDocuments"), list))+    M["project_info"] = dict(phase=3.5, **ok(project=LP), check=lambda d: d.get("name") == "lane" and len(d.get("files") or []) >= 3)+    M["cross_probe"] = dict(phase=3.5, **ok(filePath=LB, ref="U1"), check=lambda d: len(d.get("matches") or []) == 1)+    M["read_footprint"] = dict(phase=3.5, **ok(libraryPath=PL, name="TST_SOIC8"), check=lambda d: len(d.get("pads") or []) == 8)+    M["project_create"] = dict(phase=3.5, timeout=320, **ok(parentDir=D, name="NewProj", layers=4), check=lambda d: len(d.get("files") or []) == 3)+    M["project_rename"] = dict(phase=3.5, **ok(project=D + "/NewProj/NewProj.PrjPcb", newName="NewProj2", dryRun=True), check=lambda d: len(d.get("renamed") or []) == 3)+    M["project_snapshot"] = dict(phase=3.5, **ok(project=LP, label="battery", pdfs=False), check=lambda d: len(d.get("files") or []) >= 3)+    M["render_board_3d"] = dict(phase=3.5, timeout=700, **anyo("a 3D picture of the lane board, or a named refusal", filePath=LB, width=800))+    M["render_board_layers"] = dict(phase=3.5, timeout=700, **ok(filePath=LB, preset="top_copper", dpi=100), check=lambda d: str(d.get("path", "")).endswith(".png"))+    M["library_views"] = dict(phase=3.5, timeout=600, **anyo("symbol and footprint pictures of TST_SOIC8", libraryPath=SL, parts=["TST_SOIC8"], views=["symbol", "footprint"]))+    M["export_library_part"] = dict(phase=3.5, timeout=600, **anyo("the symbol and footprint in their own libraries, model missing named", part="TST_SOIC8", libraryPath=SL, outputDir=D + "/export"))+    M["create_part_project"] = dict(phase=3.5, timeout=950, **anyo("a demo project round TST_SOIC8, or a named refusal", part="TST_SOIC8", libraryPath=SL, outputDir=D + "/partproj"))+    M["close_all_documents"] = dict(phase=5, timeout=200, **ok(), check=lambda d: isinstance(d.get("closed"), list) and isinstance(d.get("keptOpen"), list))      # ---- phase 4: outputs --------------------------------------------------------------------     M["export_odb"] = dict(phase=4, timeout=700, **anyo("ODB++ of the lane board, or no project / OutJob named", filePath=LB))
package.json+1−1
@@ -1,6 +1,6 @@ {   "slug": "altium-bridge",-  "version": "0.2.76",+  "version": "0.2.77",   "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+16−3
@@ -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.76",+  "version": "0.2.77",   "hero": {     "type": "image",     "path": "screenshots/hero.png"@@ -214,7 +214,20 @@     "copy routing to another channel in altium",     "altium part clearance check",     "export ipc-2581 from altium",-    "check my altium board against pcbway limits"+    "check my altium board against pcbway limits",+    "which altium documents are open",+    "close all altium documents without losing changes",+    "altium project summary",+    "create a new altium project",+    "rename an altium project",+    "snapshot my altium project",+    "cross probe altium schematic to pcb",+    "read an altium footprint's pads",+    "export one part from an altium library",+    "make a demo project for an altium part",+    "render altium board in 3d to an image",+    "render altium copper layer to png",+    "show altium symbol and footprint images"   ],   "discovery_pitch": "An AI that runs Altium Designer in the user's own session: libraries, schematics, Update PCB, stack-up, routing, DRC, Gerbers and BOMs.",   "metadata": {},@@ -269,4 +282,4 @@     "tools/symbol_modes.py",     "uninstall.sh"   ]-}\ No newline at end of file+}
skills/altium-libraries/SKILL.md+17
@@ -189,3 +189,20 @@ altium_footprint_from_land_pattern '{"libraryPath":"C:\\lib\\Parts.PcbLib","name   `body.height` an extruded 3D body. - `dryRun:true` returns the pad table (name, x, y, w, h) and the spec without Altium: compare it with the datasheet   drawing first.++## 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+  the courtyard, in mm from the footprint's origin (not the library's sheet). The courtyard is the extent of the+  Mechanical 15 graphics, else of everything but the pads.+- `altium_library_views {libraryPath, parts, views?}`: images of the symbol, the footprint and its 3D body (`device` is+  KiCad's; Altium answers it as not in Altium); a view the part lacks is listed with why.+- `altium_export_library_part {part, libraryPath, outputDir?, what?}`: `<part>.SchLib` and `<part>.PcbLib` holding only+  that part (the footprint is moved onto the new library's origin), plus its STEP when the source file still exists.+  A footprint with no body still succeeds (`complete:false` says the model is missing); name `what:["model"]` to+  make the model required.+- `altium_create_part_project {part, libraryPath, outputDir?, overwrite?}`: `<part>-demo/` with the symbol on the+  sheet as U1, the footprint on the board by Altium's change order, and a board 5 mm round the part with its corner+  at the origin. The source libraries join the project and are not rewritten. `overwrite:true` closes only that+  folder's documents before replacing it.+
skills/altium-outputs/SKILL.md+11−1
@@ -123,6 +123,15 @@ bottom, parts with their designators) and its PCB Print fabrication drawing to t Assembly and Fabrication OutJob templates the install ships. Measured on the battery project: 6 pages (2 sheets, the composite, the drawings) in 26 s. `board: true` alone adds just the composite print. +## Board pictures without a window (0.2.77)++- `altium_render_board_layers {filePath?, preset?, layers?, mirror?, dpi?, area?, outputPath?}`: Altium's composite+  print of a preset (`listPresets:true` names the 14) or of layers by standard copper name (`F.Cu`, `In1.Cu`, `B.Cu`),+  rendered to PNG by Windows. It prints the board's outline plus 1 mm; `area:"extent"` prints every object (the+  change order's rooms and parts left off the board widen it). The board shape is not drawn unless it is also on+  Mechanical 1.+- `altium_render_board_3d {filePath?, side: top|bottom}`: Altium's 3D print, from above or below.+ ## One format on its own, and checks by the shared engine (0.2.76)  - `altium_export_odb {filePath?, outputDir?}`: ODB++ alone (the whole tree, `lane.tgz` and `lane.zip` first).@@ -132,7 +141,8 @@ Both run Altium's own output through the board's project (a .PrjPcb beside it mu manufacturing OutJob, as `altium_export_manufacturing` needs).  `altium_fab_check`, `altium_copper_balance`, `altium_return_path`, `altium_impedance` and `altium_current_capacity`-are answered by the EDA Bridge Standard's shared engine (the same code on KiCad and Fusion). `fab_check {fab}` takes+are answered by the EDA Bridge Standard's shared engine (the same code on KiCad and Fusion; adom-eda-checks 0.1.4,+standard 0.4.5, named in each reply's `engine`). `fab_check {fab}` takes any vendor adom/pcb-design-rules covers (`jlcpcb`, `pcbway`, `osh-park`, `eurocircuits` ...): the record for the board's layer count, with its page and the date it was read in every finding. 
src/BRIDGE_VERSION+1−1
@@ -1 +1 @@-0.2.76+0.2.77
src/agent/AdomAgent.pas.tmpl+327−4
@@ -243,6 +243,46 @@ Begin     If B Then Result := 'true' Else Result := 'false'; End; +{ An edit made through the scripting API does not mark a schematic document as changed (no * in the title, 2026-10-27):+  a save:false edit then looked unchanged and was lost when the document closed. Mark it after every edit. }+Function BaseNameOf(S : String) : String;+Var+    I : Integer;+Begin+    Result := S;+    For I := Length(S) DownTo 1 Do+        If (S[I] = '\') Or (S[I] = '/') Then Begin Result := Copy(S, I + 1, Length(S) - I); Exit; End;+End;++Function MarkSchModified(Doc : ISch_Document) : String;+Var+    SM : IServerModule;+    D  : IServerDocument;+    I, J : Integer;+    Nm : String;+Begin+    { by file name: a sheet's DocumentName and its server document's FileName are not always the same form, and the+      agent's own script view is the "current view" while it runs }+    Result := '';+    Try+        Nm := UpperCase(BaseNameOf(Doc.DocumentName));+        Result := Nm + ':';+        For I := 0 To Client.Count - 1 Do+        Begin+            SM := Client.ServerModule[I];+            If SM = Nil Then Continue;+            For J := 0 To SM.DocumentCount - 1 Do+            Begin+                D := SM.Documents[J];+                If (D <> Nil) And (UpperCase(BaseNameOf(D.FileName)) = Nm) Then Begin D.Modified := True; Result := Result + 'set;'; End;+            End;+        End;+    Except+        Result := Result + 'raised';+    End;+End;++  { Close a dangling PCBServer transaction. A command that halted between   PreProcess and PostProcess leaves Altium in "a command is currently active",@@ -467,6 +507,42 @@ End;   through the document HANDLE: the menu processes are broken for this on ADDevelop - RunProcess   Client:CloseDocument no-ops, and Client:CloseAllOpenDocuments unregisters documents while   their views stay open (both measured 2026-09-02, adom/altium-bridge issue 7). }+{ Before a NEW document is named onto Path: close any document already open at that path, unless it has changes.+  Altium holds a second document at the same path otherwise, and AD 26 (which reopens its last session) then crashed+  in ADVPCB.DLL when DRC ran on the battery's board (measured 2026-10-27, twice). }+Function SamePathText(P : String) : String;+Var+    K : Integer;+Begin+    Result := '';+    For K := 1 To Length(P) Do+        If Copy(P, K, 1) = '/' Then Result := Result + '\' Else Result := Result + Copy(P, K, 1);+    Result := UpperCase(Result);+End;++Procedure FreePath(Path : String);+Var+    SM : IServerModule;+    D  : IServerDocument;+    I, J : Integer;+    Changed : Boolean;+Begin+    If Path = '' Then Exit;+    For I := 0 To Client.Count - 1 Do+    Begin+        SM := Client.ServerModule[I];+        If SM = Nil Then Continue;+        For J := SM.DocumentCount - 1 DownTo 0 Do+        Begin+            D := SM.Documents[J];+            If (D = Nil) Or (SamePathText(D.FileName) <> SamePathText(Path)) Then Continue;+            Changed := True;+            Try Changed := D.Modified; Except End;+            If Not Changed Then Try Client.CloseDocument(D); Except End;+        End;+    End;+End;+ Function CmdCloseDocument(Lines : TStringList) : String; Var     Path : String;@@ -1815,6 +1891,7 @@ Begin         Pts.Free;     End;     SchServer.ProcessControl.PostProcess(SLib, '');+    MarkSchModified(SLib);     PL.Free;     SLib.GraphicallyInvalidate;     Result := '{' + JRaw('ok', 'true') + ',' + JStr('libref', Comp.LibReference) + ',' + JRaw('polylines', IntToStr(NPoly)) + ',' +@@ -2366,7 +2443,7 @@ Begin     ResetParameters; AddStringParameter('Action','All'); RunProcess('Sch:Zoom');     If SchPath <> '' Then     Begin-        If Not Append Then SD.SetFileName(SchPath);+        If Not Append Then Begin FreePath(SchPath); SD.SetFileName(SchPath); End;         SD.DoFileSave('');     End;     PWs.Free; CXs.Free; CYs.Free; TPs.Free; BTs.Free;@@ -2528,6 +2605,7 @@ Begin     ResetParameters; AddStringParameter('Action','All'); RunProcess('PCB:Zoom');     If PcbPath <> '' Then     Begin+        FreePath(PcbPath);         SD.SetFileName(PcbPath);         SD.DoFileSave('');     End;@@ -3193,6 +3271,7 @@ Begin     End;     PL.Free;     SchServer.ProcessControl.PostProcess(SLib, '');+    MarkSchModified(SLib);     SLib.GraphicallyInvalidate;     Result := '{' + JRaw('ok','true') + ',' + JStr('libref', Cmp.LibReference) + ',' +         JRaw('models', IntToStr(NModels)) + ',' + JRaw('params', IntToStr(NParams)) + '}';@@ -3714,7 +3793,7 @@ Begin     Board.ViewManager_FullUpdate;     If PcbPath <> '' Then     Begin-        If Not Append Then SD.SetFileName(PcbPath);+        If Not Append Then Begin FreePath(PcbPath); SD.SetFileName(PcbPath); End;         SD.DoFileSave('');     End;     Result := '{' + JRaw('ok','true') + ',' + JStr('pcb', PcbPath) + ',' + JStr('placed', FpName) + ',' +@@ -4344,6 +4423,9 @@ Begin     While Prim <> Nil Do     Begin         Cpy := Prim.Replicate;+        { a footprint sits on its library's origin, and libraries differ (a new one is at 50000 mil, measured+          2026-10-27), so the copy moves by the difference }+        Cpy.MoveByXY(DstLib.Board.XOrigin - SrcLib.Board.XOrigin, DstLib.Board.YOrigin - SrcLib.Board.YOrigin);         Dst.AddPCBObject(Cpy);         NCopied := NCopied + 1;         Prim := GIt.NextPCBObject;@@ -4406,9 +4488,13 @@ End; Function CompJson(Comp : IPCB_Component) : String; Var     R : TCoordRect;+    Src : String; Begin     R := Comp.BoundingRectangle;-    Result := '{' + JStr('designator', Comp.Name.Text) + ',' ++    { the link to the schematic symbol (its UniqueId path); empty for a part placed by hand }+    Src := '';+    Try Src := Comp.SourceUniqueId; Except End;+    Result := '{' + JStr('designator', Comp.Name.Text) + ',' + JStr('sourceUniqueId', Src) + ',' +         JStr('pattern', Comp.Pattern) + ',' +         JStr('comment', Comp.Comment.Text) + ',' +         JRaw('layerId', IntToStr(Comp.Layer)) + ',' +@@ -5034,6 +5120,7 @@ Begin     End;     Doc.SchIterator_Destroy(Iter);     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Missing := '';     For I := 0 To Want.Count - 1 Do@@ -7071,6 +7158,7 @@ Begin     End;     PCBServer.PostProcess;     Board.ViewManager_FullUpdate;+    FreePath(PcbPath);     SD.SetFileName(PcbPath);     SD.DoFileSave('');     Ops.Free; Fps.Free;@@ -7432,6 +7520,7 @@ Begin     Doc.RegisterSchObjectInContainer(SS);     SchServer.RobotManager.SendMessage(Doc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, SS.I_ObjectAddress);     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free;     Result := '{' + JRaw('ok','true') + ',' + JStr('name', SS.SheetName.Text) + ',' + JStr('file', SS.SheetFileName.Text) + ',' +@@ -7509,6 +7598,7 @@ Begin             ',' + JRaw('stubEndMil', '[' + IntToStr(Round(CoordToMils(WX))) + ',' + IntToStr(Round(CoordToMils(PY))) + ']') + '}';     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free; Have.Free;     Result := '{' + JRaw('ok','true') + ',' + JRaw('placed', '[' + S + ']') + ',' + JRaw('alreadyThere', '[' + Skip + ']') + '}';@@ -7640,6 +7730,7 @@ Begin     PCBServer.SendMessageToRobots(PB.I_ObjectAddress, c_Broadcast, PCBM_BoardRegisteration, E.I_ObjectAddress);     PCBServer.PostProcess;     PB.ViewManager_FullUpdate;+    FreePath(Param(Lines, 'panel'));     SD.SetFileName(Param(Lines, 'panel'));     SD.DoFileSave('');     Result := '{' + JRaw('ok','true') + ',' + JStr('panel', Param(Lines, 'panel')) + ',' + JRaw('originX', IntToStr(PB.XOrigin)) + ',' + JRaw('originY', IntToStr(PB.YOrigin)) + ',' +@@ -7840,6 +7931,7 @@ Begin         S := S + '}';     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free;     Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('connected', IntToStr(NOk)) + ',' + JRaw('results', '[' + S + ']') + '}';@@ -7909,6 +8001,7 @@ Begin         SchServer.RobotManager.SendMessage(Doc.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, C.I_ObjectAddress);     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free; Dead.Free;     Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('applied', IntToStr(NOk)) + ',' + JRaw('results', '[' + S + ']') + '}';@@ -8046,6 +8139,7 @@ Begin     Rot := (StrToIntDef(Param(Lines, 'rotation'), 0) Div 90) Mod 4;     For K := 1 To Rot Do Inst.RotateBy90(Inst.Location, eRotate90);     SchServer.ProcessControl.PostProcess(Sheet, '');+    MarkSchModified(Sheet);     Sheet.GraphicallyInvalidate;     Result := '{' + JRaw('ok','true') + ',' + JStr('document', Sheet.DocumentName) + ',' + JStr('designator', Inst.Designator.Text) + ',' +         JStr('libref', LibCmp.LibReference) + ',' + JRaw('pins', IntToStr(NPins)) + ',' + JRaw('footprints', '[' + Models + ']') + ',' +@@ -8084,6 +8178,7 @@ Begin         End;         Items.Free;         SchServer.ProcessControl.PostProcess(Doc, '');+        MarkSchModified(Doc);         Doc.GraphicallyInvalidate;     End;     S := '';@@ -8145,6 +8240,7 @@ Begin         S := S + '{' + JStr('from', FieldP(Op, 1)) + ',' + JStr('to', FieldP(Op, 2)) + ',' + JStr('result', Res) + '}';     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free;     Result := '{' + JRaw('ok','true') + ',' + JRaw('results', '[' + S + ']') + '}';@@ -8184,6 +8280,7 @@ Begin         Made := Made + 1;     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free;     Result := '{' + JRaw('ok','true') + ',' + JRaw('wires', IntToStr(Made)) + '}';@@ -9240,9 +9337,229 @@ Begin         S := S + '{' + JStr('result', Res) + ',' + JStr('key', NewKey) + '}';     End;     SchServer.ProcessControl.PostProcess(Doc, '');+    K := MarkSchModified(Doc);     Doc.GraphicallyInvalidate;     Ops.Free;-    Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JRaw('applied', I2S(NOk)) + ',' + JRaw('results', '[' + S + ']') + '}';+    Result := '{' + JRaw('ok','true') + ',' + JStr('document', Doc.DocumentName) + ',' + JStr('marked', K) + ',' + JRaw('applied', I2S(NOk)) + ',' + JRaw('results', '[' + S + ']') + '}';+End;+++{ docs: every document open in Altium (each server's documents): file, kind, unsaved changes, and which one is in+  front (the focused view's document). }+Function CmdDocs(Lines : TStringList) : String;+Var+    SM   : IServerModule;+    D    : IServerDocument;+    V    : IServerDocumentView;+    S, Cur, Kd : String;+    I, J : Integer;+    Md   : Boolean;+Begin+    S := ''; Cur := '';+    Try+        V := Client.GetCurrentView;+        If (V <> Nil) And (V.OwnerDocument <> Nil) Then Cur := V.OwnerDocument.FileName;+    Except+    End;+    For I := 0 To Client.Count - 1 Do+    Begin+        SM := Client.ServerModule[I];+        If SM = Nil Then Continue;+        For J := 0 To SM.DocumentCount - 1 Do+        Begin+            D := SM.Documents[J];+            If D = Nil Then Continue;+            Kd := ''; Md := False;+            Try Kd := D.Kind; Except End;+            Try If D.Modified Then Md := True; Except End;+            Try If D.GetModified Then Md := True; Except End;+            If S <> '' Then S := S + ',';+            S := S + '{' + JStr('file', D.FileName) + ',' + JStr('kind', Kd) + ',' + JRaw('modified', JBool(Md)) + '}';+        End;+    End;+    Result := '{' + JRaw('ok','true') + ',' + JStr('current', Cur) + ',' + JRaw('documents', '[' + S + ']') + '}';+End;++{ lib_fp: one footprint of the CURRENT PcbLib in full: name=<footprint>. Pads (mil, hole, layer, shape, rotation,+  plated), other primitives counted per layer, the bounding box, description, height and 3D bodies. }+Function CmdLibFootprint(Lines : TStringList) : String;+Var+    PLib  : IPCB_Library;+    Fp    : IPCB_LibComponent;+    GIt   : IPCB_GroupIterator;+    Prim  : IPCB_Primitive;+    Pad   : IPCB_Pad;+    S, B, L, Nm, Mf : String;+    I, OX, OY : Integer;+    R : TCoordRect;+Begin+    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;+    S := ''; B := ''; L := '';+    { positions from the footprint's origin, which is its library's (not 0 on a library made by this Altium) }+    OX := PLib.Board.XOrigin; OY := PLib.Board.YOrigin;+    GIt := Fp.GroupIterator_Create;+    GIt.AddFilter_LayerSet(AllLayers);+    Prim := GIt.FirstPCBObject;+    While Prim <> Nil Do+    Begin+        If Prim.ObjectId = ePadObject Then+        Begin+            Pad := Prim;+            If S <> '' Then S := S + ',';+            S := S + '[' + '"' + JsonEsc(Pad.Name) + '",' + IntToStr(Pad.x - OX) + ',' + IntToStr(Pad.y - OY) + ',' + IntToStr(Pad.TopXSize) + ',' + IntToStr(Pad.TopYSize) + ',' ++                IntToStr(Pad.HoleSize) + ',' + IntToStr(Pad.Layer) + ',' + IntToStr(Pad.TopShape) + ',' + IntToStr(Round(Pad.Rotation * 1000)) + ',' + JBool(Pad.Plated) + ']';+        End+        Else If Prim.ObjectId = eComponentBodyObject Then+        Begin+            Mf := '';+            Try If Prim.Model <> Nil Then Mf := Prim.Model.FileName; Except End;+            If B <> '' Then B := B + ',';+            B := B + '{' + JStr('model', Mf) + ',' + JRaw('overallHeight', IntToStr(Prim.OverallHeight)) + ',' + JRaw('standoff', IntToStr(Prim.StandoffHeight)) + '}';+        End+        Else+        Begin+            R := Prim.BoundingRectangle;+            If L <> '' Then L := L + ',';+            L := L + '[' + IntToStr(Prim.ObjectId) + ',' + IntToStr(Prim.Layer) + ',' + IntToStr(R.Left - OX) + ',' + IntToStr(R.Bottom - OY) + ',' + IntToStr(R.Right - OX) + ',' + IntToStr(R.Top - OY) + ']';+        End;+        Prim := GIt.NextPCBObject;+    End;+    Fp.GroupIterator_Destroy(GIt);+    R := Fp.BoundingRectangle;+    Result := '{' + JRaw('ok','true') + ',' + JStr('name', Fp.Name) + ',' + JStr('description', Fp.Description) + ',' + JRaw('height', IntToStr(Fp.Height)) + ',' ++        JRaw('k', IntToStr(MilsToCoord(1000))) + ',' + JRaw('box', '[' + IntToStr(R.Left - OX) + ',' + IntToStr(R.Bottom - OY) + ',' + IntToStr(R.Right - OX) + ',' + IntToStr(R.Top - OY) + ']') + ',' ++        JRaw('pads', '[' + S + ']') + ',' + JRaw('bodies', '[' + B + ']') + ',' + JRaw('other', '[' + L + ']') + '}';+End;+++{ new_pcb: an empty board saved at path= (Altium's default new board). Refuses an existing file. }+Function CmdNewPcb(Lines : TStringList) : String;+Var+    Path : String;+    Doc  : IServerDocument;+Begin+    Path := Param(Lines, 'path');+    If FileExists(Path) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','exists') + ',' + JStr('error', Path + ' exists') + '}'; Exit; End;+    Doc := CreateNewDocumentFromDocumentKind('PCB');+    If Doc = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','Altium made no new PCB document') + '}'; Exit; End;+        Client.ShowDocument(Doc);+    { as build_board saves its new board: name it, then save (DoSafeChangeFileNameAndSave left no file for a PCB) }+    FreePath(Path);+    Doc.SetFileName(Path);+    Doc.DoFileSave('');+    If Not FileExists(Path) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_saved') + ',' + JStr('error','the new board did not save to ' + Path) + '}'; Exit; End;+    Result := '{' + JRaw('ok','true') + ',' + JStr('path', Path) + ',' + JRaw('saved', 'true') + '}';+End;+++{ save_doc: save the document at path= itself. The save process saves the FOCUSED document, and open shows a document+  without focusing it, so a save by path through it saved whichever document had focus (a source library, measured+  2026-10-27). }+Function CmdSaveDoc(Lines : TStringList) : String;+Var+    Doc : IServerDocument;+Begin+    Doc := Nil;+    Try Doc := Client.GetDocumentByPath(Param(Lines, 'path')); Except Doc := Nil; End;+    If Doc = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','not_open') + ',' + JStr('error', Param(Lines, 'path') + ' is not open in Altium') + '}'; Exit; End;+    Doc.DoFileSave('');+    Result := '{' + JRaw('ok','true') + ',' + JStr('path', Doc.FileName) + '}';+End;+++{ ensure_lib: open, or create and save, a library: kind=PCBLIB|SCHLIB path=<file>. It becomes the current document. }+Function CmdEnsureLib(Lines : TStringList) : String;+Var+    St : String;+Begin+    St := EnsureLibrary(Param(Lines, 'kind'), Param(Lines, 'path'));+    If Copy(St, 1, 5) = 'error' Then Result := '{' + JRaw('ok','false') + ',' + JStr('error', St) + '}'+    Else Result := '{' + JRaw('ok','true') + ',' + JStr('state', St) + ',' + JStr('path', Param(Lines, 'path')) + '}';+End;++{ how many pins a symbol holds (the empty default symbol holds none) }+Function SchChildCount(C : ISch_Component) : Integer;+Var+    It : ISch_Iterator;+    P  : ISch_GraphicalObject;+Begin+    Result := 0;+    It := C.SchIterator_Create;+    P := It.FirstSchObject;+    While P <> Nil Do+    Begin+        If P.ObjectID = ePin Then Result := Result + 1;+        P := It.NextSchObject;+    End;+    C.SchIterator_Destroy(It);+End;++{ xcopy_symbol: copy one symbol from fromLib (a .SchLib, opened if need be) into the CURRENT SchLib, under its own+  name: its graphics, pins, parameters (but the Comment, which the new symbol carries already) and model links. }+Function CmdXCopySymbol(Lines : TStringList) : String;+Var+    DstLib, SrcLib : ISch_Lib;+    Src, Dst : ISch_Component;+    It  : ISch_Iterator;+    Prim, Cpy : ISch_GraphicalObject;+    SD  : IServerDocument;+    Dflt : ISch_Component;+    NCopied : Integer;+    Dropped : String;+Begin+    DstLib := SchServer.GetCurrentSchDocument;+    If (DstLib = Nil) Or (DstLib.ObjectID <> eSchLib) Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','open the destination SchLib first') + '}'; Exit; End;+    SrcLib := SchServer.GetSchDocumentByPath(Param(Lines, 'fromLib'));+    If SrcLib = Nil Then+    Begin+        Try SD := Client.OpenDocument('SCHLIB', Param(Lines, 'fromLib')); Except SD := Nil; End;+        SrcLib := SchServer.GetSchDocumentByPath(Param(Lines, 'fromLib'));+    End;+    If SrcLib = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','source library not loadable: ' + Param(Lines, 'fromLib')) + '}'; Exit; End;+    Src := FindSchComp(SrcLib, Param(Lines, 'from'));+    If Src = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','symbol_not_found') + ',' + JStr('error','symbol not found in source: ' + Param(Lines, 'from')) + '}'; Exit; End;+    If FindSchComp(DstLib, Src.LibReference) <> Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','target already has ' + Src.LibReference) + '}'; Exit; End;+    SchServer.ProcessControl.PreProcess(DstLib, '');+    Dst := SchServer.SchObjectFactory(eSchComponent, eCreate_Default);+    Dst.LibReference := Src.LibReference;+    Dst.ComponentDescription := Src.ComponentDescription;+    Dst.CurrentPartID := 1;+    Dst.DisplayMode := 0;+    Dst.Designator.Text := Src.Designator.Text;+    Dst.Comment.Text := Src.Comment.Text;+    NCopied := 0;+    It := Src.SchIterator_Create;+    Prim := It.FirstSchObject;+    While Prim <> Nil Do+    Begin+        If (Prim.ObjectID <> eParameter) Or (UpperCase(Prim.Name) <> 'COMMENT') Then+        Begin+            Cpy := Prim.Replicate;+            Dst.AddSchObject(Cpy);+            NCopied := NCopied + 1;+        End;+        Prim := It.NextSchObject;+    End;+    Src.SchIterator_Destroy(It);+    Dst.DisplayModeCount := Src.DisplayModeCount;+    DstLib.AddSchComponent(Dst);+    SchServer.RobotManager.SendMessage(DstLib.I_ObjectAddress, c_BroadCast, SCHM_PrimitiveRegistration, Dst.I_ObjectAddress);+    { a SchLib Altium has just made holds an empty Component_1: it goes once a real symbol is in }+    Dropped := '';+    Dflt := FindSchComp(DstLib, 'Component_1');+    If (Dflt <> Nil) And (UpperCase(Src.LibReference) <> 'COMPONENT_1') And (SchChildCount(Dflt) = 0) Then+    Begin+        DstLib.RemoveSchComponent(Dflt);+        Dropped := 'Component_1';+    End;+    SchServer.ProcessControl.PostProcess(DstLib, '');+    DstLib.GraphicallyInvalidate;+    Result := '{' + JRaw('ok','true') + ',' + JStr('symbol', Dst.LibReference) + ',' + JRaw('primitives', IntToStr(NCopied)) + ',' + JStr('removedDefault', Dropped) + '}'; End;  @@ -9252,6 +9569,7 @@ Begin     Else If Cmd = 'state' Then Result := CmdState(Lines)     Else If Cmd = 'run_process' Then Result := CmdRunProcess(Lines)     Else If Cmd = 'open' Then Result := CmdOpen(Lines)+    Else If Cmd = 'save_doc' Then Result := CmdSaveDoc(Lines)     Else If Cmd = 'close_document' Then Result := CmdCloseDocument(Lines)     Else If Cmd = 'eval' Then Result := CmdEval(Lines, Payload)     Else If Cmd = 'io_bench' Then Result := CmdIoBench(Lines)@@ -9292,6 +9610,11 @@ Begin     Else If Cmd = 'sheet_params' Then Result := CmdSheetParams(Lines)     Else If Cmd = 'sch_connect' Then Result := CmdSchConnect(Lines, Payload)     Else If Cmd = 'sch_dump' Then Result := CmdSchDump(Lines)+    Else If Cmd = 'docs' Then Result := CmdDocs(Lines)+    Else If Cmd = 'ensure_lib' Then Result := CmdEnsureLib(Lines)+    Else If Cmd = 'xcopy_symbol' Then Result := CmdXCopySymbol(Lines)+    Else If Cmd = 'new_pcb' Then Result := CmdNewPcb(Lines)+    Else If Cmd = 'lib_fp' Then Result := CmdLibFootprint(Lines)     Else If Cmd = 'board_graphics' Then Result := CmdBoardGraphics(Lines)     Else If Cmd = 'sch_ops' Then Result := CmdSchOps(Lines, Payload)     Else If Cmd = 'sheet_symbol' Then Result := CmdSheetSymbol(Lines, Payload)
src/bridge.json+28−2
@@ -2,7 +2,7 @@   "manifest_version": 1,   "name": "altium",   "displayName": "Altium Designer",-  "version": "0.2.76",+  "version": "0.2.77",   "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",@@ -66,6 +66,7 @@     "altium_cleanup_libs",     "altium_clone_symbol",     "altium_close",+    "altium_close_all_documents",     "altium_close_document",     "altium_compile",     "altium_compile_intlib",@@ -78,8 +79,10 @@     "altium_copy_footprint",     "altium_copy_routing",     "altium_create_footprint",+    "altium_create_part_project",     "altium_create_symbol",     "altium_cross_check",+    "altium_cross_probe",     "altium_current_capacity",     "altium_demo",     "altium_describe",@@ -88,12 +91,14 @@     "altium_diff_pairs",     "altium_dismiss_dialogs",     "altium_doc_params",+    "altium_document_info",     "altium_edit_parts",     "altium_ensure_licensed",     "altium_eval",     "altium_export_bom",     "altium_export_gerber",     "altium_export_ipc2581",+    "altium_export_library_part",     "altium_export_manufacturing",     "altium_export_odb",     "altium_export_pdf",@@ -122,6 +127,7 @@     "altium_layers",     "altium_layers_in_use",     "altium_length_tune",+    "altium_library_views",     "altium_license",     "altium_license_status",     "altium_list_commands",@@ -150,7 +156,12 @@     "altium_plate_vias",     "altium_pour_state",     "altium_progress",+    "altium_project_create",+    "altium_project_info",+    "altium_project_rename",+    "altium_project_snapshot",     "altium_read_board",+    "altium_read_footprint",     "altium_read_rules",     "altium_read_schematic",     "altium_read_sheet_file",@@ -164,6 +175,8 @@     "altium_remove_symbol",     "altium_rename_footprint",     "altium_rename_symbol",+    "altium_render_board_3d",+    "altium_render_board_layers",     "altium_render_schematic",     "altium_replicate_layout",     "altium_repour",@@ -437,7 +450,20 @@       "check_clearance": 320,       "remove_graphics": 320,       "export_odb": 660,-      "export_ipc2581": 660+      "export_ipc2581": 660,+      "document_info": 320,+      "close_all_documents": 320,+      "project_info": 320,+      "project_create": 320,+      "project_rename": 320,+      "project_snapshot": 320,+      "cross_probe": 320,+      "read_footprint": 320,+      "render_board_3d": 660,+      "render_board_layers": 660,+      "library_views": 960,+      "export_library_part": 960,+      "create_part_project": 960     },     "prefixes": [       {