by adom
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.
← Commit history
0.2.90 (source, not released; final shapes not run in Altium yet): the eleven verbs of standard 0.30.14 in the standard's shapes, track ids in routing_state, license release, license no longer answers success for a press that never happened, routing_state and board edits take filePath, edit_drill.py
18 files changed
+1658−21
CHANGELOG.md+21README.md+15−4bridge-rs/src/design.rs+25bridge-rs/src/importdesign.rs+4−1bridge-rs/src/license.rs+69−2bridge-rs/src/main.rs+2bridge-rs/src/prefs.rs+249bridge-rs/src/routing.rs+184−2bridge-rs/src/runs.rs+86bridge-rs/src/schbatch.rs+6−3bridge-rs/src/schwire.rs+172bridge-rs/src/verbs.rs+59−4dev-skills/altium-bridge-test/edit_drill.py+497dev-skills/altium-bridge-test/run_verb_tests.py+62−1package.json+14−1page.json+15−2src/agent/AdomAgent.pas.tmpl+166src/bridge.json+12−1CHANGELOG.md+21@@ -1,5 +1,26 @@ # Changelog +## 0.2.90 (unreleased)++Source only, not released. The unit tests pass and it builds, but the final shapes of these verbs have not run in Altium yet: an earlier build passed most of `edit_drill.py`, and the batteries, the drill's real-project steps and `license` `release` on Altium Designer are still to run.++- **Eleven verbs new in the standard** (EDA Bridge Standard #29, 0.30.14):+ - `altium_sch_no_connect`: No ERC markers at a point or on a pin, and removal by id.+ - `altium_sch_label`: a net label on an existing wire at a point, and deletion.+ - `altium_sch_wire`: a wire through given points, with junctions where it makes a T.+ - `altium_place_parts`: footprints from a library onto the board, with position, rotation and side, each read back.+ - `altium_edit_tracks`: given tracks by id (`routing_state` now gives each track one): width, layer, ends, as one undo step.+ - `altium_model_check`: per part or footprint, is there a model, where it is, whether its source file is found, whether it holds geometry.+ - `altium_extensions`: Altium's own installed extensions, listed by edition. Install and remove are refused by name.+ - `altium_preferences`: Altium's preferences from where it keeps them (the registry), by section or key; `set` changes existing ones, with Altium closed.+ - `altium_select_items`: select parts by designator on a board or sheet, or clear, read back.+ - `altium_cancel_run`: stop the bridge's own long job between steps (`sch_batch` takes its ops back; `import_design`'s wizard closes with nothing imported). It never claims to interrupt Altium.+ - `altium_physical_properties`: refused with the reason. Altium keeps no material or mass on a part.+- **`altium_license` has a `release` action** (#29): gives the seat back through the licence page's Release button, and `released` says the page no longer shows a licence in use. Altium Designer only: Develop has no licence page the bridge can reach, so it is refused with that reason.+- **`altium_license` no longer answers success for a press that never happened.** An action now presses a button only when the licence page is showing (`licence_page_not_open` otherwise), and a click that failed answers `click_failed`. On Develop, `use_license` used to answer success, and its pixel fallback clicked the Home page instead.+- **`routing_state` and the board edits that read it take `filePath`** (`route_net`, `move_parts`, `place_vias`, `remove_items`, `ripup_nets` and others). They acted on the current board and ignored the argument, so naming a board that wasn't current was refused, or read and edited whichever board was in front. Found by the new edit drill.+- **`dev-skills/altium-bridge-test/edit_drill.py`:** runs the edit verbs the battery only dry-runs for real, on its own scratch board and sheet, and a second read confirms each.+ ## 0.2.89 - **`import_design` reads EAGLE** (EDA Bridge Standard #29): an EAGLE schematic and its board, together, into a new Altium project through Altium's Import Wizard, run outside the script engine with Altium's own import options. Run end to end on a real 109-part, 4-layer board and a small fixture, on Altium Designer Develop 26.9.
README.md+15−4@@ -15,7 +15,7 @@ normal session. Ask in plain words and it: - makes the outputs: Gerbers, NC drill, pick and place, BOMs grouped by MPN (JLCPCB, Mouser, DigiKey files), schematic PDF and STEP, checking that the outline and every copper layer reached the Gerbers -270 commands, tested on Altium Designer 26.11 and Altium Designer Develop. It runs in **Hydrogen**, Adom's free+281 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. 270 verbs; each row names the ones+Tested on Altium Designer 26.11.1 and Altium Designer Develop. 281 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 270 `altium_*` verbs.+**DelphiScript agent** inside it, and gives the AI 281 `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 270 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example.+All 281 verbs, by area (prefix `altium_`). `altium_describe` returns the live catalog with every input, output, hint and example. ### Running Altium: launch, close, health, dialogs @@ -242,6 +242,17 @@ All 270 verbs, by area (prefix `altium_`). `altium_describe` returns the live ca ### Placing and routing a live board +- `altium_sch_no_connect`: Flag points or pins left open on purpose with Altium's No ERC marker, or remove markers by id or point.+- `altium_sch_label`: Put net labels on existing wires at given points, or delete labels by id or point.+- `altium_sch_wire`: Draw a wire through exactly the given points, with junctions where it makes a T.+- `altium_edit_tracks`: Change given tracks: width, layer or ends, by the id routing_state gives each track (or its start, end and layer).+- `altium_select_items`: Select parts by designator on the current board or sheet, everything else deselected, or clear the selection, and read it back.+- `altium_preferences`: Read Altium's own preferences from where it keeps them, by section or key, or set existing ones with Altium closed.+- `altium_extensions`: List Altium's own installed extensions by edition, with their versions.+- `altium_cancel_run`: Stop a long job the bridge started, between its steps: sch_batch (it takes its ops back) and import_design's wizard (it closes with nothing imported).+- `altium_physical_properties`: Mass, volume and centre of mass per part.+- `altium_model_check`: Per part of a board or footprint of a library: does it have a 3D model, where the model is, whether its source file is still found, and whether it holds any geometry.+- `altium_place_parts`: Put footprints from a library on the current board at given positions, rotations and sides, each read back. - `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_plan_route`: Find a path for one net between two pads, clear of other nets' copper by the board's clearance rule, on the copper layers you allow, with vias between them (the standard's shared planner).
bridge-rs/src/design.rs+25@@ -441,6 +441,31 @@ pub fn selection(args: &Value) -> Value { else { "Sheet positions in mils, as altium_sch_edit {action:'move'} takes them." }}) } +/// altium_select_items {filePath?, refs?, clear?}: select parts by designator, everything else deselected; or clear.+pub fn select_items(args: &Value) -> Value {+ if let Some(g) = support::need_licensed() { return g; }+ if let Some(p) = s(args, "filePath") { if let Some(e) = support::must_open(&p, 60) { return e; } }+ let refs = name_list(args.get("refs"));+ let clear = args.get("clear").and_then(|v| v.as_bool()) == Some(true);+ if refs.is_empty() && !clear { return json!({"success": false, "errorCode": "bad_args", "error": "refs: [designator], or clear: true"}); }+ // the standard's where: board by default, or what filePath names. A mismatch with the current document is refused.+ let named = s(args, "filePath").map(|p| if p.to_lowercase().ends_with(".schdoc") { "sheet" } else { "board" });+ let wher = args.get("where").and_then(|v| v.as_str()).or(named).unwrap_or("board").to_string();+ if wher != "board" && wher != "sheet" { return json!({"success": false, "errorCode": "bad_args", "error": format!("where is board or sheet (got {wher})")}); }+ let now = match agent_data(&agent::call("selection", &[], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };+ if now["kind"].as_str() != Some(wher.as_str()) {+ return json!({"success": false, "errorCode": "wrong_document", "error": format!("where is {wher}, but the current document is a {}: name the document with filePath", now["kind"].as_str().unwrap_or("different kind")), "document": now["document"], "mutated": false});+ }+ // a name no part has clears every part, on a board and on a sheet+ let set = if refs.is_empty() { "\u{1}none".to_string() } else { refs.join(";") };+ let d = match agent_data(&agent::call("selection", &[("set", set)], None, Duration::from_secs(60))) { Ok(d) => d, Err(e) => return e };+ let got: Vec<String> = d["selected"].as_array().cloned().unwrap_or_default().iter().filter_map(|r| r[0].as_str().map(str::to_string)).collect();+ let failed: Vec<Value> = refs.iter().filter(|r| !got.iter().any(|g| g.eq_ignore_ascii_case(r))).map(|r| json!({"ref": r, "error": "not on this document"})).collect();+ let verified = if clear && refs.is_empty() { got.is_empty() } else { failed.is_empty() && got.len() == refs.len() };+ json!({"success": verified, "kind": d["kind"], "document": d["document"], "selected": got, "failed": failed, "verified": verified,+ "_hint": "The parts Altium reports selected after the call, read back: everything else is deselected. failed names designators not on this document. select_net selects a whole net; altium_selection reads what the user selected."})+}+ fn dist(a: (f64, f64), b: (f64, f64)) -> f64 { ((a.0 - b.0).powi(2) + (a.1 - b.1).powi(2)).sqrt() } pub fn mst_pub(pts: &[(f64, f64)]) -> f64 { mst(pts) }
bridge-rs/src/importdesign.rs+4−1@@ -122,10 +122,12 @@ fn drive_pages(eagle: i64, out_dir: Option<&Path>, steps: &mut Vec<Value>) -> Re let t0 = Instant::now(); let (mut pressed_on, mut pressed_at, mut shown, mut dir_set) = (None::<String>, Instant::now(), String::new(), out_dir.is_none()); while t0.elapsed().as_secs() < 600 {+ // once the import itself runs it goes to its end; until then a cancel closes the wizard with nothing imported+ if crate::runs::cancelled() && shown != "Sheet_Output" && shown != "Sheet_Finish" { return Err("cancelled by cancel_run".into()); } let tree = nodes(eagle); if tree.len() <= 1 && window("EAGLE Import Wizard", 1).is_none() { return Err(format!("the EAGLE Import Wizard closed on {shown} before the import finished")); } let page = page_of(&tree);- if page != shown { steps.push(json!({"step": "page", "page": page, "atSec": t0.elapsed().as_secs()})); shown = page.clone(); }+ if page != shown { steps.push(json!({"step": "page", "page": page, "atSec": t0.elapsed().as_secs()})); crate::runs::stage(&format!("wizard page {page}")); shown = page.clone(); } if page == "Sheet_IntLib" && !dir_set { let want = out_dir.map(|d| d.to_string_lossy().replace('/', "\\")).unwrap_or_default(); let _ = std::fs::create_dir_all(&want);@@ -238,6 +240,7 @@ pub fn import_design(args: &Value) -> Value { let stop = crate::lifecycle::stop(); if stop.get("success").and_then(|v| v.as_bool()) != Some(true) { return json!({"success": false, "errorCode": "agent_stop_failed", "stop": stop}); } let mut steps = Vec::new();+ let _run = crate::runs::begin("import_design"); let run = run_eagle(&files, out_dir.as_deref(), &mut steps); let start = crate::lifecycle::start(Duration::from_secs(90)); let prj = new_project(&dir, since);
bridge-rs/src/license.rs+69−2@@ -23,6 +23,7 @@ fn page_name(action: &str) -> &str { match action { "refresh" => "Refresh", "use_license" => "Use License",+ "release" => "Release", "start_trial" => "Start Trial", "sign_out" => "Sign Out", other => other,@@ -32,10 +33,30 @@ fn page_name(action: &str) -> &str { fn page_automation_id(action: &str) -> Option<&'static str> { match action { "use_license" => Some("UseLicenseButton"),+ "release" => Some("ReleaseButton"), _ => None, } } +/// Is the licence page in front? The main window's title names its document. Altium takes a moment to show it.+fn on_licence_page() -> bool {+ let t0 = std::time::Instant::now();+ loop {+ instance::invalidate_snapshot();+ if instance::main_window().map(|w| title_is_licence_page(w.get("title").and_then(|t| t.as_str()).unwrap_or(""))).unwrap_or(false) { return true; }+ if t0.elapsed() > Duration::from_secs(8) { return false; }+ std::thread::sleep(Duration::from_millis(500));+ }+}++/// Pure: the title of Altium's window while its licence page is the document in front.+pub fn title_is_licence_page(title: &str) -> bool { title.starts_with("License Management") }++/// Pure: has a find for the Release button come back with none? A failed find is not an answer.+pub fn release_button_gone(found: &Value) -> bool {+ match found.get("matches").and_then(|m| m.as_array()) { Some(a) => a.is_empty(), None => found.get("errorCode").and_then(|c| c.as_str()) == Some("uia_not_found") }+}+ /// UIA first (quiet), image-space click only if UIA cannot reach the control. fn click_by_name_then_pixels(hwnd: i64, name: &str, automation_id: Option<&str>, pixel: impl FnOnce() -> Value) -> Value { let mut args = json!({"hwnd": hwnd, "name": name, "role": "button", "reason": "altium licence page: click the named button"});@@ -114,10 +135,10 @@ pub fn license(args: &Value) -> Value { let hwnd = lic.get("hwnd").and_then(|h| h.as_i64()).unwrap_or(0); let action = s_or(args, "action", "show"); // An unknown action used to do nothing and answer success:true (found 2026-09-21).- if !matches!(action.as_str(), "show" | "refresh" | "use_license" | "start_trial" | "sign_out") {+ if !matches!(action.as_str(), "show" | "refresh" | "use_license" | "release" | "start_trial" | "sign_out") { return json!({"success": false, "errorCode": "unknown_action", "action": action, "error": format!("unknown licence action '{action}'"),- "_hint": "action is one of: show (default, returns the page screenshot), refresh, use_license, start_trial, sign_out. altium_ensure_licensed does the usual sequence in one call; altium_install {stage:'license'} does it after a fresh install."});+ "_hint": "action is one of: show (default, returns the page screenshot), refresh, use_license, release, start_trial, sign_out. altium_ensure_licensed does the usual sequence in one call; altium_install {stage:'license'} does it after a fresh install."}); } if agent::is_alive() { agent::call_no_autostart("run_process", &[("process", "Client:LicenseSubscriptionNotification".into()), ("params", "".into())], Duration::from_secs(15));@@ -149,6 +170,37 @@ pub fn license(args: &Value) -> Value { out["pixelFallbackUnavailable"] = json!({"screenshotSuccess": win.get("success"), "error": win.get("error"), "errorCode": win.get("errorCode"), "keys": win.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>())}); }+ // an action presses a button on the licence page, so that page has to be showing. Altium Develop's Client:MyAccount+ // leaves the Home page in front (measured 2026-11-02), where the pixel fallback would click whatever is there, and+ // the action used to answer success all the same.+ if action != "show" && action != "refresh" && !on_licence_page() {+ out["success"] = json!(false);+ out["errorCode"] = json!("licence_page_not_open");+ out["error"] = json!(format!("the bridge could not open Altium's License Management page, so nothing was pressed for {action}"));+ out["_hint"] = json!("Altium Designer Develop has no way to its licence page the bridge can reach. altium_close releases the seat; starting Altium claims a free one.");+ return out;+ }+ if action == "release" {+ // no pixel fallback: Release is on every row in use, so only the button itself will do+ let r = ab::call("desktop_ui_click", json!({"hwnd": hwnd, "automationId": "ReleaseButton", "name": "Release", "role": "button", "reason": "altium licence page: release the seat"}), &[], 30);+ let pressed = r.get("success").and_then(|b| b.as_bool()) != Some(false) && r.get("status").and_then(|s| s.as_str()) != Some("error");+ let mut gone = false;+ if pressed {+ let t0 = std::time::Instant::now();+ while t0.elapsed() < Duration::from_secs(15) && !gone {+ std::thread::sleep(Duration::from_secs(1));+ gone = release_button_gone(&ab::call("desktop_find_controls", json!({"hwnd": hwnd, "automationId": "ReleaseButton"}), &[], 20));+ }+ }+ instance::invalidate_snapshot();+ out["success"] = json!(pressed && gone);+ out["released"] = json!(gone);+ out["clicked"] = json!({"action": action, "lane": "uia", "result": r});+ out["licenceStateAfter"] = instance::licence_state().get("state").cloned().unwrap_or(Value::Null);+ if !(pressed && gone) { out["errorCode"] = json!("release_failed"); out["error"] = json!(if pressed { "Release was pressed and the page still shows a licence in use" } else { "there is no Release button on the page: no licence is in use" }); }+ out["_hint"] = json!("released says the page no longer shows a licence in use. Altium then stops running scripts, so the bridge's verbs answer not_licensed until altium_license {action:'use_license'} claims one again.");+ return out;+ } if let Some((x, y)) = page_coords(&action) { let sid = shot_id.clone(); let rect = instance::main_window().map(|w| instance::norm_rect(&w));@@ -165,6 +217,8 @@ pub fn license(args: &Value) -> Value { } }); out["windowEtiquette"] = r.get("windowEtiquette").cloned().unwrap_or(json!("foreground"));+ // the click's own answer: a press that failed is not a success+ if r.get("success").and_then(|b| b.as_bool()) == Some(false) || r.get("status").and_then(|s| s.as_str()) == Some("error") { out["success"] = json!(false); out["errorCode"] = json!("click_failed"); } out["clicked"] = json!({"action": action, "lane": r.get("lane"), "result": r}); std::thread::sleep(Duration::from_secs(2)); instance::invalidate_snapshot();@@ -356,6 +410,19 @@ pub fn connect_workspace(_args: &Value) -> Value { mod page_tests { use super::*; + #[test]+ fn the_licence_page_is_named_in_the_title() {+ assert!(title_is_licence_page("License Management - Altium Designer (26.11.1) - Viewer"));+ assert!(!title_is_licence_page("Home Page - Altium Designer Develop"), "Develop's account command leaves this in front");+ }++ #[test]+ fn a_release_is_confirmed_by_the_button_going() {+ assert!(release_button_gone(&json!({"matches": []})));+ assert!(!release_button_gone(&json!({"matches": [{"name": "Release"}]})));+ assert!(!release_button_gone(&json!({"error": "the relay dropped"})), "a failed find proves nothing");+ }+ #[test] fn page_to_screen_maps_through_the_window_rect() { // the laptop's maximised AD 26.11.1 window: 2582 x 1550 physical px at (-11, -11), safe frame 1400 px
bridge-rs/src/main.rs+2@@ -65,6 +65,8 @@ mod silkplace; mod sim; mod support; mod surfaces;+mod prefs;+mod runs; mod taskbar; mod variants; mod verbs;
bridge-rs/src/prefs.rsadded+249@@ -0,0 +1,249 @@+//! preferences and extensions (EDA Bridge Standard #29, app tier).+//! - Altium keeps its preferences in the registry, HKCU\Software\Altium\<product>\DesignExplorer\Preferences\<server>\...+//! (measured on Altium Designer Develop 26.9 and Altium Designer 26.11). They read any time. A set changes existing+//! values only, with Altium closed: Altium writes its preferences back when it exits.+//! - Altium's installed extensions are folders of ...\ProgramData\Altium\<product>\Extensions, each with its .ins. They+//! list from there. Altium's Extensions & Updates page is not in UI Automation, so install and remove are refused.+use serde_json::{json, Value};+use std::process::Command;++fn ps(script: &str) -> Option<String> {+ let full = format!("[Console]::OutputEncoding=[Text.Encoding]::UTF8; $ErrorActionPreference='Stop'; {script}");+ let o = Command::new("powershell").args(["-NoProfile", "-Command", &full]).output().ok()?;+ o.status.success().then(|| String::from_utf8_lossy(&o.stdout).to_string())+}++fn sq(s: &str) -> String { s.replace('\'', "''") }++/// The Altium products with preferences: (registry name, edition). Only the ones that hold any: an old install's key+/// may be empty.+fn products() -> Vec<(String, String)> {+ let out = ps("Get-ChildItem 'HKCU:\\Software\\Altium' | Where-Object { Test-Path (Join-Path $_.PSPath 'DesignExplorer\\Preferences\\Client') } | ForEach-Object { $_.PSChildName }").unwrap_or_default();+ out.lines().map(str::trim).filter(|l| l.starts_with("Altium Designer") && !l.ends_with("_Security"))+ .map(|l| (l.to_string(), edition_of(l).to_string())).collect()+}++/// The edition a product name is. Pure.+pub fn edition_of(product: &str) -> &'static str { if product.to_ascii_lowercase().contains("develop") { "Altium Designer Develop" } else { "Altium Designer" } }++/// Which product a call means: the edition asked for, else the one alone, else the one running. Pure over its inputs.+pub fn pick_product(all: &[(String, String)], want: Option<&str>, running: Option<&str>) -> Result<(String, String), String> {+ let names = || all.iter().map(|p| p.1.clone()).collect::<Vec<_>>().join(", ");+ if let Some(w) = want {+ let w = w.to_ascii_lowercase();+ let exact = all.iter().find(|p| p.1.to_ascii_lowercase() == w);+ let hit = exact.or_else(|| all.iter().find(|p| p.1.to_ascii_lowercase().contains(&w)));+ return hit.cloned().ok_or_else(|| format!("no Altium edition {w} here: {}", names()));+ }+ if all.len() == 1 { return Ok(all[0].clone()); }+ if let Some(r) = running { if let Some(p) = all.iter().find(|p| p.1 == r) { return Ok(p.clone()); } }+ if all.is_empty() { return Err("no Altium preferences on this machine: start Altium once".into()); }+ Err(format!("several Altiums here and none running: name one with edition ({})", names()))+}++/// A key the caller names to a registry path and value name: Server/Group/Name. Pure.+pub fn split_key(key: &str) -> Option<(String, String)> {+ // the standard's dotted path, or Altium's own Server/Group/Name+ let k = key.trim_matches('/').replace('\\', "/");+ let k = if k.contains('/') { k } else { k.replace('.', "/") };+ let (path, name) = k.rsplit_once('/')?;+ if path.is_empty() || name.is_empty() || k.contains("..") { return None; }+ Some((path.replace('/', "\\"), name.to_string()))+}++fn running_edition() -> Option<String> {+ let l = crate::instance::licence_state();+ l.get("running").and_then(|b| b.as_bool()).filter(|b| *b)?;+ Some(edition_of(l["edition"].as_str().unwrap_or("")).to_string())+}++/// altium_preferences {edition?, key?, under?, set?: {key: value}, dryRun?}+pub fn preferences(args: &Value) -> Value {+ let all = products();+ let want = args.get("edition").and_then(|v| v.as_str());+ let (product, edition) = match pick_product(&all, want, running_edition().as_deref()) {+ Ok(p) => p,+ Err(e) => return json!({"success": false, "errorCode": "no_edition", "error": e, "editions": all.iter().map(|p| p.1.clone()).collect::<Vec<_>>()}),+ };+ let root = format!("HKCU:\\Software\\Altium\\{}\\DesignExplorer\\Preferences", sq(&product));+ if let Some(set) = args.get("set").and_then(|v| v.as_object()) {+ if crate::health::is_running() {+ return json!({"success": false, "errorCode": "altium_running", "reason": "tool_running", "edition": edition, "error": "Altium writes its preferences back when it exits, so they are set with Altium closed", "_hint": "altium_close, then call again."});+ }+ let (mut before, mut applied, mut failed) = (serde_json::Map::new(), serde_json::Map::new(), Vec::new());+ for (k, v) in set {+ let Some((path, name)) = split_key(k) else { failed.push(json!({"key": k, "error": "a key is Server/Group/Name, as a read lists it"})); continue; };+ let reg = format!("'{root}\\{}'", sq(&path));+ let was = ps(&format!("(Get-ItemProperty -LiteralPath {reg} -Name '{}').'{}'", sq(&name), sq(&name)));+ let Some(was) = was else { failed.push(json!({"key": k, "error": "Altium has no such preference: a set changes existing ones only"})); continue; };+ before.insert(k.clone(), json!(was.trim()));+ if args.get("dryRun").and_then(|b| b.as_bool()) == Some(true) { continue; }+ let text = match v { Value::String(s) => s.clone(), Value::Bool(b) => if *b { "1".into() } else { "0".into() }, o => o.to_string() };+ let wrote = ps(&format!("Set-ItemProperty -LiteralPath {reg} -Name '{}' -Value '{}'; (Get-ItemProperty -LiteralPath {reg} -Name '{}').'{}'", sq(&name), sq(&text), sq(&name), sq(&name)));+ match wrote {+ Some(back) if back.trim() == text => { applied.insert(k.clone(), json!({"ok": true, "requested": v, "read": back.trim()})); }+ o => { applied.insert(k.clone(), json!({"ok": false, "requested": v, "read": o.as_deref().map(str::trim)})); failed.push(json!({"key": k, "error": "the value did not read back"})); }+ }+ }+ return json!({"success": failed.is_empty(), "edition": edition, "before": before, "applied": applied, "failed": failed, "mutated": !applied.is_empty(), "needsRestart": false,+ "_hint": "Altium reads its preferences when it starts. Each value is read back from where Altium keeps it."});+ }+ // a read: one key, or everything under a section; with neither, the sections+ if let Some(k) = args.get("key").and_then(|v| v.as_str()) {+ let Some((path, name)) = split_key(k) else { return json!({"success": false, "errorCode": "bad_args", "error": "key is Server/Group/Name"}) };+ return match ps(&format!("(Get-ItemProperty -LiteralPath '{root}\\{}' -Name '{}').'{}'", sq(&path), sq(&name), sq(&name))) {+ Some(v) => json!({"success": true, "edition": edition, "current": {k: v.trim()}}),+ None => json!({"success": false, "errorCode": "not_found", "edition": edition, "error": format!("Altium has no preference {k}")}),+ };+ }+ // the whole of Altium's preferences by default, or one section+ let under = args.get("under").and_then(|v| v.as_str()).map(|u| { let u = u.trim_matches('/').replace('/', "\\"); if u.contains('\\') { u } else { u.replace('.', "\\") } });+ if under.as_deref().map(|u| u.contains("..")).unwrap_or(false) { return json!({"success": false, "errorCode": "bad_args", "error": "under is a section such as ExtensionManager.AutoUpdatePrefs"}); }+ let start = match &under { Some(u) => format!("{root}\\{}", sq(u)), None => root.clone() };+ let script = format!(r#"$r='{start}'; $o=[ordered]@{{}}; foreach($k in @(Get-Item -LiteralPath $r)+@(Get-ChildItem -LiteralPath $r -Recurse)) {{ $i=$k.PSPath.IndexOf('Preferences\'); if($i -lt 0) {{ continue }}; $p=$k.PSPath.Substring($i+12).Replace('\','.'); foreach($n in $k.Property) {{ $v=$k.GetValue($n); if($v -is [byte[]]) {{ $v=[BitConverter]::ToString($v) }} $o["$p.$n"]="$v" }} }}; $o | ConvertTo-Json -Depth 2 -Compress"#);+ match ps(&script).and_then(|t| serde_json::from_str::<Value>(t.trim()).ok()) {+ Some(v) => {+ let n = v.as_object().map(|m| m.len()).unwrap_or(0);+ let sections: std::collections::BTreeSet<String> = v.as_object().map(|m| m.keys().filter_map(|k| k.split('.').next().map(str::to_string)).collect()).unwrap_or_default();+ json!({"success": true, "edition": edition, "under": under.map(|u| u.replace('\\', ".")), "count": n, "sections": sections, "current": v,+ "_hint": "Altium's preferences as dotted keys. key reads one, under reads a section, and set: {key: value} changes existing ones with Altium closed."})+ }+ None => json!({"success": false, "errorCode": "not_found", "edition": edition, "error": "no preferences there"}),+ }+}++/// An extension's name, description and version from its .ins text. Pure.+pub fn parse_ins(text: &str) -> (Option<String>, Option<String>, Option<String>) {+ let field = |k: &str| text.lines().find_map(|l| { let (a, b) = l.split_once('=')?; (a.trim().eq_ignore_ascii_case(k)).then(|| b.trim().trim_matches('\'').to_string()) });+ (field("EditorName"), field("EditorDescription"), field("Version"))+}++/// altium_extensions {action: list | install | remove, name?, edition?}+pub fn extensions(args: &Value) -> Value {+ let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("list").to_ascii_lowercase();+ if action == "install" || action == "remove" {+ return json!({"success": false, "errorCode": "not_supported", "action": action,+ "error": format!("the bridge cannot {action} an Altium extension: Altium does that on its Extensions & Updates page, which is not in UI Automation, and it restarts Altium to apply"),+ "_hint": "The user does it in Altium: Extensions & Updates. altium_install_extension is the separate one for Adom's own AdomBridge extension."});+ }+ if action != "list" { return json!({"success": false, "errorCode": "bad_args", "error": format!("action is list, install or remove (got {action})")}); }+ let want = args.get("edition").and_then(|v| v.as_str()).map(str::to_ascii_lowercase);+ let data = std::env::var("ProgramData").unwrap_or_else(|_| "C:\\ProgramData".into());+ let mut editions = Vec::new();+ for prod in std::fs::read_dir(std::path::Path::new(&data).join("Altium")).into_iter().flatten().flatten() {+ let name = prod.file_name().to_string_lossy().to_string();+ if !name.starts_with("Altium Designer") || name.ends_with("_Security") { continue; }+ let edition = edition_of(&name);+ if want.as_ref().map(|w| !edition.to_ascii_lowercase().contains(w.as_str())).unwrap_or(false) { continue; }+ let mut list = Vec::new();+ for ext in std::fs::read_dir(prod.path().join("Extensions")).into_iter().flatten().flatten() {+ if !ext.path().is_dir() { continue; }+ let folder = ext.file_name().to_string_lossy().to_string();+ let ins = std::fs::read_dir(ext.path()).into_iter().flatten().flatten().map(|f| f.path()).find(|p| p.extension().map(|x| x.eq_ignore_ascii_case("ins")).unwrap_or(false));+ let (server, desc, ver) = ins.and_then(|p| std::fs::read(p).ok()).map(|b| parse_ins(&String::from_utf8_lossy(&b))).unwrap_or((None, None, None));+ let version = ver.map(|v| v.trim_start_matches("Version ").to_string());+ list.push(json!({"id": folder, "name": desc.unwrap_or_else(|| folder.clone()), "server": server, "version": version, "kind": "altium"}));+ }+ list.sort_by_key(|e| e["id"].as_str().unwrap_or("").to_ascii_lowercase());+ if !list.is_empty() { editions.push(json!({"edition": edition, "count": list.len(), "extensions": list})); }+ }+ let flat: Vec<Value> = editions.first().and_then(|e| e["extensions"].as_array().cloned()).unwrap_or_default();+ json!({"success": true, "extensions": flat, "count": flat.len(), "editions": editions,+ "_hint": "Altium's optional extensions on this machine, by edition (extensions is the first edition's). Installing and removing them happens on Altium's Extensions & Updates page, not through the bridge."})+}++/// What one part's models say: the row is the agent's [ref, footprint, [[file, overall, standoff, w, h]]], `to_mm` turns+/// raw units to mm, and `found` says whether a named file is on disk. A model sits inside the Altium document, so it is+/// there whether or not the file it came from still is; that file is reported beside it. Pure.+pub fn check_part(row: &Value, to_mm: f64, found: &dyn Fn(&str) -> bool) -> Value {+ let models: Vec<Value> = row[2].as_array().cloned().unwrap_or_default().iter().map(|b| {+ let file = b[0].as_str().unwrap_or("");+ let n = |i: usize| b[i].as_f64().unwrap_or(0.0) * to_mm;+ let (h, s) = (n(1), n(2));+ let geometry = h > s && n(3) > 0.0 && n(4) > 0.0;+ json!({"path": if file.is_empty() { Value::Null } else { json!(file) }, "location": "embedded", "found": true, "hasGeometry": geometry,+ "kind": if file.is_empty() { "extruded" } else { "model" }, "sourceFileFound": if file.is_empty() { Value::Null } else { json!(found(file)) }, "heightMm": ((h - s) * 1000.0).round() / 1000.0})+ }).collect();+ let mut issues = Vec::new();+ if models.is_empty() { issues.push("no 3D model".to_string()); }+ if models.iter().any(|m| m["hasGeometry"] != json!(true)) { issues.push("a model holds no geometry".to_string()); }+ json!({"name": row[0], "footprint": row[1], "models": models, "issues": issues})+}++/// altium_model_check {filePath? | library?, footprint?, refs?, limit?}+pub fn model_check(args: &Value) -> Value {+ if let Some(g) = crate::support::need_licensed() { return g; }+ let doc = crate::support::s(args, "filePath").or_else(|| crate::support::s(args, "library"));+ if let Some(p) = &doc { if let Some(e) = crate::support::must_open(p, 60) { return e; } }+ let r = crate::agent::call("model_check", &[], None, std::time::Duration::from_secs(180));+ let d = r.get("data").cloned().unwrap_or(Value::Null);+ if d["ok"] != json!(true) { return json!({"success": false, "errorCode": "no_document", "error": d.get("error").cloned().unwrap_or(json!("no board or footprint library is current")), "reply": r}); }+ let mut want: Vec<String> = args.get("refs").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_ascii_lowercase)).collect();+ if let Some(f) = crate::support::s(args, "footprint") { want.push(f.to_ascii_lowercase()); }+ let to_mm = 0.0254 / 10000.0;+ let found = |f: &str| std::path::Path::new(f).is_file();+ let parts: Vec<Value> = d["parts"].as_array().cloned().unwrap_or_default().iter()+ .filter(|p| want.is_empty() || p[0].as_str().map(|x| want.contains(&x.to_ascii_lowercase())).unwrap_or(false))+ .map(|p| check_part(p, to_mm, &found)).collect();+ if !want.is_empty() && parts.is_empty() { return json!({"success": false, "errorCode": "not_found", "error": format!("none of {want:?} is on this document"), "document": d["document"]}); }+ let names = |f: &dyn Fn(&Value) -> bool| parts.iter().filter(|p| f(p)).filter_map(|p| p["name"].as_str().map(str::to_string)).collect::<Vec<_>>();+ let no_model = names(&|p| p["models"].as_array().map(|b| b.is_empty()).unwrap_or(true));+ let no_geometry = names(&|p| p["models"].as_array().map(|b| !b.is_empty() && b.iter().any(|x| x["hasGeometry"] != json!(true))).unwrap_or(false));+ let lost_source = names(&|p| p["models"].as_array().map(|b| b.iter().any(|x| x["sourceFileFound"] == json!(false))).unwrap_or(false));+ // the report is capped, the answer is not: ok and checked speak for every part, with the worst ones listed first+ let limit = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as usize;+ let mut shown = parts.clone();+ shown.sort_by_key(|p| p["issues"].as_array().map(|i| i.is_empty()).unwrap_or(true));+ shown.truncate(limit);+ json!({"success": true, "ok": no_model.is_empty() && no_geometry.is_empty(), "kind": d["kind"], "document": d["document"], "checked": parts.len(), "parts": shown, "noModel": no_model, "noGeometry": no_geometry, "sourceFileMissing": lost_source,+ "_hint": "Altium keeps a part's 3D model inside the document, so a model still draws when its source file has gone: sourceFileMissing is for information, and an update from that file would fail. ok and checked cover every part; parts lists up to limit, those with issues first. altium_bodies says whether each body sits where the board puts the part."})+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_parts_models() {+ let k = 10000.0 / 0.0254;+ let to_mm = 1.0 / k;+ let raw = |mm: f64| mm * k;+ let row = json!(["U1", "QFN", [["C:/m/u1.step", raw(1.0), 0.0, raw(4.0), raw(4.0)], ["", raw(0.5), 0.0, raw(2.0), raw(2.0)]]]);+ let r = check_part(&row, to_mm, &|_| false);+ assert_eq!(r["name"], "U1");+ assert_eq!(r["issues"], json!([]), "a lost source file is not an issue: the model is in the document");+ assert_eq!(r["models"][0]["location"], "embedded");+ assert_eq!(r["models"][0]["found"], true);+ assert_eq!(r["models"][0]["sourceFileFound"], false);+ assert_eq!(r["models"][0]["heightMm"], 1.0);+ assert_eq!(r["models"][1]["kind"], "extruded");+ assert_eq!(r["models"][1]["sourceFileFound"], Value::Null);+ assert_eq!(check_part(&json!(["R1", "R", []]), to_mm, &|_| true)["issues"], json!(["no 3D model"]));+ assert_eq!(check_part(&json!(["R1", "R", [["x.step", 0.0, 0.0, 0.0, 0.0]]]), to_mm, &|_| true)["models"][0]["hasGeometry"], false);+ }++ #[test]+ fn a_key_is_its_section_and_name() {+ assert_eq!(split_key("ExtensionManager/AutoUpdatePrefs/UpdatesCheckFrequency"), Some(("ExtensionManager\\AutoUpdatePrefs".to_string(), "UpdatesCheckFrequency".to_string())));+ assert_eq!(split_key("ExtensionManager.AutoUpdatePrefs.UpdatesCheckFrequency"), Some(("ExtensionManager\\AutoUpdatePrefs".to_string(), "UpdatesCheckFrequency".to_string())), "the standard's dotted path");+ assert_eq!(split_key("Plain"), None);+ assert_eq!(split_key("../../Evil/Name"), None, "stays under Altium's preferences");+ }++ #[test]+ fn which_altium_a_call_means() {+ let a = |n: &str, e: &str| (n.to_string(), e.to_string());+ let two = vec![a("D {1}", "Altium Designer"), a("V {2}", "Altium Designer Develop")];+ assert_eq!(pick_product(&two, Some("develop"), None).unwrap().0, "V {2}");+ assert_eq!(pick_product(&two, Some("altium designer"), None).unwrap().0, "D {1}", "the exact edition, not the first that contains it");+ assert_eq!(pick_product(&two, None, Some("Altium Designer Develop")).unwrap().0, "V {2}");+ assert!(pick_product(&two, None, None).is_err());+ assert_eq!(pick_product(&two[..1], None, None).unwrap().0, "D {1}");+ }++ #[test]+ fn an_extensions_ins_file() {+ let (n, d, v) = parse_ins("ClientInsFile 1.0\n\nServer\n EditorName = 'PcbDrawing'\n EditorDescription = 'Draftsman'\n Version = 'Version 1.0.0.0'\nEnd\n");+ assert_eq!((n.as_deref(), d.as_deref(), v.as_deref()), (Some("PcbDrawing"), Some("Draftsman"), Some("Version 1.0.0.0")));+ }+}
bridge-rs/src/routing.rs+184−2@@ -231,7 +231,7 @@ pub fn unrouted(st: &Value) -> (usize, Vec<Value>, Vec<Value>) { /// Convert the agent's compact dump into the mm-based state AI Flow reads. pub fn shape(d: &Value) -> Value { let tracks: Vec<Value> = arr(d, "tracks").iter().map(|t| json!({- "start": {"x": mm(&t[0]), "y": mm(&t[1])}, "end": {"x": mm(&t[2]), "y": mm(&t[3])},+ "id": track_id(t), "start": {"x": mm(&t[0]), "y": mm(&t[1])}, "end": {"x": mm(&t[2]), "y": mm(&t[3])}, "width": mm(&t[4]), "layer": layer_name(i(&t[5])), "layerId": t[5], "net": t[6]})).collect(); let arcs: Vec<Value> = arr(d, "arcs").iter().map(|a| json!({ "center": {"x": mm(&a[0]), "y": mm(&a[1])}, "radius": mm(&a[2]),@@ -285,6 +285,10 @@ pub fn shape(d: &Value) -> Value { /// altium_routing_state {expectPath?} pub fn routing_state(args: &Value) -> Value {+ // a board named by filePath is opened first: read as the current board only, naming another read the wrong one+ if let Some(b) = crate::support::s(args, "filePath").filter(|p| p.to_lowercase().ends_with(".pcbdoc")) {+ if let Some(e) = crate::support::must_open(&b, 60) { return e; }+ } let mut r = agent::call("routing_state", &[], None, Duration::from_secs(180)); let data = match r.get("data") { Some(d) if d.get("ok").and_then(|v| v.as_bool()) == Some(true) => d.clone(),@@ -345,7 +349,7 @@ fn err(code: &str, msg: String, hint: &str) -> Value { /// Read the live board and check the caller's guard: the right board and the revision it last /// read. A board changed behind the caller's back is refused, never edited blind. pub(crate) fn guarded(args: &Value) -> Result<Value, Value> {- let st = routing_state(&json!({"expectPath": args.get("expectPath").cloned().unwrap_or(Value::Null)}));+ let st = routing_state(&json!({"expectPath": args.get("expectPath").cloned().unwrap_or(Value::Null), "filePath": args.get("filePath").cloned().unwrap_or(Value::Null)})); if st.get("success").and_then(|v| v.as_bool()) != Some(true) { return Err(st); }@@ -580,6 +584,144 @@ pub fn remove_items(args: &Value) -> Value { apply(&ops, &st, "remove_items") } +/// A track's id: Altium gives tracks none, so it is a hash of what the track is, good until the track changes. Pure.+pub fn track_id(t: &Value) -> String { format!("track-{}", &fnv(&t.to_string())[..10]) }++/// The ops that change one track: delete it, draw it again with what `set` changes (mm, layer, ends). Pure.+pub fn edit_track_ops(t: &Value, set: &Value) -> Result<Vec<String>, String> {+ let n = |k: &str, a: &str| t[k][a].as_f64().map(raw).ok_or("the track has no ends");+ let (x1, y1, x2, y2) = (n("start", "x")?, n("start", "y")?, n("end", "x")?, n("end", "y")?);+ let layer = t["layerId"].as_i64().ok_or("the track has no layer")?;+ let m = set.as_object().ok_or("a track edit is an object: id, width, layer, start, end")?;+ let xy = |v: &Value| -> Option<(f64, f64)> { Some((v.get(0).or(v.get("x"))?.as_f64()?, v.get(1).or(v.get("y"))?.as_f64()?)) };+ let (mut nx1, mut ny1, mut nx2, mut ny2, mut w, mut l) = (x1, y1, x2, y2, raw(t["width"].as_f64().unwrap_or(0.0)), layer);+ for (k, v) in m {+ match k.as_str() {+ "width" => { let mm = v.as_f64().filter(|x| *x > 0.0).ok_or("width is mm, above 0")?; w = raw(mm); }+ "layer" => l = layer_id(v).ok_or(format!("unknown layer {v}"))?,+ "start" => { let (x, y) = xy(v).ok_or("start is [x, y] mm")?; nx1 = raw(x); ny1 = raw(y); }+ "end" => { let (x, y) = xy(v).ok_or("end is [x, y] mm")?; nx2 = raw(x); ny2 = raw(y); }+ "id" => {}+ o => return Err(format!("{o} is not a track property this verb changes: width, layer, start, end")),+ }+ }+ if !m.keys().any(|k| k != "id") { return Err("name something to change: width, layer, start or end".into()); }+ let net = t["net"].as_str().unwrap_or("");+ Ok(vec![format!("D|T|{x1}|{y1}|{x2}|{y2}|{layer}"), format!("T|{nx1}|{ny1}|{nx2}|{ny2}|{w}|{l}|{net}")])+}++/// What a track reads as for the reply: its ends, width, layer. Pure.+fn track_view(t: &Value) -> Value { json!({"start": [t["start"]["x"], t["start"]["y"]], "end": [t["end"]["x"], t["end"]["y"]], "width": t["width"], "layer": t["layer"]}) }++/// altium_edit_tracks {filePath?, tracks:[{id, width?, layer?, start?, end?}], dryRun?, expectedRevision?}+pub fn edit_tracks(args: &Value) -> Value {+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let all = st["tracks"].as_array().cloned().unwrap_or_default();+ let want = args.get("tracks").and_then(|v| v.as_array()).cloned().unwrap_or_default();+ if want.is_empty() { return err("bad_args", "tracks: [{id, width?, layer?, start?, end?}] is required".into(), "Read ids with altium_routing_state."); }+ let (mut ops, mut picked) = (Vec::new(), Vec::new());+ for (i, e) in want.iter().enumerate() {+ let id = e["id"].as_str().unwrap_or("");+ let Some(t) = all.iter().find(|t| t["id"].as_str() == Some(id)) else { return err("not_found", format!("tracks[{i}]: no track {id} on the board"), "Ids change when a track changes: read altium_routing_state again."); };+ match edit_track_ops(t, e) { Ok(o) => { let line = o[1].clone(); ops.extend(o); picked.push((t.clone(), line)); } Err(why) => return err("bad_args", format!("tracks[{i}]: {why}"), "") }+ }+ if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {+ return json!({"success": true, "dryRun": true, "mutated": false, "edits": want, "before": picked.iter().map(|(t, _)| track_view(t)).collect::<Vec<_>>(), "revision": st["revision"]});+ }+ let mut r = apply(&ops, &st, "edit_tracks");+ if r["success"] != json!(true) { return r; }+ // read each one back: the id it had, what it was, what the board now holds+ let after = r["state"]["tracks"].as_array().cloned().unwrap_or_default();+ let mut verified = true;+ let changes: Vec<Value> = picked.iter().map(|(t, line)| {+ let f: Vec<&str> = line.split('|').collect();+ let n = |i: usize| f.get(i).and_then(|v| v.parse::<i64>().ok()).unwrap_or(0);+ let hit = after.iter().find(|x| {+ let g = |k: &str, a: &str| raw(x[k][a].as_f64().unwrap_or(f64::MAX));+ (g("start", "x") - n(1)).abs() <= 1000 && (g("start", "y") - n(2)).abs() <= 1000 && (g("end", "x") - n(3)).abs() <= 1000 && (g("end", "y") - n(4)).abs() <= 1000+ && (raw(x["width"].as_f64().unwrap_or(0.0)) - n(5)).abs() <= 1000 && x["layerId"].as_i64() == Some(n(6))+ });+ if hit.is_none() { verified = false; }+ json!({"id": t["id"], "newId": hit.map(|h| h["id"].clone()), "before": track_view(t), "after": hit.map(track_view)})+ }).collect();+ r["changes"] = json!(changes);+ r["verified"] = json!(verified);+ r["success"] = json!(verified);+ r["edited"] = json!(want.len());+ r["_hint"] = json!("Each track is deleted and drawn again as one undo step, on its own net, so its id changes: newId is the new one. verified says every change read back. The board is unsaved: altium_save keeps it. A changed layer doesn't add the vias its ends now need: check with altium_routing_drc.");+ r+}++/// The agent's line for one part: ref|footprint|x|y|assigns, raw units. Pure.+pub fn place_op(p: &Value) -> Result<String, String> {+ let r = p["ref"].as_str().filter(|r| !r.is_empty()).ok_or("every part needs a ref")?;+ let f = p["footprint"].as_str().filter(|f| !f.is_empty()).ok_or(format!("{r}: footprint is required"))?;+ let (x, y) = (p["x"].as_f64().ok_or(format!("{r}: x is mm"))?, p["y"].as_f64().ok_or(format!("{r}: y is mm"))?);+ let nets = p.get("nets").and_then(|n| n.as_object()).map(|m| m.iter().map(|(k, v)| format!("{k}={}", v.as_str().unwrap_or(""))).collect::<Vec<_>>().join(";")).unwrap_or_default();+ Ok(format!("{r}|{f}|{}|{}|{nets}", raw(x), raw(y)))+}++/// The next free U number, for a part that names no ref. Pure.+pub fn next_ref(taken: &[String]) -> String {+ let mut n = 1;+ while taken.iter().any(|t| t.eq_ignore_ascii_case(&format!("U{n}"))) { n += 1; }+ format!("U{n}")+}++/// altium_place_parts {filePath?, libraryPath?, parts:[{library?, footprint, ref?, value?, x, y, rotation?, side?, nets?}], dryRun?, expectedRevision?}+pub fn place_parts(args: &Value) -> Value {+ let mut parts = args.get("parts").and_then(|v| v.as_array()).cloned().unwrap_or_default();+ if parts.is_empty() { return err("bad_args", "parts: [{library, footprint, ref?, value?, x, y, rotation?, side?, nets?}] is required".into(), ""); }+ let board = match crate::support::s(args, "filePath") {+ Some(b) => b,+ None => match crate::project::document_info(&json!({}))["path"].as_str().filter(|p| p.to_lowercase().ends_with(".pcbdoc")) { Some(p) => p.to_string(), None => return err("bad_args", "filePath (the .PcbDoc) is required: the current document is not a board".into(), "") },+ };+ if let Some(e) = crate::support::must_open(&board, 60) { return e; }+ let st = match guarded(args) { Ok(s) => s, Err(e) => return e };+ let top = crate::support::s(args, "libraryPath").or_else(|| crate::support::s(args, "library"));+ // refused before anything is placed: a ref the board has, a bad part, a part with no library+ let mut taken: Vec<String> = st["components"].as_array().cloned().unwrap_or_default().iter().filter_map(|c| c["ref"].as_str().map(str::to_string)).collect();+ let mut groups: Vec<(String, Vec<String>)> = Vec::new();+ for p in parts.iter_mut() {+ if p["ref"].as_str().unwrap_or("").is_empty() { p["ref"] = json!(next_ref(&taken)); }+ let r = p["ref"].as_str().unwrap_or("").to_string();+ let op = match place_op(p) { Ok(o) => o, Err(e) => return err("bad_args", e, "") };+ if taken.iter().any(|t| t.eq_ignore_ascii_case(&r)) { return err("ref_taken", format!("{r} is already on the board"), "move_parts moves it; edit_parts renames it."); }+ taken.push(r.clone());+ let Some(lib) = p["library"].as_str().map(str::to_string).or(top.clone()) else { return err("bad_args", format!("{r}: library (a .PcbLib) is required"), "") };+ match groups.iter_mut().find(|g| g.0 == lib) { Some(g) => g.1.push(op), None => groups.push((lib, vec![op])) }+ }+ if args.get("dryRun").and_then(|v| v.as_bool()) == Some(true) {+ return json!({"success": true, "dryRun": true, "mutated": false, "results": parts.iter().map(|_| "ok").collect::<Vec<_>>(), "placed": parts.iter().map(|p| json!({"ref": p["ref"], "x": p["x"], "y": p["y"], "rotation": p.get("rotation").cloned().unwrap_or(json!(0)), "side": p.get("side").cloned().unwrap_or(json!("top"))})).collect::<Vec<_>>(), "revision": st["revision"]});+ }+ let mut placed: Vec<String> = Vec::new();+ for (lib, ops) in &groups {+ if let Some(e) = crate::support::must_open(lib, 60) { return e; }+ let r = agent::call("place_parts", &[("board", crate::agent::win_path(&board))], Some(&ops.join("\n")), Duration::from_secs(300));+ let d = r.get("data").cloned().unwrap_or(Value::Null);+ if d["ok"] != json!(true) {+ let mut o = json!({"success": false, "errorCode": d.get("errorCode").cloned().unwrap_or(json!("place_failed")), "error": d.get("error").cloned().unwrap_or(json!("the parts were not placed")), "library": lib, "placedRefs": placed});+ if !placed.is_empty() { o["_hint"] = json!("placedRefs lists the parts from earlier libraries, which stay on the board unsaved."); }+ return o;+ }+ placed.extend(d["refs"].as_array().cloned().unwrap_or_default().iter().filter_map(|x| x.as_str().map(str::to_string)));+ }+ if let Some(e) = crate::support::must_open(&board, 60) { return e; }+ crate::project::mark_unsaved(&board);+ // rotation and side, exactly as move_parts sets and reads them back; value through edit_parts+ let moves: Vec<Value> = parts.iter().map(|p| { let mut m = json!({"ref": p["ref"], "x": p["x"], "y": p["y"], "rotation": p.get("rotation").cloned().unwrap_or(json!(0))}); if let Some(s) = p.get("side") { m["side"] = s.clone(); } m }).collect();+ let moved = move_parts(&json!({"parts": moves}));+ let values: Vec<Value> = parts.iter().filter(|p| p.get("value").is_some()).map(|p| json!({"ref": p["ref"], "value": p["value"]})).collect();+ let valued = if values.is_empty() { Value::Null } else { crate::verbs::dispatch("edit_parts", &json!({"edits": values}), &[]) };+ let after = routing_state(&json!({}));+ let read = |p: &Value| after["components"].as_array().and_then(|a| a.iter().find(|c| c["ref"] == p["ref"]).cloned());+ let results: Vec<Value> = parts.iter().map(|p| json!(if read(p).is_some() { "ok".to_string() } else { format!("err:{} is not on the board", p["ref"].as_str().unwrap_or("")) })).collect();+ let rows: Vec<Value> = parts.iter().filter_map(read).map(|c| json!({"ref": c["ref"], "footprint": c["pattern"], "x": c["x"], "y": c["y"], "rotation": c["rotation"], "side": c["side"]})).collect();+ let value_ok = valued.is_null() || valued.get("success").and_then(|b| b.as_bool()) == Some(true);+ json!({"success": moved["success"] == json!(true) && rows.len() == parts.len() && value_ok, "results": results, "placed": rows, "moved": moved.get("errorCode").map(|_| moved.clone()), "valueEdit": if value_ok { Value::Null } else { valued }, "revisionBefore": st["revision"], "revision": after["revision"], "unconnected": after["unconnected"], "countsBefore": st["counts"], "counts": after["counts"], "mutated": true,+ "_hint": "Each part is read back from the board, which is left unsaved: altium_save keeps it. On a board with a schematic, parts normally arrive through altium_update_pcb: a part placed here is on no sheet, and the next update_pcb lists it for removal. nets sets pads' nets by pad name; a net must already exist on the board."})+}+ /// altium_ripup_nets {nets:[...], expectedRevision?}: every free track, arc and via on each net. pub fn ripup_nets(args: &Value) -> Value { let st = match guarded(args) { Ok(s) => s, Err(e) => return e };@@ -1175,6 +1317,46 @@ pub fn set_design_rules(args: &Value) -> Value { "_hint": "Every rule of each kind now carries the fab's values (scopes kept). failed[] names any kind this Altium build refused; the rest landed."}) } +#[cfg(test)]+mod track_edit_tests {+ use super::*;++ #[test]+ fn a_track_edit_is_a_delete_and_a_redraw_on_its_net() {+ let t = json!({"start": {"x": 0.0, "y": 0.0}, "end": {"x": 10.0, "y": 0.0}, "width": 0.25, "layerId": 1, "layer": "F.Cu", "net": "GND"});+ let ops = edit_track_ops(&t, &json!({"width": 0.5})).unwrap();+ assert_eq!(ops[0], format!("D|T|0|0|{}|0|1", raw(10.0)));+ assert_eq!(ops[1], format!("T|0|0|{}|0|{}|1|GND", raw(10.0), raw(0.5)));+ let ops = edit_track_ops(&t, &json!({"id": "track-x", "layer": "B.Cu", "end": [5.0, 1.0]})).unwrap();+ assert_eq!(ops[1], format!("T|0|0|{}|{}|{}|{}|GND", raw(5.0), raw(1.0), raw(0.25), layer_id(&json!("B.Cu")).unwrap()));+ assert!(edit_track_ops(&t, &json!({"colour": "red"})).is_err());+ assert!(edit_track_ops(&t, &json!({"width": -1.0})).is_err());+ assert!(edit_track_ops(&t, &json!({"id": "track-x"})).is_err(), "nothing to change");+ }++ #[test]+ fn a_part_with_no_ref_takes_the_next_free_one() {+ assert_eq!(next_ref(&["R1".to_string()]), "U1");+ assert_eq!(next_ref(&["U1".to_string(), "u2".to_string(), "U4".to_string()]), "U3");+ }++ #[test]+ fn a_part_as_the_agents_line() {+ assert_eq!(place_op(&json!({"ref": "R1", "footprint": "R0603", "x": 1.0, "y": 2.0})).unwrap(), format!("R1|R0603|{}|{}|", raw(1.0), raw(2.0)));+ assert!(place_op(&json!({"ref": "R1", "footprint": "R0603", "x": 1.0, "y": 2.0, "nets": {"1": "GND"}})).unwrap().ends_with("|1=GND"));+ assert!(place_op(&json!({"footprint": "R0603", "x": 1.0, "y": 2.0})).is_err());+ assert!(place_op(&json!({"ref": "R1", "x": 1.0, "y": 2.0})).is_err());+ assert!(place_op(&json!({"ref": "R1", "footprint": "R0603"})).is_err());+ }++ #[test]+ fn a_track_id_follows_what_the_track_is() {+ let a = json!([0, 0, 100, 0, 10, 1, "A"]);+ assert_eq!(track_id(&a), track_id(&a.clone()));+ assert_ne!(track_id(&a), track_id(&json!([0, 0, 100, 0, 20, 1, "A"])));+ }+}+ #[cfg(test)] mod tests { use super::*;
bridge-rs/src/runs.rsadded+86@@ -0,0 +1,86 @@+//! cancel_run (EDA Bridge Standard #29, app tier): stop a long job the bridge started, between its steps. A process+//! running inside Altium cannot be interrupted from outside, so this covers the bridge's own multi-step verbs (sch_batch,+//! import_design's wizard): each one registers here and asks `cancelled()` between steps. Every request has its own+//! thread, so a cancel arrives while the job runs.+use serde_json::{json, Value};+use std::cell::Cell;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;++#[derive(Clone)]+struct Run { id: u64, verb: String, stage: String, cancel: bool, started: std::time::Instant }++static NEXT: AtomicU64 = AtomicU64::new(1);+static RUNS: Mutex<Vec<Run>> = Mutex::new(Vec::new());+thread_local! { static MINE: Cell<u64> = const { Cell::new(0) }; }++/// A running job; dropping it ends the run.+pub struct Guard(u64);+impl Drop for Guard {+ fn drop(&mut self) {+ if let Ok(mut r) = RUNS.lock() { r.retain(|x| x.id != self.0); }+ MINE.with(|m| m.set(0));+ }+}++pub fn begin(verb: &str) -> Guard {+ let id = NEXT.fetch_add(1, Ordering::SeqCst);+ if let Ok(mut r) = RUNS.lock() { r.push(Run { id, verb: verb.to_string(), stage: "started".into(), cancel: false, started: std::time::Instant::now() }); }+ MINE.with(|m| m.set(id));+ Guard(id)+}++/// Say where this thread's job has got to.+pub fn stage(what: &str) {+ let id = MINE.with(|m| m.get());+ if let Ok(mut r) = RUNS.lock() { if let Some(x) = r.iter_mut().find(|x| x.id == id) { x.stage = what.to_string(); } }+}++/// Has this thread's job been told to stop?+pub fn cancelled() -> bool {+ let id = MINE.with(|m| m.get());+ RUNS.lock().map(|r| r.iter().any(|x| x.id == id && x.cancel)).unwrap_or(false)+}++fn row(x: &Run) -> Value { json!({"runId": x.id.to_string(), "verb": x.verb, "stage": x.stage, "runningSec": x.started.elapsed().as_secs()}) }++/// altium_cancel_run {runId?}+pub fn cancel_run(args: &Value) -> Value {+ let Ok(mut r) = RUNS.lock() else { return json!({"success": false, "errorCode": "internal", "error": "the run list is locked"}) };+ let want = args.get("runId").map(|v| v.as_str().map(str::to_string).unwrap_or(v.to_string()));+ let running: Vec<Value> = r.iter().map(row).collect();+ let hit = match &want {+ Some(id) => r.iter_mut().find(|x| x.id.to_string() == *id),+ None => r.iter_mut().max_by_key(|x| x.id),+ };+ match hit {+ Some(x) => {+ x.cancel = true;+ json!({"success": true, "cancelRequested": true, "runId": x.id.to_string(), "verb": x.verb, "stage": x.stage, "running": running,+ "_hint": "The job stops at its next step and answers cancelled in its own reply, with what it took back. A step already inside Altium runs to its end."})+ }+ None => json!({"success": true, "cancelRequested": false, "runId": want, "running": running,+ "reason": if want.is_some() { "no run with that id is going" } else { "nothing the bridge can stop is running" },+ "_hint": "cancel_run stops the bridge's own multi-step verbs (sch_batch, import_design) between steps. A process inside Altium cannot be interrupted from outside: altium_agent_status says whether one is busy."}),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_run_is_told_to_stop_and_ends() {+ let g = begin("sch_batch");+ stage("op 1");+ assert!(!cancelled());+ let id = RUNS.lock().unwrap().iter().find(|x| x.verb == "sch_batch").unwrap().id.to_string();+ let r = cancel_run(&json!({"runId": id}));+ assert_eq!(r["cancelRequested"], true);+ assert_eq!(r["stage"], "op 1");+ assert!(cancelled());+ drop(g);+ assert!(!cancelled());+ assert_eq!(cancel_run(&json!({"runId": "999999"}))["cancelRequested"], false);+ }+}
bridge-rs/src/schbatch.rs+6−3@@ -7,7 +7,7 @@ use serde_json::{json, Value}; use std::time::Duration; /// The schematic verbs a batch may run: they each edit one sheet, named by `sheet`, and leave it unsaved.-pub const OPS: &[&str] = &["sch_place_part", "sch_connect_pins", "sch_connect", "sch_edit", "sch_edit_label", "sch_junction", "sch_bus",+pub const OPS: &[&str] = &["sch_place_part", "sch_connect_pins", "sch_connect", "sch_edit", "sch_edit_label", "sch_junction", "sch_no_connect", "sch_label", "sch_wire", "sch_bus", "sch_bus_entry", "sch_connect_to_bus", "sch_text", "sch_delete_wire", "sch_split_wire", "sch_move_region", "sch_reset_fields", "sch_update_from_library", "sch_swap_part", "sch_fix_connectivity", "annotate"]; @@ -98,8 +98,11 @@ pub fn sch_batch(args: &Value) -> Value { let erc_before = if erc { erc_counts(project.as_deref().unwrap_or(""), &sheet) } else { Value::Null }; let Some(before) = fingerprint(&sheet) else { return json!({"success": false, "errorCode": "sheet_unread", "error": "the sheet's items could not be read, so a failed batch could not be checked back: nothing was run"}) }; let mut results = Vec::new();+ let _run = crate::runs::begin("sch_batch"); for (i, (name, a)) in steps.iter().enumerate() {- let r = crate::verbs::dispatch(name, a, &[]);+ crate::runs::stage(&format!("op {i}: {name}"));+ let stop = crate::runs::cancelled();+ let r = if stop { json!({"success": false, "errorCode": "cancelled", "error": "cancelled by cancel_run"}) } else { crate::verbs::dispatch(name, a, &[]) }; if ok(&r) { results.push(json!({"op": name, "output": r})); continue; } // take the batch back: Undo once per op applied, then the sheet must be as it was let applied = i;@@ -108,7 +111,7 @@ pub fn sch_batch(args: &Value) -> Value { } let back = fingerprint(&sheet); let restored = back.as_deref() == Some(before.as_str());- let mut out = json!({"success": false, "errorCode": if restored { "op_failed" } else { "partial" }, "failedOp": i, "op": name,+ let mut out = json!({"success": false, "errorCode": if !restored { "partial" } else if stop { "cancelled" } else { "op_failed" }, "failedOp": i, "op": name, "error": r.get("error").cloned().unwrap_or(json!("the op failed")), "reply": r, "results": results, "mutated": !restored, "undone": applied, "restored": restored}); out["_hint"] = json!(if restored { "The batch was taken back: the sheet is as it was before it. Fix failedOp and run the batch again." }
bridge-rs/src/schwire.rs+172@@ -683,6 +683,163 @@ pub fn tees(sh: &Sheet, route: &[P]) -> Vec<P> { out } +/// A point on the sheet: [x, y] mm, or a pin's outer end ("U1.3").+fn point_or_pin(sh: &Sheet, v: &Value) -> Option<P> {+ if let Some(key) = v.as_str() { return pin_of(sh, key).map(|p| p.at); }+ pts_arg(v).map(|m| (sh.raw(m.0), sh.raw(m.1)))+}++/// Does a wire pass through the point, or a pin end sit on it? Then a marker or label there means something.+fn touches(sh: &Sheet, p: P) -> bool {+ let tol = sh.tol();+ sh.pins.iter().any(|q| same(q.at, p, tol)) || sh.items.iter().filter(|it| it.t == 'W').any(|w| segs(w).iter().any(|(a, b)| on_seg(p, *a, *b, tol).0))+}++/// The standard's `remove`: true with `id`, or with `at`/`points`/`pin`/`pins`; or a list of ids and points. Items of the kinds in `ts`.+fn removals(sh: &Sheet, ts: &[char], what: &str, args: &Value) -> Result<(Vec<String>, Vec<Value>), Value> {+ let tol = sh.tol();+ let mut wanted: Vec<Value> = args.get("remove").and_then(|v| v.as_array()).cloned().unwrap_or_default();+ if args.get("remove").and_then(|v| v.as_bool()) == Some(true) {+ if let Some(i) = args.get("id") { wanted.push(i.clone()); }+ wanted.extend(where_args(args));+ if wanted.is_empty() { return Err(bad(format!("remove needs the {what}'s id, or where it is"))); }+ }+ let (mut ops, mut ids) = (Vec::new(), Vec::new());+ for v in wanted {+ let hit = if let Some(id) = v.as_str().filter(|x| by_id(sh, x).is_some()) { by_id(sh, id).filter(|(_, it)| ts.contains(&it.t)).map(|(_, it)| it) }+ else { point_or_pin(sh, &v).and_then(|p| sh.items.iter().find(|it| ts.contains(&it.t) && (same(it.at, p, tol) || (it.t == 'P' && port_ends(it).iter().any(|e| same(*e, p, tol)))))) };+ match hit { Some(it) => { ops.push(format!("D|{}", it.key)); ids.push(json!(id_of(&it.key))); } None => return Err(json!({"success": false, "errorCode": "not_found", "error": format!("no {what} {v}: read ids with altium_sch_items")})) }+ }+ Ok((ops, ids))+}++/// The points and pins an edit names: at, points, pin, pins. Pure.+fn where_args(args: &Value) -> Vec<Value> {+ let mut out = Vec::new();+ if let Some(a) = args.get("at") { out.push(a.clone()); }+ if let Some(p) = args.get("points").and_then(|v| v.as_array()) { out.extend(p.iter().cloned()); }+ if let Some(a) = args.get("pin") { out.push(a.clone()); }+ if let Some(p) = args.get("pins").and_then(|v| v.as_array()) { out.extend(p.iter().cloned()); }+ out+}++/// altium_sch_no_connect {sheet, at | points | pin | pins, remove?, id?, dryRun, save}+pub fn no_connect(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let tol = sh.tol();+ let (mut ops, mut planned, mut skipped, mut on_nothing, mut bad_items) = (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());+ let removing = args.get("remove").and_then(|v| v.as_bool()) == Some(true);+ if !removing {+ for v in where_args(args) {+ let Some(p) = point_or_pin(&sh, &v) else { bad_items.push(json!({"item": v, "error": "not [x, y] mm, or that pin is not on this sheet"})); continue; };+ if sh.items.iter().any(|it| it.t == 'X' && same(it.at, p, tol)) { skipped.push(sh.pt(p)); continue; }+ if !touches(&sh, p) { on_nothing.push(sh.pt(p)); }+ ops.push(format!("X|{}|{}", p.0, p.1));+ planned.push(sh.pt(p));+ }+ }+ let (rem, removed) = match removals(&sh, &['X'], "no-connect marker", args) { Ok(x) => x, Err(e) => return e };+ ops.extend(rem);+ if planned.is_empty() && removed.is_empty() && skipped.is_empty() { return json!({"success": false, "errorCode": "bad_args", "error": "give at, points, pin or pins to flag; remove with id or a place", "failed": bad_items}); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "skipped": skipped, "onNothing": on_nothing, "failed": bad_items}); }+ if ops.is_empty() { return json!({"success": bad_items.is_empty(), "sheet": sheet, "added": [], "removed": [], "skipped": skipped, "onNothing": [], "failed": bad_items, "mutated": false}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res[..planned.len().min(res.len())]);+ let added: Vec<Value> = ids.iter().zip(planned.iter()).map(|(i, a)| json!({"id": i, "at": a})).collect();+ let mut fails = failed(&res);+ fails.extend(bad_items);+ json!({"success": fails.is_empty(), "sheet": sheet, "added": added, "removed": removed, "skipped": skipped, "onNothing": on_nothing, "failed": fails, "saved": maybe_save(args, &sheet),+ "_hint": "Altium's No ERC marker: ERC says nothing about a pin or wire end left open under one. onNothing lists markers placed where no pin end or wire is: they flag nothing."})+}++/// The op for one label, by its kind: local is Altium's net label, global its power port, hierarchical its port. Pure.+pub fn label_op(kind: &str, text: &str, p: P, rot: i64, just: &str) -> Result<String, String> {+ match kind {+ "local" => Ok(format!("N|{text}|{}|{}|{rot}|{just}", p.0, p.1)),+ "global" => Ok(format!("O|{text}|{}|{}|{rot}", p.0, p.1)),+ "hierarchical" => Ok(format!("P|{text}|{}|{}|{}", p.0, p.1, if rot == 2 { 1 } else { 0 })),+ o => Err(format!("kind is local, global or hierarchical (got {o})")),+ }+}++/// altium_sch_label {sheet, text | net, at, kind?, rotation?, justify?, remove?, id?, labels?: [...], dryRun, save}+pub fn label(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let removing = args.get("remove").and_then(|v| v.as_bool()) == Some(true);+ // one label at the top level, as the standard has it, or several in labels+ let mut list: Vec<Value> = args.get("labels").and_then(|v| v.as_array()).cloned().unwrap_or_default();+ if !removing && (args.get("text").is_some() || args.get("net").is_some()) { list.insert(0, args.clone()); }+ let (mut ops, mut planned, mut off_wire) = (Vec::new(), Vec::new(), Vec::new());+ for l in list {+ let Some(text) = l.get("text").or(l.get("net")).and_then(|v| v.as_str()).map(clean).filter(|t| !t.is_empty()) else { return bad("every label needs text (its net's name)") };+ let Some(p) = l.get("at").and_then(|v| point_or_pin(&sh, v)) else { return bad(format!("label {text}: at is [x, y] mm or a pin (U1.3) on this sheet")) };+ let rot = l.get("rotation").and_then(|v| v.as_i64()).unwrap_or(0).rem_euclid(360) / 90;+ let just = l.get("justify").and_then(|v| v.as_str()).map(|j| justification(j).to_string()).unwrap_or_default();+ let kind = l.get("kind").and_then(|v| v.as_str()).unwrap_or("local").to_ascii_lowercase();+ match label_op(&kind, &text, p, rot, &just) { Ok(op) => ops.push(op), Err(e) => return bad(e) }+ if !touches(&sh, p) { off_wire.push(json!({"text": text, "at": sh.pt(p)})); }+ planned.push(json!({"text": text, "kind": kind, "at": sh.pt(p), "rotation": rot * 90}));+ }+ // by text with at, as the standard allows, or by id or place+ let mut by_text = Vec::new();+ if removing && args.get("id").is_none() {+ if let (Some(t), Some(p)) = (args.get("text").and_then(|v| v.as_str()), args.get("at").and_then(|v| point_or_pin(&sh, v))) {+ let tol = sh.tol();+ match sh.items.iter().find(|it| matches!(it.t, 'N' | 'O' | 'P') && it.text == t && same(it.at, p, tol)) {+ Some(it) => by_text.push(it),+ None => return json!({"success": false, "errorCode": "not_found", "error": format!("no label {t} at that point")}),+ }+ }+ }+ let (rem, mut removed) = if by_text.is_empty() { match removals(&sh, &['N', 'O', 'P'], "label", args) { Ok(x) => x, Err(e) => return e } } else { (by_text.iter().map(|it| format!("D|{}", it.key)).collect(), by_text.iter().map(|it| json!(id_of(&it.key))).collect()) };+ ops.extend(rem);+ removed.dedup();+ if ops.is_empty() { return bad("give text and at to add a label, or remove with id"); }+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "add": planned, "removed": removed, "offWire": off_wire}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res[..planned.len().min(res.len())]);+ let added: Vec<Value> = planned.into_iter().zip(ids).map(|(mut a, id)| { a["id"] = id; a }).collect();+ let fails = failed(&res);+ json!({"success": fails.is_empty(), "sheet": sheet, "label": added.first().cloned(), "added": added, "removed": removed, "offWire": off_wire, "failed": fails, "saved": maybe_save(args, &sheet),+ "_hint": "local is Altium's net label, joining the same text on this sheet; global its power port, joining across sheets; hierarchical its port, joining through a sheet entry. offWire lists labels with no wire or pin end under them: they name nothing yet. sch_edit_label moves or renames net labels."})+}++/// altium_sch_wire {sheet, points | wires:[{points}], junctions?, dryRun, save}+pub fn wire(args: &Value) -> Value {+ let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };+ let lists: Vec<Value> = match args.get("wires").and_then(|v| v.as_array()) {+ Some(w) => w.iter().map(|x| x["points"].clone()).collect(),+ None => vec![args.get("points").cloned().unwrap_or(Value::Null)],+ };+ let (mut ops, mut routes, mut dots) = (Vec::new(), Vec::new(), Vec::<P>::new());+ let want_dots = args.get("junctions").and_then(|v| v.as_bool()).unwrap_or(true);+ for l in lists {+ let Some(a) = l.as_array() else { return bad("points: at least two [x, y] mm or pins (U1.3); wires: [{points}] for several") };+ let mut pts = Vec::new();+ for v in a { match point_or_pin(&sh, v) { Some(p) => pts.push(p), None => return bad(format!("{v} is not [x, y] mm or a pin on this sheet")) } }+ pts.dedup();+ if pts.len() < 2 { return bad("a wire needs at least two different points"); }+ if want_dots { dots.extend(tees(&sh, &pts)); }+ ops.push(format!("W|{}", raw_pts(&sh, &pts)));+ routes.push(pts);+ }+ dots.sort(); dots.dedup();+ let n = ops.len();+ ops.extend(dots.iter().map(|p| format!("J|{}|{}", p.0, p.1)));+ let plain: Vec<Value> = routes.iter().map(|r| json!(r.iter().map(|p| sh.pt(*p)).collect::<Vec<_>>())).collect();+ if dry(args) { return json!({"success": true, "dryRun": true, "sheet": sheet, "routes": plain, "junctionsAdded": dots.iter().map(|p| json!({"at": sh.pt(*p)})).collect::<Vec<_>>()}); }+ let res = match apply(args, &ops) { Ok(r) => r, Err(e) => return e };+ let ids = new_ids(&res[..n.min(res.len())]);+ // one row per segment, as the standard has it; an Altium wire is one polyline, so its segments share an id+ let mut rows = Vec::new();+ for (r, id) in routes.iter().zip(ids.iter()) { for w in r.windows(2) { rows.push(json!({"id": id, "from": sh.pt(w[0]), "to": sh.pt(w[1])})); } }+ let jids = new_ids(&res[n.min(res.len())..]);+ let added: Vec<Value> = dots.iter().zip(jids.iter()).map(|(p, id)| json!({"id": id, "at": sh.pt(*p)})).collect();+ let fails = failed(&res);+ json!({"success": fails.is_empty(), "sheet": sheet, "wires": rows, "junctionsAdded": added, "failed": fails, "saved": maybe_save(args, &sheet),+ "_hint": "One row per segment; an Altium wire is one polyline through exactly the points given, so a wire's segments share its id. It doesn't avoid bodies or other wires: a leg along another wire merges the nets. Check with altium_sch_pins or altium_compile."})+}+ /// altium_sch_connect_pins {sheet, pairs:[{from, to, first?, via?}], dryRun, save} pub fn connect_pins(args: &Value) -> Value { let (sheet, sh) = match load(args) { Ok(x) => x, Err(e) => return e };@@ -860,6 +1017,21 @@ pub fn fix_connectivity(args: &Value) -> Value { mod tests { use super::*; + #[test]+ fn a_labels_kind_picks_altiums_object() {+ assert_eq!(label_op("local", "SDA", (1, 2), 0, "").unwrap(), "N|SDA|1|2|0|");+ assert_eq!(label_op("global", "VBUS", (1, 2), 1, "").unwrap(), "O|VBUS|1|2|1");+ assert_eq!(label_op("hierarchical", "IO", (1, 2), 2, "").unwrap(), "P|IO|1|2|1", "turned 180, the port's far end is at the point");+ assert_eq!(label_op("hierarchical", "IO", (1, 2), 0, "").unwrap(), "P|IO|1|2|0");+ assert!(label_op("sideways", "X", (0, 0), 0, "").is_err());+ }++ #[test]+ fn the_places_an_edit_names() {+ let w = where_args(&json!({"at": [1, 2], "points": [[3, 4]], "pin": "U1.1", "pins": ["U1.2"]}));+ assert_eq!(w, vec![json!([1, 2]), json!([3, 4]), json!("U1.1"), json!("U1.2")]);+ }+ #[test] fn the_sheet_as_the_standards_drawing() { let k = 10_000_000.0; // raw units per inch: 1 mm = k / 25.4
bridge-rs/src/verbs.rs+59−4@@ -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", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "import_step", "edit_pours", "export_3d", "tool_update", "import_design", "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", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "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",+ "sch_no_connect", "sch_label", "sch_wire", "edit_tracks", "select_items", "preferences", "extensions", "cancel_run", "physical_properties", "model_check", "place_parts", "routing_state", "route_net", "plan_route", "move_parts", "place_decoupling", "plan_fanout", "estimate_cost", "simulate", "export_spice", "update_footprints_from_library", "lint_library", "export_pos", "verb_times", "prewarm", "render_board", "log_tail", "sch_batch", "import_step", "edit_pours", "export_3d", "tool_update", "import_design", "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", "export_ipc356", "export_dxf", "export_gencad", "import_svg", "edit_footprint", "generate_body", "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",@@ -186,9 +186,9 @@ fn describe() -> Value { &["The caller owns the VOICE (adom-tts) - the bridge never synthesizes speech.", "After done:true, restore the user's own document (altium_activate_document)."], json!({"live": true, "stage": 0})),- verb_doc("license", "Drive the License Management page (UIA first - no cursor, no foreground).", json!({"action": "show|refresh|use_license|start_trial|sign_out"}), shot.clone(), 60,- "One On-Demand seat serves EVERY Altium app on this machine. use_license claims a free seat.",- &["ensure_licensed", "license_status", "close"], &["NEVER kill an Altium holding the seat: the lease strands, the page shows Seats 0/1 while every claim fails. altium_close releases it."], json!({"action": "use_license"})),+ verb_doc("license", "Drive the License Management page (UIA first - no cursor, no foreground).", json!({"action": "show|refresh|use_license|release|start_trial|sign_out"}), shot.clone(), 60,+ "One On-Demand seat serves EVERY Altium app on this machine. use_license claims a free seat; release gives it back and released says the page confirms it. Altium then stops running scripts, so the bridge's verbs answer not_licensed until it is claimed again.",+ &["ensure_licensed", "license_status", "close"], &["NEVER kill an Altium holding the seat: the lease strands, the page shows Seats 0/1 while every claim fails. altium_close releases it.", "Altium Designer Develop has no licence page the bridge can reach: every action but show and refresh answers licence_page_not_open. altium_close releases its seat."], json!({"action": "use_license"})), verb_doc("close", "Polite close (releases the licence seat). Frees a script engine parked on a breakpoint first (Altium refuses to close over one). discardChanges:true answers Altium's save prompts with Save None for callers whose modified documents are ALL their own; force needs acceptSeatLoss.", json!({"discardChanges": "bool, default false: press Save None + confirm on 'Confirm Save Locally'", "waitSec": "float, default 20", "force": "bool", "acceptSeatLoss": "bool", "instance": "pid, when several Altiums run"}), json!({"closedInSec": "float", "engineFreed": "object|null", "stuckModalOrphan": "{pid,tid,hwnd} when Altium was wedged in a modal loop and the bridge ended it gracefully", "errorCode": "unsaved_changes | close_blocked_by_dialog | altium_modal_orphan | modal_orphan_survived_quit | close_timeout"}), 120, "A save prompt on close NAMES the documents - read it; on a shared machine one may belong to another AI thread. Never defaulted.", &["license", "launch"], &["force:true without acceptSeatLoss is refused: a kill strands the On-Demand seat.",@@ -457,6 +457,50 @@ fn describe() -> Value { json!({"current": "the installed version", "offered": "the newer release, or null", "newest": "the newest release on Altium's downloads page", "installs": "[{edition, version, major, exe, offered}]", "checked": "bool: the page answered", "noticeSeen": "bool: Altium raised its Update Available box since the bridge started", "applied": "bool", "whatToApprove": "string (apply)", "started": "the installer started (apply)", "unsaved": "[document] (apply)", "needsRestart": "bool", "auto": "bool", "settings": "[{edition, checkFrequency, auto}]"}), 150, "Updating Altium is the user's machine changing, so say so before apply with humanIsPresent.", &["install", "readiness", "license_status"], &["Altium's installer asks for a Windows approval that refuses itself after about two minutes with nobody there, so apply never starts it unasked; a refused prompt leaves a windowless AltiumInstaller.exe behind, which does nothing and can be ended.", "Altium writes its preferences back when it exits, so on is refused while Altium runs."], json!({"action": "check"})),+ verb_doc("sch_no_connect", "Flag points or pins left open on purpose with Altium's No ERC marker, or remove markers by id or point. One undo step. sch_connect kind noerc flags one pin; this flags any point and takes a flag away.",+ json!({"sheet": "path to the schematic sheet file (required)", "at": "[x, y] mm: a point", "points": "[[x, y]] mm: several points", "pin": "designator.pin, e.g. U1.12", "pins": "[designator.pin]", "id": "a marker's id from sch_items (with remove)", "remove": "bool, default false: remove the marker at id or at", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"added": "[{id, at}]", "removed": "[id]", "skipped": "[[x, y]]: already flagged", "onNothing": "[[x, y]]: flagged where no pin end or wire is", "failed": "[{item, error}]", "saved": "bool"}), 150,+ "Read ids with sch_items.", &["sch_items", "sch_connect", "run_erc"], &["A marker where no pin end or wire is flags nothing: onNothing lists those."], json!({"sheet": "C:/proj/Main.SchDoc", "pins": ["U1.7"], "at": [110.49, 60.96]})),+ verb_doc("sch_label", "Put net labels on existing wires at given points, or delete labels by id or point. One undo step. sch_connect labels a pin through a new stub; sch_edit_label changes labels that exist.",+ json!({"sheet": "path to the schematic sheet file (required)", "text": "the net name (required to add)", "at": "[x, y] mm: a point on the wire, or a pin (U1.3)", "kind": "local|global|hierarchical, default local: Altium's net label, power port or port", "rotation": "0|90|180|270, default 0", "justify": "optional (local)", "labels": "[{text, at, kind?, rotation?, justify?}]: several", "remove": "bool, default false: delete the label named by id, or by text with at", "id": "a label's id from sch_items (with remove)", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"label": "{id, text, kind, at, rotation} when added", "added": "[the same, one per label]", "removed": "[id]", "offWire": "[{text, at}]: labels with no wire or pin end under them", "saved": "bool"}), 150,+ "Labels with the same text join across the sheet. Check with altium_sch_pins or altium_compile.", &["sch_items", "sch_edit_label", "sch_connect", "sch_trace_point"], &["A label off any wire names nothing yet: offWire lists those."], json!({"sheet": "C:/proj/Main.SchDoc", "text": "SDA", "at": [110.49, 60.96]})),+ verb_doc("sch_wire", "Draw a wire through exactly the given points, with junctions where it makes a T. One undo step. sch_connect_pins routes pin to pin; this draws what it is told.",+ json!({"sheet": "path to the schematic sheet file (required)", "points": "[[x, y] mm or a pin (U1.3), ...]: two or more (required, or wires)", "wires": "[{points}]: several wires", "junctions": "bool, default true: add a junction where the wire ends on another wire", "dryRun": "bool, default false: answer the plan and change nothing", "save": "bool, default true: save the sheet after the edit"}),+ json!({"wires": "[{id, from, to}] one per segment; an Altium wire is one polyline, so its segments share an id", "junctionsAdded": "[{id, at}]", "saved": "bool"}), 150,+ "Each wire is one Altium polyline. Check the result with altium_sch_pins or altium_compile.", &["sch_connect_pins", "sch_delete_wire", "sch_split_wire", "sch_junction"], &["It does not avoid bodies or other wires: a leg along another wire merges the nets."], json!({"sheet": "C:/proj/Main.SchDoc", "points": ["U1.3", [120.0, 60.96], "R1.1"]})),+ verb_doc("edit_tracks", "Change given tracks: width, layer or ends, by the id routing_state gives each track (or its start, end and layer). One undo step, on the track's own net. set_track_width works by net or class.",+ json!({"filePath": "the board (default the current one)", "tracks": "[{id, width?, layer?, start?: [x, y], end?: [x, y]}] mm; id is the track's handle from routing_state (required)", "dryRun": "bool, default false: answer the plan and change nothing", "expectedRevision": "optional: refused with stale_board if the board changed"}),+ json!({"results": "[ok|err:...] per op", "changes": "[{id, newId, before, after}]", "verified": "bool: every change read back", "revision": "string", "state": "the board after"}), 300,+ "A track's id changes when the track does. The board is left unsaved: altium_save keeps it.", &["routing_state", "set_track_width", "routing_drc", "remove_items"], &["Moving an end can leave the track off its pad: check routing_state's unconnected or run routing_drc."], json!({"tracks": [{"id": "track-0a1b2c3d4e", "width": 0.5}]})),+ verb_doc("select_items", "Select parts by designator on the current board or sheet, everything else deselected, or clear the selection, and read it back. select_net selects a net; selection reads what the user selected.",+ json!({"refs": "[designator]", "clear": "bool: deselect every part", "where": "board (default) | sheet: refused if the current document is the other kind", "filePath": "the .PcbDoc or .SchDoc, opened first"}),+ json!({"selected": "[ref]", "failed": "[{ref, error}]", "verified": "bool: read back from Altium", "kind": "board | sheet", "document": "path"}), 60,+ "The selection is what Altium's own Selected commands act on.", &["selection", "select_net", "sch_zoom"], &["It selects parts: tracks and wires are select_net's and sch_trace_point's."], json!({"refs": ["U1", "R3"]})),+ verb_doc("preferences", "Read Altium's own preferences from where it keeps them, by section or key, or set existing ones with Altium closed.",+ json!({"edition": "Altium Designer | Altium Designer Develop (needed when both are here and neither runs)", "key": "dotted path of one setting (default all), or Server/Group/Name", "under": "one section, such as ExtensionManager.AutoUpdatePrefs", "set": "{key: value} (omit to read): existing preferences, with Altium closed", "dryRun": "bool (set): answer what they are now and change nothing"}),+ json!({"edition": "string", "current": "{key: value}", "count": "int", "sections": "[string]", "before": "{key: value} (set)", "applied": "{key: {ok, requested, read}} (set)", "failed": "[{key, error}]", "reason": "tool_running when a set is refused because Altium runs", "needsRestart": "bool"}), 60,+ "Altium reads its preferences when it starts. A set changes the user's Altium, so say so first.", &["tool_update", "readiness"], &["Altium writes its preferences back when it exits, so a set is refused while Altium runs.", "A set changes existing preferences only: an unknown key is refused."], json!({"key": "ExtensionManager/AutoUpdatePrefs/UpdatesCheckFrequency"})),+ verb_doc("extensions", "List Altium's own installed extensions by edition, with their versions. Installing and removing them is refused by name: Altium does that on its Extensions & Updates page, which the bridge cannot read or drive.",+ json!({"action": "list|install|remove, default list", "id": "the extension (install, remove)", "edition": "only this edition"}),+ json!({"extensions": "[{id, name, server, version, kind}]", "count": "int", "editions": "[{edition, count, extensions}]"}), 60,+ "Not install_extension: that is Adom's own AdomBridge extension.", &["install_extension", "tool_update"], &["install and remove answer not_supported: the user does them in Altium."], json!({"action": "list"})),+ verb_doc("cancel_run", "Stop a long job the bridge started, between its steps: sch_batch (it takes its ops back) and import_design's wizard (it closes with nothing imported). With nothing to stop it says so.",+ json!({"runId": "str (default the latest run in flight)"}),+ json!({"cancelRequested": "bool", "reason": "str (when false)", "runId": "str", "stage": "str at the time of the request", "verb": "str", "running": "[{runId, verb, stage, runningSec}]"}), 15,+ "The job answers errorCode cancelled in its own reply.", &["sch_batch", "import_design", "agent_status", "agent_recover"], &["A process inside Altium can't be interrupted from outside: a step already in Altium runs to its end, and once the wizard's import is running it finishes too."], json!({})),+ verb_doc("physical_properties", "Mass, volume and centre of mass per part. Altium keeps no material or mass on a part, so this is refused with that reason.",+ json!({"names": "[part]", "accuracy": "string"}),+ json!({"success": "false", "errorCode": "not_supported"}), 15,+ "bodies gives each part's 3D box and height; layer_stack gives the board's thickness.", &["bodies", "layer_stack", "height_check"], &["Altium's 3D bodies hold shape only."], json!({})),+ verb_doc("place_parts", "Put footprints from a library on the current board at given positions, rotations and sides, each read back. Designators already on the board are refused before anything is placed. place_on_pcb and test_board make or add to a test board with no position.",+ json!({"filePath": "the board (default the current one)", "libraryPath": "the .PcbLib, when every part comes from one", "parts": "[{library, footprint, ref?, value?, x, y, rotation?: 0, side?: top|bottom, nets?: {pad: net}}] mm and degrees (required)", "dryRun": "bool, default false: answer the plan and change nothing", "expectedRevision": "optional: refused with stale_board if the board changed"}),+ json!({"results": "[ok|err:...] per part", "placed": "[{ref, footprint, x, y, rotation, side}]", "revision": "string", "unconnected": "int", "counts": "{...}"}), 600,+ "On a board with a schematic, parts normally arrive through update_pcb. The board is left unsaved: altium_save keeps it.", &["move_parts", "edit_parts", "remove_parts", "update_pcb", "routing_state"], &["A net in nets must already exist on the board.", "A footprint missing from the library places nothing from that library."], json!({"filePath": "C:/proj/Board.PcbDoc", "parts": [{"library": "C:/proj/Parts.PcbLib", "ref": "R9", "footprint": "R0603", "x": 12.0, "y": 8.0, "rotation": 90}]})),+ verb_doc("model_check", "Per part of a board or footprint of a library: does it have a 3D model, where the model is, whether its source file is still found, and whether it holds any geometry. Whether a body sits in the right place is bodies'.",+ json!({"filePath": "a board: every part on it", "library": "a footprint library (with footprint)", "footprint": "one footprint's name", "refs": "[ref] (default all)", "limit": "int, default 50: parts reported"}),+ json!({"parts": "[{name, footprint, models: [{path, location, found, hasGeometry, kind: model|extruded, sourceFileFound, heightMm}], issues: [string]}]", "checked": "int", "ok": "bool: every part has a model that is found and holds geometry", "noModel": "[name]", "noGeometry": "[name]", "sourceFileMissing": "[name]", "kind": "board | library"}), 180,+ "Read only. Altium keeps the model inside the document, so a model still draws after its source file has gone.", &["bodies", "lint_library", "add_body", "height_check"], &["sourceFileFound looks on this machine, at the name the model was loaded from."], json!({"filePath": "C:/proj/Board.PcbDoc"})), verb_doc("import_design", "Bring a foreign design into a new Altium project: eagle through Altium's Import Wizard (the schematic and its board together), kicad through Altium's KiCad importer. A format the bridge does not drive yet is refused by name.", json!({"format": "eagle | kicad (required)", "filePath": "the design: an EAGLE .sch or .brd (its pair beside it comes too), or a KiCad file (required)", "boardPath": "the EAGLE board, when its name differs from the schematic's", "name": "rename the new project", "outputDir": "the folder the new project goes in, default the source's folder", "timeout": "seconds (kicad), default 300"}), json!({"design": "the new .PrjPcb", "project": "the same", "parts": "int", "nets": "int", "warnings": "[what the importer's log says it could not read]", "check": "{imported, source, matchesSource, unconnected}: the board against the EAGLE file", "files": "[the files imported]", "steps": "[every wizard step and how it went]", "agentRestarted": "bool"}), 900,@@ -2151,6 +2195,17 @@ pub fn dispatch(command: &str, args: &Value, _forwarded: &[(String, String)]) -> "sch_pins" => crate::schwire::pins(args), "sch_trace_point" => crate::schwire::trace_point(args), "sch_junction" => crate::schwire::junction(args),+ "sch_no_connect" => crate::schwire::no_connect(args),+ "sch_label" => crate::schwire::label(args),+ "sch_wire" => crate::schwire::wire(args),+ "edit_tracks" => { if let Some(g) = need_licensed() { return g; } crate::routing::edit_tracks(args) }+ "select_items" => crate::design::select_items(args),+ "preferences" => crate::prefs::preferences(args),+ "place_parts" => { if let Some(g) = need_licensed() { return g; } crate::routing::place_parts(args) }+ "model_check" => crate::prefs::model_check(args),+ "extensions" => crate::prefs::extensions(args),+ "cancel_run" => crate::runs::cancel_run(args),+ "physical_properties" => json!({"success": false, "errorCode": "not_supported", "error": "Altium keeps no material or mass on a part: its 3D bodies hold shape only, so there is nothing to compute mass from", "_hint": "altium_bodies gives each part's 3D box and height; altium_layer_stack the board's thickness."}), "sch_bus" => crate::schwire::bus(args), "sch_bus_entry" => crate::schwire::bus_entry(args), "sch_split_wire" => crate::schwire::split_wire(args),
dev-skills/altium-bridge-test/edit_drill.pyadded+497@@ -0,0 +1,497 @@+#!/usr/bin/env python3+"""Run altium-bridge's edit verbs for real, and confirm each with a separate read.++The verb battery only dry-runs these, or accepts a named refusal, because it shares one board and sheet between all its+verbs. A dry run can't catch a verb that plans correctly and then changes nothing, so this drill builds its own board+and sheet and runs each edit for real. A step passes only when a second verb reads the change back.++ python3 edit_drill.py --target DESKTOP-BAR6S0F --thread altium-lane [--only a,b] [--json out.json]++Scratch only: everything lives in <Documents>/Adom/altium-bridge-drill on the target, emptied at the start.+"""+import argparse+import json+import os+import subprocess+import sys+import time++HERE = os.path.dirname(os.path.abspath(__file__))+ROWS = []+++def main():+ ap = argparse.ArgumentParser()+ ap.add_argument("--target", required=True)+ ap.add_argument("--thread", default="altium-lane")+ ap.add_argument("--only", default="")+ ap.add_argument("--json", default="")+ ap.add_argument("--install", default="develop")+ a = ap.parse_args()+ only = [x for x in a.only.split(",") if x]++ def call(verb, args=None, timeout=300):+ args = dict(args or {})+ args.setdefault("reason", "altium-bridge edit drill, on scratch copies")+ p = subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "altium_" + verb, json.dumps(args)], capture_output=True, text=True, timeout=timeout)+ try:+ d = json.loads(p.stdout)+ except ValueError:+ return {"success": False, "error": (p.stdout or p.stderr)[:400]}+ o = d.get("output")+ if isinstance(o, str) and o.startswith("{"):+ try:+ return json.loads(o)+ except ValueError:+ pass+ return d++ def shell(cmd):+ p = subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "shell_execute", json.dumps({"command": cmd, "reason": "altium-bridge edit drill scratch folder"})], capture_output=True, text=True, timeout=120)+ d = json.loads(p.stdout)+ o = d.get("output")+ if isinstance(o, str) and o.startswith("{"):+ d = json.loads(o)+ return d.get("stdout") or ""++ def step(verb, fn):+ if only and verb not in only:+ return+ t0 = time.time()+ try:+ good, detail = fn()+ except Exception as e: # a read that came back in another shape is a failure of this step, not of the drill+ good, detail = False, f"{type(e).__name__}: {e}"+ ROWS.append(dict(verb=verb, ok=bool(good), detail=str(detail)[:400], sec=round(time.time() - t0, 1)))+ print(("PASS " if good else "FAIL ") + verb + ": " + str(detail)[:300], flush=True)++ home = shell('powershell -NoProfile -Command "[Environment]::GetFolderPath(\'UserProfile\')"').strip().replace("\\", "/")+ D = home + "/Documents/Adom/altium-bridge-drill"+ dw = D.replace("/", "\\")+ fx = [os.path.join(HERE, "fixtures", n) for n in ("Adom_Test.SchLib", "Adom_Test.PcbLib")]+ call("close_all_documents", {"save": True})+ shell(f'cmd /c rmdir /S /Q "{dw}" 2>nul & mkdir "{dw}"')+ subprocess.run(["adom-bridge", "--ai-thread", a.thread, "--target", a.target, "send_files", json.dumps({"filePaths": fx, "dest": D, "destIsFolder": True, "reason": "edit drill libraries"})], capture_output=True, text=True, timeout=300)+ SL, PL = D + "/Adom_Test.SchLib", D + "/Adom_Test.PcbLib"+ B, S, P = D + "/drill.PcbDoc", D + "/drill.SchDoc", D + "/drill.PrjPcb"+ call("launch", {"install": a.install})+ nets = {"N1": ["U1.8", "U2.1"], "N2": ["U2.8", "U3.1"], "GND": ["U1.4", "U2.5", "U3.5"]}+ parts = [{"ref": f"U{i}", "footprint": "TST_SOIC8", "x": 10 + 20 * (i - 1), "y": 20, "rotation": 0} for i in (1, 2, 3)]+ r = call("build_board", {"pcbPath": B, "libraryPath": PL, "outline": {"rect": [0, 0, 70, 40]}, "parts": parts, "nets": nets})+ if r.get("placed") != 3:+ sys.exit(f"build_board did not make the drill board: {json.dumps(r)[:400]}")+ r = call("build_schematic", {"schPath": S, "libraryPath": SL, "pcbLibPath": PL, "pcbPath": B, "projectPath": P, "title": "edit drill",+ "parts": [{"ref": f"U{i}", "symbol": "TST_SOIC8", "block": "core", "footprint": "TST_SOIC8"} for i in (1, 2, 3)], "nets": nets}, timeout=600)+ if not r.get("success"):+ sys.exit(f"build_schematic did not make the drill sheet: {json.dumps(r)[:400]}")++ # -- reads ----------------------------------------------------------------------------------------------------+ items = lambda: call("sch_items", {"sheet": S})+ n = lambda key: len(items().get(key) or [])+ state = lambda: call("routing_state", {"filePath": B})+ comps = lambda: {c["ref"]: c for c in state().get("components") or []}+ # a free corner of the sheet, each step on its own row+ Y = {"y": 170.0}+ def row():+ Y["y"] -= 5.08+ return Y["y"]++ # -- schematic ------------------------------------------------------------------------------------------------+ def sch_wire():+ y = row(); w0 = n("wires")+ r = call("sch_wire", {"sheet": S, "points": [[20.32, y], [40.64, y]]})+ return r.get("success") and n("wires") == w0 + 1, f"wires {w0} -> {w0 + 1}: {r.get('error') or 'read back'}"+ step("sch_wire", sch_wire)++ def sch_connect_pins():+ w0 = n("wires")+ r = call("sch_connect_pins", {"sheet": S, "pairs": [{"from": "U1.2", "to": "U1.3"}]})+ pins = call("sch_pins", {"sheet": S, "references": ["U1"]}).get("pins") or []+ pin2 = next((p for p in pins if str(p.get("pin") or p.get("number")) == "2"), {})+ return r.get("success") and n("wires") > w0 and "U1.3" in json.dumps(pin2), f"U1.2 reads {json.dumps(pin2)[:160]}"+ step("sch_connect_pins", sch_connect_pins)++ def sch_bus():+ b0, y = n("buses"), row()+ Y["bus"] = y+ r = call("sch_bus", {"sheet": S, "points": [[50.8, y], [101.6, y]], "label": "D[0..2]"})+ return r.get("success") and n("buses") == b0 + 1, f"buses {b0} -> {n('buses')}: {r.get('error')}"+ step("sch_bus", sch_bus)++ def sch_bus_entry():+ e0 = n("busEntries")+ r = call("sch_bus_entry", {"sheet": S, "entries": [{"at": [60.96, Y["bus"] - 2.54], "direction": "up-right"}]})+ return r.get("success") and n("busEntries") == e0 + 1, f"entries {e0} -> {n('busEntries')}: {r.get('error')}"+ step("sch_bus_entry", sch_bus_entry)++ def sch_connect_to_bus():+ pins = {str(p.get("number")): p["at"] for p in call("sch_pins", {"sheet": S, "references": ["U3"]}).get("pins") or []}+ x = pins["2"][0] - 10.16+ b = call("sch_bus", {"sheet": S, "points": [[x, pins["3"][1] - 7.62], [x, pins["2"][1] + 7.62]]})+ e0, w0 = n("busEntries"), n("wires")+ r = call("sch_connect_to_bus", {"sheet": S, "bus": (b.get("ids") or [""])[0], "pins": ["U3.2", "U3.3"], "prefix": "D", "start": 0})+ return r.get("success") and n("busEntries") == e0 + 2 and n("wires") >= w0 + 2, f"entries {e0} -> {n('busEntries')}, wires {w0} -> {n('wires')}: {r.get('error')}"+ step("sch_connect_to_bus", sch_connect_to_bus)++ def wire_at():+ y = row()+ call("sch_wire", {"sheet": S, "points": [[20.32, y], [40.64, y]]})+ return y++ def sch_junction():+ y = wire_at(); j0 = n("junctions")+ r = call("sch_junction", {"sheet": S, "points": [[30.48, y]]})+ up = n("junctions")+ i = (r.get("added") or [{}])[0].get("id")+ r2 = call("sch_junction", {"sheet": S, "remove": [i]})+ return r.get("success") and up == j0 + 1 and r2.get("success") and n("junctions") == j0, f"junctions {j0} -> {up} -> {n('junctions')}"+ step("sch_junction", sch_junction)++ def sch_split_wire():+ y = wire_at(); w0 = n("wires")+ r = call("sch_split_wire", {"sheet": S, "at": [30.48, y]})+ return r.get("success") and n("wires") == w0 + 1, f"wires {w0} -> {n('wires')}: {r.get('error')}"+ step("sch_split_wire", sch_split_wire)++ def sch_delete_wire():+ y = wire_at(); w0 = n("wires")+ r = call("sch_delete_wire", {"sheet": S, "at": [30.48, y]})+ return r.get("success") and n("wires") == w0 - 1, f"wires {w0} -> {n('wires')}: {r.get('error')}"+ step("sch_delete_wire", sch_delete_wire)++ def sch_edit_label():+ y = wire_at()+ a0 = call("sch_label", {"sheet": S, "text": "DRILL_A", "at": [30.48, y]})+ i = (a0.get("label") or {}).get("id")+ r = call("sch_edit_label", {"sheet": S, "edits": [{"id": i, "rename": "DRILL_B"}]})+ texts = [x.get("text") for x in items().get("labels") or []]+ return r.get("success") and "DRILL_B" in texts and "DRILL_A" not in texts, f"labels read {texts[-3:]}: {r.get('error')}"+ step("sch_edit_label", sch_edit_label)++ def sch_label():+ y = wire_at()+ r = call("sch_label", {"sheet": S, "text": "DRILL_L", "at": [30.48, y]})+ i = (r.get("label") or {}).get("id")+ here = i in [x.get("id") for x in items().get("labels") or []]+ r2 = call("sch_label", {"sheet": S, "remove": True, "id": i})+ gone = i not in [x.get("id") for x in items().get("labels") or []]+ # global is Altium's power port, hierarchical its port: each its own object, read back and taken away by text and place+ y2 = wire_at()+ g = call("sch_label", {"sheet": S, "text": "DRILL_G", "at": [30.48, y2], "kind": "global"})+ gnet = any(x.get("net") == "DRILL_G" for x in items().get("powerPorts") or [])+ call("sch_label", {"sheet": S, "remove": True, "text": "DRILL_G", "at": [30.48, y2]})+ ggone = not any(x.get("net") == "DRILL_G" for x in items().get("powerPorts") or [])+ h = call("sch_label", {"sheet": S, "text": "DRILL_H", "at": [40.64, y2], "kind": "hierarchical"})+ hport = any(x.get("text") == "DRILL_H" and x.get("kind") == "hierarchical" for x in items().get("labels") or [])+ return r.get("success") and here and r2.get("success") and gone and not r.get("offWire") and g.get("success") and gnet and ggone and h.get("success") and hport, f"local added {here}, removed {gone}; global {gnet}, removed {ggone}; hierarchical {hport}"+ step("sch_label", sch_label)++ def sch_no_connect():+ y = wire_at()+ r = call("sch_no_connect", {"sheet": S, "points": [[20.32, y]]})+ i = (r.get("added") or [{}])[0].get("id")+ here = i in [x.get("id") for x in items().get("noConnects") or []]+ r2 = call("sch_no_connect", {"sheet": S, "remove": True, "id": i})+ gone = i not in [x.get("id") for x in items().get("noConnects") or []]+ return r.get("success") and here and r2.get("success") and gone, f"added {here}, removed {gone}"+ step("sch_no_connect", sch_no_connect)++ def sch_move_region():+ y = wire_at()+ call("sch_label", {"sheet": S, "text": "DRILL_M", "at": [30.48, y]})+ r = call("sch_move_region", {"sheet": S, "box": [29, y - 1, 32, y + 1], "by": [2.54, 0]})+ lab = next((x for x in items().get("labels") or [] if x.get("text") == "DRILL_M"), {})+ return r.get("success") and abs((lab.get("at") or [0])[0] - 33.02) < 0.01, f"DRILL_M at {lab.get('at')}: {r.get('error')}"+ step("sch_move_region", sch_move_region)++ def sch_edit():+ before = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U3"]+ x0 = before[0]["xMil"]+ r = call("sch_edit", {"sheet": S, "edits": [{"designator": "U3", "action": "move", "x": x0 + 100, "y": before[0]["yMil"]}]})+ after = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U3"]+ return r.get("success") and abs(after[0]["xMil"] - (x0 + 100)) < 2, f"U3 x {x0} -> {after[0]['xMil']}: {r.get('error')}"+ step("sch_edit", sch_edit)++ def sch_place_part():+ c0 = len((call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []))+ r = call("sch_place_part", {"sheet": S, "library": SL, "symbol": "TST_SOIC8", "designator": "U9", "x": 8000, "y": 2000})+ got = (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", [])+ return r.get("success") and len(got) == c0 + 1 and any(c.get("designator") == "U9" for c in got), f"parts {c0} -> {len(got)}: {r.get('error')}"+ step("sch_place_part", sch_place_part)++ def sch_swap_part():+ r = call("sch_swap_part", {"sheet": S, "designator": "U9", "library": SL, "symbol": "TST_QFN24"})+ got = [c for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U9"]+ return r.get("success") and got and got[0].get("libReference") == "TST_QFN24", f"U9 is {got and got[0].get('libReference')}: {r.get('error')}"+ step("sch_swap_part", sch_swap_part)++ def sch_reset_fields():+ r = call("sch_reset_fields", {"sheet": S, "all": True})+ return r.get("success"), f"reply {json.dumps({k: r.get(k) for k in ('reset', 'moved', 'unchanged', 'error')})[:200]} (no separate read: the fields have no verb of their own)"+ step("sch_reset_fields", sch_reset_fields)++ def sch_update_from_library():+ # change the library's symbol, then the placed parts must take it+ params = lambda: json.dumps([c.get("params") for c in (call("schematic_data", {"filePath": S}).get("data") or {}).get("components", []) if c.get("designator") == "U1"])+ before = params()+ call("set_params", {"libraryPath": SL, "symbolName": "TST_SOIC8", "params": {"DrillParam": "drilled"}})+ call("save", {"filePath": SL})+ r = call("sch_update_from_library", {"sheet": S})+ after = params()+ return r.get("success") and "drilled" not in before and "drilled" in after, f"U1 params {after[:160]}: updated {r.get('updated')} {r.get('error')}"+ step("sch_update_from_library", sch_update_from_library)++ def cancel_run():+ # a long batch, stopped from another thread: it has to answer cancelled and leave the sheet as it was+ import threading+ y = row()+ w0 = n("wires")+ ops = [{"op": "sch_wire", "points": [[20.32 + i * 2.54, y], [20.32 + i * 2.54, y - 2.54]]} for i in range(30)]+ box = {}+ t = threading.Thread(target=lambda: box.update(call("sch_batch", {"filePath": S, "ops": ops, "erc": False}, timeout=500)))+ t.start()+ got = {}+ for _ in range(60):+ time.sleep(1)+ got = call("cancel_run", {})+ if got.get("cancelRequested"):+ break+ t.join()+ return got.get("cancelRequested") and box.get("errorCode") == "cancelled" and box.get("restored") is True and n("wires") == w0, f"asked at stage {got.get('stage')}; batch answered {box.get('errorCode')}, undone {box.get('undone')}, restored {box.get('restored')}, wires {w0} -> {n('wires')}"+ step("cancel_run", cancel_run)++ # -- board ----------------------------------------------------------------------------------------------------+ def route_net():+ r = call("route_net", {"filePath": B, "net": "N1", "width": 0.254, "paths": [[{"pad": "U1.8"}, {"pad": "U2.1"}]]})+ t = [x for x in state().get("tracks") or [] if x["net"] == "N1"]+ return r.get("success") and len(t) >= 1, f"N1 tracks {len(t)}: {r.get('error')}"+ step("route_net", route_net)++ def place_parts():+ r = call("place_parts", {"filePath": B, "parts": [{"library": PL, "ref": "U9", "footprint": "TST_QFN24", "value": "DRILLQ", "x": 60, "y": 32, "rotation": 90, "side": "bottom", "nets": {"25": "GND"}}]})+ c = comps().get("U9") or {}+ pad = [p for p in state().get("pads") or [] if p["ref"] == "U9" and p["name"] == "25"]+ if not pad or pad[0].get("net") != "GND":+ return False, f"U9.25 reads {pad and pad[0].get('net')}: nets did not land"+ return r.get("success") and abs(c.get("x", 0) - 60) < 0.01 and abs(c.get("y", 0) - 32) < 0.01 and abs(c.get("rotation", 0) - 90) < 0.01 and c.get("side") == "bottom", f"U9 reads {json.dumps({k: c.get(k) for k in ('x', 'y', 'rotation', 'side')})}: {r.get('error')}"+ step("place_parts", place_parts)++ def edit_tracks():+ t = state()["tracks"][0]+ r = call("edit_tracks", {"tracks": [{"id": t["id"], "width": t["width"] + 0.1}]})+ hit = [x for x in state()["tracks"] if x["start"] == t["start"] and x["end"] == t["end"]]+ return r.get("success") and hit and abs(hit[0]["width"] - t["width"] - 0.1) < 0.001, f"width {t['width']} -> {hit and hit[0]['width']}: {r.get('error')}"+ step("edit_tracks", edit_tracks)++ def set_track_width():+ r = call("set_track_width", {"filePath": B, "nets": ["N1"], "widthMm": 0.4})+ ws = {x["width"] for x in state()["tracks"] if x["net"] == "N1"}+ # back to the default rule's own width (exactly 10 mil), so the copy below adds no DRC error+ call("set_track_width", {"filePath": B, "nets": ["N1"], "widthMm": 0.254})+ return r.get("success") and ws == {0.4}, f"N1 widths {ws}: {r.get('error')}"+ step("set_track_width", set_track_width)++ def copy_routing():+ t0 = len(state()["tracks"])+ r = call("copy_routing", {"filePath": B, "box": [0, 10, 40, 30], "offset": [0, 15], "keepUnmappedNets": True})+ t1 = len(state()["tracks"])+ return r.get("success") and t1 > t0, f"tracks {t0} -> {t1}: {r.get('error')}"+ step("copy_routing", copy_routing)++ def length_tune():+ l0 = call("net_lengths", {"filePath": B, "nets": ["N1"]})+ r = call("length_tune", {"filePath": B, "net": "N1", "targetMm": l0["nets"][0]["lengthMm"] + 1.9})+ l1 = call("net_lengths", {"filePath": B, "nets": ["N1"]})+ return r.get("success") and json.dumps(l0.get("nets")) != json.dumps(l1.get("nets")), f"before {json.dumps(l0.get('nets'))[:90]}, after {json.dumps(l1.get('nets'))[:90]}: {r.get('error') or r.get('errorCode')}"+ step("length_tune", length_tune)++ def edit_parts():+ r = call("edit_parts", {"filePath": B, "edits": [{"ref": "U3", "value": "DRILLV"}]})+ d = call("component_data", {"designator": "U3", "filePath": B})+ return r.get("success") and "DRILLV" in json.dumps(d), f"U3 reads value in {json.dumps(d)[:200]}: {r.get('error')}"+ step("edit_parts", edit_parts)++ def align_parts():+ call("move_parts", {"parts": [{"ref": "U2", "x": 30, "y": 24}], "filePath": B})+ r = call("align_parts", {"filePath": B, "refs": ["U2", "U3"], "mode": "top"})+ c = comps()+ return r.get("success") and abs(c["U2"]["y"] - c["U3"]["y"]) < 0.01, f"U2 y {c['U2']['y']}, U3 y {c['U3']['y']}: {r.get('error')}"+ step("align_parts", align_parts)++ def via_fence():+ v0 = len(state()["vias"])+ r = call("via_fence", {"filePath": B, "nets": ["N1"], "viaNet": "GND", "pitchMm": 3, "edge": True})+ v1 = len(state()["vias"])+ return r.get("success") and v1 > v0, f"vias {v0} -> {v1}: {r.get('error')}"+ step("via_fence", via_fence)++ def place_vias():+ v0 = len(state()["vias"])+ r = call("place_vias", {"vias": [{"net": "GND", "x": 65, "y": 5, "size": 0.6, "drill": 0.3}]})+ v1 = len(state()["vias"])+ return r.get("success") and v1 == v0 + 1, f"vias {v0} -> {v1}: {r.get('error')}"+ step("place_vias", place_vias)++ def thermal_vias():+ call("move_parts", {"parts": [{"ref": "U9", "x": 60, "y": 32, "side": "top"}], "filePath": B})+ v0 = len(state()["vias"])+ r = call("thermal_vias", {"filePath": B, "ref": "U9"})+ v1 = len(state()["vias"])+ return r.get("success") and v1 > v0, f"vias {v0} -> {v1}: {r.get('error') or r.get('errorCode')}"+ step("thermal_vias", thermal_vias)++ def remove_parts():+ r = call("remove_parts", {"filePath": B, "refs": ["U9"]})+ return r.get("success") and "U9" not in comps(), f"U9 gone: {'U9' not in comps()}: {r.get('error')}"+ step("remove_parts", remove_parts)++ def set_layer_count():+ r = call("set_layer_count", {"filePath": B, "count": 4}, timeout=400)+ d = call("layer_stack", {"filePath": B})+ n_cu = (d.get("data") or d).get("copperLayers")+ return r.get("success") and n_cu == 4, f"copper layers {n_cu}: {r.get('error')}"+ step("set_layer_count", set_layer_count)++ def set_outline():+ r = call("set_outline", {"filePath": B, "outline": {"rect": [0, 0, 72, 42]}})+ o = state().get("outline") or []+ xs = [p[0] for p in o]+ return r.get("success") and xs and abs(max(xs) - 72) < 0.01, f"outline reaches x {xs and max(xs)}: {r.get('error')}"+ step("set_outline", set_outline)++ call("save", {"filePath": B})+ call("save", {"filePath": S})++ def project_rename():+ call("close_all_documents", {"save": True})+ r0 = call("project_create", {"parentDir": D + "/renamed-parent", "name": "Drill"}, timeout=400)+ d2 = D + "/renamed-parent/Drill"+ call("close_all_documents", {"save": True})+ r = call("project_rename", {"project": d2 + "/Drill.PrjPcb", "newName": "Drill2"})+ listing = shell(f'cmd /c dir /b "{d2.replace("/", chr(92))}"')+ return r.get("success") and "Drill2.PrjPcb" in listing and "Drill.PrjPcb" not in listing.split(), f"folder holds {listing.split()[:6]}: {r0.get('error')} {r.get('error')}"+ step("project_rename", project_rename)++ # -- a real project, with parts and libraries this bridge did not make ----------------------------------------+ # A copy of Altium's own example. Fixtures the code generated are shaped the way the code expects, so they can't+ # catch what real libraries do differently.+ call("close_all_documents", {"save": True})+ examples = "C:\\Users\\Public\\Documents\\Altium\\{}\\Examples\\SpiritLevel-SL1"+ fw = dw + "\\foreign"+ shell(f'cmd /c (if exist "{examples.format("ADDevelop")}" (xcopy /E /I /Y /Q "{examples.format("ADDevelop")}" "{fw}") else (xcopy /E /I /Y /Q "{examples.format("AD26")}" "{fw}")) >nul')+ found = shell(f'cmd /c dir /s /b "{fw}"')+ pick = lambda ext: next((l.strip().replace("\\", "/") for l in found.splitlines() if l.strip().lower().endswith(ext)), "")+ FB, FP, FL, FS = pick(".pcbdoc"), pick(".prjpcb"), pick(".pcblib"), pick(".schlib")+ sheets = [l.strip().replace("\\", "/") for l in found.splitlines() if l.strip().lower().endswith(".schdoc")]+ if not (FB and FP and FL and sheets):+ ROWS.append(dict(verb="foreign project", ok=False, detail=f"the example was not copied: {found[:200]}", sec=0))+ else:+ def lib_first(path):+ d = call("list_library", {"libraryPath": path})+ names = (d.get("data") or d).get("names") or (d.get("data") or d).get("components") or [""]+ return names[0].get("name") if isinstance(names[0], dict) else names[0]+ fstate = lambda: call("routing_state", {"filePath": FB})+ fcomps = lambda: {c["ref"]: c for c in fstate().get("components") or []}+ first = fcomps()+ FR = sorted(first)[0] if first else ""++ def f_read():+ return len(first) > 0, f"{len(first)} parts read from {os.path.basename(FB)}"+ step("foreign:routing_state", f_read)++ def f_move():+ c = first[FR]+ r = call("move_parts", {"parts": [{"ref": FR, "x": c["x"] + 1.27, "y": c["y"]}], "filePath": FB})+ x1 = fcomps()[FR]["x"]+ call("move_parts", {"parts": [{"ref": FR, "x": c["x"], "y": c["y"]}], "filePath": FB})+ return r.get("success") and abs(x1 - c["x"] - 1.27) < 0.01, f"{FR} x {c['x']} -> {x1}: {r.get('error')}"+ step("foreign:move_parts", f_move)++ def f_edit_parts():+ r = call("edit_parts", {"filePath": FB, "edits": [{"ref": FR, "value": "DRILLV"}]})+ d = call("component_data", {"designator": FR, "filePath": FB})+ return r.get("success") and "DRILLV" in json.dumps(d), f"{FR} after: {json.dumps(r.get('edited'))[:180]}: {r.get('error')}"+ step("foreign:edit_parts", f_edit_parts)++ def f_edit_tracks():+ tr = fstate().get("tracks") or []+ t = next((x for x in tr if x.get("net")), tr[0])+ r = call("edit_tracks", {"tracks": [{"id": t["id"], "width": round(t["width"] + 0.05, 4)}]})+ hit = [x for x in fstate().get("tracks") or [] if x["start"] == t["start"] and x["end"] == t["end"] and x["layer"] == t["layer"]]+ return r.get("success") and hit and abs(hit[0]["width"] - t["width"] - 0.05) < 0.001 and hit[0].get("net") == t.get("net"), f"net {t.get('net')} width {t['width']} -> {hit and hit[0]['width']}, net kept {hit and hit[0].get('net')}: {r.get('error')}"+ step("foreign:edit_tracks", f_edit_tracks)++ def f_place_parts():+ fp = lib_first(FL)+ call("routing_state", {"filePath": FB})+ r = call("place_parts", {"filePath": FB, "parts": [{"library": FL, "ref": "DRILL1", "footprint": fp, "x": 5, "y": 5, "rotation": 90}]})+ c = fcomps().get("DRILL1") or {}+ pads = [p for p in fstate().get("pads") or [] if p["ref"] == "DRILL1"]+ good = r.get("success") and abs(c.get("x", 0) - 5) < 0.01 and abs(c.get("rotation", 0) - 90) < 0.01 and len(pads) > 0+ gone = call("remove_parts", {"filePath": FB, "refs": ["DRILL1"]})+ return good and gone.get("success") and "DRILL1" not in fcomps(), f"{fp}: {len(pads)} pads, at {c.get('x')},{c.get('y')} rot {c.get('rotation')}: {r.get('error')}"+ step("foreign:place_parts", f_place_parts)++ def f_model_check():+ r = call("model_check", {"filePath": FB, "limit": 500})+ withb = [p for p in r.get("parts") or [] if p.get("models")]+ return r.get("success") and r.get("checked") == len(first) and len(withb) > 0, f"{r.get('checked')} parts checked, {len(withb)} with bodies, noModel {len(r.get('noModel') or [])}, kinds {sorted({b['kind'] for p in withb for b in p['models']})}, sample {json.dumps(withb[0]['models'][0])[:120] if withb else ''}"+ step("foreign:model_check", f_model_check)++ def f_select():+ r = call("select_items", {"filePath": FB, "refs": [FR]})+ n = call("selection", {"filePath": FB}).get("count")+ call("select_items", {"filePath": FB, "clear": True})+ return r.get("verified") is True and n == 1, f"selected {r.get('selected')}, read {n}"+ step("foreign:select_items", f_select)++ FSH = next((x for x in sheets if call("sch_items", {"sheet": x}).get("wires")), sheets[0])+ fitems = lambda: call("sch_items", {"sheet": FSH})+ def f_sch_wire_label():+ it = fitems()+ w0, l0 = len(it.get("wires") or []), len(it.get("labels") or [])+ r = call("sch_wire", {"sheet": FSH, "points": [[2.54, 2.54], [12.7, 2.54]]})+ r2 = call("sch_label", {"sheet": FSH, "text": "DRILL_F", "at": [5.08, 2.54]})+ it2 = fitems()+ good = r.get("success") and r2.get("success") and len(it2.get("wires") or []) == w0 + 1 and len(it2.get("labels") or []) == l0 + 1+ call("sch_label", {"sheet": FSH, "remove": True, "id": (r2.get("label") or {}).get("id")})+ call("sch_delete_wire", {"sheet": FSH, "at": [5.08, 2.54]})+ it3 = fitems()+ return good and len(it3.get("wires") or []) == w0 and len(it3.get("labels") or []) == l0, f"wires {w0} -> {len(it2.get('wires') or [])} -> {len(it3.get('wires') or [])}, labels {l0} -> {len(it2.get('labels') or [])} -> {len(it3.get('labels') or [])} on {os.path.basename(FSH)}"+ step("foreign:sch_wire+label", f_sch_wire_label)++ def f_sch_edit_label():+ labs = [x for x in fitems().get("labels") or []]+ if not labs:+ return True, "no net labels on this sheet: nothing to rename"+ t = labs[0]+ r = call("sch_edit_label", {"sheet": FSH, "edits": [{"id": t["id"], "by": [0, 2.54]}]})+ hit = [x for x in fitems().get("labels") or [] if x.get("text") == t["text"] and abs(x["at"][1] - t["at"][1] - 2.54) < 0.01]+ call("sch_edit_label", {"sheet": FSH, "edits": [{"id": hit[0]["id"] if hit else "", "by": [0, -2.54]}]})+ return r.get("success") and len(hit) == 1, f"{t['text']} moved up: {len(hit) == 1}: {r.get('error')}"+ step("foreign:sch_edit_label", f_sch_edit_label)++ def f_update_pcb():+ # a real library's part from the sheet to the board, through Altium's own ECO: it must arrive named+ sym = lib_first(FS)+ n0 = set(fcomps())+ r = call("sch_place_part", {"sheet": FSH, "library": FS, "symbol": sym, "designator": "DRILL7", "x": 300, "y": 300})+ call("save", {"filePath": FSH})+ u = call("update_pcb", {"projectPath": FP, "execute": True}, timeout=400)+ n1 = fcomps()+ new = sorted(set(n1) - n0)+ part = n1.get("DRILL7") or {}+ return r.get("success") and new == ["DRILL7"] and part.get("pattern"), f"{sym}: new on the board {new}, footprint {part.get('pattern')}: place {r.get('error')} update {json.dumps({k: u.get(k) for k in ('success', 'error', 'errorCode', 'added', 'applied')})[:160]}"+ step("foreign:update_pcb", f_update_pcb)+ call("save", {"filePath": FB})++ call("close_all_documents", {"save": True})+ bad = [r for r in ROWS if not r["ok"]]+ print(f"\n{len(ROWS) - len(bad)} of {len(ROWS)} real edits confirmed" + (": FAILED " + ", ".join(r["verb"] for r in bad) if bad else ""))+ if a.json:+ json.dump(ROWS, open(a.json, "w"), indent=1)+ sys.exit(1 if bad else 0)+++if __name__ == "__main__":+ main()
dev-skills/altium-bridge-test/run_verb_tests.py+62−1@@ -472,6 +472,67 @@ def matrix(w): # 0.2.88: the standard's export_3d through Altium's own Parasolid exporter (File > Export, its dialogs answered) M["export_3d"] = dict(phase=3.5, timeout=360, **ok(filePath=LB, format="parasolid", outputDir=D + "/export"), check=lambda d: (d.get("bytes") or 0) > 1000 and str(d.get("path", "")).lower().endswith(".x_t"))+ # 0.2.90: the eleven from the standard's 0.30.13 batch. The edits really run, a second read confirms each, and each+ # takes back what it did, so the verbs after them see the board and sheet as they were.+ W_A, W_B, W_M = [100, 150], [120, 150], [110, 150]+ def item_ids(key):+ return [x.get("id") for x in w["call"]("altium_sch_items", {"sheet": LS}).get(key) or []]+ def wire_ok(d):+ return bool(d.get("wires")) and d["wires"][0].get("id") in item_ids("wires") and d["wires"][0].get("from") == W_A+ def label_ok(d):+ i = (d.get("label") or {}).get("id")+ if d.get("offWire") or i not in item_ids("labels"):+ return False+ return w["call"]("altium_sch_label", {"sheet": LS, "remove": True, "id": i}).get("success") is True and i not in item_ids("labels")+ def no_connect_ok(d):+ i = (d.get("added") or [{}])[0].get("id")+ good = not d.get("onNothing") and i in item_ids("noConnects")+ good = good and w["call"]("altium_sch_no_connect", {"sheet": LS, "remove": True, "id": i}).get("success") is True and i not in item_ids("noConnects")+ return good and w["call"]("altium_sch_delete_wire", {"sheet": LS, "at": W_M}).get("success") is True+ M["sch_wire"] = dict(phase=3.5, **ok(sheet=LS, points=[W_A, W_B]), check=wire_ok)+ M["sch_label"] = dict(phase=3.5, **ok(sheet=LS, text="ADOM_DRILL", at=W_M), check=label_ok)+ M["sch_no_connect"] = dict(phase=3.5, **ok(sheet=LS, at=W_B), check=no_connect_ok)+ def place_ok(d):+ got = [p for p in w["call"]("altium_routing_state", {"filePath": LB}).get("components") or [] if p.get("ref") == "R99"]+ good = len(got) == 1 and abs(got[0]["x"] - 20) < 0.01 and abs(got[0]["y"] - 5) < 0.01 and got[0].get("side") == "bottom" and abs(got[0]["rotation"] - 90) < 0.01+ gone = w["call"]("altium_remove_parts", {"refs": ["R99"], "filePath": LB})+ return good and gone.get("success") is True and not [p for p in w["call"]("altium_routing_state", {"filePath": LB}).get("components") or [] if p.get("ref") == "R99"]+ M["place_parts"] = dict(phase=3.5, timeout=300, **ok(filePath=LB, parts=[{"library": PL, "ref": "R99", "footprint": "TST_SOIC8", "x": 20, "y": 5, "rotation": 90, "side": "bottom"}]), check=place_ok)+ # the track to edit is read at run time, routed first when an earlier verb ripped the net up+ def tracks_now():+ return w["call"]("altium_routing_state", {"filePath": LB}).get("tracks") or []+ def edit_tracks_args():+ if not tracks_now():+ w["call"]("altium_route_net", {"net": "N1", "width": 0.25, "paths": [[{"pad": "U1.8"}, {"pad": "U2.1"}]]})+ w["routed_for_edit"] = True+ tr = tracks_now()+ w["edit_track"] = tr[0] if tr else {}+ return {"tracks": [{"id": w["edit_track"].get("id", "none"), "width": w["edit_track"].get("width", 0.25) + 0.05}]}+ def edit_tracks_ok(d):+ t = w["edit_track"]+ hit = [x for x in tracks_now() if x["start"] == t["start"] and x["end"] == t["end"] and x["layer"] == t["layer"]]+ good = d.get("verified") is True and len(hit) == 1 and abs(hit[0]["width"] - (t["width"] + 0.05)) < 0.001+ back = w["call"]("altium_edit_tracks", {"tracks": [{"id": hit[0]["id"] if hit else "", "width": t["width"]}]})+ if w.get("routed_for_edit"):+ w["call"]("altium_ripup_nets", {"nets": ["N1"]})+ return good and back.get("success") is True+ M["edit_tracks"] = dict(phase=3.5, timeout=300, expect="ok", args=edit_tracks_args, check=edit_tracks_ok)+ def select_ok(d):+ if sorted(d.get("selected") or []) != ["U1", "U2"] or d.get("verified") is not True:+ return False+ read = w["call"]("altium_selection", {"filePath": LB})+ cleared = w["call"]("altium_select_items", {"filePath": LB, "clear": True})+ return read.get("count") == 2 and cleared.get("selected") == [] and w["call"]("altium_selection", {"filePath": LB}).get("count") == 0 \+ and w["call"]("altium_select_items", {"filePath": LB, "where": "sheet", "refs": ["U1"]}).get("errorCode") == "wrong_document"+ M["select_items"] = dict(phase=3.5, **ok(filePath=LB, refs=["U1", "U2"]), check=select_ok)+ M["model_check"] = dict(phase=3.5, timeout=200, **ok(filePath=LB), check=lambda d: d.get("checked", 0) >= 2 and all("models" in p and "issues" in p for p in d["parts"]) and isinstance(d.get("ok"), bool) and isinstance(d.get("noModel"), list))+ M["extensions"] = dict(phase=1, **ok(action="list"), check=lambda d: len(d.get("extensions") or []) > 0 and d.get("count") == len(d["extensions"]) and all(x.get("id") and x.get("name") for x in d["extensions"])+ and w["call"]("altium_extensions", {"action": "install", "id": "x"}).get("errorCode") == "not_supported")+ M["preferences"] = dict(phase=3.5, **ok(key="ExtensionManager.AutoUpdatePrefs.UpdatesCheckFrequency"), check=lambda d: len(d.get("current") or {}) == 1+ and w["call"]("altium_preferences", {"set": {"ExtensionManager/AutoUpdatePrefs/UpdatesCheckFrequency": 2}}).get("reason") == "tool_running")+ M["cancel_run"] = dict(phase=1, **ok(), check=lambda d: d.get("cancelRequested") is False and d.get("reason"))+ M["physical_properties"] = dict(phase=1, **ref("Altium keeps no material or mass on a part: refused with the reason"))+ # 0.2.89: the standard's import_design: a small EAGLE pair through Altium's Import Wizard, matched against its source; # a format the bridge does not drive yet is refused by name, and the imported project is closed again def eagle_ok(d):@@ -677,7 +738,7 @@ def main(): rows.append(dict(verb=verb, outcome="SKIP", note="--keep-open", sec=0)); continue if spec["expect"] == "skip": rows.append(dict(verb=verb, outcome="SKIP", note=spec.get("note", ""), sec=0)); continue- d = ab(T, TH, "altium_" + verb, spec["args"], timeout=spec.get("timeout", 200))+ d = ab(T, TH, "altium_" + verb, spec["args"]() if callable(spec["args"]) else spec["args"], timeout=spec.get("timeout", 200)) okv, why = d.get("success") is True, reason_of(d) if d.get("_transport") or "HTTP error" in str(d.get("error", "")) or d.get("errorCode") in ("timed_out", "agent_timeout"): outcome, detail = "FAIL", f"transport/timeout: {d.get('_transport') or d.get('errorCode') or d.get('error')}"
package.json+14−1@@ -290,7 +290,20 @@ "import eagle board into altium", "check for altium updates", "is there a newer altium version",- "turn off altium update check"+ "turn off altium update check",+ "place a no connect flag in altium",+ "no erc marker altium",+ "add a net label on a wire in altium",+ "draw a wire in altium schematic",+ "place footprints on an altium board",+ "change a track width in altium",+ "check 3d models on an altium board",+ "list altium extensions",+ "read altium preferences",+ "change an altium setting",+ "select parts in altium",+ "cancel a running altium job",+ "release my altium licence seat" ], "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.", "sample_prompts": [
page.json+15−2@@ -282,7 +282,20 @@ "import eagle board into altium", "check for altium updates", "is there a newer altium version",- "turn off altium update check"+ "turn off altium update check",+ "place a no connect flag in altium",+ "no erc marker altium",+ "add a net label on a wire in altium",+ "draw a wire in altium schematic",+ "place footprints on an altium board",+ "change a track width in altium",+ "check 3d models on an altium board",+ "list altium extensions",+ "read altium preferences",+ "change an altium setting",+ "select parts in altium",+ "cancel a running altium job",+ "release my altium licence seat" ], "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": {},@@ -337,4 +350,4 @@ "tools/symbol_modes.py", "uninstall.sh" ]-}+}
src/agent/AdomAgent.pas.tmpl+166@@ -9174,6 +9174,148 @@ End; { select_net: select every primitive of one net (tracks, arcs, vias, pads, fills, regions, pours) and deselect everything else; net empty = clear the selection. Answers the counts by kind. }+{ place_parts: footprints of the CURRENT PcbLib onto a board that may not be current. Payload lines+ ref|footprint|x|y|assigns, raw units from the board's origin. All the footprints are checked first, so a missing one+ places nothing. The bridge sets rotation and side after with move_parts and reads them back. }+Function CmdPlaceParts(Lines : TStringList; Payload : String) : String;+Var+ PLib : IPCB_Library;+ LibFp : IPCB_LibComponent;+ Board : IPCB_Board;+ SD : IServerDocument;+ Inst : IPCB_Component;+ Ops : TStringList;+ Op, Missing, S : String;+ I, K, N : Integer;+ Hit : Boolean;+Begin+ PLib := PCBServer.GetCurrentPCBLibrary;+ If PLib = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','the footprint library is not current') + '}'; Exit; End;+ Ops := TStringList.Create; Ops.Text := Payload;+ Missing := '';+ For K := 0 To Ops.Count - 1 Do+ Begin+ If Trim(Ops[K]) = '' Then Continue;+ Hit := False;+ For I := 0 To PLib.ComponentCount - 1 Do+ Begin+ LibFp := PLib.GetComponent(I);+ If UpperCase(LibFp.Name) = UpperCase(FieldP(Ops[K], 2)) Then Hit := True;+ End;+ If Not Hit Then Missing := Missing + FieldP(Ops[K], 2) + ' ';+ End;+ If Missing <> '' Then+ Begin+ Result := '{' + JRaw('ok','false') + ',' + JStr('errorCode','footprint_not_found') + ',' + JStr('error','not in this library: ' + Trim(Missing)) + '}';+ Ops.Free;+ Exit;+ End;+ SD := DocAt(Param(Lines, 'board'));+ If SD = Nil Then SD := Client.OpenDocument('PCB', Param(Lines, 'board'));+ If SD = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','could not open the board') + '}'; Ops.Free; Exit; End;+ Client.ShowDocument(SD);+ Board := PCBServer.GetCurrentPCBBoard;+ If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current PCB board after open') + '}'; Ops.Free; Exit; End;+ S := ''; N := 0;+ PCBServer.PreProcess;+ For K := 0 To Ops.Count - 1 Do+ Begin+ Op := Ops[K];+ If Trim(Op) = '' Then Continue;+ For I := 0 To PLib.ComponentCount - 1 Do+ Begin+ LibFp := PLib.GetComponent(I);+ If UpperCase(LibFp.Name) = UpperCase(FieldP(Op, 2)) Then Break;+ End;+ Inst := PlaceCopy(Board, LibFp, Board.XOrigin + AdomInt(FieldP(Op, 3)), Board.YOrigin + AdomInt(FieldP(Op, 4)));+ Inst.Name.Text := FieldP(Op, 1);+ Inst.Pattern := LibFp.Name;+ Inst.NameOn := True;+ If FieldP(Op, 5) <> '' Then AssignPadNets(Board, Inst, FieldP(Op, 5));+ If S <> '' Then S := S + ',';+ S := S + '"' + JsonEsc(Inst.Name.Text) + '"';+ N := N + 1;+ End;+ PCBServer.PostProcess;+ Board.ViewManager_FullUpdate;+ Ops.Free;+ Result := '{' + JRaw('ok','true') + ',' + JRaw('placed', IntToStr(N)) + ',' + JRaw('refs', '[' + S + ']') + '}';+End;++{ One body as ["file",overall,standoff,width,height]: file is the model's own name, empty for an extruded body. }+Function ModelBodyJson(Body : IPCB_ComponentBody) : String;+Var+ F : String;+ R : TCoordRect;+Begin+ F := '';+ Try If Body.Model <> Nil Then F := Body.Model.FileName; Except F := ''; End;+ R := Body.BoundingRectangle;+ Result := '["' + JsonEsc(F) + '",' + IntToStr(Body.OverallHeight) + ',' + IntToStr(Body.StandoffHeight) + ',' + IntToStr(R.Right - R.Left) + ',' + IntToStr(R.Top - R.Bottom) + ']';+End;++Function GroupModelBodies(Grp : IPCB_Group) : String;+Var+ GIt : IPCB_GroupIterator;+ Prim : IPCB_Primitive;+ S : String;+Begin+ S := '';+ GIt := Grp.GroupIterator_Create;+ GIt.AddFilter_ObjectSet(MkSet(eComponentBodyObject));+ GIt.AddFilter_LayerSet(AllLayers);+ Prim := GIt.FirstPCBObject;+ While Prim <> Nil Do+ Begin+ If S <> '' Then S := S + ',';+ S := S + ModelBodyJson(Prim);+ Prim := GIt.NextPCBObject;+ End;+ Grp.GroupIterator_Destroy(GIt);+ Result := '[' + S + ']';+End;++{ model_check: every part of the current board, or footprint of the current library, with its bodies' models. }+Function CmdModelCheck(Lines : TStringList) : String;+Var+ Board : IPCB_Board;+ BIt : IPCB_BoardIterator;+ Comp : IPCB_Component;+ PLib : IPCB_Library;+ Fp : IPCB_LibComponent;+ S : String;+ I : Integer;+Begin+ S := '';+ Board := PCBServer.GetCurrentPCBBoard;+ PLib := PCBServer.GetCurrentPCBLibrary;+ If PLib <> Nil Then+ Begin+ For I := 0 To PLib.ComponentCount - 1 Do+ Begin+ Fp := PLib.GetComponent(I);+ If S <> '' Then S := S + ',';+ S := S + '["' + JsonEsc(Fp.Name) + '","' + JsonEsc(Fp.Name) + '",' + GroupModelBodies(Fp) + ']';+ End;+ Result := '{' + JRaw('ok','true') + ',' + JStr('kind','library') + ',' + JStr('document', PLib.Board.FileName) + ',' + JRaw('parts', '[' + S + ']') + '}';+ Exit;+ End;+ If Board = Nil Then Begin Result := '{' + JRaw('ok','false') + ',' + JStr('error','no current board or footprint library') + '}'; Exit; End;+ BIt := Board.BoardIterator_Create;+ BIt.AddFilter_ObjectSet(MkSet(eComponentObject));+ BIt.AddFilter_LayerSet(AllLayers);+ BIt.AddFilter_Method(eProcessAll);+ Comp := BIt.FirstPCBObject;+ While Comp <> Nil Do+ Begin+ If S <> '' Then S := S + ',';+ S := S + '["' + JsonEsc(Comp.Name.Text) + '","' + JsonEsc(Comp.Pattern) + '",' + GroupModelBodies(Comp) + ']';+ Comp := BIt.NextPCBObject;+ End;+ Board.BoardIterator_Destroy(BIt);+ Result := '{' + JRaw('ok','true') + ',' + JStr('kind','board') + ',' + JStr('document', Board.FileName) + ',' + JRaw('parts', '[' + S + ']') + '}';+End;+ Function CmdSelectNet(Lines : TStringList) : String; Var Board : IPCB_Board;@@ -9741,6 +9883,28 @@ Begin If FieldP(Op, 6) <> '' Then Obj.Justification := AdomInt(FieldP(Op, 6)); SchRegister(Doc, Obj); NewKey := SchKey(Obj); End+ Else If K = 'O' Then+ Begin+ { O|net|x|y|orientation: a power port, Altium's global net label }+ Obj := SchServer.SchObjectFactory(ePowerObject, eCreate_Default);+ Obj.Text := FieldP(Op, 2);+ Obj.Location := Point(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4)));+ Obj.Style := PowerStyleOf(FieldP(Op, 2));+ Obj.Orientation := AdomInt(FieldP(Op, 5));+ Obj.ShowNetName := True;+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End+ Else If K = 'P' Then+ Begin+ { P|name|x|y|left(1/0): a port, Altium's hierarchical label, its connecting end at x,y }+ Obj := SchServer.SchObjectFactory(ePort, eCreate_Default);+ Obj.Name := FieldP(Op, 2);+ Obj.Width := MilsToCoord(600);+ Obj.IOType := ePortUnspecified;+ If FieldP(Op, 5) = '1' Then Begin Obj.Style := ePortLeft; Obj.Location := Point(AdomInt(FieldP(Op, 3)) - Obj.Width, AdomInt(FieldP(Op, 4))); End+ Else Begin Obj.Style := ePortRight; Obj.Location := Point(AdomInt(FieldP(Op, 3)), AdomInt(FieldP(Op, 4))); End;+ SchRegister(Doc, Obj); NewKey := SchKey(Obj);+ End Else If K = 'T' Then Begin Obj := SchServer.SchObjectFactory(eLabel, eCreate_Default);@@ -10496,6 +10660,8 @@ Begin Else If Cmd = 'build_schematic' Then Result := CmdBuildSchematic(Lines, Payload) Else If Cmd = 'project_nets' Then Result := CmdProjectNets(Lines) Else If Cmd = 'select_net' Then Result := CmdSelectNet(Lines)+ Else If Cmd = 'place_parts' Then Result := CmdPlaceParts(Lines, Payload)+ Else If Cmd = 'model_check' Then Result := CmdModelCheck(Lines) Else If Cmd = 'close_old_agents' Then Result := CmdCloseOldAgents(Lines) Else If Cmd = 'silk_state' Then Result := CmdSilkState(Lines) Else If Cmd = 'apply_silk' Then Result := CmdApplySilk(Lines, Payload)
src/bridge.json+12−1@@ -209,6 +209,17 @@ "altium_export_3d", "altium_tool_update", "altium_import_design",+ "altium_sch_no_connect",+ "altium_sch_label",+ "altium_sch_wire",+ "altium_edit_tracks",+ "altium_select_items",+ "altium_preferences",+ "altium_extensions",+ "altium_cancel_run",+ "altium_physical_properties",+ "altium_model_check",+ "altium_place_parts", "altium_route_pair", "altium_routing_drc", "altium_routing_state",@@ -302,7 +313,7 @@ "launch": 240, "panelize": 240, "impedance": 120,- "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900,+ "current_capacity": 120, "plan_route": 300, "place_decoupling": 300, "plan_fanout": 300, "estimate_cost": 120, "simulate": 900, "export_spice": 900, "update_footprints_from_library": 600, "lint_library": 600, "export_pos": 120, "verb_times": 15, "prewarm": 120, "render_board": 300, "log_tail": 60, "sch_batch": 900, "import_step": 180, "edit_pours": 600, "export_3d": 360, "tool_update": 150, "import_design": 900, "sch_no_connect": 150, "sch_label": 150, "sch_wire": 150, "edit_tracks": 300, "select_items": 60, "preferences": 60, "extensions": 60, "cancel_run": 15, "physical_properties": 15, "model_check": 180, "place_parts": 600, "height_check": 150, "copper_balance": 240, "return_path": 240,