← Commit history
.gitignoreadded+1
@@ -0,0 +1 @@+/target
Cargo.tomladded+25
@@ -0,0 +1,25 @@+[package]+name = "adom-2dboard"+version = "0.4.0"+edition = "2021"+description = "Interactive PCB viewer (.kicad_pcb → themed, net-highlightable SVG) with component hover info — embeddable in any app"++[[bin]]+name = "adom-2dboard"+path = "src/main.rs"++[dependencies]+tiny_http = "0.12"+regex = "1"+anyhow = "1"+clap = { version = "4", features = ["derive"] }+serde = { version = "1", features = ["derive"] }+serde_json = "1"+ureq = "2"+roxmltree = "0.20"+cfb = "0.10"++[profile.release]+opt-level = "z"+lto = true+strip = true
LICENSEadded+21
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Adom Industries Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
README.md+89−2
@@ -1,3 +1,90 @@-# Adom 2D Board+# adom-2dboard -Interactive 2D board view: your EDA's own PCB render plus live net/trace highlighting and per-pad stock, price and wiki lookup+Interactive **PCB layout viewer**. The picture is your EDA's *own* export — the+real silkscreen, the real trace widths, the real theme colours — and on top of it+sits an invisible, coordinate-aligned interaction layer that knows the netlist.+So you get a board that looks exactly like it does in KiCad, except you can click+a pad and watch its entire net light up.++![A net highlighted in adom-2dboard](screenshots/shot.png)++## Why it works this way++A flat SVG export is authentic but dead — no nets, no pads, nothing to click.+A self-drawn render is interactive but never quite looks like your EDA. This app+does both at once:++- **Visual base** — per-layer SVG straight from the EDA (KiCad via the shared+  **service-kicad** container, `POST /kicad/pcb/export/svg?layers=<L>`), one group+  per layer, in KiCad's own theme colours.+- **Interaction overlay** — the `.kicad_pcb` parsed in Rust into pads, traces,+  vias and zones carrying `data-net` / `data-ref`, drawn invisibly in the *same*+  board-mm coordinate system. No Y-flip, no offset, so the two align exactly.++## What you get++- **Net highlighting** — click any pad, via, trace or zone fill; the whole net+  lights in its own copper colour while the rest of the board dims. The net list+  on the right stays in sync (and is clickable itself).+- **Per-pad hover** — pad number, size, shape, side and net, plus live+  **stock, price, wiki page and popularity** for the parent part.++  ![Hovering a pad](screenshots/hover.png)+- **Layer control** — every layer toggles independently, and the Top/Bottom+  switch mirrors the board and brings that side's stack to the front so you can+  select parts on the far side.+- **Embeddable** — `embed` emits one self-contained interactive HTML file with+  no external assets, so any app can drop it in an iframe as a live PCB view.+  (adom-nucleus uses exactly this for its board pane.)++## Install++```+adom-wiki pkg install adom/adom-2dboard+```++## Use++```bash+# one self-contained interactive HTML (what you embed in another app)+adom-2dboard embed --file board.kicad_pcb --out board.html++# a composed interactive SVG (+ board.meta.json with --meta)+adom-2dboard render --file board.kicad_pcb --out board.svg --meta++# the live app — hover/click, with enrichment served from /enrich+adom-2dboard serve --file board.kicad_pcb --port 8790+```++### Embedding in your own app++`embed` inlines the SVG, the metadata and the viewer JS into a single file, so+an iframe is all you need:++```html+<iframe src="/board-view/my-board/pcb" style="border:0;width:100%;height:100%"></iframe>+```++An embed has no server of its own, so its enrichment `fetch("enrich")` is+**relative** — it resolves against whatever serves the page. Host apps can+answer it (`/…/enrich?mpn=&lcsc=`) to give the embedded card live stock and+price; if nothing answers, the card simply shows identity only.++## Enrichment++Hover data comes from sibling Adom CLIs, cached per part and fetched off the+render path (`/enrich` returns `{"pending":true}` and warms in the background,+so hovering never blocks):++- `adom-parts-search search <mpn>` — stock and price+- `adom-wiki discover search --query <mpn> --json` — wiki page and popularity++## Notes++- Requires network access to **service-kicad**; override with `KICAD_SERVICE_API`.+  If it is unreachable the app falls back to its own self-render so you still get+  a usable (if less authentic-looking) board.+- KiCad today; the same overlay architecture is what will carry Altium and+  Fusion exports.++See also: **adom-schematic** — the same idea for `.kicad_sch`.
SKILL.mdadded+101
@@ -0,0 +1,101 @@+---+name: adom-2dboard+description: "Use when the user asks to view, open, preview, or inspect a PCB layout or .kicad_pcb board; to highlight a net or trace; to see which pads are on a net; to look up a part on the board (stock, price, MPN, wiki page); or to embed an interactive PCB view inside another app or web page. Also trigger for questions like 'show me the board', 'what net is this pad on', 'make the PCB preview clickable', or 'replace the board image with something interactive'."+---++# adom-2dboard++Interactive PCB layout viewer for `.kicad_pcb`. The visual is the EDA's OWN+render (authentic silkscreen, trace widths, theme colours); an invisible overlay+parsed from the board file adds net/trace/pad interactivity on top of it.++## Architecture++```+adom-2dboard (single Rust binary, no Node, no local KiCad)+  |+  +-- visual base      per-layer SVG from service-kicad+  |                    POST /kicad/pcb/export/svg?layers=<L>   (KICAD_SERVICE_API)+  |                    one <g class="adom-layer-*"> per layer, KiCad theme colours+  |+  +-- interaction      .kicad_pcb parsed in Rust -> pads / traces / vias / zones+  |   overlay          carrying data-net, data-ref, data-pad, data-side+  |                    drawn INVISIBLY in the same board-mm coordinate system+  |                    (no Y-flip, no offset) so the two align exactly+  |+  +-- enrichment       GET /enrich?mpn=&lcsc=  (non-blocking: returns+                       {"pending":true} and warms in a background thread)+                         adom-parts-search search <mpn>          -> stock, price+                         adom-wiki discover search --json        -> wiki, popularity+```++If service-kicad is unreachable it falls back to a self-render, so the app still+works — it just looks less like KiCad.++## Quick start++```bash+# self-contained interactive HTML for embedding in another app+adom-2dboard embed --file board.kicad_pcb --out board.html++# composed interactive SVG (+ board.meta.json)+adom-2dboard render --file board.kicad_pcb --out board.svg --meta++# live app+adom-2dboard serve --file board.kicad_pcb --port 8790+```++## Commands++| Command | Description |+|---|---|+| `embed --file F [--out O]` | One self-contained interactive HTML file (no external assets) |+| `render --file F --out O [--meta]` | Composed interactive SVG, optional `<out>.meta.json` |+| `serve [--file F] [--port P]` | Live app server (default :8790) |++## Server routes (serve)++| Route | Purpose |+|---|---|+| `GET /state` | Current SVG + metadata (frontend poller) |+| `POST /load` | Push a new `.kicad_pcb` |+| `GET /enrich?mpn=&lcsc=` | Stock / price / wiki for a part (async, cached) |+| `POST /eval`, `GET /console` | AI-drivable UI channel |+| `POST /shutdown` | Stop the server |++## Interactions++- **Click** a pad, via, trace or zone fill -> the whole net highlights in its own+  copper colour, everything else dims. The net list stays in sync.+- **Hover** a pad or via -> pad number, size, shape, side, net + live stock,+  price, wiki page, popularity for the parent part.+- **Layers** toggle independently; Top/Bottom mirrors the board and brings that+  side's stack to the front.++## Embedding in another app++`embed` inlines SVG + metadata + viewer JS into one file, so an iframe is enough:++```html+<iframe src="/board-view/<slug>/pcb" style="border:0;width:100%;height:100%"></iframe>+```++An embed has no server, so its `fetch("enrich")` is RELATIVE — it resolves+against whoever serves the page. A host app can answer that route to give the+embedded card live stock/price (adom-nucleus does exactly this). If+nothing answers, the card degrades to identity only.++The side panels auto-hide below 620px width, so a small embedded pane shows just+the board and a fullscreened one shows the full chrome.++## Environment++| Variable | Purpose |+|---|---|+| `KICAD_SERVICE_API` | service-kicad base URL (default: the shared container) |++## Notes++- KiCad today. The overlay architecture is EDA-agnostic by design; Altium and+  Fusion exports are the planned next step.+- Sibling app: **adom-schematic** (same idea for `.kicad_sch`).
build.shadded+11
@@ -0,0 +1,11 @@+#!/bin/bash+# build.sh — compile the release binary and stage it into bin/ for packaging.+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++cargo build --release+mkdir -p bin+install -m 0755 "target/release/adom-2dboard" "bin/adom-2dboard"+echo "staged bin/adom-2dboard ($(du -h bin/adom-2dboard | cut -f1))"
install.shadded+16
@@ -0,0 +1,16 @@+#!/bin/bash+# install.sh for adom-2dboard (app).+# Runs from the extracted module directory (~/project/adom_modules/adom-2dboard/).+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++BIN_DIR="${HOME}/.local/bin"+mkdir -p "$BIN_DIR"+install -m 0755 "$DIR/bin/adom-2dboard" "$BIN_DIR/adom-2dboard"+echo "Installed adom-2dboard -> $BIN_DIR/adom-2dboard"++# Renamed from adom-layout-viewer: drop the old command so upgraders don't keep a+# stale binary shadowing this one.+rm -f "$BIN_DIR/adom-layout-viewer"
package.jsonadded+68
@@ -0,0 +1,68 @@+{+  "slug": "adom-2dboard",+  "version": "0.4.0",+  "type": "app",+  "description": "Interactive 2D board view: your EDA's own PCB render plus live net/trace highlighting and per-pad stock, price and wiki lookup",+  "dependencies": {+    "adom/adom-parts-search": "*"+  },+  "scripts": {+    "install": "./install.sh",+    "uninstall": "./uninstall.sh"+  },+  "needs_sudo": false,+  "hero": {+    "type": "image",+    "path": "docs/hero.png"+  },+  "discovery_triggers": [+    "show me the pcb",+    "open the board layout",+    "view this kicad_pcb",+    "highlight this net",+    "what net is this pad on",+    "what trace is this",+    "make the pcb preview clickable",+    "interactive pcb view",+    "embed a board view in my app",+    "what part is this on the board"+  ],+  "discovery_pitch": "Use to view or embed a PCB layout that looks exactly like the user's EDA drew it, with clickable nets, traces and pads plus live stock, price and wiki data per part.",+  "sample_prompts": [+    {+      "label": "Open a board",+      "prompt": "open this kicad_pcb so I can click around it"+    },+    {+      "label": "Trace a net",+      "prompt": "show me everything on the +3.3V net on this board"+    },+    {+      "label": "Identify a pad",+      "prompt": "what net is this pad on, and is the part in stock?"+    },+    {+      "label": "Embed it",+      "prompt": "replace the flat PCB image in my app with an interactive board view"+    }+  ],+  "tags": [+    "kicad",+    "pcb",+    "2d",+    "board",+    "layout",+    "eda",+    "viewer",+    "netlist",+    "traces",+    "svg",+    "interactive",+    "embed",+    "altium",+    "fusion",+    "eagle",+    "pcbdoc",+    "schdoc"+  ]+}
release.shadded+87
@@ -0,0 +1,87 @@+#!/bin/bash+#+# Canonical release.sh for an adompkg source repo.+#+# Reads version from package.json, optionally bumps it (--bump patch|minor|major),+# runs build.sh if present, then runs `adompkg publish` and prints the resulting+# package URL.+#+# Usage:+#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh                # publish current version+#   ADOMPKG_TOKEN=<carbon-api-key> ./release.sh --bump patch   # bump + publish+#+set -euo pipefail++DIR="$(cd "$(dirname "$0")" && pwd)"+cd "$DIR"++if [ ! -f package.json ]; then+  echo "release.sh: no package.json found in $DIR" >&2+  exit 1+fi++REGISTRY="${ADOMPKG_REGISTRY:-https://git-wiki-ktqxite5iglh.adom.cloud}"++if [ -z "${ADOMPKG_TOKEN:-}" ]; then+  if [ -r /var/run/adom/api-key ]; then+    ADOMPKG_TOKEN="$(cat /var/run/adom/api-key)"+    export ADOMPKG_TOKEN+  else+    echo "release.sh: ADOMPKG_TOKEN is required (set ADOMPKG_TOKEN=<carbon-api-key>)" >&2+    exit 1+  fi+fi++# Read current version.+CUR_VERSION=$(node -e "console.log(require('./package.json').version)")+SLUG=$(node -e "console.log(require('./package.json').slug || require('./package.json').name)")++BUMP=""+for a in "$@"; do+  case "$a" in+    --bump)+      shift+      BUMP="${1:-patch}"+      shift || true+      ;;+    --bump=*)+      BUMP="${a#--bump=}"+      shift+      ;;+  esac+done++if [ -n "$BUMP" ]; then+  NEXT=$(node -e "+    const [maj, min, pat] = process.argv[1].split('.').map(n => parseInt(n, 10));+    const b = process.argv[2];+    let out;+    if (b === 'major') out = (maj + 1) + '.0.0';+    else if (b === 'minor') out = maj + '.' + (min + 1) + '.0';+    else out = maj + '.' + min + '.' + (pat + 1);+    console.log(out);+  " "$CUR_VERSION" "$BUMP")+  echo "release.sh: bumping $CUR_VERSION -> $NEXT ($BUMP)"+  node -e "+    const fs = require('fs');+    const p = JSON.parse(fs.readFileSync('package.json', 'utf8'));+    p.version = process.argv[1];+    fs.writeFileSync('package.json', JSON.stringify(p, null, 2) + '\n');+  " "$NEXT"+  CUR_VERSION="$NEXT"+fi++# Optional build step.+if [ -x ./build.sh ]; then+  echo "release.sh: running build.sh"+  ./build.sh+fi++# Publish.+echo "release.sh: publishing $SLUG@$CUR_VERSION to $REGISTRY"+adompkg publish . --org adom --public --yes++# Print published URL.+echo+echo "Published: $REGISTRY/pages/$SLUG"+echo "Install:   adompkg install $SLUG"
screenshots/hover.pngadded
⋯ 1 unchanged line ⋯
screenshots/shot.pngadded
⋯ 1 unchanged line ⋯
scripts/drive-embed.mjsadded+46
@@ -0,0 +1,46 @@+import puppeteer from 'puppeteer';+const url = 'file://' + process.argv[2];+const b = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });+const p = await b.newPage();+await p.setViewport({ width: 900, height: 760, deviceScaleFactor: 2 });+const errs = [];+p.on('pageerror', e => errs.push(String(e)));+await p.goto(url, { waitUntil: 'networkidle0' });+await new Promise(r => setTimeout(r, 400));++// sanity: how many tagged elements mounted?+const info = await p.evaluate(() => {+  const svg = document.querySelector('#svgbox svg');+  return {+    hasSvg: !!svg,+    nets: svg ? svg.querySelectorAll('[data-net]').length : 0,+    hotspots: svg ? svg.querySelectorAll('.adom-hotspot').length : 0,+    netNames: Object.keys((window.__PCB__ && window.__PCB__.meta.net_names) || {}).length,+  };+});+console.log('MOUNT', JSON.stringify(info));++// 1) highlight net 1 (+3.3V) and screenshot+await p.evaluate(() => window.AdomPcb.highlightNet('1'));+await new Promise(r => setTimeout(r, 200));+await p.screenshot({ path: process.argv[3] || '/tmp/pcbtest/hl_net1.png' });+const hl = await p.evaluate(() => document.querySelectorAll('#svgbox svg .hl').length);+console.log('NET1_HL_COUNT', hl);++// 2) hover a component hotspot (U1) → info card+const cardShown = await p.evaluate(async () => {+  const hs = [...document.querySelectorAll('.adom-hotspot')].find(h => h.getAttribute('data-ref') === 'U1')+          || document.querySelector('.adom-hotspot');+  if (!hs) return { ok: false };+  const r = hs.getBoundingClientRect();+  const ev = new MouseEvent('mousemove', { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 });+  hs.dispatchEvent(ev);+  await new Promise(r => setTimeout(r, 100));+  const card = document.querySelector('#card');+  return { ok: card && card.style.display === 'block', ref: hs.getAttribute('data-ref'), text: card ? card.innerText.slice(0, 120) : '' };+});+console.log('CARD', JSON.stringify(cardShown));+await p.screenshot({ path: '/tmp/pcbtest/hover_comp.png' });++console.log('ERRORS', JSON.stringify(errs));+await b.close();
scripts/drive-live.mjsadded+20
@@ -0,0 +1,20 @@+import puppeteer from 'puppeteer';+const b = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });+const p = await b.newPage();+await p.setViewport({ width: 900, height: 760, deviceScaleFactor: 2 });+const errs = []; p.on('pageerror', e => errs.push(String(e)));+await p.goto('http://localhost:8795/', { waitUntil: 'networkidle0' });+await new Promise(r => setTimeout(r, 500));+// hover U1 (has MPN) → card + enrichment+await p.evaluate(async () => {+  const hs = [...document.querySelectorAll('.adom-hotspot')].find(h => h.getAttribute('data-ref') === 'U1');+  const r = hs.getBoundingClientRect();+  hs.dispatchEvent(new MouseEvent('mousemove', { bubbles: true, clientX: r.left + r.width / 2, clientY: r.top + r.height / 2 }));+});+// wait for enrichment pills to arrive (server already warmed cache)+await new Promise(r => setTimeout(r, 2500));+const card = await p.evaluate(() => document.querySelector('#card').innerText);+console.log('CARD:\n' + card);+console.log('ERRORS', JSON.stringify(errs));+await p.screenshot({ path: '/tmp/pcbtest/live_card.png' });+await b.close();
scripts/drive-sides.mjsadded+30
@@ -0,0 +1,30 @@+import puppeteer from 'puppeteer';+const b = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });+const p = await b.newPage();+await p.setViewport({ width: 1000, height: 800, deviceScaleFactor: 2 });+const errs = []; p.on('pageerror', e => errs.push(String(e)));+await p.goto('file://' + process.argv[2], { waitUntil: 'networkidle0' });+await new Promise(r => setTimeout(r, 500));+// TOP view (default)+await p.screenshot({ path: '/tmp/pcbtest/side_top.png' });+// click a pad's net to test click-highlight brightness+const netInfo = await p.evaluate(() => {+  const pad = [...document.querySelectorAll('.adom-pad')].find(p => p.getAttribute('data-net') !== '0');+  pad.dispatchEvent(new MouseEvent('click', { bubbles: true }));+  return { net: pad.getAttribute('data-net'), lit: document.querySelectorAll('.hl').length, dim: document.querySelector('#svgbox svg').classList.contains('dim') };+});+await new Promise(r => setTimeout(r, 200));+await p.screenshot({ path: '/tmp/pcbtest/side_top_net.png' });+console.log('NET_CLICK', JSON.stringify(netInfo));+// clear, then BOTTOM view+await p.evaluate(() => { document.querySelector('#svgbox svg').dispatchEvent(new MouseEvent('click', { bubbles: true })); });+const flipped = await p.evaluate(() => {+  document.querySelector('.sidebtn[data-side="bottom"]').click();+  const flip = document.querySelector('.adom-flip');+  return { transform: flip.getAttribute('transform'), silkBopacity: document.querySelector('.adom-layer-silkB').style.opacity, silkFopacity: document.querySelector('.adom-layer-silkF').style.opacity };+});+await new Promise(r => setTimeout(r, 300));+await p.screenshot({ path: '/tmp/pcbtest/side_bottom.png' });+console.log('FLIP', JSON.stringify(flipped));+console.log('ERRS', JSON.stringify(errs));+await b.close();
scripts/rasterize.mjsadded+14
@@ -0,0 +1,14 @@+import puppeteer from 'puppeteer';+import fs from 'fs';+const svg = fs.readFileSync(process.argv[2], 'utf8');+const bg = process.argv[4] || '#0a0f0c';+const html = `<!doctype html><html><body style="margin:0;background:${bg};display:grid;place-items:center;height:100vh">${svg}</body></html>`;+const b = await puppeteer.launch({headless:'new', args:['--no-sandbox']});+const p = await b.newPage();+await p.setViewport({width:700, height:700, deviceScaleFactor:2});+await p.setContent(html, {waitUntil:'networkidle0'});+const el = await p.$('svg');+await el.evaluate(s=>{s.style.width='640px';s.style.height='640px';});+await p.screenshot({path: process.argv[3]});+await b.close();+console.log('shot →', process.argv[3]);
src/altium.rsadded+411
@@ -0,0 +1,411 @@+//! Altium `.PcbDoc` board parser.+//!+//! A PcbDoc is an OLE2 / Compound File. Each primitive type lives in its own+//! storage (`Tracks6`, `Vias6`, `Arcs6`, `Pads6`, `Nets6`, `Components6`,+//! `Board6`), each with a `Data` stream. Two record shapes appear:+//!+//!   * TEXT streams (Nets6, Components6, Board6): `[u32 len][ASCII |KEY=VAL|…]`+//!   * BINARY streams (Tracks6, Vias6, Arcs6): `[u8 type][u32 len][payload]`,+//!     with a common payload prefix — layer at 0, net index at 3 (u16, 0xFFFF =+//!     no net), component at 7 — and coordinates from offset 13 as i32 in+//!     Altium's internal unit of 1/10000 mil.+//!+//!   * Pads6 is the odd one: record type 0x02 followed by SIX length-prefixed+//!     sub-blocks; block 0 is the designator pstring and block 4 the geometry.+//!+//! Altium is Y-up, we are Y-down, so every Y is negated.+//!+//! Like the EAGLE path there is no headless Altium renderer (Altium has no CLI),+//! so these boards use our own self-render with the same interaction overlay.++use crate::pcb_render::{Arc, Board, Comp, Gfx, Pad, Track, Via, ZonePoly};+use std::collections::HashMap;+use std::fmt::Write as _;+use std::io::{Cursor, Read};++/// Altium internal unit (1/10000 mil) -> mm+const U: f64 = 2.54e-6;++pub fn looks_like_altium(bytes: &[u8]) -> bool {+    bytes.len() > 8 && bytes[..8] == [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]+}++fn i32_at(b: &[u8], o: usize) -> i32 {+    if o + 4 > b.len() { return 0; }+    i32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])+}+fn u32_at(b: &[u8], o: usize) -> u32 {+    if o + 4 > b.len() { return 0; }+    u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]])+}+fn u16_at(b: &[u8], o: usize) -> u16 {+    if o + 2 > b.len() { return 0; }+    u16::from_le_bytes([b[o], b[o + 1]])+}+fn f64_at(b: &[u8], o: usize) -> f64 {+    if o + 8 > b.len() { return 0.0; }+    let mut a = [0u8; 8];+    a.copy_from_slice(&b[o..o + 8]);+    f64::from_le_bytes(a)+}+fn mm(v: i32) -> f64 { v as f64 * U }++/// `|KEY=VAL|KEY=VAL|` -> map (keys upper-cased by Altium already)+fn kv(rec: &str) -> HashMap<String, String> {+    rec.trim_matches('|')+        .split('|')+        .filter_map(|p| p.split_once('='))+        .map(|(k, v)| (k.to_uppercase(), v.to_string()))+        .collect()+}++/// Altium writes lengths like "10909.6457mil" or "1.5mm".+fn dim(s: &str) -> f64 {+    let t = s.trim();+    if let Some(v) = t.strip_suffix("mil") { v.trim().parse::<f64>().unwrap_or(0.0) * 0.0254 }+    else if let Some(v) = t.strip_suffix("mm") { v.trim().parse::<f64>().unwrap_or(0.0) }+    else { t.parse::<f64>().unwrap_or(0.0) * U }+}++fn altium_layer(n: u8) -> &'static str {+    match n {+        1 => "F.Cu",+        32 => "B.Cu",+        2..=31 => "In.Cu",+        33 => "F.SilkS",+        34 => "B.SilkS",+        74 => "F.Cu",        // multi-layer (vias/THT pads)+        56..=73 => "F.Fab",  // mechanical / assembly layers+        _ => "",+    }+}++fn read_stream(c: &mut cfb::CompoundFile<Cursor<Vec<u8>>>, path: &str) -> Option<Vec<u8>> {+    let mut s = c.open_stream(path).ok()?;+    let mut buf = Vec::new();+    s.read_to_end(&mut buf).ok()?;+    Some(buf)+}++/// `[u32 len][bytes]*` — the ASCII property-record streams.+fn text_records(d: &[u8]) -> Vec<String> {+    let mut out = Vec::new();+    let mut off = 0usize;+    while off + 4 <= d.len() {+        let ln = u32_at(d, off) as usize;+        off += 4;+        if ln == 0 || off + ln > d.len() { break; }+        out.push(String::from_utf8_lossy(&d[off..off + ln]).trim_end_matches('\0').to_string());+        off += ln;+    }+    out+}++/// `[u8 type][u32 len][payload]*` — the fixed-shape binary streams.+fn bin_records(d: &[u8]) -> Vec<(u8, &[u8])> {+    let mut out = Vec::new();+    let mut off = 0usize;+    while off + 5 <= d.len() {+        let t = d[off];+        let ln = u32_at(d, off + 1) as usize;+        off += 5;+        if off + ln > d.len() { break; }+        out.push((t, &d[off..off + ln]));+        off += ln;+    }+    out+}++pub fn parse_pcbdoc(bytes: &[u8]) -> Result<Board, String> {+    let mut cf = cfb::CompoundFile::open(Cursor::new(bytes.to_vec()))+        .map_err(|e| format!("altium .PcbDoc: not a compound file ({e})"))?;+    let mut b = Board::default();+    // Mechanical-layer geometry, kept with its layer number and extent so we can+    // pick out which one is the BOARD OUTLINE (see below).+    let mut mech: Vec<(u8, Gfx, f64, f64, f64, f64)> = Vec::new();++    // ── nets: index -> name (the binary streams reference nets by index) ────+    let mut net_names: Vec<String> = Vec::new();+    if let Some(d) = read_stream(&mut cf, "/Nets6/Data") {+        for r in text_records(&d) {+            net_names.push(kv(&r).get("NAME").cloned().unwrap_or_default());+        }+    }+    // our model keys nets by u32 starting at 1; 0 means "no net"+    for (i, n) in net_names.iter().enumerate() {+        b.nets.insert(i as u32 + 1, n.clone());+    }+    let netid = |raw: u16| -> u32 { if raw == 0xFFFF || raw as usize >= net_names.len() { 0 } else { raw as u32 + 1 } };++    // ── tracks ──────────────────────────────────────────────────────────────+    if let Some(d) = read_stream(&mut cf, "/Tracks6/Data") {+        for (_, p) in bin_records(&d) {+            if p.len() < 33 { continue; }+            let layer = altium_layer(p[0]);+            if layer.is_empty() { continue; }+            let (x1, y1) = (mm(i32_at(p, 13)), -mm(i32_at(p, 17)));+            let (x2, y2) = (mm(i32_at(p, 21)), -mm(i32_at(p, 25)));+            let w = mm(i32_at(p, 29));+            let net = netid(u16_at(p, 3));+            if layer.ends_with(".Cu") {+                b.tracks.push(Track { x1, y1, x2, y2, width: w, layer: layer.into(), net });+            } else {+                let g = Gfx { d: format!("M {:.4} {:.4} L {:.4} {:.4}", x1, y1, x2, y2), width: w, closed_fill: false };+                match layer {+                    "F.SilkS" => b.silk_f.push(g),+                    "B.SilkS" => b.silk_b.push(g),+                    _ => mech.push((p[0], g, x1.min(x2), y1.min(y2), x1.max(x2), y1.max(y2))),+                }+            }+        }+    }++    // ── arcs (centre + radius + start/end angle, degrees CCW) ───────────────+    if let Some(d) = read_stream(&mut cf, "/Arcs6/Data") {+        for (_, p) in bin_records(&d) {+            if p.len() < 45 { continue; }+            let layer = altium_layer(p[0]);+            if layer.is_empty() { continue; }+            let (cx, cy) = (mm(i32_at(p, 13)), -mm(i32_at(p, 17)));+            let r = mm(i32_at(p, 21));+            let (sa, ea) = (f64_at(p, 25), f64_at(p, 33));+            let w = mm(i32_at(p, 41));+            let d_path = arc_path(cx, cy, r, sa, ea);+            let net = netid(u16_at(p, 3));+            if layer.ends_with(".Cu") {+                b.arcs.push(Arc { d: d_path, layer: layer.into(), width: w, net });+            } else {+                let g = Gfx { d: d_path, width: w, closed_fill: false };+                match layer {+                    "F.SilkS" => b.silk_f.push(g),+                    "B.SilkS" => b.silk_b.push(g),+                    _ => mech.push((p[0], g, cx - r, cy - r, cx + r, cy + r)),+                }+            }+        }+    }++    // ── vias ────────────────────────────────────────────────────────────────+    if let Some(d) = read_stream(&mut cf, "/Vias6/Data") {+        for (_, p) in bin_records(&d) {+            if p.len() < 29 { continue; }+            b.vias.push(Via {+                x: mm(i32_at(p, 13)), y: -mm(i32_at(p, 17)),+                size: mm(i32_at(p, 21)), drill: mm(i32_at(p, 25)),+                net: netid(u16_at(p, 3)),+            });+        }+    }++    // ── copper pours ────────────────────────────────────────────────────────+    // Polygons6 (TEXT) holds each pour's net; Regions6 (BINARY) holds the poured+    // outlines and references its parent by polygon index at payload offset 5.+    // The region's OWN net field is always 0xFFFF, so the net must come from here.+    let mut poly_net: Vec<u32> = Vec::new();+    if let Some(d) = read_stream(&mut cf, "/Polygons6/Data") {+        for r in text_records(&d) {+            let m = kv(&r);+            let raw = m.get("NET").map(|v| v.trim_end_matches('\0').trim().to_string()).unwrap_or_default();+            poly_net.push(raw.parse::<u16>().map(netid).unwrap_or(0));+        }+    }+    if let Some(d) = read_stream(&mut cf, "/Regions6/Data") {+        for (_, p) in bin_records(&d) {+            if p.len() < 22 { continue; }+            let layer = altium_layer(p[0]);+            if !layer.ends_with(".Cu") { continue; }+            let poly = u16_at(p, 5) as usize;+            let net = poly_net.get(poly).copied().unwrap_or(0);+            // [u32 kvlen][kv ascii][u32 vertex count][(f64 x, f64 y) * count]+            let kvlen = u32_at(p, 18) as usize;+            let mut q = 22 + kvlen;+            if q + 4 > p.len() { continue; }+            let count = u32_at(p, q) as usize;+            q += 4;+            if count < 3 || q + count * 16 > p.len() { continue; }+            let mut d_path = String::new();+            for k in 0..count {+                let x = f64_at(p, q + k * 16) * U;+                let y = -f64_at(p, q + k * 16 + 8) * U;+                let _ = write!(d_path, "{} {:.4} {:.4} ", if k == 0 { "M" } else { "L" }, x, y);+            }+            d_path.push('Z');+            b.zones.push(ZonePoly { d: d_path, layer: layer.into(), net, outline: false });+        }+    }+    // Fills6: axis-aligned rectangular copper fills+    if let Some(d) = read_stream(&mut cf, "/Fills6/Data") {+        for (_, p) in bin_records(&d) {+            if p.len() < 29 { continue; }+            let layer = altium_layer(p[0]);+            if !layer.ends_with(".Cu") { continue; }+            let (x1, y1) = (mm(i32_at(p, 13)), -mm(i32_at(p, 17)));+            let (x2, y2) = (mm(i32_at(p, 21)), -mm(i32_at(p, 25)));+            b.zones.push(ZonePoly {+                d: format!("M {x1:.4} {y1:.4} L {x2:.4} {y1:.4} L {x2:.4} {y2:.4} L {x1:.4} {y2:.4} Z"),+                layer: layer.into(),+                net: netid(u16_at(p, 3)),+                outline: false,+            });+        }+    }++    // ── pads (record 0x02, six length-prefixed sub-blocks) ──────────────────+    let mut pad_by_comp: HashMap<u16, Vec<usize>> = HashMap::new();+    if let Some(d) = read_stream(&mut cf, "/Pads6/Data") {+        let mut off = 0usize;+        while off < d.len() {+            let rt = d[off];+            off += 1;+            let nblocks = match rt { 0x02 => 6, 0x05 => 2, 0x01 | 0x03 | 0x04 | 0x06 | 0x09 | 0x0B | 0x0C => 1, _ => break };+            let mut blocks: Vec<&[u8]> = Vec::with_capacity(nblocks);+            let mut ok = true;+            for _ in 0..nblocks {+                if off + 4 > d.len() { ok = false; break; }+                let bl = u32_at(&d, off) as usize;+                off += 4;+                if off + bl > d.len() { ok = false; break; }+                blocks.push(&d[off..off + bl]);+                off += bl;+            }+            if !ok { break; }+            if rt != 0x02 || blocks.len() < 5 { continue; }+            let designator = {+                let b0 = blocks[0];+                if b0.is_empty() { String::new() }+                else { let n = b0[0] as usize; String::from_utf8_lossy(&b0[1..(1 + n).min(b0.len())]).to_string() }+            };+            let pd = blocks[4];+            if pd.len() < 50 { continue; }+            let layer = pd[0];+            let net = netid(u16_at(pd, 3));+            let comp = u16_at(pd, 7);+            let x = mm(i32_at(pd, 13));+            let y = -mm(i32_at(pd, 17));+            let w = u32_at(pd, 21) as f64 * U;+            let h = u32_at(pd, 25) as f64 * U;+            let hole = u32_at(pd, 45) as f64 * U;+            // Altium shape byte: 1 Round, 2 Rectangular, 3 Octagonal, 4 RoundedRect.+            // A "Round" pad is only a CIRCLE when it's square — otherwise it's a+            // stadium (e.g. the SOT-223's 1.31x3.24 tab), which read as a tiny+            // circle when this mapped 1 => circle unconditionally.+            let square = (w - h).abs() < 0.01;+            let shape = match pd[49] {+                1 => if square { "circle" } else { "oval" },+                2 => "rect",+                3 | 4 => "roundrect",+                _ => "rect",+            };+            // Rotation is a f64 in BLOCK 4 at offset 52 (not block 5, which is+            // usually absent or holds a subnormal). Reading the wrong block left+            // every rotated pad unrotated — e.g. the SOT-223's 270-degree tab and+            // pins rendered with width/height transposed.+            let rot = {+                let r = f64_at(pd, 52);+                if r.is_finite() && r.abs() <= 360.0 { r } else { 0.0 }+            };+            let side = if layer == 32 { 'B' } else { 'F' };+            let mount = if hole > 0.0 { "thru_hole" } else { "smd" };+            pad_by_comp.entry(comp).or_default().push(b.pads.len());+            b.pads.push(Pad {+                reference: String::new(), // filled in from Components6 below+                num: designator, net, x, y, rot: -rot, w, h,+                shape: shape.into(), drill: hole, mount: mount.into(), side,+            });+        }+    }++    // ── components: designator + placement; also names the pads ─────────────+    if let Some(d) = read_stream(&mut cf, "/Components6/Data") {+        for (i, r) in text_records(&d).iter().enumerate() {+            let m = kv(r);+            let reference = m.get("SOURCEDESIGNATOR").or_else(|| m.get("NAME"))+                .cloned().unwrap_or_else(|| format!("C{i}"));+            let x = m.get("X").map(|v| dim(v)).unwrap_or(0.0);+            let y = -m.get("Y").map(|v| dim(v)).unwrap_or(0.0);+            let side = if m.get("LAYER").map(|l| l.eq_ignore_ascii_case("BOTTOM")).unwrap_or(false) { "bottom" } else { "top" };++            // adopt this component's pads (they carry the component index)+            let mut bbox = [x - 0.5, y - 0.5, x + 0.5, y + 0.5];+            let idxs = pad_by_comp.get(&(i as u16)).cloned().unwrap_or_default();+            if !idxs.is_empty() {+                let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+                for &pi in &idxs {+                    let p = &mut b.pads[pi];+                    p.reference = reference.clone();+                    mnx = mnx.min(p.x - p.w / 2.0); mxx = mxx.max(p.x + p.w / 2.0);+                    mny = mny.min(p.y - p.h / 2.0); mxy = mxy.max(p.y + p.h / 2.0);+                }+                bbox = [mnx, mny, mxx, mxy];+            }+            b.comps.push(Comp {+                reference,+                value: m.get("COMMENT").cloned().unwrap_or_default(),+                footprint: m.get("PATTERN").cloned().unwrap_or_default(),+                side: side.into(),+                mpn: String::new(), lcsc: String::new(),+                x, y, bbox, pad_count: idxs.len(),+            });+        }+    }++    // ── board outline ───────────────────────────────────────────────────────+    // Altium keeps the REAL outline as ordinary geometry on a mechanical layer,+    // arcs and all — that's the properly filleted shape. `Board6`'s VX/VY vertex+    // list describes the same outline but its fillets live in separate KIND/CX/+    // CY/R/SA/EA fields, and chaining those back into one path is fiddly; drawing+    // just the vertices chamfers every rounded corner. So prefer the mechanical+    // outline: pick the mech layer whose geometry spans the largest area (the+    // outline bounds everything else) and promote it to the edge layer.+    let mut per_layer: HashMap<u8, (f64, f64, f64, f64, usize)> = HashMap::new();+    for (ly, _, x0, y0, x1, y1) in &mech {+        let e = per_layer.entry(*ly).or_insert((f64::MAX, f64::MAX, f64::MIN, f64::MIN, 0));+        e.0 = e.0.min(*x0); e.1 = e.1.min(*y0); e.2 = e.2.max(*x1); e.3 = e.3.max(*y1); e.4 += 1;+    }+    // Pick the TIGHTEST mech layer that still bounds all the copper. Taking the+    // largest instead grabs the drawing frame / title block on boards that have+    // one (SL1's A3 sheet border ballooned the board to 395x283mm).+    let (mut cx0, mut cy0, mut cx1, mut cy1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+    let mut fit_cu = |x: f64, y: f64| { cx0 = cx0.min(x); cy0 = cy0.min(y); cx1 = cx1.max(x); cy1 = cy1.max(y); };+    for p in &b.pads { fit_cu(p.x - p.w / 2.0, p.y - p.h / 2.0); fit_cu(p.x + p.w / 2.0, p.y + p.h / 2.0); }+    for t in &b.tracks { fit_cu(t.x1, t.y1); fit_cu(t.x2, t.y2); }+    for v in &b.vias { fit_cu(v.x - v.size / 2.0, v.y - v.size / 2.0); fit_cu(v.x + v.size / 2.0, v.y + v.size / 2.0); }+    let have_cu = cx0 <= cx1;+    let area = |v: &(f64, f64, f64, f64, usize)| (v.2 - v.0) * (v.3 - v.1);+    let tol = 2.0; // mm of slack: the outline sits slightly outside the copper+    let bounds_copper = |v: &(f64, f64, f64, f64, usize)| {+        !have_cu || (v.0 <= cx0 + tol && v.1 <= cy0 + tol && v.2 >= cx1 - tol && v.3 >= cy1 - tol)+    };+    let cands: Vec<_> = per_layer.iter().filter(|(_, v)| v.4 >= 4 && v.2 > v.0 && v.3 > v.1).collect();+    let outline_layer = cands.iter()+        .filter(|(_, v)| bounds_copper(v))+        .min_by(|a, b| area(a.1).partial_cmp(&area(b.1)).unwrap_or(std::cmp::Ordering::Equal))+        .or_else(|| cands.iter().max_by(|a, b| area(a.1).partial_cmp(&area(b.1)).unwrap_or(std::cmp::Ordering::Equal)))+        .map(|(k, _)| **k);++    for (ly, g, ..) in mech {+        if Some(ly) == outline_layer { b.edges.push(g); } else { b.fab_f.push(g); }+    }++    if b.pads.is_empty() && b.tracks.is_empty() && b.comps.is_empty() {+        return Err("altium .PcbDoc: no primitives decoded".into());+    }+    Ok(b)+}++/// Centre/radius/angles -> SVG arc. Altium angles are degrees CCW from +X, and+/// our Y is already flipped, so the sweep direction inverts.+fn arc_path(cx: f64, cy: f64, r: f64, sa: f64, ea: f64) -> String {+    let mut sweep = ea - sa;+    while sweep <= 0.0 { sweep += 360.0; }+    if sweep >= 359.9 {+        // full circle — two half arcs (a single arc command can't close)+        return format!("M {:.4} {:.4} A {r:.4} {r:.4} 0 1 0 {:.4} {:.4} A {r:.4} {r:.4} 0 1 0 {:.4} {:.4} Z",+            cx - r, cy, cx + r, cy, cx - r, cy);+    }+    let pt = |deg: f64| (cx + r * deg.to_radians().cos(), cy - r * deg.to_radians().sin());+    let (x1, y1) = pt(sa);+    let (x2, y2) = pt(ea);+    let large = if sweep > 180.0 { 1 } else { 0 };+    format!("M {:.4} {:.4} A {r:.4} {r:.4} 0 {} 0 {:.4} {:.4}", x1, y1, large, x2, y2)+}
src/app.htmladded+174
@@ -0,0 +1,174 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>adom-2dboard</title>+<style>+  /* Canonical Adom design tokens (adom-ui-design). Legacy names kept as aliases.+     Primary accent #00b8b0; #00e6dc is the bright hover variant. */+  :root { color-scheme: dark;+    --bg:#0d1117; --panel:#161b22; --elevated:#1c2128; --overlay:#21262d; --edge:#30363d;+    --ink:#e6edf3; --mut:#8b949e; --acc:#00b8b0; --acc2:#00e6dc;+    --green:#3fb950; --red:#f85149; --yellow:#d29922; --hl:#4ff0e6;+    --line:var(--edge); --txt:var(--ink); --muted:var(--mut); --accent:var(--acc); }+  * { box-sizing: border-box; }+  /* Three fonts by role: body Satoshi, headers Familjen Grotesk, data JetBrains Mono. */+  html, body { margin: 0; height: 100%; background: var(--bg); color: var(--txt); font: 13px/1.45 'Satoshi', -apple-system, 'Segoe UI', Roboto, sans-serif; overflow: hidden; }+  #svgbox { position: absolute; inset: 0; cursor: grab; }+  #svgbox:active { cursor: grabbing; }+  #svgbox svg { display: block; }+  .empty { position: absolute; inset: 0; display: grid; place-items: center; color: var(--muted); }++  /* overlay is invisible until hovered / net-highlighted; only pads+vias+traces take pointer events.+     pointer-events:FILL (not all) so the hit area is the pad SHAPE only — `all` would include the+     phantom 1mm default stroke and make the hit zone ~2.5mm wide. */+  #svgbox svg .adom-overlay .adom-pad .pad-body, #svgbox svg .adom-overlay .adom-via .pad-body { pointer-events: fill; cursor: pointer; }+  #svgbox svg .adom-overlay .ov-trace { pointer-events: stroke; cursor: pointer; }+  /* fills are clickable (select the net) but never hovered — hover only targets pads/vias */+  #svgbox svg .adom-overlay .ov-zone { pointer-events: fill; cursor: pointer; }+  /* ── hover: gentle white outline on the single pad/via ── */+  #svgbox svg .adom-pad.pad-hl .pad-body { stroke: #fff !important; stroke-width: .07; paint-order: stroke; }+  #svgbox svg .adom-via.pad-hl .pad-body { stroke: #fff !important; stroke-width: .05; }+  /* cross-probe: the part selected from the schematic view — bright accent outline+     on all of its pads so the whole footprint reads as "this component". */+  #svgbox svg .adom-pad.comp-xhl .pad-body { stroke: var(--acc2) !important; stroke-width: .14 !important; paint-order: stroke; }+  /* ── click net: dim every base layer; show the selected net's copper EXACTLY as on the+        PCB (solid traces w/ round joins, real pads w/ drill holes), just in focus. No+        outlines, no brightness boost, no transition (that caused the shrink). ── */+  #svgbox svg.dim .adom-flip > g[class*="adom-layer-"] { opacity: .16 !important; }+  #svgbox svg .adom-overlay .ov-trace.hl { stroke: var(--hlc) !important; }+  #svgbox svg .adom-overlay .ov-zone.hl { fill: var(--hlc) !important; fill-opacity: .3 !important; stroke: none !important; }+  #svgbox svg .adom-overlay .adom-pad.hl .pad-body, #svgbox svg .adom-overlay .adom-via.hl .pad-body { fill: var(--hlc) !important; }+  #svgbox svg .adom-overlay .adom-pad.hl .pad-hole, #svgbox svg .adom-overlay .adom-via.hl .pad-hole { fill: #161b22 !important; }++  /* ── chrome ── */+  .panel { position: absolute; background: rgba(22,27,34,.82); backdrop-filter: blur(8px); border: 1px solid var(--line); border-radius: 10px; }+  /* single right-side panel: Layers section on top, Nets below */+  #side { top: 12px; right: 12px; width: 212px; max-height: 94vh; padding: 10px 12px; display: flex; flex-direction: column; }+  #side h1 { margin: 0 0 8px; font-size: 12px; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); font-weight: 600; }+  .sec { margin-bottom: 10px; min-height: 0; display: flex; flex-direction: column; }+  .sec-h { font-size: 10px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); font-weight: 600; margin: 2px 0 5px; border-bottom: 1px solid var(--line); padding-bottom: 3px; }+  #layers { max-height: 42vh; overflow-y: auto; }+  #netlist { max-height: 30vh; overflow-y: auto; }+  .lyr { display: flex; align-items: center; gap: 7px; padding: 2px 0; cursor: pointer; user-select: none; }+  .lyr input { accent-color: var(--accent); }+  #fitbtn { margin-top: 4px; width: 100%; background: #17231c; color: var(--txt); border: 1px solid var(--line); border-radius: 7px; padding: 5px; cursor: pointer; }+  #fitbtn:hover { border-color: var(--accent); }+  #sidebtns { display: flex; align-items: center; gap: 4px; margin-bottom: 8px; }+  #sidebtns .lbl { color: var(--muted); font-size: 11px; margin-right: auto; }+  .sidebtn { background: #17231c; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; padding: 2px 8px; cursor: pointer; font-size: 11px; }+  .sidebtn.on { background: var(--accent); color: #111; border-color: var(--accent); font-weight: 600; }+  .lyr-name { cursor: pointer; }+  .lyr-name:hover { color: var(--accent); text-decoration: underline; }+  /* the copper layer currently raised to the front (click its name again to reset) */+  .lyr.raised .lyr-name { color: var(--accent); font-weight: 600; }+  .lyr.raised .lyr-name::after { content: " \2191"; }+  .netrow { padding: 3px 7px; border-radius: 5px; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-variant-numeric: tabular-nums; }+  .netrow:hover { background: #1c2a22; color: var(--hl); }+  .netrow.sel { background: var(--accent); color: #06232a; font-weight: 600; }+  .netrow.sel:hover { color: #06232a; }++  #stat { bottom: 12px; left: 12px; padding: 6px 11px; color: var(--muted); font-variant-numeric: tabular-nums; }+  #netchip { bottom: 12px; left: 50%; transform: translateX(-50%); padding: 6px 13px; display: none; }+  #netchip b { color: var(--accent); text-transform: uppercase; font-size: 10px; letter-spacing: .06em; margin-right: 4px; }+  .muted { color: var(--muted); }++  /* ── component info card ── */+  #card { position: fixed; z-index: 9999; display: none; min-width: 180px; max-width: 260px; padding: 10px 12px; pointer-events: none; }+  .ci-h { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 6px; padding-bottom: 6px; border-bottom: 1px solid var(--line); }+  .ci-ref { font-weight: 700; color: var(--accent); font-size: 14px; }+  .ci-val { color: var(--txt); }+  .ci-row { display: flex; justify-content: space-between; gap: 10px; padding: 1px 0; }+  .ci-k { color: var(--muted); }+  .ci-v { text-align: right; word-break: break-word; }+  .ci-enrich { margin-top: 7px; padding-top: 7px; border-top: 1px solid var(--line); }+  .pills { display: flex; flex-wrap: wrap; gap: 5px; }+  .pill { background: #17231c; border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px; font-size: 11px; }+  .pill.ok { color: #57d97e; border-color: #2c5a3a; }+  .pill.no { color: #e08a8a; border-color: #5a2c2c; }+  .pill.tier { color: #f2d060; }+  .pill.pop { color: #cba6ff; }+  .ci-wiki { display: inline-block; margin-top: 6px; color: #6bb3ff; text-decoration: none; }+  #side h1, .sec-h { font-family: 'Familjen Grotesk', -apple-system, sans-serif; }++  /* ── canonical Adom 44px three-zone header (brand · subject · actions) ── */+  header.app { display: none; position: fixed; top: 0; left: 0; right: 0; height: 44px; z-index: 50;+    grid-template-columns: 1fr auto 1fr; align-items: center; gap: 12px; padding: 0 14px;+    background: var(--panel); border-bottom: 1px solid var(--edge); }+  body.chrome header.app { display: grid; }+  body.chrome #svgbox { top: 44px; }+  body.chrome #side { top: 56px; }+  header.app .brand { display: flex; align-items: center; gap: 8px; min-width: 0; position: relative; cursor: default; padding-right: 14px; border-right: 1px solid var(--edge); }+  header.app .brand svg { width: 16px; height: 16px; color: var(--ink); flex: 0 0 16px; }+  header.app .app-name { font-family: 'Familjen Grotesk', -apple-system, sans-serif; font-weight: 600; font-size: 13px; color: var(--acc); white-space: nowrap; }+  header.app .app-sub { color: var(--mut); font-size: 12px; white-space: nowrap; }+  header.app .app-sub::before { content: "·"; margin: 0 6px; color: var(--mut); }+  header.app .subject { justify-self: center; display: flex; align-items: baseline; gap: 10px; min-width: 0; }+  header.app .subject-name { font-weight: 600; font-size: 13px; max-width: 44vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+  header.app .subject-meta { font-family: 'JetBrains Mono', ui-monospace, monospace; font-size: 11px; color: var(--mut); white-space: nowrap; }+  header.app .actions { justify-self: end; display: flex; align-items: center; gap: 8px; }+  header.app .actions button { background: var(--elevated); color: var(--ink); border: 1px solid var(--edge); border-radius: 7px; width: 30px; height: 26px; cursor: pointer; display: grid; place-items: center; }+  header.app .actions button:hover { border-color: var(--acc); }+  header.app .actions button svg { width: 15px; height: 15px; }+  header.app .appinfo { position: absolute; top: calc(100% + 6px); left: 0; min-width: 220px; background: var(--overlay); border: 1px solid var(--edge);+    border-radius: 10px; box-shadow: 0 12px 34px #000a; padding: 12px 14px; font-size: 12px; opacity: 0; visibility: hidden; transition: opacity .18s ease; pointer-events: none; z-index: 60; }+  header.app .brand:hover .appinfo { opacity: 1; visibility: visible; pointer-events: auto; transition-delay: .6s; }+  header.app .appinfo .ai-row { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }+  header.app .appinfo .ai-k { color: var(--mut); }+  header.app .appinfo .ai-v { font-family: 'JetBrains Mono', ui-monospace, monospace; }+  header.app .appinfo a { color: var(--acc); text-decoration: none; }+  header.app .appinfo a:hover { text-decoration: underline; }++  /* ── toasts: transient feedback, bottom-center; also the AI's live channel ── */+  #toasts { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); z-index: 3000; display: flex; flex-direction: column-reverse; gap: 8px; align-items: center; pointer-events: none; }+  .toast { pointer-events: auto; min-width: 200px; max-width: min(420px,90vw); display: flex; align-items: center; gap: 10px; padding: 10px 13px; border-radius: 10px;+    background: var(--overlay); border: 1px solid var(--edge); color: var(--ink); font-size: 13px; box-shadow: 0 10px 30px #000a; cursor: pointer; animation: toastin .18s ease; }+  @keyframes toastin { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }+  .toast.out { opacity: 0; transform: translateY(8px); transition: opacity .2s ease, transform .2s ease; }+  .toast .ti { flex: 0 0 16px; width: 16px; height: 16px; }+  .toast.success .ti { color: var(--green); } .toast.success { border-color: #2c5a3a; }+  .toast.error .ti { color: var(--red); } .toast.error { border-color: #5a2c2c; }+  .toast.info .ti { color: var(--acc); }+  .toast .tmsg { flex: 1; min-width: 0; }++  /* ── tooltips: body-appended fixed div, 600ms reveal, clamped both axes ── */+  #tt { position: fixed; z-index: 99999; max-width: 260px; background: var(--overlay); color: var(--ink); border: 1px solid var(--edge);+    border-radius: 7px; padding: 6px 9px; font-size: 12px; line-height: 1.4; box-shadow: 0 8px 22px #000b; pointer-events: none;+    opacity: 0; transform: translateY(3px); transition: opacity .18s ease, transform .18s ease; text-transform: none; }+  #tt.show { opacity: 1; transform: none; }+  @media (hover: none), (pointer: coarse) { #tt { display: none; } }+</style>+</head>+<body>+  <header class="app">+    <div class="brand">+      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="1.5"/><path d="M7 8h4v4H7zM14 14h3M15.5 8v4"/><circle cx="17" cy="8" r="1.1"/></svg>+      <span class="app-name">PCB Viewer</span><span class="app-sub">interactive layout</span>+      <div class="appinfo">+        <div class="ai-row"><span class="ai-k">version</span><span class="ai-v" id="ai-ver">-</span></div>+        <div class="ai-row"><span class="ai-k">engine</span><span class="ai-v">KiCad · Altium · Fusion</span></div>+        <div class="ai-row"><span class="ai-k">source</span><a href="https://wiki.adom.inc/adom/adom-2dboard" target="_blank" rel="noopener">wiki page ↗</a></div>+      </div>+    </div>+    <div class="subject"><span class="subject-name" id="hdr-name"></span><span class="subject-meta" id="hdr-meta"></span></div>+    <div class="actions">+      <button id="hdr-fit" data-tip="Fit the whole board to the view"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg></button>+    </div>+  </header>+  <div id="svgbox"><div class="empty">loading…</div></div>++  <div id="side" class="panel">+    <div class="sec"><div class="sec-h">Layers</div><div id="layers"></div></div>+    <div class="sec"><div class="sec-h">Nets</div><div id="netlist"></div></div>+    <button id="fitbtn" data-tip="Zoom to fit the entire board">Fit</button>+  </div>++  <div id="stat" class="panel"></div>+  <div id="netchip" class="panel"></div>+  <div id="card" class="panel"></div>+  <div id="toasts"></div>++  <script src="viewer.js"></script>+</body>+</html>
src/eagle.rsadded+375
@@ -0,0 +1,375 @@+//! Fusion 360 Electronics / EAGLE `.brd` board parser.+//!+//! Fusion Electronics is EAGLE underneath: `fusion_export_eagle_source` writes a+//! plain-XML `.brd`, so one parser covers both EDAs. We build the SAME neutral+//! `Board` model the KiCad parser produces, which means net highlighting, pad+//! hover, the overlay and the embed all work unchanged.+//!+//! Coordinates: EAGLE XML is already in **mm**, but its Y axis points UP while+//! ours (like KiCad's) points DOWN — so every Y is negated on the way in. Angles+//! are counter-clockwise in EAGLE, clockwise for us, hence the rotation negation.+//!+//! Unlike KiCad there is no native SVG export to sit under the overlay (Fusion+//! has no headless renderer), so these boards use our own self-render — the same+//! one that already backstops KiCad when service-kicad is down.++use crate::pcb_render::{Arc, Board, Comp, Gfx, Pad, Track, Via, ZonePoly};+use roxmltree::{Document, Node};+use std::collections::HashMap;+use std::fmt::Write as _;++pub fn looks_like_eagle(text: &str) -> bool {+    let head = &text[..text.len().min(4096)];+    head.contains("<eagle") && text.contains("<board")+}++fn at(n: Node, k: &str) -> String { n.attribute(k).unwrap_or("").to_string() }+fn num(n: Node, k: &str) -> f64 { n.attribute(k).and_then(|v| v.parse().ok()).unwrap_or(0.0) }++fn esc(s: &str) -> String {+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")+}++/// Render one on-board label (element NAME / VALUE) as an SVG `<text>` string,+/// honouring EAGLE `size`/`align`/`rot` incl. the R180 "keep-readable" rule (so a+/// smashed label at R180 doesn't render upside down / flow the wrong way). `x,y`+/// are already board coords (Y-down).+#[allow(clippy::too_many_arguments)]+fn sr_text(x: f64, y: f64, text: &str, size: f64, color: &str, rot: f64, align: &str, mirror: bool) -> String {+    if text.is_empty() { return String::new(); }+    let a = if align.is_empty() { "bottom-left" } else { align };+    let (mut valign, mut halign) = ("bottom", "left");+    if a == "center" { valign = "center"; halign = "center"; }+    else { for p in a.split('-') { match p { "top" | "center" | "bottom" => valign = p, "left" | "right" => halign = p, _ => {} } } }+    let mut r = ((rot % 360.0) + 360.0) % 360.0;+    if mirror { halign = if halign == "left" { "right" } else if halign == "right" { "left" } else { halign }; r = (360.0 - r) % 360.0; }+    let mut gr = r;+    if r > 90.0 && r <= 270.0 {+        gr = r - 180.0;+        halign = if halign == "left" { "right" } else if halign == "right" { "left" } else { halign };+        valign = if valign == "top" { "bottom" } else if valign == "bottom" { "top" } else { valign };+    }+    let anchor = match halign { "center" => "middle", "right" => "end", _ => "start" };+    let baseline = match valign { "center" => "central", "top" => "hanging", _ => "auto" };+    let tf = if gr.abs() > 0.01 { format!(r##" transform="rotate({:.2} {:.3} {:.3})""##, gr, x, y) } else { String::new() };+    format!(r##"<text x="{:.3}" y="{:.3}" font-size="{:.3}" fill="{}" text-anchor="{}" dominant-baseline="{}"{}>{}</text>"##,+        x, y, size.max(0.4), color, anchor, baseline, tf, esc(text))+}++/// EAGLE layer number -> our layer bucket.+fn layer_of(n: i32) -> &'static str {+    match n {+        1 => "F.Cu",+        16 => "B.Cu",+        2..=15 => "In.Cu",+        17 | 18 => "F.Cu",         // Pads / Vias layers+        20 => "Edge",              // Dimension+        21 | 25 => "F.SilkS",      // tPlace / tNames+        22 | 26 => "B.SilkS",      // bPlace / bNames+        27 => "F.SilkS",           // tValues+        28 => "B.SilkS",+        39 | 41 => "F.Keepout",    // tKeepout / tRestrict — Fusion draws these hatched+        40 | 42 => "B.Keepout",+        51 => "F.Fab",             // tDocu+        52 => "B.Fab",+        _ => "",+    }+}++/// EAGLE rotation strings: "R90", "MR90" (mirrored), "SR90" (spin).+fn rot_of(s: &str) -> (f64, bool) {+    let mirror = s.contains('M');+    let deg = s.trim_start_matches(['M', 'S', 'R'])+        .parse::<f64>()+        .unwrap_or_else(|_| s.chars().filter(|c| c.is_ascii_digit() || *c == '.' || *c == '-').collect::<String>().parse().unwrap_or(0.0));+    (deg, mirror)+}++/// Place a package-local point into board coordinates.+/// Mirroring flips X in the package frame (EAGLE mirrors about the Y axis).+fn place(px: f64, py: f64, ex: f64, ey: f64, deg: f64, mirror: bool) -> (f64, f64) {+    let x = if mirror { -px } else { px };+    let r = deg.to_radians();+    let (s, c) = (r.sin(), r.cos());+    let (rx, ry) = (x * c - py * s, x * s + py * c);+    // negate Y last: EAGLE is Y-up, we are Y-down+    (ex + rx, -(ey + ry))+}++/// An arc from (x1,y1) to (x2,y2) with EAGLE's `curve` (included angle, degrees).+fn curve_path(x1: f64, y1: f64, x2: f64, y2: f64, curve: f64) -> String {+    let (dx, dy) = (x2 - x1, y2 - y1);+    let chord = (dx * dx + dy * dy).sqrt();+    if chord < 1e-9 || curve.abs() < 1e-9 {+        return format!("M {:.4} {:.4} L {:.4} {:.4}", x1, y1, x2, y2);+    }+    let half = (curve.abs().to_radians()) / 2.0;+    let r = (chord / 2.0) / half.sin().max(1e-9);+    let large = if curve.abs() > 180.0 { 1 } else { 0 };+    // EAGLE curve is CCW-positive; our Y is already flipped, which reverses the+    // apparent sweep, so a positive curve draws with sweep=1 here.+    let sweep = if curve > 0.0 { 1 } else { 0 };+    format!("M {:.4} {:.4} A {:.4} {:.4} 0 {} {} {:.4} {:.4}", x1, y1, r.abs(), r.abs(), large, sweep, x2, y2)+}++struct Pkg<'a, 'i> { nodes: Vec<Node<'a, 'i>> }++pub fn parse_brd(xml: &str) -> Result<Board, String> {+    let opts = roxmltree::ParsingOptions { allow_dtd: true, ..Default::default() };+    let doc = Document::parse_with_options(xml, opts).map_err(|e| format!("eagle .brd: {e}"))?;+    let root = doc.root_element();+    let board = root.descendants().find(|n| n.has_tag_name("board")).ok_or("eagle: no <board>")?;+    let mut b = Board::default();++    // ── packages, keyed "library:package" ────────────────────────────────────+    let mut pkgs: HashMap<String, Pkg> = HashMap::new();+    for lib in board.descendants().filter(|n| n.has_tag_name("library")) {+        let lname = at(lib, "name");+        for p in lib.descendants().filter(|n| n.has_tag_name("package")) {+            pkgs.insert(format!("{}:{}", lname, at(p, "name")), Pkg { nodes: p.children().filter(|c| c.is_element()).collect() });+        }+    }++    // ── nets: one id per <signal>, plus (element,pad) -> net ─────────────────+    let mut pad_net: HashMap<(String, String), u32> = HashMap::new();+    let signals: Vec<Node> = board.descendants().filter(|n| n.has_tag_name("signal")).collect();+    for (i, sig) in signals.iter().enumerate() {+        let id = (i + 1) as u32;+        b.nets.insert(id, at(*sig, "name"));+        for cr in sig.children().filter(|c| c.has_tag_name("contactref")) {+            pad_net.insert((at(cr, "element"), at(cr, "pad")), id);+        }+    }++    // ── routing inside signals: wires (tracks/arcs), vias, copper polygons ───+    for (i, sig) in signals.iter().enumerate() {+        let net = (i + 1) as u32;+        for w in sig.children().filter(|c| c.has_tag_name("wire")) {+            let layer = layer_of(num(w, "layer") as i32);+            if !layer.ends_with(".Cu") { continue; }+            let (x1, y1) = (num(w, "x1"), -num(w, "y1"));+            let (x2, y2) = (num(w, "x2"), -num(w, "y2"));+            let width = num(w, "width");+            let curve = num(w, "curve");+            if curve.abs() > 1e-9 {+                b.arcs.push(Arc { d: curve_path(x1, y1, x2, y2, -curve), layer: layer.into(), width, net });+            } else {+                b.tracks.push(Track { x1, y1, x2, y2, width, layer: layer.into(), net });+            }+        }+        for v in sig.children().filter(|c| c.has_tag_name("via")) {+            let drill = num(v, "drill");+            let size = if num(v, "diameter") > 0.0 { num(v, "diameter") } else { drill + 0.5 };+            b.vias.push(Via { x: num(v, "x"), y: -num(v, "y"), size, drill, net });+        }+        for poly in sig.children().filter(|c| c.has_tag_name("polygon")) {+            let layer = layer_of(num(poly, "layer") as i32);+            if !layer.ends_with(".Cu") { continue; }+            let pts: Vec<(f64, f64)> = poly.children().filter(|c| c.has_tag_name("vertex"))+                .map(|v| (num(v, "x"), -num(v, "y"))).collect();+            if pts.len() < 3 { continue; }+            let mut d = String::new();+            for (i, (x, y)) in pts.iter().enumerate() {+                let _ = write!(d, "{} {:.4} {:.4} ", if i == 0 { "M" } else { "L" }, x, y);+            }+            d.push('Z');+            b.zones.push(ZonePoly { d, layer: layer.into(), net, outline: false });+        }+    }++    // ── board outline + free graphics from <plain> ───────────────────────────+    for n in board.children().filter(|c| c.has_tag_name("plain")).flat_map(|p| p.children()) {+        if !n.is_element() { continue; }+        push_plain(&mut b, n);+    }++    // ── elements: place package geometry, resolve pads ───────────────────────+    for el in board.descendants().filter(|n| n.has_tag_name("element")) {+        let name = at(el, "name");+        let (ex, ey) = (num(el, "x"), num(el, "y"));+        let (deg, mirror) = rot_of(&at(el, "rot"));+        let key = format!("{}:{}", at(el, "library"), at(el, "package"));+        let side = if mirror { 'B' } else { 'F' };+        let mut pad_count = 0usize;+        // bbox is accumulated from PLACED points as we go — never by re-parsing+        // numbers back out of a path `d` (arc radii would be read as coordinates)+        let mut ext: Vec<(f64, f64)> = Vec::new();++        if let Some(pkg) = pkgs.get(&key) {+            for n in &pkg.nodes {+                let n = *n;+                match n.tag_name().name() {+                    // THT pad+                    "pad" => {+                        let (x, y) = place(num(n, "x"), num(n, "y"), ex, ey, deg, mirror);+                        let dia = if num(n, "diameter") > 0.0 { num(n, "diameter") } else { num(n, "drill") * 1.8 };+                        let shape = match at(n, "shape").as_str() {+                            "square" => "rect", "octagon" => "roundrect", "long" => "oval", _ => "circle",+                        };+                        let (w, h) = if shape == "oval" { (dia * 2.0, dia) } else { (dia, dia) };+                        let numname = at(n, "name");+                        let net = *pad_net.get(&(name.clone(), numname.clone())).unwrap_or(&0);+                        ext.push((x - w / 2.0, y - h / 2.0)); ext.push((x + w / 2.0, y + h / 2.0));+                        pad_count += 1;+                        b.pads.push(Pad {+                            reference: name.clone(), num: numname, net, x, y,+                            rot: -(deg + num(n, "rot")), w, h,+                            shape: shape.into(), drill: num(n, "drill"), mount: "thru_hole".into(), side: 'F',+                        });+                    }+                    // SMD pad+                    "smd" => {+                        let (x, y) = place(num(n, "x"), num(n, "y"), ex, ey, deg, mirror);+                        let numname = at(n, "name");+                        let net = *pad_net.get(&(name.clone(), numname.clone())).unwrap_or(&0);+                        let lay = num(n, "layer") as i32;+                        let pside = if (lay == 16) != mirror { 'B' } else { 'F' };+                        let shape = if num(n, "roundness") > 0.0 { "roundrect" } else { "rect" };+                        let (pw, ph) = (num(n, "dx"), num(n, "dy"));+                        ext.push((x - pw / 2.0, y - ph / 2.0)); ext.push((x + pw / 2.0, y + ph / 2.0));+                        pad_count += 1;+                        b.pads.push(Pad {+                            reference: name.clone(), num: numname, net, x, y,+                            rot: -(deg + num(n, "rot")), w: pw, h: ph,+                            shape: shape.into(), drill: 0.0, mount: "smd".into(), side: pside,+                        });+                    }+                    _ => {+                        if let Some((g, layer, pts)) = gfx_of(n, ex, ey, deg, mirror) {+                            ext.extend(pts);+                            push_layer(&mut b, layer, g, side);+                        }+                    }+                }+            }+        }++        let bbox = if ext.is_empty() {+            [ex - 0.5, -ey - 0.5, ex + 0.5, -ey + 0.5]+        } else {+            let (mut mnx, mut mny, mut mxx, mut mxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);+            for (x, y) in &ext { mnx = mnx.min(*x); mxx = mxx.max(*x); mny = mny.min(*y); mxy = mxy.max(*y); }+            [mnx, mny, mxx, mxy]+        };+        // On-board silk labels: element name (light) + value (dimmer), like Fusion.+        let elval = at(el, "value");+        emit_label(&mut b, el, "NAME", &name, deg, mirror, ex, ey, pkgs.get(&key), "#c8ccd2");+        emit_label(&mut b, el, "VALUE", &elval, deg, mirror, ex, ey, pkgs.get(&key), "#9aa0a8");+        b.comps.push(Comp {+            reference: name,+            value: at(el, "value"),+            footprint: at(el, "package"),+            side: if side == 'B' { "bottom".into() } else { "top".into() },+            mpn: String::new(),+            lcsc: String::new(),+            x: ex, y: -ey,+            bbox,+            pad_count,+        });+    }++    Ok(b)+}++/// Emit an element's on-board NAME / VALUE label into the silk text lists. Prefers+/// the element's smashed `<attribute>` (absolute coords + its own size/align/rot);+/// falls back to the package's `>NAME`/`>VALUE` text placeholder placed by the+/// element. Layer routes it to the front or back silk.+#[allow(clippy::too_many_arguments)]+fn emit_label(b: &mut Board, el: Node, which: &str, text: &str, deg: f64, mirror: bool, ex: f64, ey: f64, pkg: Option<&Pkg>, color: &str) {+    if let Some(a) = el.children().find(|c| c.has_tag_name("attribute") && at(*c, "name").eq_ignore_ascii_case(which)) {+        let sz = if num(a, "size") > 0.0 { num(a, "size") } else { 0.8 };+        let (lx, ly) = (num(a, "x"), -num(a, "y"));+        let e = (text.chars().count() as f64 * sz * 0.7).max(sz) + 0.5;+        b.label_pts.push((lx - e, ly - e)); b.label_pts.push((lx + e, ly + e));+        let t = sr_text(lx, ly, text, sz, color, rot_of(&at(a, "rot")).0, &at(a, "align"), false);+        if matches!(num(a, "layer") as i32, 22 | 26 | 28) { b.txt_b.push(t) } else { b.txt_f.push(t) }+        return;+    }+    let want = if which.eq_ignore_ascii_case("NAME") { ">NAME" } else { ">VALUE" };+    if let Some(pkg) = pkg {+        for n in &pkg.nodes {+            let n = *n;+            if n.has_tag_name("text") && n.text().unwrap_or("").trim().eq_ignore_ascii_case(want) {+                let (x, y) = place(num(n, "x"), num(n, "y"), ex, ey, deg, mirror);+                let sz = if num(n, "size") > 0.0 { num(n, "size") } else { 0.8 };+                let t = sr_text(x, y, text, sz, color, deg + rot_of(&at(n, "rot")).0, &at(n, "align"), mirror);+                if matches!(num(n, "layer") as i32, 22 | 26 | 28) { b.txt_b.push(t) } else { b.txt_f.push(t) }+                return;+            }+        }+    }+}++/// Free graphics on the board itself (outline on layer 20, silk, etc).+fn push_plain(b: &mut Board, n: Node) {+    if let Some((g, layer, _)) = gfx_of(n, 0.0, 0.0, 0.0, false) {+        push_layer(b, layer, g, 'F');+    }+}++fn push_layer(b: &mut Board, layer: &str, g: Gfx, side: char) {+    match layer {+        "Edge" => b.edges.push(g),+        // Keepout / restrict areas render as a hatched zone (Fusion's look), net 0.+        "F.Keepout" => b.zones.push(ZonePoly { d: g.d, layer: if side == 'B' { "B.Keepout".into() } else { "F.Keepout".into() }, net: 0, outline: false }),+        "B.Keepout" => b.zones.push(ZonePoly { d: g.d, layer: if side == 'B' { "F.Keepout".into() } else { "B.Keepout".into() }, net: 0, outline: false }),+        "F.SilkS" => { if side == 'B' { b.silk_b.push(g) } else { b.silk_f.push(g) } }+        "B.SilkS" => { if side == 'B' { b.silk_f.push(g) } else { b.silk_b.push(g) } }+        "F.Fab" => { if side == 'B' { b.fab_b.push(g) } else { b.fab_f.push(g) } }+        "B.Fab" => { if side == 'B' { b.fab_f.push(g) } else { b.fab_b.push(g) } }+        "F.CrtYd" => { if side == 'B' { b.crtyd_b.push(g) } else { b.crtyd_f.push(g) } }+        "B.CrtYd" => { if side == 'B' { b.crtyd_f.push(g) } else { b.crtyd_b.push(g) } }+        _ => {}+    }+}++/// Turn one EAGLE graphic element into an SVG path in board coordinates.+fn gfx_of(n: Node, ex: f64, ey: f64, deg: f64, mirror: bool) -> Option<(Gfx, &'static str, Vec<(f64, f64)>)> {+    let layer = layer_of(num(n, "layer") as i32);+    if layer.is_empty() || layer.ends_with(".Cu") { return None; }+    let p = |x: f64, y: f64| place(x, y, ex, ey, deg, mirror);+    match n.tag_name().name() {+        "wire" => {+            let (x1, y1) = p(num(n, "x1"), num(n, "y1"));+            let (x2, y2) = p(num(n, "x2"), num(n, "y2"));+            let curve = num(n, "curve");+            let d = if curve.abs() > 1e-9 { curve_path(x1, y1, x2, y2, -curve) }+                    else { format!("M {:.4} {:.4} L {:.4} {:.4}", x1, y1, x2, y2) };+            Some((Gfx { d, width: num(n, "width").max(0.05), closed_fill: false }, layer, vec![(x1, y1), (x2, y2)]))+        }+        "circle" => {+            let (cx, cy) = p(num(n, "x"), num(n, "y"));+            let r = num(n, "radius");+            let d = format!("M {:.4} {:.4} A {r:.4} {r:.4} 0 1 0 {:.4} {:.4} A {r:.4} {r:.4} 0 1 0 {:.4} {:.4} Z",+                cx - r, cy, cx + r, cy, cx - r, cy);+            Some((Gfx { d, width: num(n, "width").max(0.05), closed_fill: false }, layer, vec![(cx - r, cy - r), (cx + r, cy + r)]))+        }+        "rectangle" => {+            let (x1, y1) = (num(n, "x1"), num(n, "y1"));+            let (x2, y2) = (num(n, "x2"), num(n, "y2"));+            let corners = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)];+            let mut d = String::new();+            let mut pts = Vec::new();+            for (i, (x, y)) in corners.iter().enumerate() {+                let (px, py) = p(*x, *y);+                pts.push((px, py));+                let _ = write!(d, "{} {:.4} {:.4} ", if i == 0 { "M" } else { "L" }, px, py);+            }+            d.push('Z');+            Some((Gfx { d, width: 0.0, closed_fill: true }, layer, pts))+        }+        "polygon" => {+            let pts: Vec<(f64, f64)> = n.children().filter(|c| c.has_tag_name("vertex"))+                .map(|v| p(num(v, "x"), num(v, "y"))).collect();+            if pts.len() < 3 { return None; }+            let mut d = String::new();+            for (i, (x, y)) in pts.iter().enumerate() {+                let _ = write!(d, "{} {:.4} {:.4} ", if i == 0 { "M" } else { "L" }, x, y);+            }+            d.push('Z');+            Some((Gfx { d, width: num(n, "width"), closed_fill: true }, layer, pts))+        }+        _ => None, // <text>, <hole>, <dimension>, <attribute> — not stroke geometry+    }+}
src/enrich.rsadded+102
@@ -0,0 +1,102 @@+//! Component enrichment: MPN → { price, stock, tier, popularity, wiki_url }.+//!+//! Sources (sibling Adom CLIs, shelled with a hard timeout so a slow/absent CLI+//! never hangs the UI):+//!   • popularity + wiki page — `adom-wiki discover search --query <mpn> --json`+//!     (vouch_count / star_count → popularity; owner/slug → wiki_url)+//!   • price + stock — `adom-parts-search search <mpn>` (max stock across+//!     vendors; first real unit price; JLCPCB tier from flags)+//!+//! Because the vendor lookup is slow (~30 s, live APIs), the server PRE-WARMS the+//! cache for every board MPN in a background thread at load time; hover then hits+//! the cache. `lookup()` is the (slow) cache-fill; `/enrich` reads the result.++use serde_json::{json, Value};+use std::process::{Command, Stdio};+use std::sync::mpsc;+use std::time::Duration;++/// Run a command, capping wall-clock at `secs`. Returns stdout on success.+fn run_capped(bin: &str, args: &[&str], secs: u64) -> Option<String> {+    let bin = bin.to_string();+    let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();+    let (tx, rx) = mpsc::channel();+    std::thread::spawn(move || {+        let out = Command::new(&bin).args(&args).stdin(Stdio::null()).output();+        let _ = tx.send(out.ok().filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).into_owned()));+    });+    rx.recv_timeout(Duration::from_secs(secs)).ok().flatten()+}++/// Strip any leading non-JSON preamble (parts-search prints an "OK: …" summary+/// line before its JSON) and parse.+fn parse_json_tail(s: &str) -> Option<Value> {+    let start = s.find(['{', '['])?;+    serde_json::from_str(&s[start..]).ok()+}++/// The slow path: hit both CLIs and assemble the enrichment record as a JSON+/// string. Safe to call off-thread; degrades field-by-field.+pub fn lookup(mpn: &str, _lcsc: &str) -> String {+    let mut out = json!({});+    let o = out.as_object_mut().unwrap();++    // ── wiki page + popularity (vouches/score) ──+    if let Some(txt) = run_capped("adom-wiki", &["discover", "search", "--query", mpn, "--limit", "5", "--json"], 12) {+        if let Some(v) = parse_json_tail(&txt) {+            if let Some(results) = v.get("data").and_then(|d| d.get("results")).and_then(|r| r.as_array()) {+                // prefer an exact (case-insensitive) title/slug match, else the first component+                let pick = results.iter().find(|r| r.get("title").and_then(|t| t.as_str()).map(|t| t.eq_ignore_ascii_case(mpn)).unwrap_or(false))+                    .or_else(|| results.iter().find(|r| r.get("type").and_then(|t| t.as_str()) == Some("component")))+                    .or_else(|| results.first());+                if let Some(r) = pick {+                    let owner = r.get("owner").and_then(|x| x.as_str()).unwrap_or("");+                    let slug = r.get("slug").and_then(|x| x.as_str()).unwrap_or("");+                    if !slug.is_empty() {+                        o.insert("wiki_url".into(), json!(format!("https://wiki.adom.inc/{owner}/{slug}")));+                    }+                    let vouch = r.get("vouch_count").and_then(|x| x.as_i64()).unwrap_or(0);+                    let stars = r.get("star_count").and_then(|x| x.as_i64()).unwrap_or(0);+                    let installs = r.get("installs_30d").and_then(|x| x.as_i64()).unwrap_or(0);+                    o.insert("popularity".into(), json!(vouch.max(stars).max(installs)));+                }+            }+        }+    }++    // ── price + stock (parts-search across vendors) ──+    if let Some(txt) = run_capped("adom-parts-search", &["search", mpn, "--limit", "3"], 40) {+        if let Some(v) = parse_json_tail(&txt) {+            let mut best_stock: i64 = 0;+            let mut price: Option<String> = None;+            let mut tier: Option<String> = None;+            for vendor in ["mouser", "digikey", "jlcpcb"] {+                if let Some(hits) = v.get(vendor).and_then(|m| m.get("hits")).and_then(|h| h.as_array()) {+                    for h in hits {+                        best_stock = best_stock.max(h.get("stock").and_then(|s| s.as_i64()).unwrap_or(0));+                        if price.is_none() {+                            let up = h.get("unit_price").and_then(|p| p.as_f64())+                                .or_else(|| h.get("price_100").and_then(|p| p.as_f64()));+                            if let Some(p) = up { price = Some(format!("${:.3}", p)); }+                        }+                        if vendor == "jlcpcb" && tier.is_none() {+                            if let Some(flags) = h.get("flags").and_then(|f| f.as_array()) {+                                for f in flags {+                                    if let Some(fs) = f.as_str() {+                                        if ["Basic", "Preferred", "Extended"].contains(&fs) { tier = Some(fs.to_string()); }+                                    }+                                }+                            }+                        }+                    }+                }+            }+            o.insert("stock".into(), json!(best_stock));+            if let Some(p) = price { o.insert("price".into(), json!(p)); }+            if let Some(t) = tier { o.insert("tier".into(), json!(t)); }+        }+    }++    if o.is_empty() { return "{\"error\":\"no data\"}".into(); }+    out.to_string()+}
src/kicad.rsadded+165
@@ -0,0 +1,165 @@+//! Fetch a board's AUTHENTIC per-layer SVG from service-kicad (KiCad 10 headless).+//!+//! This is the visual base of the viewer: each layer rendered exactly as the EDA+//! draws it (real Newstroke silk, knockout, theme colours). We request one layer+//! at a time (`?layers=<L>`) so each comes back cleanly in its own theme colour+//! and we can wrap it in our own toggle/flip/dim group. All layers share the+//! board's mm coordinate system, so they align with each other AND with our+//! parsed interaction overlay (same viewBox).++use anyhow::{bail, Result};+use std::time::Duration;++const SERVICE_DEFAULT: &str = "https://kicad-rk5ue5pcfemi.adom.cloud";++pub struct KLayer {+    pub group: String, // our layer group class suffix+    pub side: char,    // 'F' | 'B' | 'I' (inner) | 'X' (shared)+    pub inner: String, // the KiCad SVG content (between <svg> and </svg>)+}++/// (KiCad layer name, our group class, side). Order here is z-order bottom→top;+/// the frontend re-orders F/B when flipping sides.+// Mask sits BELOW copper (so pads read as copper, not mask-purple).+const LAYERS: &[(&str, &str, char)] = &[+    ("B.Fab", "fabB", 'B'),+    ("B.Mask", "maskB", 'B'),+    ("B.Cu", "copperB", 'B'),+    ("B.SilkS", "silkB", 'B'),+    ("F.Mask", "maskF", 'F'),+    ("F.Cu", "copperF", 'F'),+    ("F.SilkS", "silkF", 'F'),+    ("F.Fab", "fabF", 'F'),+    ("B.CrtYd", "crtydB", 'B'),+    ("F.CrtYd", "crtydF", 'F'),+    ("Edge.Cuts", "edge", 'X'),+];++/// Inner copper layers (`In1.Cu`, `In2.Cu`, …) declared in the board's stackup,+/// ordered as they sit physically from the FRONT downwards. A 4-layer board gives+/// `["In1.Cu", "In2.Cu"]`. Returns empty for a plain 2-layer board.+///+/// These are NOT in `LAYERS` because the set is board-specific — a 2/4/6-layer+/// board must not request layers it doesn't have (and a 4-layer board whose pours+/// live only on In1/In2, like the USB3-to-Ethernet molecule, would otherwise show+/// no copper fills at all).+pub fn inner_copper_layers(board: &str) -> Vec<String> {+    let re = regex::Regex::new(r#"\((\d+)\s+"(In\d+\.Cu)"#).unwrap();+    let mut v: Vec<(u32, String)> = re+        .captures_iter(board)+        .filter_map(|c| c[1].parse::<u32>().ok().map(|n| (n, c[2].to_string())))+        .collect();+    v.sort_by_key(|(_, name)| {+        name.trim_start_matches("In").trim_end_matches(".Cu").parse::<u32>().unwrap_or(0)+    });+    v.dedup_by(|a, b| a.1 == b.1);+    v.into_iter().map(|(_, name)| name).collect()+}++/// Our group-class suffix for an inner copper layer: `In1.Cu` -> `copperIn1`.+pub fn inner_group(layer: &str) -> String {+    format!("copper{}", layer.trim_end_matches(".Cu"))+}++fn base() -> String {+    std::env::var("KICAD_SERVICE_API")+        .unwrap_or_else(|_| SERVICE_DEFAULT.to_string())+        .trim_end_matches('/')+        .to_string()+}++/// Fetch every board layer. Errors (or an empty result) let the caller fall back+/// to the self-render path.+pub fn fetch_all(board: &str) -> Result<Vec<KLayer>> {+    let base = base();+    let mut out = Vec::new();++    // Base layers, plus this board's inner copper layers. Inner layers are inserted+    // directly after B.Cu in z-order (bottom->top when viewed from the top), i.e.+    // B.Cu, In(n) .. In1, F.Cu — deepest first. The frontend re-orders on flip.+    let inners = inner_copper_layers(board);+    let mut plan: Vec<(String, String, char)> =+        LAYERS.iter().map(|(l, g, s)| (l.to_string(), g.to_string(), *s)).collect();+    if let Some(at) = plan.iter().position(|(l, _, _)| l == "B.Cu") {+        // reverse: the layer nearest the BACK goes lowest in the stack+        for layer in inners.iter().rev() {+            plan.insert(at + 1, (layer.clone(), inner_group(layer), 'I'));+        }+    }++    for (layer, group, side) in &plan {+        let url = format!("{base}/kicad/pcb/export/svg?layers={layer}");+        match ureq::post(&url)+            .set("Content-Type", "application/octet-stream")+            .timeout(Duration::from_secs(30))+            .send_bytes(board.as_bytes())+        {+            Ok(resp) => {+                if let Ok(svg) = resp.into_string() {+                    let mut inner = extract_inner(&svg);+                    // On copper: make the ZONE POUR translucent (traces/pads stay solid),+                    // and recolor KiCad's WHITE drill holes (via/pad barrels) to the dark+                    // board colour so via insides read black, not white.+                    if group.starts_with("copper") {+                        inner = dim_pours(&inner);+                        inner = inner.replace("fill:#FFFFFF", "fill:#0b0e13").replace("fill:#ffffff", "fill:#0b0e13");+                    }+                    if inner.contains("<path") || inner.contains("<circle") {+                        out.push(KLayer { group: group.clone(), side: *side, inner });+                    }+                }+            }+            Err(e) => eprintln!("[kicad] layer {layer}: {e}"),+        }+    }+    if out.is_empty() {+        bail!("service-kicad returned no usable layers");+    }+    Ok(out)+}++/// Make copper zone POURS translucent while leaving traces (stroked, no fill) and+/// pads (small filled paths) solid. Heuristic: a filled path with many `L`+/// segments is a pour; give it a low fill-opacity via an inline style.+fn dim_pours(inner: &str) -> String {+    // KiCad draws each shape as its own `<path style="fill:#…; fill-opacity:1.0000; …">`+    // with the polygon as `M x,y\n x,y … Z` (one comma per vertex). A pour has many+    // vertices; pads/traces have few. For big FILLED paths, knock the fill down.+    //+    // THRESHOLD: measured on the USB3-to-Ethernet molecule (KiCad 10) — the largest+    // PAD on F.Cu is 28 vertices (U3, a SOT-223 tab), while the In1.Cu GND pour is+    // 4182. The old cutoff of 20 sat BELOW the biggest pads, so it dimmed U3's four+    // pads to 28% and the magenta F.Mask beneath showed through: they read as+    // translucent pink instead of copper red. 200 sits ~7x above the largest pad and+    // ~20x below a real pour.+    //+    // Deliberately NOT keyed on `fill-rule:evenodd` — 152 F.Cu paths carry it on a+    // board with zero front pours, so it does not discriminate.+    //+    // Known limit: a very small copper island zone (< ~200 verts) renders solid+    // rather than translucent. That is a cosmetic miss, and far preferable to+    // dimming real pads.+    const POUR_MIN_VERTS: usize = 200;+    let re = regex::Regex::new(r#"<path\b[^>]*>"#).unwrap();+    re.replace_all(inner, |c: &regex::Captures| {+        let tag = &c[0];+        let is_fill = tag.contains("fill:#");+        let verts = tag.matches(',').count(); // ≈ polygon vertices (style has no commas)+        if is_fill && verts > POUR_MIN_VERTS {+            tag.replacen("fill-opacity:1.0000", "fill-opacity:0.28", 1)+        } else {+            tag.to_string()+        }+    })+    .into_owned()+}++/// Keep the content between the opening `<svg …>` and the closing `</svg>`.+fn extract_inner(svg: &str) -> String {+    let open_end = match svg.find("<svg").and_then(|s| svg[s..].find('>').map(|e| s + e + 1)) {+        Some(i) => i,+        None => return String::new(),+    };+    let close = svg.rfind("</svg>").unwrap_or(svg.len());+    svg[open_end..close].to_string()+}
src/main.rsadded+200
@@ -0,0 +1,200 @@+//! adom-2dboard — standalone Rust CLI + live app for whole KiCad PCBs.+//!+//! Sibling of adom-symbol / adom-footprint, but for a whole `.kicad_pcb`. The+//! headline feature is REAL net/trace highlighting + per-component hover info,+//! which is only possible because we self-render an identity-tagged SVG+//! (`data-net`/`data-ref`/`data-pad`) instead of consuming kicad-cli's flat,+//! anonymous export. Meant to be embedded as a live PCB "view" in any app.++mod pcb_render;+mod kicad;+mod eagle;+mod altium;+mod sexpr;+mod sch_render;+mod server;+mod enrich;++use anyhow::{Context, Result};+use clap::{Parser, Subcommand};+use std::fs;+use std::path::PathBuf;++#[derive(Parser)]+#[command(name = "adom-2dboard", version, about = "Interactive PCB layout viewer (.kicad_pcb): net/trace highlighting, component outlines + hover, per-side layers")]+struct Cli {+    #[command(subcommand)]+    command: Cmd,+}++#[derive(Subcommand)]+enum Cmd {+    /// Render a `.kicad_pcb` to a themed, identity-tagged SVG (+ optional -meta.json).+    Render {+        #[arg(long)]+        file: PathBuf,+        #[arg(long)]+        out: PathBuf,+        /// Also write <out>.meta.json (nets, components, counts)+        #[arg(long)]+        meta: bool,+        /// EDA-exported SVG to use as the visual base (e.g. Altium's render/pcb.svg)+        #[arg(long)]+        base: Option<PathBuf>,+    },+    /// Export a self-contained INTERACTIVE HTML (pan/zoom + net/trace highlight ++    /// component hover) for embedding as a PCB "view" in any app via <iframe>.+    Embed {+        #[arg(long)]+        file: PathBuf,+        #[arg(long)]+        out: Option<PathBuf>,+        /// EDA-exported SVG to use as the visual base (e.g. Altium's render/pcb.svg)+        #[arg(long)]+        base: Option<PathBuf>,+    },+    /// [dev] Render a `.kicad_sch` to a themed identity-tagged SVG (adom-schematic engine).+    RenderSch {+        #[arg(long)]+        file: PathBuf,+        #[arg(long)]+        out: PathBuf,+        #[arg(long)]+        meta: bool,+    },+    /// Run the live app server (AI-drivable; the embeddable live PCB view).+    Serve {+        /// Optionally load a `.kicad_pcb` at startup.+        #[arg(long)]+        file: Option<PathBuf>,+        #[arg(long, default_value_t = 8784)]+        port: u16,+    },+    /// Drive the running server's front-end (the AI's live UI channel) as a user's+    /// click would: `ui toast "done"` · `ui fit` · `ui net GND` · `ui clear`.+    Ui { /// toast | fit | net | clear+         action: String,+         /// message (toast) or argument (net name)+         arg: Option<String>,+         #[arg(long = "type", default_value = "info")] ty: String,+         #[arg(long, default_value_t = 8784)] port: u16 },+    /// Check the live server is up on --port (prints OK:/ERROR: + a Hint:).+    Health { #[arg(long, default_value_t = 8784)] port: u16 },+    /// Install this binary to ~/.local/bin so host apps can shell it by name.+    Install,+}++const APP_HTML: &str = include_str!("app.html");+const VIEWER_JS: &str = include_str!("viewer.js");++/// Build the self-contained embed HTML: inline viewer.js + the board payload in+/// place of the live `<script src="/viewer.js">` tag.+pub fn build_embed(svg: &str, meta_json: &str) -> String {+    let payload = format!(+        "<script>window.__PCB__={{svg:{},meta:{}}};</script>\n<script>{}</script>",+        serde_json::to_string(svg).unwrap_or_else(|_| "\"\"".into()),+        meta_json,+        VIEWER_JS+    );+    APP_HTML.replace(r#"<script src="viewer.js"></script>"#, &payload)+}++// CLI contract: every response starts with `OK:` or `ERROR:`, and every error+// carries an actionable `Hint:` naming the next command.+fn main() {+    if let Err(e) = run() {+        println!("ERROR: {e}");+        println!("Hint: check the file path / arguments; run `adom-2dboard --help`");+        std::process::exit(1);+    }+}++fn run() -> Result<()> {+    let cli = Cli::parse();+    match cli.command {+        Cmd::Render { file, out, meta, base } => {+            let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?;+            let base_svg = base.as_ref().and_then(|p| fs::read_to_string(p).ok());+            let (svg, m) = pcb_render::render_board_bytes_with(&raw, base_svg.as_deref());+            fs::write(&out, &svg).with_context(|| format!("write {}", out.display()))?;+            println!(+                "OK: rendered {} -> {} ({} nets, {} comps, {} tracks, {} vias, {} pads, {:.1}x{:.1}mm)",+                file.display(), out.display(), m.net_names.len(), m.components.len(),+                m.track_count, m.via_count, m.pad_count, m.width_mm, m.height_mm+            );+            if meta {+                let mp = out.with_extension("meta.json");+                fs::write(&mp, serde_json::to_string_pretty(&m)?)?;+                println!("OK: meta -> {}", mp.display());+            }+        }+        Cmd::Embed { file, out, base } => {+            let raw = fs::read(&file).with_context(|| format!("read {}", file.display()))?;+            let base_svg = base.as_ref().and_then(|p| fs::read_to_string(p).ok());+            let (svg, m) = pcb_render::render_board_bytes_with(&raw, base_svg.as_deref());+            let html = build_embed(&svg, &serde_json::to_string(&m)?);+            let out = out.unwrap_or_else(|| file.with_extension("pcbview.html"));+            fs::write(&out, &html).with_context(|| format!("write {}", out.display()))?;+            println!("OK: embed -> {} ({} comps, {} nets)", out.display(), m.components.len(), m.net_names.len());+        }+        Cmd::RenderSch { file, out, meta } => {+            let content = fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;+            let sheet = sch_render::parse(&content);+            let (svg, m) = sch_render::render(&sheet);+            fs::write(&out, &svg)?;+            eprintln!("[adom-schematic] {} → {} ({} comps, {} wires, {} nets, {:.0}×{:.0}mm)",+                file.display(), out.display(), m.components.len(), m.track_count, m.net_names.len(), m.width_mm, m.height_mm);+            if meta { let mp = out.with_extension("meta.json"); fs::write(&mp, serde_json::to_string_pretty(&m)?)?; }+            let emb = out.with_extension("embed.html");+            fs::write(&emb, build_embed(&svg, &serde_json::to_string(&m)?))?;+            eprintln!("[adom-schematic] embed → {}", emb.display());+        }+        Cmd::Serve { file, port } => {+            if let Some(f) = file {+                let content = fs::read_to_string(&f).with_context(|| format!("read {}", f.display()))?;+                let name = f.file_stem().and_then(|s| s.to_str()).unwrap_or("board").to_string();+                server::load_pcb(&name, &content)?;+                println!("OK: loaded {}", f.display());+            }+            server::run(port)?;+        }+        Cmd::Ui { action, arg, ty, port } => {+            let base = format!("http://127.0.0.1:{port}");+            let (path, payload) = match action.as_str() {+                "toast" => ("/ui/toast", serde_json::json!({ "message": arg.unwrap_or_default(), "type": ty }).to_string()),+                "fit" | "clear" => ("/ui/cmd", serde_json::json!({ "action": action }).to_string()),+                "net" => ("/ui/cmd", serde_json::json!({ "action": "net", "arg": arg.unwrap_or_default() }).to_string()),+                other => {+                    println!("ERROR: unknown ui action '{other}'");+                    println!("Hint: use one of: toast <msg> | fit | net <name> | clear");+                    return Ok(());+                }+            };+            match ureq::post(&format!("{base}{path}")).set("Content-Type", "application/json").send_string(&payload) {+                Ok(_) => println!("OK: ui {action} sent to {base}"),+                Err(_) => {+                    println!("ERROR: could not reach the viewer server on port {port}");+                    println!("Hint: start it with `adom-2dboard serve --port {port} &`");+                }+            }+        }+        Cmd::Health { port } => match ureq::get(&format!("http://127.0.0.1:{port}/version")).call() {+            Ok(r) => println!("OK: adom-2dboard healthy on port {port} ({})", r.into_string().unwrap_or_default().trim()),+            Err(_) => {+                println!("ERROR: no adom-2dboard server responding on port {port}");+                println!("Hint: start it with `adom-2dboard serve --port {port} &`");+            }+        },+        Cmd::Install => {+            let exe = std::env::current_exe()?;+            let home = std::env::var("HOME").unwrap_or_default();+            let bin = format!("{home}/.local/bin");+            fs::create_dir_all(&bin)?;+            let dst = format!("{bin}/adom-2dboard");+            fs::copy(&exe, &dst)?;+            println!("OK: installed adom-2dboard to {dst}");+            println!("Hint: ensure ~/.local/bin is on your PATH");+        }+    }+    Ok(())+}
src/pcb_render.rsadded+848
@@ -0,0 +1,848 @@+//! Self-render a whole `.kicad_pcb` to a themed, INTERACTIVE SVG.+//!+//! kicad-cli's `pcb export svg` is FLAT and ANONYMOUS — no way to know which+//! path is which net/part. We parse the board ourselves and tag every copper+//! element with `data-net`, every pad with `data-net`/`data-ref`/`data-pad`, and+//! every component hotspot with `data-ref`/`data-side`. That identity is what+//! makes real net highlighting, per-component hover, and per-side layer raising+//! possible.+//!+//! Layers are split by side (F.Cu/B.Cu, F.Fab/B.Fab, F.SilkS/B.SilkS) so the+//! frontend can raise the back of the board to the front to select bottom parts.+//! Component OUTLINES come from the footprints' F.Fab/B.Fab graphics.+//!+//! Board coords are Y-DOWN (page mm), same as SVG → no global flip.++use regex::Regex;+use serde::Serialize;+use std::collections::HashMap;+use std::fmt::Write as _;++// ── Parsed model ───────────────────────────────────────────────────────────++// These are `pub(crate)` so sibling parser modules (eagle.rs for Fusion/EAGLE,+// altium.rs for .PcbDoc) can build the SAME neutral model. Everything downstream+// — overlay, net highlighting, hover, self-render — is then EDA-agnostic.+pub(crate) struct Track { pub x1: f64, pub y1: f64, pub x2: f64, pub y2: f64, pub width: f64, pub layer: String, pub net: u32 }+pub(crate) struct Via { pub x: f64, pub y: f64, pub size: f64, pub drill: f64, pub net: u32 }+pub(crate) struct Arc { pub d: String, pub layer: String, pub width: f64, pub net: u32 }+pub(crate) struct Pad {+    pub reference: String, pub num: String, pub net: u32,+    pub x: f64, pub y: f64, pub rot: f64, pub w: f64, pub h: f64,+    pub shape: String, pub drill: f64, pub mount: String, pub side: char,+}+pub(crate) struct ZonePoly { pub d: String, pub layer: String, pub net: u32, pub outline: bool }+/// A graphic stroke on a fab / silk / courtyard / edge layer. `d` is an SVG path.+pub(crate) struct Gfx { pub d: String, pub width: f64, pub closed_fill: bool }++#[derive(Serialize, Clone)]+pub struct Comp {+    pub reference: String,+    pub value: String,+    pub footprint: String,+    pub side: String,+    pub mpn: String,+    pub lcsc: String,+    pub x: f64,+    pub y: f64,+    pub bbox: [f64; 4],+    pub pad_count: usize,+}++#[derive(Default)]+pub struct Board {+    pub nets: HashMap<u32, String>,+    pub(crate) tracks: Vec<Track>,+    pub(crate) vias: Vec<Via>,+    pub(crate) arcs: Vec<Arc>,+    pub(crate) pads: Vec<Pad>,+    pub(crate) zones: Vec<ZonePoly>,+    pub(crate) edges: Vec<Gfx>,+    pub(crate) fab_f: Vec<Gfx>, pub(crate) fab_b: Vec<Gfx>,+    pub(crate) silk_f: Vec<Gfx>, pub(crate) silk_b: Vec<Gfx>,+    pub(crate) crtyd_f: Vec<Gfx>, pub(crate) crtyd_b: Vec<Gfx>,+    pub(crate) txt_f: Vec<String>, pub(crate) txt_b: Vec<String>, // pre-rendered <text> on F/B silk+    pub(crate) label_pts: Vec<(f64, f64)>, // extents of on-board silk labels, so the viewBox includes them+    pub comps: Vec<Comp>,+}++// ── S-expr helpers ──────────────────────────────────────────────────────────++fn blocks_ws<'a>(s: &'a str, tag: &str) -> Vec<&'a str> {+    let bytes = s.as_bytes();+    let needle = format!("({}", tag);+    let mut out = Vec::new();+    let mut search = 0;+    while let Some(rel) = s[search..].find(&needle) {+        let start = search + rel;+        let after = start + needle.len();+        let ok = bytes.get(after).map(|c| c.is_ascii_whitespace() || *c == b'(').unwrap_or(false);+        if !ok { search = after; continue; }+        let mut depth = 0i32;+        let mut end = start;+        for i in start..s.len() {+            match bytes[i] {+                b'(' => depth += 1,+                b')' => { depth -= 1; if depth == 0 { end = i; break; } }+                _ => {}+            }+        }+        out.push(&s[start..=end.min(s.len() - 1)]);+        search = end + 1;+    }+    out+}+fn f(cap: Option<regex::Match>) -> f64 { cap.and_then(|m| m.as_str().parse().ok()).unwrap_or(0.0) }+pub fn esc(s: &str) -> String { s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;") }++// ── Parse ────────────────────────────────────────────────────────────────++pub fn parse(content: &str) -> Board {+    let net_decl = Regex::new(r##"\(net\s+(\d+)\s+"([^"]*)"\)"##).unwrap();+    let net_ref = Regex::new(r"\(net\s+(\d+)\s*\)").unwrap();+    let net_name_ref = Regex::new(r##"\(net\s+"([^"]*)"\)"##).unwrap();+    let start_re = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let mid_re = Regex::new(r"\(mid\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let end_re = Regex::new(r"\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let center_re = Regex::new(r"\(center\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let width_re = Regex::new(r"\(width\s+(-?[\d.]+)\)").unwrap();+    let layer_re = Regex::new(r##"\(layer\s+"([^"]+)"\)"##).unwrap();+    let at_re = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let size_re = Regex::new(r"\(size\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let via_size_re = Regex::new(r"\(size\s+(-?[\d.]+)\)").unwrap();+    let drill_re = Regex::new(r"\(drill\s+(-?[\d.]+)").unwrap();+    let xy_re = Regex::new(r"\(xy\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let pad_head = Regex::new(r##"\(pad\s+"?([^"\s)]+)"?\s+(\w+)\s+(\w+)"##).unwrap();+    let prop_re = Regex::new(r##"\(property\s+"([^"]+)"\s+"([^"]*)""##).unwrap();+    let text_layer = Regex::new(r##"\(layer\s+"([^"]+)""##).unwrap(); // loose: allows `knockout` after++    let mut b = Board::default();++    for c in net_decl.captures_iter(content) {+        b.nets.entry(c[1].parse().unwrap_or(0)).or_insert_with(|| unescape_net(&c[2]));+    }++    // KiCad 10 (generator_version 10.0, file version 20260206+) dropped numeric net ids:+    // there is no `(net <id> "<name>")` declaration table, and pads/tracks/vias/zones carry+    // `(net "<name>")` by name only. Intern those names into synthetic ids so the rest of the+    // renderer — which keys everything by u32 — keeps working unchanged.+    let mut name_to_id: HashMap<String, u32> = HashMap::new();+    for c in net_name_ref.captures_iter(content) {+        let name = unescape_net(&c[1]);+        let next = name_to_id.len() as u32 + 1;+        name_to_id.entry(name).or_insert(next);+    }+    for (name, id) in &name_to_id {+        b.nets.entry(*id).or_insert_with(|| name.clone());+    }++    // Resolve a net from a block under either schema: `(net <id>)` [KiCad <=9 reference],+    // `(net <id> "<name>")` [KiCad <=9 pad], or `(net "<name>")` [KiCad 10].+    let resolve_net = |blk: &str| -> u32 {+        if let Some(c) = net_ref.captures(blk) {+            if let Ok(v) = c[1].parse() { return v; }+        }+        if let Some(c) = net_decl.captures(blk) {+            if let Ok(v) = c[1].parse() { return v; }+        }+        if let Some(c) = net_name_ref.captures(blk) {+            if let Some(id) = name_to_id.get(&unescape_net(&c[1])) { return *id; }+        }+        0+    };++    // strip footprints so board-level track/via/zone/gr scans don't see fp_* / pads+    let no_fp = strip_all(content, "footprint");++    for blk in blocks_ws(&no_fp, "segment") {+        let (s, e) = match (start_re.captures(blk), end_re.captures(blk)) { (Some(s), Some(e)) => (s, e), _ => continue };+        b.tracks.push(Track {+            x1: f(s.get(1)), y1: f(s.get(2)), x2: f(e.get(1)), y2: f(e.get(2)),+            width: width_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.15),+            layer: layer_re.captures(blk).map(|c| c[1].to_string()).unwrap_or_default(),+            net: resolve_net(blk),+        });+    }+    for blk in blocks_ws(&no_fp, "arc") {+        let (s, m, e) = match (start_re.captures(blk), mid_re.captures(blk), end_re.captures(blk)) {+            (Some(s), Some(m), Some(e)) => (s, m, e), _ => continue };+        b.arcs.push(Arc {+            d: arc_path((f(s.get(1)), f(s.get(2))), (f(m.get(1)), f(m.get(2))), (f(e.get(1)), f(e.get(2)))),+            width: width_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.15),+            layer: layer_re.captures(blk).map(|c| c[1].to_string()).unwrap_or_default(),+            net: resolve_net(blk),+        });+    }+    for blk in blocks_ws(&no_fp, "via") {+        let at = match at_re.captures(blk) { Some(a) => a, None => continue };+        b.vias.push(Via {+            x: f(at.get(1)), y: f(at.get(2)),+            size: via_size_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.6),+            drill: drill_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.3),+            net: resolve_net(blk),+        });+    }+    for zone in blocks_ws(&no_fp, "zone") {+        let net = resolve_net(zone);+        let mut poured = false;+        for fp in blocks_ws(zone, "filled_polygon") {+            poured = true;+            let layer = layer_re.captures(fp).map(|c| c[1].to_string()).unwrap_or_default();+            for pts_blk in blocks_ws(fp, "pts") {+                let pts: Vec<(f64, f64)> = xy_re.captures_iter(pts_blk).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+                if pts.len() >= 3 { b.zones.push(ZonePoly { d: poly_d(&pts, true), layer: layer.clone(), net, outline: false }); }+            }+        }+        // Unpoured zone: no filled copper exists, so draw its boundary polygon as an+        // outline (KiCad only writes filled_polygon once you pour). The zone's own+        // `(layer "X")` gives the copper side; its `(polygon (pts …))` is the boundary.+        if !poured {+            let zlayer = layer_re.captures(zone).map(|c| c[1].to_string()).unwrap_or_default();+            for poly_blk in blocks_ws(zone, "polygon") {+                for pts_blk in blocks_ws(poly_blk, "pts") {+                    let pts: Vec<(f64, f64)> = xy_re.captures_iter(pts_blk).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+                    if pts.len() >= 3 { b.zones.push(ZonePoly { d: poly_d(&pts, true), layer: zlayer.clone(), net, outline: true }); }+                }+            }+        }+    }+    // board graphics (gr_*) → edge / silk+    for blk in blocks_ws(&no_fp, "gr_line") {+        let (s, e) = match (start_re.captures(blk), end_re.captures(blk)) { (Some(s), Some(e)) => (s, e), _ => continue };+        let layer = layer_re.captures(blk).map(|c| c[1].to_string()).unwrap_or_default();+        let d = format!("M {:.3} {:.3} L {:.3} {:.3}", f(s.get(1)), f(s.get(2)), f(e.get(1)), f(e.get(2)));+        route_gfx(&mut b, &layer, Gfx { d, width: width_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.1), closed_fill: false });+    }+    for blk in blocks_ws(&no_fp, "gr_arc") {+        let (s, m, e) = match (start_re.captures(blk), mid_re.captures(blk), end_re.captures(blk)) {+            (Some(s), Some(m), Some(e)) => (s, m, e), _ => continue };+        let layer = layer_re.captures(blk).map(|c| c[1].to_string()).unwrap_or_default();+        let d = arc_path((f(s.get(1)), f(s.get(2))), (f(m.get(1)), f(m.get(2))), (f(e.get(1)), f(e.get(2))));+        route_gfx(&mut b, &layer, Gfx { d, width: width_re.captures(blk).map(|c| f(c.get(1))).unwrap_or(0.1), closed_fill: false });+    }+    // board-level silk text (gr_text): "3V3", "GND", "BOSCH: BME690\n…", etc.+    for blk in blocks_ws(&no_fp, "gr_text") {+        if blk.contains("(hide yes)") { continue; }+        let layer = text_layer.captures(blk).map(|c| c[1].to_string()).unwrap_or_default();+        if !layer.contains("SilkS") { continue; }+        let text = first_quoted(blk); if text.is_empty() { continue; }+        let at = match at_re.captures(blk) { Some(a) => a, None => continue };+        let size = size_re.captures(blk).map(|c| f(c.get(2))).unwrap_or(1.0);+        let side = if layer.starts_with("B.") { 'B' } else { 'F' };+        let anchor = text_anchor(blk);+        let snip = mk_text(f(at.get(1)), f(at.get(2)), f(at.get(3)), &text, size, blk.contains("(bold yes)"), side, anchor);+        if side == 'B' { b.txt_b.push(snip) } else { b.txt_f.push(snip) }+    }++    // ── Footprints → components, pads, and fab/silk/courtyard OUTLINES ──+    for fpblk in blocks_ws(content, "footprint") {+        let fat = match at_re.captures(fpblk) { Some(a) => a, None => continue };+        let (fx, fy, frot) = (f(fat.get(1)), f(fat.get(2)), f(fat.get(3)));+        let fside = layer_re.captures(fpblk).map(|c| c[1].to_string()).unwrap_or_else(|| "F.Cu".into());+        let bottom = fside.starts_with("B.");+        let side_c = if bottom { 'B' } else { 'F' };+        let xf = |lx: f64, ly: f64| -> (f64, f64) { let (rx, ry) = rot_pt(lx, ly, frot); (rx + fx, ry + fy) };++        let mut reference = String::new(); let mut value = String::new();+        let mut mpn = String::new(); let mut lcsc = String::new(); let mut fpname = String::new();+        for c in prop_re.captures_iter(fpblk) {+            match &c[1] {+                "Reference" => reference = c[2].to_string(),+                "Value" => value = c[2].to_string(),+                "Footprint" => fpname = c[2].to_string(),+                k if k.eq_ignore_ascii_case("MPN") || k.eq_ignore_ascii_case("Manufacturer Part Number") => mpn = c[2].to_string(),+                k if k.eq_ignore_ascii_case("LCSC") || k.eq_ignore_ascii_case("JLCPCB") => lcsc = c[2].to_string(),+                _ => {}+            }+        }+        if fpname.is_empty() { if let Some(q1) = fpblk.find('"') { if let Some(q2) = fpblk[q1 + 1..].find('"') { fpname = fpblk[q1 + 1..q1 + 1 + q2].to_string(); } } }++        // graphics helper: route a transformed stroke by its layer + side+        macro_rules! push_gfx { ($layer:expr, $g:expr) => {{+            let l: &str = $layer;+            if l.contains("Fab") { if bottom { b.fab_b.push($g) } else { b.fab_f.push($g) } }+            else if l.contains("SilkS") { if bottom { b.silk_b.push($g) } else { b.silk_f.push($g) } }+            else if l.contains("CrtYd") { if bottom { b.crtyd_b.push($g) } else { b.crtyd_f.push($g) } }+        }}; }+        for g in blocks_ws(fpblk, "fp_line") {+            let (s, e) = match (start_re.captures(g), end_re.captures(g)) { (Some(s), Some(e)) => (s, e), _ => continue };+            let (p1, p2) = (xf(f(s.get(1)), f(s.get(2))), xf(f(e.get(1)), f(e.get(2))));+            let layer = layer_re.captures(g).map(|c| c[1].to_string()).unwrap_or_default();+            push_gfx!(&layer, Gfx { d: format!("M {:.3} {:.3} L {:.3} {:.3}", p1.0, p1.1, p2.0, p2.1), width: width_re.captures(g).map(|c| f(c.get(1))).unwrap_or(0.12), closed_fill: false });+        }+        for g in blocks_ws(fpblk, "fp_rect") {+            let (s, e) = match (start_re.captures(g), end_re.captures(g)) { (Some(s), Some(e)) => (s, e), _ => continue };+            let (x1, y1, x2, y2) = (f(s.get(1)), f(s.get(2)), f(e.get(1)), f(e.get(2)));+            let corners = [xf(x1, y1), xf(x2, y1), xf(x2, y2), xf(x1, y2), xf(x1, y1)];+            let layer = layer_re.captures(g).map(|c| c[1].to_string()).unwrap_or_default();+            push_gfx!(&layer, Gfx { d: poly_d(&corners, false), width: width_re.captures(g).map(|c| f(c.get(1))).unwrap_or(0.12), closed_fill: false });+        }+        for g in blocks_ws(fpblk, "fp_poly") {+            let pts: Vec<(f64, f64)> = xy_re.captures_iter(g).map(|c| xf(f(c.get(1)), f(c.get(2)))).collect();+            if pts.len() < 2 { continue; }+            let layer = layer_re.captures(g).map(|c| c[1].to_string()).unwrap_or_default();+            let fill = layer.contains("SilkS");+            push_gfx!(&layer, Gfx { d: poly_d(&pts, true), width: width_re.captures(g).map(|c| f(c.get(1))).unwrap_or(0.12), closed_fill: fill });+        }+        for g in blocks_ws(fpblk, "fp_circle") {+            let (ce, en) = match (center_re.captures(g), end_re.captures(g)) { (Some(c), Some(e)) => (c, e), _ => continue };+            let (cx, cy) = (f(ce.get(1)), f(ce.get(2)));+            let r = ((f(en.get(1)) - cx).powi(2) + (f(en.get(2)) - cy).powi(2)).sqrt();+            let (bx, by) = xf(cx, cy);+            let d = format!("M {:.3} {:.3} A {:.3} {:.3} 0 1 0 {:.3} {:.3} A {:.3} {:.3} 0 1 0 {:.3} {:.3}", bx - r, by, r, r, bx + r, by, r, r, bx - r, by);+            let layer = layer_re.captures(g).map(|c| c[1].to_string()).unwrap_or_default();+            push_gfx!(&layer, Gfx { d, width: width_re.captures(g).map(|c| f(c.get(1))).unwrap_or(0.12), closed_fill: false });+        }+        for g in blocks_ws(fpblk, "fp_arc") {+            let (s, m, e) = match (start_re.captures(g), mid_re.captures(g), end_re.captures(g)) { (Some(s), Some(m), Some(e)) => (s, m, e), _ => continue };+            let d = arc_path(xf(f(s.get(1)), f(s.get(2))), xf(f(m.get(1)), f(m.get(2))), xf(f(e.get(1)), f(e.get(2))));+            let layer = layer_re.captures(g).map(|c| c[1].to_string()).unwrap_or_default();+            push_gfx!(&layer, Gfx { d, width: width_re.captures(g).map(|c| f(c.get(1))).unwrap_or(0.12), closed_fill: false });+        }+        // footprint silk text (fp_text), incl. ${REFERENCE} → the refdes+        for tb in blocks_ws(fpblk, "fp_text") {+            if tb.contains("(hide yes)") { continue; }+            let layer = text_layer.captures(tb).map(|c| c[1].to_string()).unwrap_or_default();+            if !layer.contains("SilkS") { continue; }+            let mut text = first_quoted(tb);+            text = text.replace("${REFERENCE}", &reference);+            if text.trim().is_empty() { continue; }+            let at = match at_re.captures(tb) { Some(a) => a, None => continue };+            let (tx, ty) = xf(f(at.get(1)), f(at.get(2)));+            let size = size_re.captures(tb).map(|c| f(c.get(2))).unwrap_or(1.0);+            let tside = if layer.starts_with("B.") { 'B' } else { 'F' };+            // NOTE: angle is ABSOLUTE in the file (KiCad bakes the footprint's rotation into+            // each text's `(at .. angle)`), so do NOT add frot — that double-counts. U1 above+            // is the proof case: a 180-rotated footprint whose upright texts are stored as 0.+            let snip = mk_text(tx, ty, f(at.get(3)), &text, size, tb.contains("(bold yes)"), tside, "middle");+            if tside == 'B' { b.txt_b.push(snip) } else { b.txt_f.push(snip) }+        }++        // pads+        let mut minx = f64::INFINITY; let mut miny = f64::INFINITY; let mut maxx = f64::NEG_INFINITY; let mut maxy = f64::NEG_INFINITY;+        let mut pad_n = 0usize;+        for pblk in blocks_ws(fpblk, "pad") {+            let head = match pad_head.captures(pblk) { Some(h) => h, None => continue };+            let (pat, psz) = match (at_re.captures(pblk), size_re.captures(pblk)) { (Some(a), Some(s)) => (a, s), _ => continue };+            let (lx, ly, prot) = (f(pat.get(1)), f(pat.get(2)), f(pat.get(3)));+            let (bx, by) = xf(lx, ly);+            let net = resolve_net(pblk);+            let (w, h) = (f(psz.get(1)), f(psz.get(2)));+            minx = minx.min(bx - w); miny = miny.min(by - h); maxx = maxx.max(bx + w); maxy = maxy.max(by + h);+            pad_n += 1;+            // Pad POSITION is footprint-local and unrotated (so `xf` applies frot above), but the+            // pad ANGLE is already ABSOLUTE in the file — KiCad bakes the footprint rotation into+            // every pad's `(at .. angle)`. Adding frot double-counts it: a 90-rotated footprint+            // rendered its hitboxes at 180, which reads as "rotated 90" because a symmetric rect+            // at 180 looks like 0 (U3/U5/L4/C6); Y1 at 50 came out at 100.+            b.pads.push(Pad { reference: reference.clone(), num: head[1].to_string(), net, x: bx, y: by, rot: prot, w, h, shape: head[3].to_string(), drill: drill_re.captures(pblk).map(|c| f(c.get(1))).unwrap_or(0.0), mount: head[2].to_string(), side: side_c });+        }+        if !minx.is_finite() { minx = fx - 0.5; miny = fy - 0.5; maxx = fx + 0.5; maxy = fy + 0.5; }+        b.comps.push(Comp { reference, value, footprint: fpname, side: if bottom { "bottom".into() } else { "top".into() }, mpn, lcsc, x: fx, y: fy, bbox: [minx, miny, maxx, maxy], pad_count: pad_n });+    }+    b+}++/// Un-escape KiCad's net-name escaping (`/` is stored as `{slash}`, etc.).+fn unescape_net(s: &str) -> String {+    s.replace("{slash}", "/").replace("{backslash}", "\\").replace("{colon}", ":")+        .replace("{dblquote}", "\"").replace("{lt}", "<").replace("{gt}", ">").replace("{tab}", " ")+}+fn first_quoted(s: &str) -> String {+    if let Some(a) = s.find('"') { if let Some(b) = s[a + 1..].find('"') { return s[a + 1..a + 1 + b].to_string(); } }+    String::new()+}+fn text_anchor(blk: &str) -> &'static str {+    if blk.contains("(justify") {+        if blk.contains("left") { return "start"; }+        if blk.contains("right") { return "end"; }+    }+    "middle"+}+fn route_gfx(b: &mut Board, layer: &str, g: Gfx) {+    if layer == "Edge.Cuts" { b.edges.push(g); }+    else if layer == "F.SilkS" { b.silk_f.push(g); }+    else if layer == "B.SilkS" { b.silk_b.push(g); }+    else if layer == "F.Fab" { b.fab_f.push(g); }+    else if layer == "B.Fab" { b.fab_b.push(g); }+}++// ── Geometry ────────────────────────────────────────────────────────────────++fn rot_pt(x: f64, y: f64, deg: f64) -> (f64, f64) {+    if deg.abs() < 1e-6 { return (x, y); }+    let a = -deg.to_radians();+    (x * a.cos() - y * a.sin(), x * a.sin() + y * a.cos())+}+fn poly_d(pts: &[(f64, f64)], close: bool) -> String {+    let mut d = String::new();+    for (i, &(x, y)) in pts.iter().enumerate() { let _ = write!(d, "{}{:.3} {:.3} ", if i == 0 { "M" } else { "L" }, x, y); }+    if close { d.push('Z'); }+    d+}+/// SVG path for a KiCad 3-point arc (start→end, single arc as before) — with the+/// sweep flag FLIPPED from the original so board-edge fillets bow the right way.+fn arc_path(s: (f64, f64), m: (f64, f64), e: (f64, f64)) -> String {+    let (ax, ay) = s; let (bx, by) = m; let (cx, cy) = e;+    let d = 2.0 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));+    if d.abs() < 1e-9 { return format!("M {:.3} {:.3} L {:.3} {:.3}", ax, ay, cx, cy); }+    let ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d;+    let uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d;+    let r = ((ax - ux).powi(2) + (ay - uy).powi(2)).sqrt();+    let cross = (bx - ax) * (cy - by) - (by - ay) * (cx - bx);+    let sweep = if cross < 0.0 { 0 } else { 1 }; // flipped+    format!("M {:.3} {:.3} A {:.3} {:.3} 0 0 {} {:.3} {:.3}", ax, ay, r, r, sweep, cx, cy)+}+fn collect_path_pts(d: &str, out: &mut Vec<(f64, f64)>) {+    let re = Regex::new(r"[ML]\s*(-?[\d.]+)[ ,]+(-?[\d.]+)").unwrap();+    for c in re.captures_iter(d) { if let (Ok(x), Ok(y)) = (c[1].parse::<f64>(), c[2].parse::<f64>()) { out.push((x, y)); } }+}+fn strip_all(s: &str, tag: &str) -> String {+    let mut out = s.to_string();+    for b in blocks_ws(s, tag) { out = out.replacen(b, "", 1); }+    out+}++// ── Theming ───────────────────────────────────────────────────────────────++// adom-symbol/adom-footprint palette: copper red, grey fab, cyan silk, magenta crtyd.+fn copper_color(layer: &str) -> &'static str {+    match layer { "F.Cu" => "#c83434", "B.Cu" => "#4b7bd0", "In1.Cu" => "#c89b3a", "In2.Cu" => "#3ab87a", _ => "#9a9a9a" }+}++#[derive(Serialize)]+pub struct RenderMeta {+    pub width_mm: f64, pub height_mm: f64, pub view_box: [f64; 4],+    pub net_names: HashMap<String, String>, pub components: Vec<Comp>,+    pub track_count: usize, pub via_count: usize, pub pad_count: usize,+    /// Inner copper layers in this board's stackup, front->back (e.g. ["In1.Cu","In2.Cu"]).+    /// Empty on a 2-layer board. The frontend builds its layer rows from this, so a+    /// 4/6-layer board gets inner-layer toggles and raise-to-front automatically.+    #[serde(default)]+    pub inner_layers: Vec<String>,+}++/// Board bounding box (min_x, min_y, w, h) in mm, with a 1 mm margin. Prefers+/// Edge.Cuts; falls back to component/track extent.+pub fn board_bbox(b: &Board) -> (f64, f64, f64, f64) {+    let mut pts: Vec<(f64, f64)> = vec![];+    for g in &b.edges { collect_path_pts(&g.d, &mut pts); }+    for p in &b.label_pts { pts.push(*p); } // keep on-board labels inside the viewBox+    if pts.len() < 2 {+        for c in &b.comps { pts.push((c.bbox[0], c.bbox[1])); pts.push((c.bbox[2], c.bbox[3])); }+        for t in &b.tracks { pts.push((t.x1, t.y1)); pts.push((t.x2, t.y2)); }+    }+    if pts.is_empty() { pts.push((0.0, 0.0)); pts.push((10.0, 10.0)); }+    let m = 1.0;+    let min_x = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - m;+    let min_y = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min) - m;+    let max_x = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + m;+    let max_y = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max) + m;+    (min_x, min_y, max_x - min_x, max_y - min_y)+}++pub fn build_meta(b: &Board, bbox: (f64, f64, f64, f64)) -> RenderMeta {+    build_meta_with(b, bbox, Vec::new())+}++pub fn build_meta_with(b: &Board, bbox: (f64, f64, f64, f64), inner_layers: Vec<String>) -> RenderMeta {+    let net_names: HashMap<String, String> = b.nets.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();+    RenderMeta {+        width_mm: bbox.2, height_mm: bbox.3, view_box: [bbox.0, bbox.1, bbox.2, bbox.3],+        net_names, components: b.comps.clone(),+        track_count: b.tracks.len(), via_count: b.vias.len(), pad_count: b.pads.len(),+        inner_layers,+    }+}++/// Top-level: authentic EDA (service-kicad) per-layer render as the visual base,+/// with our parsed geometry as the interaction overlay. Falls back to a full+/// self-render if the service is unreachable.+/// Compose an EDA-EXPORTED SVG as the visual base with our interaction overlay+/// on top. Used for Altium, whose own PDF->SVG export is published on the wiki+/// page (`render/pcb.svg`) — that render IS Altium's, so the board looks exactly+/// like Altium drew it.+///+/// The two coordinate systems are unrelated (the export is in PDF pixel space,+/// possibly with global transforms; our overlay is in board mm), so the fit is+/// done in the FRONTEND at mount time via getBBox(), which is transform-aware.+pub fn compose_with_base(b: &Board, base_svg: &str, bbox: (f64, f64, f64, f64)) -> String {+    let inner = {+        let open_end = base_svg.find("<svg").and_then(|i| base_svg[i..].find('>').map(|e| i + e + 1));+        let close = base_svg.rfind("</svg>");+        match (open_end, close) { (Some(a), Some(z)) if z > a => &base_svg[a..z], _ => "" }+    };+    let view = base_svg.find("viewBox=\"").map(|i| {+        let rest = &base_svg[i + 9..];+        rest.split('"').next().unwrap_or("0 0 100 100").to_string()+    }).unwrap_or_else(|| format!("{} {} {} {}", bbox.0, bbox.1, bbox.2, bbox.3));++    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{}" preserveAspectRatio="xMidYMid meet">"##, view);+    let _ = write!(s, r##"<g class="adom-base">{}</g>"##, inner);+    // .adom-fit is positioned by the frontend once both boxes can be measured+    let _ = write!(s, r##"<g class="adom-fit">{}</g>"##, build_overlay(b));+    s.push_str("</svg>");+    s+}++/// Bytes-level entry point. Altium `.PcbDoc` is a BINARY compound file, so it+/// can't come in through the text path at all; everything else is UTF-8 text.+pub fn render_board_bytes(bytes: &[u8]) -> (String, RenderMeta) { render_board_bytes_with(bytes, None) }++/// `base` is an optional EDA-exported SVG to use as the visual base (Altium).+pub fn render_board_bytes_with(bytes: &[u8], base: Option<&str>) -> (String, RenderMeta) {+    if crate::altium::looks_like_altium(bytes) {+        match crate::altium::parse_pcbdoc(bytes) {+            Ok(b) => {+                let bbox = board_bbox(&b);+                let meta = build_meta(&b, bbox);+                if let Some(bs) = base {+                    return (compose_with_base(&b, bs, bbox), meta);+                }+                return (render(&b).0, meta);+            }+            Err(e) => eprintln!("[adom-2dboard] altium parse failed ({e})"),+        }+    }+    render_board(&String::from_utf8_lossy(bytes))+}++pub fn render_board(text: &str) -> (String, RenderMeta) {+    // Fusion 360 Electronics / EAGLE `.brd`. There is no headless renderer for+    // these, so the visual is our own self-render of the same neutral model —+    // every interaction (nets, pads, hover) is identical to the KiCad path.+    if crate::eagle::looks_like_eagle(text) {+        match crate::eagle::parse_brd(text) {+            Ok(b) => {+                let bbox = board_bbox(&b);+                let meta = build_meta(&b, bbox);+                return (render_themed(&b, &fusion_theme()).0, meta);+            }+            Err(e) => eprintln!("[adom-2dboard] eagle/fusion parse failed ({e}); trying KiCad"),+        }+    }+    let b = parse(text);+    let bbox = board_bbox(&b);+    let meta = build_meta_with(&b, bbox, crate::kicad::inner_copper_layers(text));+    match crate::kicad::fetch_all(text) {+        Ok(layers) => (compose(&b, &layers, bbox), meta),+        Err(e) => {+            eprintln!("[adom-2dboard] service-kicad unavailable ({e}); self-rendering");+            (render(&b).0, meta)+        }+    }+}++/// Compose the KiCad-native per-layer SVGs (visual) + our interaction overlay.+fn compose(b: &Board, layers: &[crate::kicad::KLayer], bbox: (f64, f64, f64, f64)) -> String {+    let (mnx, mny, w, h) = bbox;+    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet">"##, mnx, mny, w, h);+    let _ = write!(s, r##"<rect class="adom-board-sub" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" rx="0.3" fill="#0d1117"/>"##, mnx, mny, w, h);+    let _ = write!(s, r##"<g class="adom-flip" data-cx="{:.3}">"##, mnx + w / 2.0);+    for kl in layers {+        let _ = write!(s, r##"<g class="adom-layer-{}" data-side="{}">{}</g>"##, kl.group, kl.side, kl.inner);+    }+    s.push_str(&build_overlay(b));+    s.push_str("</g></svg>");+    s+}++/// The interaction overlay: transparent-but-hittable pads/vias (hover) and net+/// geometry (tracks/arcs/zones) that brightens to its own copper colour on the+/// active net. Everything is invisible until hovered or net-highlighted.+fn build_overlay(b: &Board) -> String {+    let mut s = String::new();+    s.push_str(r##"<g class="adom-overlay">"##);+    // One diagonal-hatch <pattern> per copper colour used by an unpoured zone. The colour is+    // BAKED into each pattern because `currentColor` does NOT resolve inside an SVG pattern+    // tile (it would ignore the referencing zone's colour). Used to give unpoured zones a+    // KiCad-style hatch that FILLS the zone interior in its own copper colour.+    {+        let mut cols: Vec<&str> = b.zones.iter().filter(|z| z.outline).map(|z| copper_color(&z.layer)).collect();+        cols.sort();+        cols.dedup();+        if !cols.is_empty() {+            s.push_str("<defs>");+            for c in &cols {+                let id = c.trim_start_matches('#');+                let _ = write!(s, r##"<pattern id="zhatch-{id}" patternUnits="userSpaceOnUse" width="0.85" height="0.85" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="0.85" stroke="{c}" stroke-width="0.09"/></pattern>"##);+            }+            s.push_str("</defs>");+        }+    }+    // zones first (bottom of the net stack, like the pour under everything)+    for (zi, z) in b.zones.iter().enumerate() {+        if z.outline {+            // Unpoured zone: KiCad's look is a hatch BAND along the INSIDE of the boundary,+            // with an empty centre (NOT a filled interior). Achieve it by stroking the outline+            // with the hatch pattern (a wide stroke straddles the edge), then clipping to the+            // zone interior so only the inside half of that stroke survives — a border band.+            // Plus the crisp copper boundary line, and a transparent full-area path that+            // carries hover/select (a pattern-stroked path is only hittable on its lines).+            let c = copper_color(&z.layer);+            let id = c.trim_start_matches('#');+            let _ = write!(s, r##"<clipPath id="zc{zi}" clipPathUnits="userSpaceOnUse"><path d="{d}" clip-rule="evenodd"/></clipPath>"##, zi = zi, d = z.d);+            let _ = write!(s, r##"<path class="ov-zone" d="{d}" data-net="{net}" fill="transparent" fill-rule="evenodd" style="--hlc:{c}"/>"##, d = z.d, net = z.net, c = c);+            let _ = write!(s, r##"<path class="zone-hatch" d="{d}" fill="none" stroke="url(#zhatch-{id})" stroke-width="1.8" clip-path="url(#zc{zi})" pointer-events="none"/>"##, d = z.d, id = id, zi = zi);+            let _ = write!(s, r##"<path class="zone-outline" d="{d}" fill="none" stroke="{c}" stroke-width="0.12" stroke-opacity="0.95" pointer-events="none"/>"##, d = z.d, c = c);+        } else {+            let _ = write!(s, r##"<path class="ov-zone" d="{}" data-net="{}" fill="transparent" style="--hlc:{}"/>"##, z.d, z.net, copper_color(&z.layer));+        }+    }+    // traces — ROUND caps/joins so a highlighted net is continuous like the PCB+    for t in &b.tracks {+        let _ = write!(s, r##"<line class="ov-trace" x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke-width="{:.3}" data-net="{}" stroke="transparent" stroke-linecap="round" style="--hlc:{}"/>"##,+            t.x1, t.y1, t.x2, t.y2, t.width.max(0.08), t.net, copper_color(&t.layer));+    }+    for a in &b.arcs {+        let _ = write!(s, r##"<path class="ov-trace" d="{}" stroke-width="{:.3}" data-net="{}" fill="none" stroke="transparent" stroke-linecap="round" stroke-linejoin="round" style="--hlc:{}"/>"##,+            a.d, a.width.max(0.08), a.net, copper_color(&a.layer));+    }+    // vias — copper ring + drilled hole (shown on select, so it reads like a real via)+    for v in &b.vias {+        let _ = write!(s, r##"<g class="adom-via" data-net="{}" style="--hlc:#c9924a"><circle class="pad-body" cx="{:.3}" cy="{:.3}" r="{:.3}" fill="transparent"/><circle class="pad-hole" cx="{:.3}" cy="{:.3}" r="{:.3}" fill="transparent" pointer-events="none"/></g>"##,+            v.net, v.x, v.y, v.size / 2.0, v.x, v.y, v.drill / 2.0);+    }+    // pads — copper body (+ drill hole for THT) so a selected pad looks like the real pad, not a blob+    for p in &b.pads {+        let (hw, hh) = (p.w / 2.0, p.h / 2.0);+        let body = match p.shape.as_str() {+            "circle" => format!(r##"<circle class="pad-body" cx="{:.3}" cy="{:.3}" r="{:.3}" fill="transparent"/>"##, p.x, p.y, hw.min(hh)),+            "oval" | "roundrect" => format!(r##"<rect class="pad-body" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" rx="{:.3}" fill="transparent"/>"##, p.x - hw, p.y - hh, p.w, p.h, hw.min(hh) * if p.shape == "oval" { 1.0 } else { 0.25 }),+            _ => format!(r##"<rect class="pad-body" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="transparent"/>"##, p.x - hw, p.y - hh, p.w, p.h),+        };+        let hole = if (p.mount == "thru_hole" || p.mount == "np_thru_hole") && p.drill > 0.0 {+            format!(r##"<circle class="pad-hole" cx="{:.3}" cy="{:.3}" r="{:.3}" fill="transparent" pointer-events="none"/>"##, p.x, p.y, p.drill / 2.0)+        } else { String::new() };+        let hlc = if p.side == 'B' { "#4d7fc4" } else { "#c83434" };+        let (ro, rc) = if p.rot.abs() > 0.01 { (format!(r##"<g transform="rotate({:.3} {:.3} {:.3})">"##, -p.rot, p.x, p.y), "</g>") } else { (String::new(), "") };+        let _ = write!(s, r##"<g class="adom-pad" data-net="{}" data-ref="{}" data-pad="{}" data-size="{:.3}×{:.3}" data-shape="{}" data-side="{}" style="--hlc:{}">{}{}{}{}</g>"##,+            p.net, esc(&p.reference), esc(&p.num), p.w, p.h, esc(&p.shape), p.side, hlc, ro, body, rc, hole);+    }+    s.push_str("</g>");+    s+}++/// A self-render theme so the picture matches the SOURCE EDA. EAGLE/Fusion boards+/// get Fusion's dark-grid / green-pad / hatched-pour look; the KiCad fallback and+/// Altium keep the adom dark theme. (KiCad's normal path uses service-kicad's own+/// SVG, so it already looks like KiCad.)+struct Theme {+    bg: &'static str,+    grid: Option<&'static str>,   // grid line colour drawn behind the board+    cu_f: &'static str,+    cu_b: &'static str,+    green_pads: bool,             // Fusion: bright-green annular pads+    hatch_pour: bool,             // Fusion: cross-hatched copper pours+    edge: &'static str,+    via: &'static str,+}+fn adom_theme() -> Theme {+    Theme { bg: "#0d1117", grid: None, cu_f: "#c83434", cu_b: "#4b7bd0", green_pads: false, hatch_pour: false, edge: "#f2d060", via: "#c08a3e" }+}+fn fusion_theme() -> Theme {+    // Background matches the KiCad path (dark #161b22 substrate, no grid); fills+    // render solid-translucent like KiCad (no cross-hatch).+    Theme { bg: "#0d1117", grid: None, cu_f: "#cf2b2b", cu_b: "#2f7fe0", green_pads: true, hatch_pour: false, edge: "#e8e83a", via: "#22a838" }+}++pub fn render(b: &Board) -> (String, RenderMeta) { render_themed(b, &adom_theme()) }++fn render_themed(b: &Board, th: &Theme) -> (String, RenderMeta) {+    let cu = |layer: &str| -> &'static str { if layer.starts_with("B.") { th.cu_b } else { th.cu_f } };+    let mut pts: Vec<(f64, f64)> = vec![];+    for g in &b.edges { collect_path_pts(&g.d, &mut pts); }+    for p in &b.label_pts { pts.push(*p); } // keep on-board labels inside the viewBox+    if pts.len() < 2 {+        for c in &b.comps { pts.push((c.bbox[0], c.bbox[1])); pts.push((c.bbox[2], c.bbox[3])); }+        for t in &b.tracks { pts.push((t.x1, t.y1)); pts.push((t.x2, t.y2)); }+    }+    if pts.is_empty() { pts.push((0.0, 0.0)); pts.push((10.0, 10.0)); }+    let margin = 1.0;+    let min_x = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - margin;+    let min_y = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min) - margin;+    let max_x = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + margin;+    let max_y = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max) + margin;+    let (w, h) = (max_x - min_x, max_y - min_y);++    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet" font-family="ui-sans-serif,system-ui,sans-serif">"##, min_x, min_y, w, h);+    // pattern defs: Fusion's cross-hatch for copper pours (currentColor = the net's+    // copper colour) and, when the theme grids, the PCB-editor background grid.+    // Cross-hatch patterns with the copper colour baked in (currentColor doesn't+    // reliably resolve through an SVG <pattern>, so we emit one per side).+    let _ = write!(s, r##"<defs><pattern id="hatchf" width="1.3" height="1.3" patternUnits="userSpaceOnUse"><path d="M0 0 L1.3 1.3 M0 1.3 L1.3 0" stroke="{}" stroke-width="0.12"/></pattern><pattern id="hatchb" width="1.3" height="1.3" patternUnits="userSpaceOnUse"><path d="M0 0 L1.3 1.3 M0 1.3 L1.3 0" stroke="{}" stroke-width="0.12"/></pattern>"##, th.cu_f, th.cu_b);+    if let Some(gc) = th.grid {+        let _ = write!(s, r##"<pattern id="pcbgrid" width="2.54" height="2.54" patternUnits="userSpaceOnUse"><path d="M 2.54 0 L 0 0 0 2.54" fill="none" stroke="{gc}" stroke-width="0.05"/></pattern>"##);+    }+    s.push_str("</defs>");+    if th.grid.is_some() {+        // Fusion draws the board area on the same dark grid as the rest of the canvas;+        // only the yellow edge marks the outline. Grid the whole viewBox.+        let _ = write!(s, r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="{}"/>"##, min_x, min_y, w, h, th.bg);+        let _ = write!(s, r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="url(#pcbgrid)"/>"##, min_x, min_y, w, h);+    } else {+        let _ = write!(s, r##"<rect class="adom-board-sub" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" rx="0.3" fill="{}"/>"##, min_x, min_y, w, h, th.bg);+    }++    // everything below the substrate lives in a flip group so "view bottom" can+    // mirror the whole board about its vertical centre (looking at the back).+    let cx = min_x + w / 2.0;+    let _ = write!(s, r##"<g class="adom-flip" data-cx="{:.3}">"##, cx);++    // zones (copper pours) split by side+    for (grp, bottom) in [("zoneB", true), ("zoneF", false)] {+        layer_open(&mut s, grp);+        for z in b.zones.iter().filter(|z| z.layer.starts_with("B.") == bottom) {+            if z.outline {+                // unpoured zone — drawn by the interaction overlay (build_overlay) as a+                // KiCad-style inside-edge hatch band + crisp outline; nothing to draw here.+            } else if th.hatch_pour {+                // Fusion draws poured copper / keepout as a cross-hatch in the copper colour.+                let pat = if z.layer.starts_with("B.") { "hatchb" } else { "hatchf" };+                let _ = write!(s, r##"<path d="{}" data-net="{}" fill="url(#{})" stroke="{c}" stroke-width="0.12" stroke-opacity="0.9"/>"##, z.d, z.net, pat, c = cu(&z.layer));+            } else {+                let _ = write!(s, r##"<path d="{}" data-net="{}" fill="{}" fill-opacity="0.35" stroke="none"/>"##, z.d, z.net, cu(&z.layer));+            }+        }+        s.push_str("</g>");+    }++    // copper split by side (B under F)+    for (grp, want) in [("copperB", "B.Cu"), ("copperF", "F.Cu")] {+        layer_open(&mut s, grp);+        for t in b.tracks.iter().filter(|t| t.layer == want) {+            let _ = write!(s, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke-width="{:.3}" data-net="{}" data-layer="{}" stroke="{}" stroke-linecap="round"/>"##, t.x1, t.y1, t.x2, t.y2, t.width, t.net, t.layer, cu(&t.layer));+        }+        for a in b.arcs.iter().filter(|a| a.layer == want) {+            let _ = write!(s, r##"<path d="{}" data-net="{}" data-layer="{}" fill="none" stroke="{}" stroke-width="{:.3}" stroke-linecap="round"/>"##, a.d, a.net, a.layer, cu(&a.layer), a.width);+        }+        s.push_str("</g>");+    }++    // fab (component outlines) — bottom then top (footprint fab grey)+    gfx_layer(&mut s, "fabB", &b.fab_b, "#565d66");+    gfx_layer(&mut s, "fabF", &b.fab_f, "#6e7681");++    // pads split by side (so the far side dims in top/bottom view)+    for (grp, want) in [("padB", 'B'), ("padF", 'F')] {+        layer_open(&mut s, grp);+        for p in b.pads.iter().filter(|p| p.side == want) {+            let (hw, hh) = (p.w / 2.0, p.h / 2.0);+            let body = match p.shape.as_str() {+                "circle" => format!(r##"<circle cx="{:.3}" cy="{:.3}" r="{:.3}"/>"##, p.x, p.y, hw.min(hh)),+                "oval" => format!(r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" rx="{:.3}"/>"##, p.x - hw, p.y - hh, p.w, p.h, hw.min(hh)),+                "roundrect" => format!(r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" rx="{:.3}"/>"##, p.x - hw, p.y - hh, p.w, p.h, hw.min(hh) * 0.25),+                _ => format!(r##"<rect x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}"/>"##, p.x - hw, p.y - hh, p.w, p.h),+            };+            let (fill, stroke) = if th.green_pads { ("#1f9e38", "#41d65c") }+                else if p.side == 'B' { ("#3d6fb5", "#5a8fd0") } else { ("#c83434", "#ef5350") };+            let (ro, rc) = if p.rot.abs() > 0.01 { (format!(r##"<g transform="rotate({:.3} {:.3} {:.3})">"##, -p.rot, p.x, p.y), "</g>") } else { (String::new(), "") };+            let _ = write!(s, r##"<g class="sr-pad" data-net="{}" data-ref="{}" data-pad="{}" data-size="{:.3}×{:.3}" data-shape="{}" data-side="{}" fill="{}" stroke="{}" stroke-width="0.03">{}{}{}</g>"##,+                p.net, esc(&p.reference), esc(&p.num), p.w, p.h, esc(&p.shape), p.side, fill, stroke, ro, body, rc);+            if (p.mount == "thru_hole" || p.mount == "np_thru_hole") && p.drill > 0.0 {+                let _ = write!(s, r##"<circle cx="{:.3}" cy="{:.3}" r="{:.3}" fill="{}" stroke="#555" stroke-width="0.04" pointer-events="none"/>"##, p.x, p.y, p.drill / 2.0, th.bg);+            }+        }+        s.push_str("</g>");+    }++    // vias (copper ring + drilled centre) — hoverable to see their net+    layer_open(&mut s, "via");+    for v in &b.vias { let _ = write!(s, r##"<g class="sr-via" data-net="{}"><circle cx="{:.3}" cy="{:.3}" r="{:.3}" fill="{}"/><circle cx="{:.3}" cy="{:.3}" r="{:.3}" fill="{}" stroke="#555" stroke-width="0.03"/></g>"##, v.net, v.x, v.y, v.size / 2.0, th.via, v.x, v.y, v.drill / 2.0, th.bg); }+    s.push_str("</g>");++    // silk (bottom then top): thin white lines/polys + text+    layer_open(&mut s, "silkB");+    silk_paths(&mut s, &b.silk_b, "#c8ccd2");+    for t in &b.txt_b { s.push_str(t); }+    s.push_str("</g>");+    layer_open(&mut s, "silkF");+    silk_paths(&mut s, &b.silk_f, "#ffffff");+    for t in &b.txt_f { s.push_str(t); }+    s.push_str("</g>");++    // courtyard (default hidden via CSS), dashed magenta+    layer_open(&mut s, "crtyd");+    for g in b.crtyd_f.iter().chain(b.crtyd_b.iter()) {+        let _ = write!(s, r##"<path d="{}" fill="none" stroke="#ff26e2" stroke-width="{:.3}" stroke-dasharray="0.15 0.1"/>"##, g.d, g.width.max(0.05));+    }+    s.push_str("</g>");++    // board edge+    gfx_layer(&mut s, "edge", &b.edges, th.edge);++    // (no component hotspots — the pads themselves are the hover/click targets)++    s.push_str("</g>"); // close .adom-flip+    // The SAME interaction overlay the KiCad path uses. Without this a+    // self-rendered board (EAGLE/Fusion, or KiCad when service-kicad is down)+    // would draw fine but have no hover targets and no net highlighting.+    s.push_str(&build_overlay(b));+    s.push_str("</svg>");++    let net_names: HashMap<String, String> = b.nets.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();+    let meta = RenderMeta { width_mm: w, height_mm: h, view_box: [min_x, min_y, w, h], net_names, components: b.comps.clone(), track_count: b.tracks.len(), via_count: b.vias.len(), pad_count: b.pads.len(), inner_layers: Vec::new() };+    (s, meta)+}++fn layer_open(s: &mut String, name: &str) { let _ = write!(s, r##"<g class="adom-layer-{}">"##, name); }+fn gfx_layer(s: &mut String, name: &str, items: &[Gfx], color: &str) {+    layer_open(s, name);+    for g in items {+        if g.closed_fill { let _ = write!(s, r##"<path d="{}" fill="{}" stroke="{}" stroke-width="{:.3}"/>"##, g.d, color, color, g.width.max(0.1)); }+        else { let _ = write!(s, r##"<path d="{}" fill="none" stroke="{}" stroke-width="{:.3}" stroke-linecap="round" stroke-linejoin="round"/>"##, g.d, color, g.width.max(0.08)); }+    }+    s.push_str("</g>");+}+/// Silk paths (no group wrapper) — thin, width-clamped so they don't read heavy.+fn silk_paths(s: &mut String, items: &[Gfx], color: &str) {+    for g in items {+        let wraw = if g.width > 0.0 { g.width } else { 0.1 };+        let w = wraw.clamp(0.08, 0.12);+        if g.closed_fill { let _ = write!(s, r##"<path d="{}" fill="{}" stroke="{}" stroke-width="{:.3}"/>"##, g.d, color, color, w); }+        else { let _ = write!(s, r##"<path d="{}" fill="none" stroke="{}" stroke-width="{:.3}" stroke-linecap="round" stroke-linejoin="round"/>"##, g.d, color, w); }+    }+}++/// Render one silk text element as a KNOCKOUT (like KiCad): a filled silk box+/// with the glyphs cut out via an SVG mask, so the real copper/board underneath+/// shows through the letters. Multi-line via `\n`; B-side text is mirrored about+/// its anchor so it reads correctly in bottom view.+fn mk_text(x: f64, y: f64, rot: f64, text: &str, size: f64, bold: bool, side: char, anchor: &str) -> String {+    use std::sync::atomic::{AtomicUsize, Ordering};+    static UID: AtomicUsize = AtomicUsize::new(0);+    let id = UID.fetch_add(1, Ordering::Relaxed);+    let silk = if side == 'B' { "#c8ccd2" } else { "#ffffff" };+    let weight = if bold { "700" } else { "600" };+    let fs = (size * 1.05).max(0.4);+    let lines: Vec<&str> = text.split("\\n").collect();+    let lh = fs * 1.12;+    let start = -((lines.len() as f64 - 1.0) / 2.0) * lh;+    let mut spans = String::new();+    for (i, l) in lines.iter().enumerate() {+        let dy = if i == 0 { start } else { lh };+        let _ = write!(spans, r##"<tspan x="{:.3}" dy="{:.3}">{}</tspan>"##, x, dy, esc(l));+    }+    // knockout box sized snug to the text (approx glyph metrics for a bold sans)+    let charw = fs * 0.58;+    let maxlen = lines.iter().map(|l| l.chars().count()).max().unwrap_or(1).max(1) as f64;+    let bw = maxlen * charw + fs * 0.34;+    let bh = lines.len() as f64 * lh + fs * 0.16;+    let rx0 = match anchor { "start" => x - fs * 0.16, "end" => x - bw + fs * 0.16, _ => x - bw / 2.0 };+    let ry0 = y - bh / 2.0;+    let rr = (fs * 0.22).min(bh / 2.0);+    let mut tf = format!("rotate({:.2} {:.3} {:.3})", -rot, x, y);+    if side == 'B' { tf = format!("translate({:.3} 0) scale(-1 1) {}", 2.0 * x, tf); }+    format!(concat!(+        r##"<g transform="{tf}" style="pointer-events:none">"##,+        r##"<mask id="ko{id}" maskContentUnits="userSpaceOnUse">"##,+        r##"<rect x="{rx:.3}" y="{ry:.3}" width="{bw:.3}" height="{bh:.3}" rx="{rr:.3}" fill="#fff"/>"##,+        r##"<text x="{x:.3}" y="{y:.3}" text-anchor="{a}" dominant-baseline="central" font-size="{fs:.3}" font-weight="{w}" fill="#000" font-family="ui-sans-serif,system-ui,sans-serif">{spans}</text>"##,+        r##"</mask>"##,+        r##"<rect x="{rx:.3}" y="{ry:.3}" width="{bw:.3}" height="{bh:.3}" rx="{rr:.3}" fill="{silk}" mask="url(#ko{id})"/>"##,+        r##"</g>"##,+    ), tf = tf, id = id, rx = rx0, ry = ry0, bw = bw, bh = bh, rr = rr, x = x, y = y, a = anchor, fs = fs, w = weight, spans = spans, silk = silk)+}
src/sch_render.rsadded+328
@@ -0,0 +1,328 @@+//! Self-render a whole `.kicad_sch` to a themed, INTERACTIVE SVG — the sibling of+//! pcb_render, for schematics. Same payoff: kicad-cli's `.svg` export is flat and+//! anonymous, so we parse the sheet ourselves and tag every wire with+//! `data-net` and every symbol instance with `data-ref`, which is what makes+//! net highlighting + per-component hover possible.+//!+//! Symbol bodies are drawn from their `lib_symbols` definition (rectangles /+//! polylines / circles / arcs / pins) transformed to each instance's placement.+//!+//! Net grouping (label-based / connectivity v1): union-find over wire endpoints+//! (+ junctions), then clusters that share a power-symbol or label NAME are+//! merged so e.g. every GND stub highlights together. Component pins whose tip+//! lands on a cluster point inherit that net.++use crate::sexpr::{blocks, esc, f};+use regex::Regex;+use serde::Serialize;+use std::collections::HashMap;+use std::fmt::Write as _;++// schematic grid is Y-DOWN already (page mm), same as SVG → no global flip.++#[derive(Clone)]+struct Prim { kind: u8, pts: Vec<(f64, f64)>, r: f64 } // kind: 0 poly/rect,1 circle,2 pin,3 arc+struct LibSym { prims: Vec<Prim> }++#[derive(Serialize, Clone)]+pub struct Comp {+    pub reference: String,+    pub value: String,+    pub footprint: String,+    pub mpn: String,+    pub lcsc: String,+    pub x: f64,+    pub y: f64,+    pub bbox: [f64; 4],+    pub pin_count: usize,+}++struct Wire { x1: f64, y1: f64, x2: f64, y2: f64, net: usize }+struct Label { x: f64, y: f64, text: String, power: bool }++pub struct Sheet {+    libs: HashMap<String, LibSym>,+    comps: Vec<Comp>,+    comp_svgs: Vec<String>,   // pre-rendered <g data-ref> body per comp+    wires: Vec<Wire>,+    junctions: Vec<(f64, f64)>,+    labels: Vec<Label>,+    net_names: HashMap<usize, String>,+}++// ── union-find ──+struct Uf { p: Vec<usize> }+impl Uf {+    fn new(n: usize) -> Self { Uf { p: (0..n).collect() } }+    fn find(&mut self, a: usize) -> usize { let mut a = a; while self.p[a] != a { self.p[a] = self.p[self.p[a]]; a = self.p[a]; } a }+    fn union(&mut self, a: usize, b: usize) { let (ra, rb) = (self.find(a), self.find(b)); if ra != rb { self.p[ra] = rb; } }+}++fn key(x: f64, y: f64) -> (i64, i64) { ((x * 100.0).round() as i64, (y * 100.0).round() as i64) }++/// Rotate+mirror a lib point into sheet coords. Lib frame is Y-UP; the sheet is+/// Y-DOWN, so base transform negates Y, then rotation (CW on screen for KiCad's+/// `at` angle) and optional mirror compose, then translate to (px,py).+fn xf(lx: f64, ly: f64, px: f64, py: f64, rot: f64, mirror: u8) -> (f64, f64) {+    // lib Y-up → screen Y-down+    let (mut x, mut y) = (lx, -ly);+    // mirror: 1 = mirror across Y axis (x), 2 = across X axis (y)+    if mirror == 1 { x = -x; }+    if mirror == 2 { y = -y; }+    // rotation (KiCad rotates the symbol CCW by `rot`; on Y-down screen that is a+    // clockwise matrix). Use standard CCW matrix with -rot for screen.+    let a = (-rot).to_radians();+    let (c, s) = (a.cos(), a.sin());+    let (rx, ry) = (x * c - y * s, x * s + y * c);+    (px + rx, py + ry)+}++pub fn parse(content: &str) -> Sheet {+    let at3 = Regex::new(r"\(at\s+(-?[\d.]+)\s+(-?[\d.]+)(?:\s+(-?[\d.]+))?\)").unwrap();+    let se = Regex::new(r"\(start\s+(-?[\d.]+)\s+(-?[\d.]+)\)\s*\(end\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let xy = Regex::new(r"\(xy\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let center = Regex::new(r"\(center\s+(-?[\d.]+)\s+(-?[\d.]+)\)").unwrap();+    let radius = Regex::new(r"\(radius\s+(-?[\d.]+)\)").unwrap();+    let length = Regex::new(r"\(length\s+(-?[\d.]+)\)").unwrap();+    let prop = Regex::new(r##"\(property\s+"([^"]+)"\s+"([^"]*)""##).unwrap();+    let mirror_re = Regex::new(r"\(mirror\s+(x|y)\)").unwrap();++    let mut sh = Sheet {+        libs: HashMap::new(), comps: vec![], comp_svgs: vec![], wires: vec![],+        junctions: vec![], labels: vec![], net_names: HashMap::new(),+    };++    // ── lib_symbols definitions ──+    if let Some(libblk) = blocks(content, "lib_symbols").into_iter().next() {+        // top-level defs: (symbol "Lib:Name" … nested (symbol "Name_x_y" graphics))+        for def in top_symbols(libblk) {+            let name = quoted(def).unwrap_or_default();+            if name.is_empty() { continue; }+            let mut prims = vec![];+            for r in blocks(def, "rectangle") {+                if let Some(c) = se.captures(r) {+                    let (x1, y1, x2, y2) = (f(c.get(1)), f(c.get(2)), f(c.get(3)), f(c.get(4)));+                    prims.push(Prim { kind: 0, pts: vec![(x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)], r: 0.0 });+                }+            }+            for p in blocks(def, "polyline") {+                let pts: Vec<(f64, f64)> = xy.captures_iter(p).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+                if pts.len() >= 2 { prims.push(Prim { kind: 0, pts, r: 0.0 }); }+            }+            for c in blocks(def, "circle") {+                if let (Some(ce), Some(ra)) = (center.captures(c), radius.captures(c)) {+                    prims.push(Prim { kind: 1, pts: vec![(f(ce.get(1)), f(ce.get(2)))], r: f(ra.get(1)) });+                }+            }+            for pin in blocks(def, "pin") {+                if let Some(a) = at3.captures(pin) {+                    let (lx, ly, ang) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+                    let len = length.captures(pin).map(|c| f(c.get(1))).unwrap_or(2.54);+                    let (dx, dy) = (ang.to_radians().cos() * len, ang.to_radians().sin() * len);+                    prims.push(Prim { kind: 2, pts: vec![(lx, ly), (lx + dx, ly + dy)], r: 0.0 });+                }+            }+            sh.libs.insert(name, LibSym { prims });+        }+    }++    // ── wires ──+    let content_wo_lib = strip_first_block(content, "lib_symbols");+    for w in blocks(&content_wo_lib, "wire") {+        let pts: Vec<(f64, f64)> = xy.captures_iter(w).map(|c| (f(c.get(1)), f(c.get(2)))).collect();+        if pts.len() >= 2 { sh.wires.push(Wire { x1: pts[0].0, y1: pts[0].1, x2: pts[1].0, y2: pts[1].1, net: 0 }); }+    }+    for j in blocks(&content_wo_lib, "junction") {+        if let Some(a) = at3.captures(j) { sh.junctions.push((f(a.get(1)), f(a.get(2)))); }+    }+    for l in blocks(&content_wo_lib, "label").into_iter()+        .chain(blocks(&content_wo_lib, "global_label"))+        .chain(blocks(&content_wo_lib, "hierarchical_label")) {+        if let Some(a) = at3.captures(l) {+            let text = quoted(l).unwrap_or_default();+            if !text.is_empty() { sh.labels.push(Label { x: f(a.get(1)), y: f(a.get(2)), text, power: false }); }+        }+    }++    // ── symbol instances (top-level symbols outside lib_symbols) ──+    for inst in top_symbols(&content_wo_lib) {+        let lib_id = match capture1(inst, r##"\(lib_id\s+"([^"]+)"\)"##) { Some(s) => s, None => continue };+        let a = match at3.captures(inst) { Some(a) => a, None => continue };+        let (px, py, rot) = (f(a.get(1)), f(a.get(2)), f(a.get(3)));+        let mirror = mirror_re.captures(inst).map(|c| if &c[1] == "x" { 2u8 } else { 1u8 }).unwrap_or(0);++        let mut reference = String::new();+        let mut value = String::new();+        let mut footprint = String::new();+        let mut mpn = String::new();+        let mut lcsc = String::new();+        for c in prop.captures_iter(inst) {+            match &c[1] {+                "Reference" => reference = c[2].to_string(),+                "Value" => value = c[2].to_string(),+                "Footprint" => footprint = c[2].to_string(),+                k if k.eq_ignore_ascii_case("MPN") => mpn = c[2].to_string(),+                k if k.eq_ignore_ascii_case("LCSC") || k.eq_ignore_ascii_case("JLCPCB") => lcsc = c[2].to_string(),+                _ => {}+            }+        }+        let is_power = lib_id.starts_with("power:");+        // power symbols name their net (e.g. power:GND value "GND")+        if is_power && !value.is_empty() { sh.labels.push(Label { x: px, y: py, text: value.clone(), power: true }); }++        let lib = sh.libs.get(&lib_id);+        let mut body = String::new();+        let mut minx = f64::INFINITY; let mut miny = f64::INFINITY; let mut maxx = f64::NEG_INFINITY; let mut maxy = f64::NEG_INFINITY;+        let mut pin_n = 0usize;+        if let Some(lib) = lib {+            for pr in &lib.prims {+                let tp: Vec<(f64, f64)> = pr.pts.iter().map(|&(x, y)| xf(x, y, px, py, rot, mirror)).collect();+                for &(x, y) in &tp { minx = minx.min(x); miny = miny.min(y); maxx = maxx.max(x); maxy = maxy.max(y); }+                match pr.kind {+                    1 => { let _ = write!(body, r##"<circle cx="{:.3}" cy="{:.3}" r="{:.3}" fill="none" stroke="#d7c690" stroke-width="0.15"/>"##, tp[0].0, tp[0].1, pr.r); }+                    2 => { pin_n += 1; let _ = write!(body, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" stroke="#7fd9b0" stroke-width="0.15"/>"##, tp[0].0, tp[0].1, tp[1].0, tp[1].1); }+                    _ => { let _ = write!(body, r##"<path d="{}" fill="none" stroke="#d7c690" stroke-width="0.15"/>"##, poly_d(&tp)); }+                }+            }+        }+        if !minx.is_finite() { minx = px - 1.27; miny = py - 1.27; maxx = px + 1.27; maxy = py + 1.27; }+        // reference + value labels+        if !is_power && !reference.is_empty() {+            let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="1.3" fill="#f2d060">{}</text>"##, maxx + 0.4, miny + 1.2, esc(&reference));+            if !value.is_empty() { let _ = write!(body, r##"<text x="{:.3}" y="{:.3}" font-size="1.1" fill="#9fb0a8">{}</text>"##, maxx + 0.4, miny + 2.7, esc(&value)); }+        }+        let g = format!(r##"<g data-ref="{}">{}</g>"##, esc(&reference), body);+        sh.comp_svgs.push(g);+        if !is_power {+            sh.comps.push(Comp { reference, value, footprint, mpn, lcsc, x: px, y: py, bbox: [minx, miny, maxx, maxy], pin_count: pin_n });+        }+    }++    // ── net grouping: union-find over wire endpoints (+ junctions) ──+    let n = sh.wires.len();+    let mut uf = Uf::new(n.max(1));+    let mut endpoint_owner: HashMap<(i64, i64), usize> = HashMap::new();+    for (i, w) in sh.wires.iter().enumerate() {+        for k in [key(w.x1, w.y1), key(w.x2, w.y2)] {+            if let Some(&j) = endpoint_owner.get(&k) { uf.union(i, j); } else { endpoint_owner.insert(k, i); }+        }+    }+    // merge clusters that share a label/power NAME+    let mut name_to_cluster: HashMap<String, usize> = HashMap::new();+    // first assign each label to the nearest wire endpoint cluster+    let labels_snapshot: Vec<Label> = sh.labels.iter().map(|l| Label { x: l.x, y: l.y, text: l.text.clone(), power: l.power }).collect();+    for l in &labels_snapshot {+        if let Some(&wi) = endpoint_owner.get(&key(l.x, l.y)) {+            let c = uf.find(wi);+            match name_to_cluster.get(&l.text) { Some(&other) => uf.union(c, other), None => { name_to_cluster.insert(l.text.clone(), c); } }+        }+    }+    // assign a compact net id per root, remember names+    let mut root_id: HashMap<usize, usize> = HashMap::new();+    let mut next = 1usize;+    for i in 0..n {+        let r = uf.find(i);+        let id = *root_id.entry(r).or_insert_with(|| { let v = next; next += 1; v });+        sh.wires[i].net = id;+    }+    for l in &labels_snapshot {+        if let Some(&wi) = endpoint_owner.get(&key(l.x, l.y)) {+            let id = *root_id.get(&uf.find(wi)).unwrap_or(&0);+            if id != 0 { sh.net_names.entry(id).or_insert_with(|| l.text.clone()); }+        }+    }+    sh+}++pub fn render(sh: &Sheet) -> (String, RenderMeta) {+    let mut pts: Vec<(f64, f64)> = vec![];+    for w in &sh.wires { pts.push((w.x1, w.y1)); pts.push((w.x2, w.y2)); }+    for c in &sh.comps { pts.push((c.bbox[0], c.bbox[1])); pts.push((c.bbox[2], c.bbox[3])); }+    if pts.is_empty() { pts.push((0.0, 0.0)); pts.push((100.0, 100.0)); }+    let margin = 5.0;+    let min_x = pts.iter().map(|p| p.0).fold(f64::INFINITY, f64::min) - margin;+    let min_y = pts.iter().map(|p| p.1).fold(f64::INFINITY, f64::min) - margin;+    let max_x = pts.iter().map(|p| p.0).fold(f64::NEG_INFINITY, f64::max) + margin;+    let max_y = pts.iter().map(|p| p.1).fold(f64::NEG_INFINITY, f64::max) + margin;+    let (w, h) = (max_x - min_x, max_y - min_y);++    let mut s = String::new();+    let _ = write!(s, r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="{:.3} {:.3} {:.3} {:.3}" preserveAspectRatio="xMidYMid meet" font-family="ui-sans-serif,system-ui,sans-serif">"##, min_x, min_y, w, h);+    let _ = write!(s, r##"<rect class="adom-board-sub" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" fill="#0c130f"/>"##, min_x, min_y, w, h);++    // wires+    s.push_str(r##"<g class="adom-layer-copper">"##);+    for wi in &sh.wires {+        let _ = write!(s, r##"<line x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" data-net="{}" stroke="#4f8f6f" stroke-width="0.18" stroke-linecap="round"/>"##, wi.x1, wi.y1, wi.x2, wi.y2, wi.net);+    }+    s.push_str("</g>");+    // junctions+    s.push_str(r##"<g class="adom-layer-via">"##);+    for &(x, y) in &sh.junctions { let _ = write!(s, r##"<circle cx="{:.3}" cy="{:.3}" r="0.4" fill="#7fd9b0"/>"##, x, y); }+    s.push_str("</g>");+    // symbol bodies+    s.push_str(r##"<g class="adom-layer-pad">"##);+    for g in &sh.comp_svgs { s.push_str(g); }+    s.push_str("</g>");+    // component hotspots+    s.push_str(r##"<g class="adom-layer-hotspot">"##);+    for c in &sh.comps {+        let [x0, y0, x1, y1] = c.bbox;+        let _ = write!(s, r##"<rect class="adom-hotspot" x="{:.3}" y="{:.3}" width="{:.3}" height="{:.3}" data-ref="{}" fill="transparent"/>"##, x0 - 0.6, y0 - 0.6, (x1 - x0) + 1.2, (y1 - y0) + 1.2, esc(&c.reference));+    }+    s.push_str("</g>");+    s.push_str("</svg>");++    let net_names: HashMap<String, String> = sh.net_names.iter().map(|(k, v)| (k.to_string(), v.clone())).collect();+    let meta = RenderMeta {+        width_mm: w, height_mm: h, view_box: [min_x, min_y, w, h],+        net_names, components: sh.comps.clone(),+        track_count: sh.wires.len(), via_count: sh.junctions.len(), pad_count: 0,+    };+    (s, meta)+}++#[derive(Serialize)]+pub struct RenderMeta {+    pub width_mm: f64, pub height_mm: f64, pub view_box: [f64; 4],+    pub net_names: HashMap<String, String>, pub components: Vec<Comp>,+    pub track_count: usize, pub via_count: usize, pub pad_count: usize,+}++// ── helpers ──+fn poly_d(pts: &[(f64, f64)]) -> String {+    let mut d = String::new();+    for (i, &(x, y)) in pts.iter().enumerate() { let _ = write!(d, "{}{:.3} {:.3} ", if i == 0 { "M" } else { "L" }, x, y); }+    d+}+fn quoted(s: &str) -> Option<String> {+    let q1 = s.find('"')?; let rest = &s[q1 + 1..]; let q2 = rest.find('"')?; Some(rest[..q2].to_string())+}+fn capture1(s: &str, re: &str) -> Option<String> { Regex::new(re).ok()?.captures(s).map(|c| c[1].to_string()) }++/// Top-level `(symbol …)` blocks (not nested). Used for both lib defs and+/// instances — callers pass the right slice.+fn top_symbols(s: &str) -> Vec<&str> {+    let bytes = s.as_bytes();+    let mut out = vec![];+    let mut i = 0;+    while let Some(rel) = s[i..].find("(symbol") {+        let start = i + rel;+        let after = start + 7;+        if bytes.get(after).map(|c| !c.is_ascii_whitespace()).unwrap_or(true) { i = after; continue; }+        // slice this balanced block+        let mut depth = 0i32; let mut end = start;+        for j in start..s.len() { match bytes[j] { b'(' => depth += 1, b')' => { depth -= 1; if depth == 0 { end = j; break; } } _ => {} } }+        out.push(&s[start..=end.min(s.len() - 1)]);+        i = end + 1;+    }+    out+}++/// Remove the first `(<tag> …)` block so instance scanning doesn't see lib defs.+fn strip_first_block(s: &str, tag: &str) -> String {+    if let Some(b) = blocks(s, tag).into_iter().next() {+        return s.replacen(b, "", 1);+    }+    s.to_string()+}
src/server.rsadded+254
@@ -0,0 +1,254 @@+//! adom-2dboard live app server — the AI-drivable surface + the embeddable live PCB+//! view (same app-creator contract as adom-footprint/adom-symbol). Routes:+//! GET / (UI), /viewer.js, /favicon.svg, /state (poller), POST /load (push a+//! .kicad_pcb), GET /enrich (component sidecar), /eval + /console, /shutdown.++use anyhow::Result;+use serde_json::{json, Value};+use std::collections::{HashMap, VecDeque};+use std::io::Read;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;+use tiny_http::{Header, Method, Response, Server};++#[derive(Default, Clone)]+pub struct AppState {+    pub name: String,+    pub svg: String,+    pub meta_json: String, // serialized RenderMeta+    pub kicad_pcb: String, // retained for re-render / delivery+}++static STATE: Mutex<Option<AppState>> = Mutex::new(None);+static EVAL_PENDING: Mutex<VecDeque<(u64, String)>> = Mutex::new(VecDeque::new());+static EVAL_RESULTS: Mutex<Option<HashMap<u64, Value>>> = Mutex::new(None);+static CONSOLE: Mutex<Option<Vec<String>>> = Mutex::new(None);+static ENRICH_CACHE: Mutex<Option<HashMap<String, String>>> = Mutex::new(None);+static ENRICH_PENDING: Mutex<Option<std::collections::HashSet<String>>> = Mutex::new(None);+static EVAL_ID: AtomicU64 = AtomicU64::new(1);+// AI channel: narrate (POST /ui/toast) + drive (POST /ui/cmd); the UI drains both+// via GET /ui/pull. (Complements the JS /eval channel with a user-visible one.)+static TOASTS: Mutex<Vec<Value>> = Mutex::new(Vec::new());+static CMDS: Mutex<Vec<Value>> = Mutex::new(Vec::new());++const APP_HTML: &str = include_str!("app.html");+const VIEWER_JS: &str = include_str!("viewer.js");+const FAVICON: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#00e6dc" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.4"/><circle cx="16" cy="16" r="1.4"/><path d="M8 9.5v3l4 3.5"/></svg>"##;++pub fn set_state(s: AppState) { *STATE.lock().unwrap() = Some(s); }++pub fn load_pcb(name: &str, kicad_pcb: &str) -> Result<()> {+    let (svg, meta) = crate::pcb_render::render_board(kicad_pcb);+    // pre-warm enrichment for every component that carries an MPN, so hover is+    // instant. Sequential in ONE background thread — vendor APIs are slow and we+    // don't want to fan out N live requests at once.+    let mpns: Vec<(String, String)> = meta.components.iter()+        .filter(|c| !c.mpn.is_empty())+        .map(|c| (c.mpn.clone(), c.lcsc.clone())).collect();+    set_state(AppState {+        name: name.to_string(), svg,+        meta_json: serde_json::to_string(&meta)?,+        kicad_pcb: kicad_pcb.to_string(),+    });+    if !mpns.is_empty() {+        std::thread::spawn(move || {+            for (mpn, lcsc) in mpns { let _ = enrich_fill(&mpn, &lcsc); }+        });+    }+    Ok(())+}++/// Compute (blocking) and cache one enrichment record. Returns the JSON.+fn enrich_fill(mpn: &str, lcsc: &str) -> String {+    let key = format!("{mpn}|{lcsc}");+    let out = crate::enrich::lookup(mpn, lcsc);+    if let Some(m) = ENRICH_CACHE.lock().unwrap().as_mut() { m.insert(key.clone(), out.clone()); }+    if let Some(p) = ENRICH_PENDING.lock().unwrap().as_mut() { p.remove(&key); }+    out+}++fn state_json() -> String {+    match &*STATE.lock().unwrap() {+        Some(s) => format!(r#"{{"name":{},"svg":{},"meta":{}}}"#,+            serde_json::to_string(&s.name).unwrap(),+            serde_json::to_string(&s.svg).unwrap(),+            if s.meta_json.is_empty() { "{}" } else { &s.meta_json }),+        None => "{}".to_string(),+    }+}++pub fn run(port: u16) -> Result<()> {+    *EVAL_RESULTS.lock().unwrap() = Some(HashMap::new());+    *CONSOLE.lock().unwrap() = Some(Vec::new());+    *ENRICH_CACHE.lock().unwrap() = Some(HashMap::new());+    *ENRICH_PENDING.lock().unwrap() = Some(std::collections::HashSet::new());+    let server = Server::http(format!("0.0.0.0:{port}")).map_err(|e| anyhow::anyhow!("bind {port}: {e}"))?;+    eprintln!("[adom-2dboard] serving on http://127.0.0.1:{port}");+    register_port(port, "adom-2dboard", "Interactive PCB layout view (AI-drivable)");+    for mut req in server.incoming_requests() {+        let raw = req.url().to_string();+        let url = raw.split('?').next().unwrap_or("/").to_string();+        let query = raw.splitn(2, '?').nth(1).unwrap_or("").to_string();+        let method = req.method().clone();+        let mut body = String::new();+        if matches!(method, Method::Post) { let _ = req.as_reader().read_to_string(&mut body); }+        let resp = route(&method, &url, &query, &body);+        let _ = req.respond(resp);+        if url == "/shutdown" && matches!(method, Method::Post) { break; }+    }+    unregister_port(port);+    Ok(())+}++fn route(method: &Method, url: &str, query: &str, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {+    match (method, url) {+        (Method::Get, "/") | (Method::Get, "/index.html") => resp(APP_HTML, "text/html; charset=utf-8"),+        (Method::Get, "/viewer.js") => resp(VIEWER_JS, "application/javascript"),+        (Method::Get, "/favicon.svg") => resp(FAVICON, "image/svg+xml"),+        (Method::Get, "/state") => json_resp(&state_json()),+        (Method::Get, "/version") => json_resp(&json!({ "version": env!("CARGO_PKG_VERSION"), "name": "adom-2dboard" }).to_string()),+        (Method::Post, "/ui/toast") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                let msg = v.get("message").and_then(|x| x.as_str()).unwrap_or("");+                let ty = v.get("type").and_then(|x| x.as_str()).unwrap_or("info");+                if !msg.is_empty() { TOASTS.lock().unwrap().push(json!({ "message": msg, "type": ty })); }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Post, "/ui/cmd") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                if v.get("action").and_then(|x| x.as_str()).map(|s| !s.is_empty()).unwrap_or(false) { CMDS.lock().unwrap().push(v); }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Get, "/ui/pull") => {+            let toasts: Vec<Value> = std::mem::take(&mut *TOASTS.lock().unwrap());+            let cmds: Vec<Value> = std::mem::take(&mut *CMDS.lock().unwrap());+            json_resp(&json!({ "toasts": toasts, "cmds": cmds }).to_string())+        }+        (Method::Get, "/enrich") => json_resp(&enrich(query)),+        (Method::Post, "/load") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                if let Some(pcb) = v.get("kicadPcb").and_then(|x| x.as_str()) {+                    let name = v.get("name").and_then(|x| x.as_str()).unwrap_or("board").to_string();+                    match load_pcb(&name, pcb) {+                        Ok(()) => return json_resp("{\"ok\":true}"),+                        Err(e) => return json_err(422, &e.to_string()),+                    }+                }+                set_state(AppState {+                    name: v.get("name").and_then(|x| x.as_str()).unwrap_or("").to_string(),+                    svg: v.get("svg").and_then(|x| x.as_str()).unwrap_or("").to_string(),+                    meta_json: v.get("meta").map(|m| m.to_string()).unwrap_or_else(|| "{}".into()),+                    kicad_pcb: String::new(),+                });+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Post, "/eval") => {+            let code = serde_json::from_str::<Value>(body).ok()+                .and_then(|v| v.get("code").and_then(|c| c.as_str()).map(String::from)).unwrap_or_default();+            let id = EVAL_ID.fetch_add(1, Ordering::SeqCst);+            EVAL_PENDING.lock().unwrap().push_back((id, code));+            json_resp(&json!({ "id": id.to_string() }).to_string())+        }+        (Method::Get, "/eval/pending") => match EVAL_PENDING.lock().unwrap().pop_front() {+            Some((id, code)) => json_resp(&json!({ "id": id.to_string(), "code": code }).to_string()),+            None => json_resp("{}"),+        },+        (Method::Get, "/console") => {+            let log = CONSOLE.lock().unwrap().clone().unwrap_or_default();+            json_resp(&json!({ "lines": log }).to_string())+        }+        (Method::Post, "/console") => {+            if let Ok(v) = serde_json::from_str::<Value>(body) {+                let line = format!("[{}] {}", v.get("level").and_then(|l| l.as_str()).unwrap_or("log"), v.get("msg").and_then(|m| m.as_str()).unwrap_or(""));+                if let Some(buf) = CONSOLE.lock().unwrap().as_mut() { buf.push(line); let n = buf.len(); if n > 500 { buf.drain(0..n - 500); } }+            }+            json_resp("{\"ok\":true}")+        }+        (Method::Post, "/shutdown") => json_resp("{\"ok\":true}"),+        _ if url.starts_with("/eval/") => {+            let rest = &url["/eval/".len()..];+            if let Some(id_str) = rest.strip_suffix("/result") {+                if matches!(method, Method::Post) {+                    if let (Ok(id), Ok(v)) = (id_str.parse::<u64>(), serde_json::from_str::<Value>(body)) {+                        if let Some(map) = EVAL_RESULTS.lock().unwrap().as_mut() { map.insert(id, v); }+                    }+                    return json_resp("{\"ok\":true}");+                }+            }+            if let Ok(id) = rest.parse::<u64>() {+                let map = EVAL_RESULTS.lock().unwrap();+                if let Some(r) = map.as_ref().and_then(|m| m.get(&id)) {+                    return json_resp(&json!({ "done": true, "result": r }).to_string());+                }+                return json_resp("{\"done\":false}");+            }+            not_found()+        }+        _ => not_found(),+    }+}++/// Component enrichment: mpn (+optional lcsc) → price/stock/wiki/popularity.+/// Delegates to sibling Adom CLIs (adom-parts-search, adom-wiki-cli); cached+/// in-process. Best-effort — never blocks the UI, returns {} on any failure.+fn enrich(query: &str) -> String {+    let params = parse_query(query);+    let mpn = match params.get("mpn") { Some(m) if !m.is_empty() => m.clone(), _ => return "{}".into() };+    let lcsc = params.get("lcsc").cloned().unwrap_or_default();+    let key = format!("{mpn}|{lcsc}");+    if let Some(hit) = ENRICH_CACHE.lock().unwrap().as_ref().and_then(|m| m.get(&key).cloned()) { return hit; }+    // not cached — kick a one-off background fill (deduped) and tell the client+    // to retry. NEVER block the single-threaded server loop on a vendor call.+    let already = { let mut g = ENRICH_PENDING.lock().unwrap(); let set = g.get_or_insert_with(Default::default); !set.insert(key.clone()) };+    if !already {+        std::thread::spawn(move || { let _ = enrich_fill(&mpn, &lcsc); });+    }+    "{\"pending\":true}".into()+}++fn parse_query(q: &str) -> HashMap<String, String> {+    q.split('&').filter_map(|kv| {+        let mut it = kv.splitn(2, '=');+        Some((it.next()?.to_string(), urldecode(it.next().unwrap_or(""))))+    }).collect()+}+fn urldecode(s: &str) -> String {+    let b = s.as_bytes(); let mut out = String::new(); let mut i = 0;+    while i < b.len() {+        match b[i] {+            b'%' if i + 2 < b.len() => { if let Ok(c) = u8::from_str_radix(&s[i + 1..i + 3], 16) { out.push(c as char); i += 3; } else { out.push('%'); i += 1; } }+            b'+' => { out.push(' '); i += 1; }+            c => { out.push(c as char); i += 1; }+        }+    }+    out+}++// ── HD port registration (best-effort; no-op outside Hydrogen Desktop) ──+fn register_port(port: u16, name: &str, reason: &str) {+    let body = format!("{{\"port\":{port},\"action\":\"register\",\"name\":\"{name}\",\"reason\":\"{reason}\",\"expose\":\"internal\"}}");+    std::thread::spawn(move || hd_post(&body));+}+fn unregister_port(port: u16) { hd_post(&format!("{{\"port\":{port},\"action\":\"unregister\"}}")); }+fn hd_post(body: &str) {+    use std::io::Write;+    use std::net::{TcpStream, ToSocketAddrs};+    use std::time::Duration;+    let addr = match ("host.docker.internal", 47084u16).to_socket_addrs().ok().and_then(|mut a| a.next()) { Some(a) => a, None => return };+    if let Ok(mut s) = TcpStream::connect_timeout(&addr, Duration::from_millis(800)) {+        let _ = s.set_write_timeout(Some(Duration::from_millis(800)));+        let req = format!("POST /port-forward HTTP/1.1\r\nHost: host.docker.internal\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", body.len(), body);+        let _ = s.write_all(req.as_bytes());+    }+}++fn hdr(ct: &str) -> Header { Header::from_bytes(&b"Content-Type"[..], ct.as_bytes()).unwrap() }+fn resp(s: &str, ct: &str) -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string(s).with_header(hdr(ct)) }+fn json_resp(s: &str) -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string(s).with_header(hdr("application/json")) }+fn not_found() -> Response<std::io::Cursor<Vec<u8>>> { Response::from_string("{\"error\":\"not found\"}").with_status_code(404).with_header(hdr("application/json")) }+fn json_err(code: u16, msg: &str) -> Response<std::io::Cursor<Vec<u8>>> {+    Response::from_string(json!({ "ok": false, "error": msg }).to_string()).with_status_code(code).with_header(hdr("application/json"))+}
src/sexpr.rsadded+35
@@ -0,0 +1,35 @@+//! Tiny shared S-expression helpers used by both the PCB and schematic+//! renderers (balanced-paren block slicing + escaping).++/// Balanced-paren slice of every `(<tag>` block whose tag is followed by a+/// whitespace/paren boundary (so `(net` never matches `(net_name`).+pub fn blocks<'a>(s: &'a str, tag: &str) -> Vec<&'a str> {+    let bytes = s.as_bytes();+    let needle = format!("({}", tag);+    let mut out = Vec::new();+    let mut search = 0;+    while let Some(rel) = s[search..].find(&needle) {+        let start = search + rel;+        let after = start + needle.len();+        let ok = bytes.get(after).map(|c| c.is_ascii_whitespace() || *c == b'(').unwrap_or(false);+        if !ok { search = after; continue; }+        let mut depth = 0i32;+        let mut end = start;+        for i in start..s.len() {+            match bytes[i] {+                b'(' => depth += 1,+                b')' => { depth -= 1; if depth == 0 { end = i; break; } }+                _ => {}+            }+        }+        out.push(&s[start..=end.min(s.len() - 1)]);+        search = end + 1;+    }+    out+}++pub fn esc(s: &str) -> String {+    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")+}++pub fn f(cap: Option<regex::Match>) -> f64 { cap.and_then(|m| m.as_str().parse().ok()).unwrap_or(0.0) }
src/viewer.jsadded+508
@@ -0,0 +1,508 @@+/* adom-2dboard interactive viewer core — shared by the live app (app.html) and the+ * self-contained embed (embed.html). Consumes window.__PCB__ = { svg, meta }+ * (embed) OR fetches /state (live). The whole reason this works: the SVG is+ * self-rendered with data-net / data-ref / data-pad, so net/trace highlighting+ * and component hover are pure DOM queries. */+(function () {+  "use strict";+  const $ = (s, r) => (r || document).querySelector(s);+  const state = { meta: null, active: null, pinned: null, scale: 1, enrichCache: {}, side: "top", raised: null };++  // ── mount ──────────────────────────────────────────────────────────────+  function mount(svgText, meta) {+    state.meta = meta || { net_names: {}, components: [] };+    const box = $("#svgbox");+    box.innerHTML = svgText;+    const svg = box.querySelector("svg");+    if (!svg) return;+    svg.removeAttribute("width");+    svg.removeAttribute("height");+    svg.style.width = "100%";+    svg.style.height = "100%";+    state.svg = svg;+    state.vb = (svg.getAttribute("viewBox") || "0 0 10 10").split(/\s+/).map(Number);+    state.vb0 = state.vb.slice();+    fitOverlayToBase(svg);+    wireHover(svg);+    wirePanZoom(svg);+    buildLayerHUD();+    buildNetList();+    setStat();+    updateChrome();+  }+  // Show the side panel (Layers/Nets) + stat only when there's room — i.e. the+  // standalone tab or a fullscreened pane. In a small embedded thumbnail (APM+  // board view) the chrome is hidden so it doesn't clutter the little preview.+  function updateChrome() {+    const big = innerWidth > 620;+    // Header only when standalone/large; inside APM's iframe (embed) APM already+    // wears the canonical header, so we'd double it. Panels still show when big.+    document.body.classList.toggle("chrome", big && !window.__EMBED__);+    ["#side", "#stat"].forEach((s) => { const e = $(s); if (e) e.style.display = big ? "" : "none"; });+  }+  addEventListener("resize", updateChrome);++  // ── observability: mirror console + errors to the server ring buffer (GET+  // /console). Live-server only (an embed has no server). ──+  function post(path, body) { try { fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); } catch (e) {} }+  function wireObservability() {+    if (window.__EMBED__) return;+    ["log", "warn", "error"].forEach((k) => { const orig = console[k]; console[k] = function () { try { post("console", { level: k, msg: [].slice.call(arguments).map(String).join(" ") }); } catch (e) {} return orig.apply(console, arguments); }; });+    addEventListener("error", (e) => post("console", { level: "error", msg: (e.message || "") + " @" + (e.filename || "") + ":" + (e.lineno || 0) }));+    addEventListener("unhandledrejection", (e) => post("console", { level: "error", msg: "unhandledrejection: " + (e.reason && e.reason.message || e.reason) }));+  }++  // ── toasts: every action answers back + the AI's live narration channel ──+  const TOAST_ICONS = {+    success: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>',+    error: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>',+    info: '<svg class="ti" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"><path d="M12 8h.01M11 12h1v4h1"/><circle cx="12" cy="12" r="9"/></svg>',+  };+  function toast(msg, type) {+    type = type || "info";+    const box = $("#toasts"); if (!box || !msg) return;+    const el = document.createElement("div"); el.className = "toast " + type;+    el.innerHTML = (TOAST_ICONS[type] || TOAST_ICONS.info) + '<span class="tmsg"></span>';+    el.querySelector(".tmsg").textContent = msg;+    while (box.children.length >= 4) box.removeChild(box.firstChild);+    box.appendChild(el);+    const kill = () => { el.classList.add("out"); setTimeout(() => el.remove(), 200); };+    el.onclick = kill;+    if (type !== "error") setTimeout(kill, 4000);+  }+  // Drain AI-pushed toasts + drive-commands (POST /ui/toast, /ui/cmd). Live only.+  function pollUi() {+    if (window.__EMBED__) return;+    fetch("ui/pull").then((r) => r.json()).then((q) => {+      (q.toasts || []).forEach((t) => toast(t.message, t.type));+      (q.cmds || []).forEach(runCmd);+    }).catch(() => {});+    setTimeout(pollUi, 1000);+  }+  function runCmd(c) {+    if (!c || !c.action) return;+    if (c.action === "fit") { fit(); toast("Fit to view", "info"); }+    else if (c.action === "net" && c.arg) { highlightNet(c.arg); toast("Net " + c.arg, "info"); }+    else if (c.action === "clear") { clearNet && clearNet(); toast("Cleared", "info"); }+    else if (c.action === "toast") { toast(c.arg || "", c.type || "info"); }+  }++  // ── tooltip: body-appended fixed div, 600ms reveal, clamped to viewport ──+  let ttEl = null, ttTimer = null;+  function showTip(target, e) {+    const msg = target.getAttribute("data-tip"); if (!msg) return;+    clearTimeout(ttTimer);+    const cx = e.clientX, cy = e.clientY;+    ttTimer = setTimeout(() => {+      if (!ttEl) { ttEl = document.createElement("div"); ttEl.id = "tt"; document.body.appendChild(ttEl); }+      ttEl.textContent = msg; ttEl.style.left = "-9999px"; ttEl.style.top = "0px"; ttEl.classList.add("show");+      const M = 8, w = ttEl.offsetWidth, h = ttEl.offsetHeight;+      let x = cx + 14, y = cy + 16;+      if (x + w > innerWidth - M) x = cx - w - 14;+      if (y + h > innerHeight - M) y = cy - h - 14;+      x = Math.max(M, Math.min(x, innerWidth - w - M));+      y = Math.max(M, Math.min(y, innerHeight - h - M));+      ttEl.style.left = x + "px"; ttEl.style.top = y + "px";+    }, 600);+  }+  function hideTip() { clearTimeout(ttTimer); if (ttEl) ttEl.classList.remove("show"); }+  document.addEventListener("mouseover", (e) => { const t = e.target.closest && e.target.closest("[data-tip]"); if (t) showTip(t, e); });+  document.addEventListener("mouseout", (e) => { if (e.target.closest && e.target.closest("[data-tip]")) hideTip(); });+  document.addEventListener("mousedown", hideTip);++  // ── header subject ──+  function setSubject(name, meta) {+    const n = $("#hdr-name"), m = $("#hdr-meta");+    if (n) n.textContent = name || "";+    if (m) m.textContent = meta || "";+  }+  function fitToast() { fit(); toast("Fit to view", "info"); }++  // ── net + component highlighting ─────────────────────────────────────────+  function highlightNet(net) {+    if (net == null || net === "0" || net === "") return clearNet();+    state.active = net;+    state.svg.classList.add("dim");+    state.svg.querySelectorAll(".adom-overlay [data-net]").forEach((el) => {+      el.classList.toggle("hl", el.getAttribute("data-net") === String(net));+    });+    const name = state.meta.net_names[net] || "(unnamed)";+    const cnt = state.svg.querySelectorAll('.adom-overlay [data-net="' + net + '"]').length;+    chip('<b>net</b> ' + escapeHtml(name) + ' <span class="muted">· ' + cnt + " items</span>");+    document.querySelectorAll("#netlist .netrow").forEach((r) => r.classList.toggle("sel", r.getAttribute("data-net") === String(net)));+  }+  function clearNet() {+    if (state.pinned != null) return; // keep pinned net lit+    state.active = null;+    state.svg.classList.remove("dim");+    state.svg.querySelectorAll(".hl").forEach((el) => el.classList.remove("hl"));+    document.querySelectorAll("#netlist .netrow.sel").forEach((r) => r.classList.remove("sel"));+    chip("");+  }+  // gentle single-pad highlight (hover)+  function padHl(pad) { clearPadHl(); pad.classList.add("pad-hl"); }+  function clearPadHl() { state.svg.querySelectorAll(".pad-hl").forEach((el) => el.classList.remove("pad-hl")); }++  // ── CROSS-PROBE: click a part here → highlight the SAME reference in the sibling+  // schematic view (and vice-versa), relayed by the host (APM) between the two+  // same-origin iframes. Keyed by the component reference (both views tag by it). ──+  function xpost(ref) { try { if (window.parent && window.parent !== window) window.parent.postMessage({ adomXprobe: true, ref: ref }, "*"); } catch (e) {} }+  function clearComp() { if (state.svg) state.svg.querySelectorAll(".comp-xhl").forEach((el) => el.classList.remove("comp-xhl")); }+  function highlightComp(ref) {+    clearComp();+    if (!state.svg || !ref) return;+    state.svg.querySelectorAll('[data-ref="' + cssEsc(ref) + '"]').forEach((el) => el.classList.add("comp-xhl"));+  }+  // union bbox of the component's pads (svg user units = board mm), for recenter+  function compBBox(ref) {+    let mnx = 1e9, mny = 1e9, mxx = -1e9, mxy = -1e9, found = false;+    state.svg.querySelectorAll('[data-ref="' + cssEsc(ref) + '"]').forEach((el) => {+      try { const b = el.getBBox(); if (b.width || b.height) { mnx = Math.min(mnx, b.x); mny = Math.min(mny, b.y); mxx = Math.max(mxx, b.x + b.width); mxy = Math.max(mxy, b.y + b.height); found = true; } } catch (e) {}+    });+    return found ? [mnx, mny, mxx, mxy] : null;+  }+  function centerOn(ref) { const bb = compBBox(ref); if (bb) frameBBox(bb); }+  // Zoom-to-fit a bbox: frame the part with margin (matching the viewport aspect),+  // keep some context for tiny parts, never zoom out past the whole board.+  function frameBBox(bb) {+    if (!bb || !state.svg) return;+    const x0 = bb[0], y0 = bb[1], x1 = bb[2], y1 = bb[3], cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;+    const rc = state.svg.getBoundingClientRect();+    const aspect = (rc.width && rc.height) ? rc.width / rc.height : ((state.vb0[2] / state.vb0[3]) || 1);+    let span = Math.max(x1 - x0, y1 - y0, 0.3) * 3.2; // the part fills ~1/3 of the short side+    span = Math.max(span, 8);                          // don't over-zoom a tiny footprint+    let w = aspect >= 1 ? span * aspect : span;+    let h = aspect >= 1 ? span : span / aspect;+    if (w > state.vb0[2] && h > state.vb0[3]) { w = state.vb0[2]; h = state.vb0[3]; }+    state.vb = [cx - w / 2, cy - h / 2, w, h];+    state.svg.setAttribute("viewBox", state.vb.join(" "));+  }+  function xclear() { try { if (window.parent && window.parent !== window) window.parent.postMessage({ adomXprobe: true, clear: true }, "*"); } catch (e) {} }+  // Apply a cross-probe FROM the schematic view: HIGHLIGHT ONLY + recenter (no info+  // card — the card shows only when the user clicks a part IN this app). No re-emit.+  function applyXprobe(ref) { if (!ref) return; highlightComp(ref); centerOn(ref); }+  // deselect propagated from the sibling view → clear our cross-probe highlight+  function applyXclear() { clearComp(); }+  addEventListener("message", (e) => { const d = e.data; if (!d || !d.adomXprobe) return; if (d.clear) applyXclear(); else if (d.ref) applyXprobe(d.ref); });++  function wireHover(svg) {+    // HOVER: pads + vias. Highlight the element + show its info. No net/fill lighting.+    svg.addEventListener("mousemove", (e) => {+      const pad = e.target.closest(".adom-pad");+      if (pad) { padHl(pad); showPadCard(pad, e); return; }+      const via = e.target.closest(".adom-via");+      if (via) { padHl(via); showViaCard(via, e); return; }+      clearPadHl(); hideCard();+    });+    svg.addEventListener("mouseleave", () => { clearPadHl(); hideCard(); });+    // CLICK: light up the whole net (the "fill") + show fill info. Toggle off on+    // empty click or clicking the same net again.+    svg.addEventListener("click", (e) => {+      // A pan-drag ends with mouseup then click; if the pointer actually moved,+      // this "click" is the tail of a drag — don't highlight where the drag stopped.+      if (svg.__panned) { svg.__panned = false; return; }+      const t = e.target.closest("[data-net]");+      // click empty space = deselect here AND in the sibling schematic view+      if (!t) { state.pinned = null; clearNet(); clearComp(); xclear(); return; }+      const net = t.getAttribute("data-net");+      state.pinned = state.pinned === net ? null : net;+      if (state.pinned) highlightNet(net); else clearNet();+      // Net highlighting is NET-ONLY: do NOT add the component teal outline (comp-xhl)+      // here — it competes with the net highlight. We still cross-probe the part to the+      // schematic so it follows along; explicit component selection (and its teal+      // outline in this view) comes from the schematic side via applyXprobe.+      const ref = t.getAttribute("data-ref");+      if (ref) xpost(ref);+    });+  }++  // ── pad info card (with async enrichment for the parent part) ─────────────+  function showPadCard(pad, e) {+    const ref = pad.getAttribute("data-ref");+    const num = pad.getAttribute("data-pad");+    const net = pad.getAttribute("data-net");+    const c = (state.meta.components || []).find((k) => k.reference === ref) || {};+    const card = $("#card");+    const mpn = c.mpn || "";+    const netName = (state.meta.net_names || {})[net] || (net === "0" ? "(no net)" : "net " + net);+    const rows = [];+    rows.push('<div class="ci-h"><span class="ci-ref">' + escapeHtml(ref || "?") + ' · pad ' + escapeHtml(num || "?") ++      '</span><span class="ci-val">' + escapeHtml(c.value || "") + "</span></div>");+    rows.push(row("net", netName));+    rows.push(row("pad", (pad.getAttribute("data-size") || "") + " · " + (pad.getAttribute("data-shape") || "") + " · " + (pad.getAttribute("data-side") === "B" ? "bottom" : "top")));+    if (mpn) rows.push(row("mpn", mpn));+    if (c.lcsc) rows.push(row("lcsc", c.lcsc));+    rows.push('<div class="ci-enrich" id="ci-enrich">' + (mpn ? '<span class="muted">loading price · stock · wiki…</span>' : "") + "</div>");+    card.innerHTML = rows.join("");+    card.style.display = "block";+    placeCard(card, e);+    if (mpn) enrich(mpn, c.lcsc);+  }+  function showViaCard(via, e) {+    const net = via.getAttribute("data-net");+    const netName = (state.meta.net_names || {})[net] || (net === "0" ? "(no net)" : "net " + net);+    const card = $("#card");+    card.innerHTML = '<div class="ci-h"><span class="ci-ref">via</span></div>' + row("net", netName);+    card.style.display = "block";+    placeCard(card, e);+  }+  function row(k, v) { return '<div class="ci-row"><span class="ci-k">' + k + '</span><span class="ci-v">' + escapeHtml(String(v)) + "</span></div>"; }+  function hideCard() { const c = $("#card"); if (c) c.style.display = "none"; }+  function placeCard(card, e) {+    const pad = 14, w = card.offsetWidth, h = card.offsetHeight;+    let x = e.clientX + pad, y = e.clientY + pad;+    if (x + w > innerWidth) x = e.clientX - w - pad;+    if (y + h > innerHeight) y = e.clientY - h - pad;+    card.style.left = Math.max(4, x) + "px";+    card.style.top = Math.max(4, y) + "px";+  }+  function enrich(mpn, lcsc) {+    const key = mpn + "|" + (lcsc || "");+    const render = (d) => {+      const el = $("#ci-enrich");+      if (!el || state.enrichKey !== key) return;+      if (!d || d.error) { el.innerHTML = '<span class="muted">enrichment unavailable</span>'; return; }+      const parts = [];+      if (d.stock != null) parts.push('<span class="pill ' + (d.stock > 0 ? "ok" : "no") + '">' + (d.stock > 0 ? d.stock + " in stock" : "no stock") + "</span>");+      if (d.price) parts.push('<span class="pill">' + escapeHtml(d.price) + "</span>");+      if (d.tier) parts.push('<span class="pill tier">' + escapeHtml(d.tier) + "</span>");+      if (d.popularity != null) parts.push('<span class="pill pop">★ ' + d.popularity + "</span>");+      let html = '<div class="pills">' + parts.join("") + "</div>";+      if (d.wiki_url) html += '<a class="ci-wiki" href="' + escapeHtml(d.wiki_url) + '" target="_blank" rel="noopener">wiki page ↗</a>';+      el.innerHTML = html || '<span class="muted">no data</span>';+    };+    state.enrichKey = key;+    if (state.enrichCache[key]) return render(state.enrichCache[key]);+    if (typeof fetch !== "function" || window.__EMBED__) return render(null);+    const url = "enrich?mpn=" + encodeURIComponent(mpn) + (lcsc ? "&lcsc=" + encodeURIComponent(lcsc) : "");+    let tries = 0;+    const go = () => fetch(url).then((r) => r.json()).then((d) => {+      if (d && d.pending && tries++ < 20) { setTimeout(go, 1500); return; } // vendor lookup warming+      state.enrichCache[key] = d; render(d);+    }).catch(() => render(null));+    go();+  }++  // When the visual base is the EDA's OWN exported SVG (Altium's render/pcb.svg),+  // the base is in PDF pixel space and our overlay is in board mm — unrelated+  // systems. Measure both with getBBox() (which accounts for any transforms the+  // exporter baked in) and scale/translate the overlay onto the base.+  function fitOverlayToBase(svg) {+    const base = svg.querySelector(".adom-base");+    const fit = svg.querySelector(".adom-fit");+    if (!base || !fit) return;+    let bb, ob;+    try { bb = base.getBBox(); ob = fit.getBBox(); } catch (e) { return; }+    if (!bb.width || !bb.height || !ob.width || !ob.height) return;+    // uniform scale so the overlay can't shear relative to the render+    const s = Math.min(bb.width / ob.width, bb.height / ob.height);+    const tx = bb.x + (bb.width - ob.width * s) / 2 - ob.x * s;+    const ty = bb.y + (bb.height - ob.height * s) / 2 - ob.y * s;+    fit.setAttribute("transform", "translate(" + tx + " " + ty + ") scale(" + s + ")");+    state.baseFit = s;+  }++  // ── pan / zoom (mutate viewBox) ───────────────────────────────────────────+  function wirePanZoom(svg) {+    svg.addEventListener("wheel", (e) => {+      e.preventDefault();+      const [x, y, w, h] = state.vb;+      const f = e.deltaY > 0 ? 1.12 : 0.893;+      const r = svg.getBoundingClientRect();+      const mx = x + ((e.clientX - r.left) / r.width) * w;+      const my = y + ((e.clientY - r.top) / r.height) * h;+      const nw = Math.min(state.vb0[2] * 8, Math.max(state.vb0[2] / 200, w * f));+      const nh = nw * (h / w);+      state.vb = [mx - (mx - x) * (nw / w), my - (my - y) * (nh / h), nw, nh];+      svg.setAttribute("viewBox", state.vb.join(" "));+    }, { passive: false });+    let drag = null;+    svg.addEventListener("mousedown", (e) => { drag = { x: e.clientX, y: e.clientY, vb: state.vb.slice() }; svg.__panned = false; });+    addEventListener("mouseup", () => (drag = null));+    addEventListener("mousemove", (e) => {+      if (!drag) return;+      // Past a small threshold this is a real pan, not a jittery click — mark it so+      // the trailing click doesn't net-highlight where the drag was released.+      if (Math.abs(e.clientX - drag.x) + Math.abs(e.clientY - drag.y) > 4) svg.__panned = true;+      const r = svg.getBoundingClientRect();+      const dx = ((e.clientX - drag.x) / r.width) * drag.vb[2];+      const dy = ((e.clientY - drag.y) / r.height) * drag.vb[3];+      state.vb = [drag.vb[0] - dx, drag.vb[1] - dy, drag.vb[2], drag.vb[3]];+      svg.setAttribute("viewBox", state.vb.join(" "));+    });+  }+  function fit() { if (state.svg) { state.vb = state.vb0.slice(); state.svg.setAttribute("viewBox", state.vb.join(" ")); } }++  // ── Layers HUD ────────────────────────────────────────────────────────────+  // key = <g class="adom-layer-KEY">; label shown; on = visible by default.+  // KiCad-native base layers (each a <g class="adom-layer-KEY"> wrapping the EDA SVG)+  const LAYERS = [+    ["copperF", "Copper · Top", true], ["copperB", "Copper · Bot", true],+    ["maskF", "Mask · Top", true], ["maskB", "Mask · Bot", true],+    ["silkF", "Silk · Top", true], ["silkB", "Silk · Bot", true],+    ["fabF", "Fab · Top", true], ["fabB", "Fab · Bot", true],+    ["crtydF", "Courtyard · Top", false], ["crtydB", "Courtyard · Bot", false],+    ["edge", "Board edge", true],+  ];+  const SIDED = ["copper", "mask", "silk", "fab", "crtyd"]; // bases with F/B groups+  // canonical z-order (bottom→top): whole FAR side first, then whole NEAR side.+  // Within a side: mask (under copper), copper, silk, fab, courtyard.+  const STACK = ["mask", "copper", "silk", "fab", "crtyd"];++  // Inner copper layers for THIS board, front->back e.g. ["In1.Cu","In2.Cu"].+  // Comes from meta so a 2/4/6-layer board configures itself.+  function innerLayers() {+    return (state.meta && state.meta.inner_layers) || [];+  }+  const innerKey = (l) => "copper" + String(l).replace(/\.Cu$/, "");++  // Full copper stack, FRONT -> BACK: copperF, copperIn1 .. copperInN, copperB.+  // This is the physical depth order and drives both z-ordering and dimming.+  function copperStack() {+    return ["copperF", ...innerLayers().map(innerKey), "copperB"];+  }++  function order(side) {+    const F = side !== "bottom";+    const lo = (b) => (F ? b + "B" : b + "F"); // far+    const hi = (b) => (F ? b + "F" : b + "B"); // near+    // inner copper sits physically between the two sides. Deepest-from-the-viewer+    // first: viewing top that's In(n)..In1; viewing bottom it reverses.+    const inners = innerLayers().map(innerKey);+    const mid = F ? inners.slice().reverse() : inners.slice();+    return [...STACK.map(lo), ...mid, ...STACK.map(hi), "edge"];+  }+  function setActiveSide(side) {+    state.side = side;+    const svg = state.svg, flip = svg.querySelector(".adom-flip");+    if (!flip) return;+    order(side).forEach((k) => { const g = svg.querySelector(".adom-layer-" + k); if (g) flip.appendChild(g); });+    const ov = svg.querySelector(".adom-overlay"); if (ov) flip.appendChild(ov); // overlay stays on top+    // MIRROR the board about its vertical centre when viewing the bottom+    const cx = parseFloat(flip.getAttribute("data-cx")) || 0;+    if (side === "bottom") flip.setAttribute("transform", "translate(" + (2 * cx) + " 0) scale(-1 1)");+    else flip.removeAttribute("transform");+    // fade the FAR side back (like KiCad) so the near side reads clearly+    const far = side === "bottom" ? "F" : "B", near = side === "bottom" ? "B" : "F";+    SIDED.forEach((base) => {+      const fg = svg.querySelector(".adom-layer-" + base + far); if (fg) fg.style.opacity = "0.28";+      const ng = svg.querySelector(".adom-layer-" + base + near); if (ng) ng.style.opacity = "1";+    });+    // buried copper reads dimmed until explicitly raised+    innerLayers().map(innerKey).forEach((k) => {+      const g = svg.querySelector(".adom-layer-" + k); if (g) g.style.opacity = "0.28";+    });+    state.raised = null;+    document.querySelectorAll("#sidebtns .sidebtn").forEach((b) => b.classList.toggle("on", b.dataset.side === side));+    markRaised();+  }++  // Copper layers physically IN FRONT of `key`, from the current viewing side.+  // Viewing top, in front of In2 = [In1, F]; viewing bottom it is [In1's far side…]+  // i.e. the same stack walked from the other end.+  function copperInFrontOf(key) {+    const stack = state.side === "bottom" ? copperStack().slice().reverse() : copperStack();+    const i = stack.indexOf(key);+    return i <= 0 ? [] : stack.slice(0, i);+  }++  function markRaised() {+    document.querySelectorAll("#layers .lyr").forEach((r) => {+      r.classList.toggle("raised", r.dataset.key === state.raised);+    });+  }++  function raise(key) {+    const svg = state.svg, flip = svg.querySelector(".adom-flip"), g = svg.querySelector(".adom-layer-" + key);+    if (!g || !flip) return;++    // Raising the SAME layer twice restores the normal stack.+    if (state.raised === key) { setActiveSide(state.side); return; }++    flip.appendChild(g);+    const ov = svg.querySelector(".adom-overlay"); if (ov) flip.appendChild(ov);+    const cb = document.querySelector('#layers input[data-layer="' + key + '"]');+    if (cb && !cb.checked) { cb.checked = true; g.style.display = ""; }++    if (copperStack().indexOf(key) >= 0) {+      // Bring this copper layer fully forward and dim everything stacked in front+      // of it — the near outer layer AND any intermediate inner layers — so the+      // raised layer reads clearly through the board.+      g.style.opacity = "1";+      copperInFrontOf(key).forEach((k) => {+        const o = svg.querySelector(".adom-layer-" + k); if (o) o.style.opacity = "0.28";+      });+      state.raised = key;+      markRaised();+    }+  }+  // LAYERS + this board's inner copper, inserted right after Copper · Top so the+  // panel reads in physical stack order (Top, In1, In2, Bot).+  function layerRows() {+    const inners = innerLayers().map((l) => [innerKey(l), "Copper · " + String(l).replace(/\.Cu$/, ""), true]);+    if (!inners.length) return LAYERS;+    const rows = LAYERS.slice();+    const at = rows.findIndex(([k]) => k === "copperF");+    rows.splice(at < 0 ? 0 : at + 1, 0, ...inners);+    return rows;+  }++  function buildLayerHUD() {+    const el = $("#layers"); if (!el) return;+    el.innerHTML =+      '<div id="sidebtns"><span class="lbl">Front side</span>' ++      '<button class="sidebtn on" data-side="top">Top</button>' ++      '<button class="sidebtn" data-side="bottom">Bottom</button></div>' ++      layerRows().map(([k, label, on]) =>+        '<div class="lyr" data-key="' + k + '"><input type="checkbox" data-layer="' + k + '"' + (on ? " checked" : "") ++        '><span class="lyr-name" data-raise="' + k + '">' + label + "</span></div>"+      ).join("");+    el.querySelectorAll("input").forEach((cb) => cb.addEventListener("change", () => {+      const g = state.svg.querySelector(".adom-layer-" + cb.getAttribute("data-layer"));+      if (g) g.style.display = cb.checked ? "" : "none";+    }));+    el.querySelectorAll(".lyr-name").forEach((n) => n.addEventListener("click", () => raise(n.dataset.raise)));+    el.querySelectorAll("#sidebtns .sidebtn").forEach((b) => b.addEventListener("click", () => setActiveSide(b.dataset.side)));+    // apply default order + hide default-off layers+    setActiveSide("top");+    layerRows().filter(([, , on]) => !on).forEach(([k]) => { const g = state.svg.querySelector(".adom-layer-" + k); if (g) g.style.display = "none"; });+  }+  function buildNetList() {+    const el = $("#netlist"); if (!el) return;+    const names = state.meta.net_names || {};+    const rows = Object.keys(names).filter((k) => k !== "0" && names[k]).sort((a, b) => names[a].localeCompare(names[b]));+    el.innerHTML = rows.map((id) => '<div class="netrow" data-net="' + id + '">' + escapeHtml(names[id]) + "</div>").join("") || '<div class="muted">no named nets</div>';+    el.querySelectorAll(".netrow").forEach((r) => {+      // click-to-toggle only (net/fill highlight is a click action, not hover)+      r.addEventListener("click", () => { const n = r.getAttribute("data-net"); state.pinned = state.pinned === n ? null : n; state.pinned ? highlightNet(n) : clearNet(); });+    });+  }+  function setStat() {+    const m = state.meta, el = $("#stat");+    const txt = (m.components ? m.components.length : 0) + " components · " + (m.track_count || 0) + " tracks · " + (Object.keys(m.net_names || {}).length) + " nets";+    if (el) el.textContent = txt;+    setSubject(m.name || "Board", txt);+  }++  // ── helpers ───────────────────────────────────────────────────────────────+  function chip(html) { const c = $("#netchip"); if (!c) return; c.innerHTML = html; c.style.display = html ? "block" : "none"; }+  function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c])); }+  function cssEsc(s) { return String(s).replace(/["\\]/g, "\\$&"); }++  // ── boot ──────────────────────────────────────────────────────────────────+  window.AdomPcb = { mount, fit, highlightNet, toast, runCmd };+  function boot() {+    $("#fitbtn") && $("#fitbtn").addEventListener("click", fitToast);+    $("#hdr-fit") && $("#hdr-fit").addEventListener("click", fitToast);+    if (window.__PCB__) { window.__EMBED__ = true; mount(window.__PCB__.svg, window.__PCB__.meta); return; }+    // live mode: AI channel (toasts + drive cmds), console ring buffer, header version+    wireObservability();+    pollUi();+    fetch("version").then((r) => r.json()).then((v) => { const el = $("#ai-ver"); if (el && v && v.version) el.textContent = "v" + v.version; }).catch(() => {});+    fetch("state").then((r) => r.json()).then((s) => {+      if (s && s.svg) mount(s.svg, s.meta || {});+      else $("#svgbox").innerHTML = '<div class="empty">No board loaded. POST a .kicad_pcb to /load.</div>';+    }).catch(() => { $("#svgbox").innerHTML = '<div class="empty">server unreachable</div>'; });+  }+  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot); else boot();+})();
uninstall.shadded+6
@@ -0,0 +1,6 @@+#!/bin/bash+# uninstall.sh for adom-2dboard (app).+set -euo pipefail++rm -f "${HOME}/.local/bin/adom-2dboard"+echo "Uninstalled adom-2dboard"