Public: anyone can read this; the crew can change it.

KiCad boards draw their outline and list their layers in the browser #16033

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16015-kicad-boards-draw-their-outline-and-list → main 0 commits fork 7 threads · 7 unresolved

  • Merged. torque/16015-kicad-boards-draw-their-outline-and-list was merged into main as 48a5ed3.

Review

Sign in to review this change.
15 files changed +621 −16
docs/design/areas/render.md +4
@@ -94,3 +94,7 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
9494 ## Copper layer (.gbr)
9595
9696 `src/web/render/gerber.ts` draws a Gerber layer as one inline SVG in `.gerber-view` (same rules as `.dxf-view`: no fixed size, `max-width: 100%`, `currentColor`, no accent), with its units, board size and counts as the existing `.status-rows`.
97
98 ## KiCad board (.kicad_pcb)
99
100 `src/web/render/kicad.ts` draws the Edge.Cuts outline as one inline SVG in the existing `.gerber-view` (no new class: `currentColor`, no fixed size), with units, board size and counts as the existing `.status-rows`. The layers are a second `.status-rows` (name, type).
docs/features/file-kicad.md added +22
@@ -0,0 +1,22 @@
1 ---
2 topic: Files in the browser
3 row: A .kicad_pcb file as its outline
4 ---
5 # A .kicad_pcb file as its outline
6
7 A KiCad board (`.kicad_pcb`, an s-expression opening `(kicad_pcb`) opens on its
8 blob page as an SVG of its Edge.Cuts outline, with its layer list and counts of
9 footprints, tracks, vias and zones as text. Source is one tap away.
10
11 - `src/web/render/kicad.ts` parses and draws; `kinds.ts` maps the extension to
12 the `kicad` kind (the first bytes must be `(kicad_pcb`, else the file stays
13 text); `renderers.ts` names the renderer.
14 - Drawn: `gr_line`, `gr_arc` (three-point and the older angle form), `gr_circle`,
15 `gr_rect` and `gr_poly` on Edge.Cuts, in millimetres. Counted, not drawn:
16 footprints, tracks, vias, zones; graphics inside footprints.
17 - At most 20,000 outline graphics are drawn and 64 layers listed, the rest said
18 so. A file over 5 MB or that does not parse keeps the source view, with the
19 reason in one line.
20 - The MCP `read_file` tool answers the same facts as `about` for a `.kicad_pcb`:
21 `{kind, version, layers, copperLayers, footprints, tracks, vias, outlineItems, size}`.
22 - Try it: commit a `.kicad_pcb` file to a repository and open its file page.
docs/features/file-kinds.md +1
@@ -55,6 +55,7 @@ The forge draws a file on its page when its kind is below and it is within the s
5555 - **G-code**, drawn up to 50 MB: `.gcode`, `.gco`
5656 - **DXF drawing**, drawn up to 5 MB: `.dxf`, a file that opens on 0 then SECTION
5757 - **Gerber layer**, drawn up to 5 MB: `.gbr`, `.gtl`, `.gbl`
58 - **KiCad board**, drawn up to 5 MB: `.kicad_pcb`
5859 - **Mermaid diagram**, drawn up to 1 MB: `.mmd`, `.mermaid`
5960 - **draw.io diagram**, drawn up to 1 MB: `.drawio`
6061 - **Excalidraw**, drawn up to 1 MB: `.excalidraw`
scripts/kinds-guide.ts +1 −1
@@ -14,7 +14,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1414 slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", xcf: "GIMP", cad: "CAD or 3D source (header facts)", cert: "PEM certificate", sbom: "Bill of materials (CycloneDX, SPDX)", wasm: "WebAssembly module", config: "Config", markdown: "Markdown",
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
1616 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
17 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
17 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", kicad: "KiCad board", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
1818 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile",
2020 dockerfile: "Dockerfile", workflow: "GitHub workflow", compose: "Compose file", sql: "SQL", graphql: "GraphQL",
src/http/mcp/tools/read_file.ts +5
@@ -4,6 +4,7 @@ import { isSafeRef, isSafeTreePath } from "../../../git/guard.ts";
44 import { blobForRender, listTree } from "../../../git/read.ts";
55 import { readStl, sayStl, stlSize, TOO_LARGE } from "../../../text/stl.ts";
66 import { checkConfig, configKind, type ConfigKind } from "../../../text/config_check.ts";
7 import { kicadFacts, parseKicad } from "../../../web/render/kicad.ts";
78 import { aboutUsd } from "../../../web/render/usd.ts";
89 import { readMidi, Unreadable } from "../../../web/render/midi.ts";
910 import { aboutPcd } from "../../../web/render/pcd.ts";
@@ -76,6 +77,10 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
7677 const { format, triangles } = stl.value;
7778 return { kind: "stl", format, triangles, size: stlSize(stl.value), says: sayStl(stl.value) };
7879 }
80 if (/\.kicad_pcb$/i.test(path) && text !== undefined) {
81 const board = parseKicad(text);
82 return "error" in board ? { kind: "kicad_pcb", parses: false, message: board.error } : kicadFacts(board);
83 }
7984 if (/\.(usda|usdz)$/i.test(path)) {
8085 const usd = aboutUsd(path, body);
8186 if (usd) return usd;
src/web/render/bounds.ts added +27
@@ -0,0 +1,27 @@
1 /** Shared by the drawn formats: a number read from a file, and the box that grows around points. */
2
3 /**
4 * The value as a finite number no larger than `limit` in size; a string is read as a number, blank
5 * is none.
6 */
7 export const within = (v: unknown, limit: number): number | undefined => {
8 const n = typeof v === "string" ? (v.trim() === "" ? NaN : Number(v)) : v;
9 return typeof n === "number" && Number.isFinite(n) && Math.abs(n) <= limit ? n : undefined;
10 };
11
12 export interface Box {
13 minX: number;
14 minY: number;
15 maxX: number;
16 maxY: number;
17 }
18
19 /** An empty box (Infinity bounds) that `grow` widens to include each point. */
20 export const emptyBox = (): Box => ({ minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity });
21
22 export const grow = (b: Box, x: number, y: number): void => {
23 b.minX = Math.min(b.minX, x);
24 b.maxX = Math.max(b.maxX, x);
25 b.minY = Math.min(b.minY, y);
26 b.maxY = Math.max(b.maxY, y);
27 };
src/web/render/diagram.ts +6 −10
@@ -15,6 +15,7 @@ import { html, raw } from "../html.ts";
1515 import type { Rendered, RenderInput } from "./renderers.ts";
1616 import { RENDER_CAP } from "./kinds.ts";
1717 import { fileSize } from "../ui.ts";
18 import { emptyBox, grow, within } from "./bounds.ts";
1819
1920 /** Elements drawn in all; the rest are counted out. */
2021 export const ELEMENT_CAP = 5_000;
@@ -28,10 +29,7 @@ export type Item =
2829 | { readonly t: "line"; readonly pts: readonly (readonly [number, number])[]; readonly arrow: boolean }
2930 | { readonly t: "text"; readonly x: number; readonly y: number; readonly lines: readonly string[]; readonly size: number; readonly anchor: "start" | "middle" };
3031
31 const num = (v: unknown): number | undefined => {
32 const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
33 return typeof n === "number" && Number.isFinite(n) && Math.abs(n) <= LIMIT ? n : undefined;
34 };
32 const num = (v: unknown): number | undefined => within(v, LIMIT);
3533
3634 const ENTITIES: Record<string, string> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'", nbsp: " " };
3735 const decode = (s: string): string =>
@@ -163,11 +161,8 @@ const f = (n: number): string => (Number.isFinite(n) ? n : 0).toFixed(1);
163161
164162 /** One SVG body and its extent, from the items. Pure. */
165163 export function draw(items: readonly Item[]): { width: number; height: number; body: string } {
166 let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
167 const see = (x: number, y: number): void => {
168 minX = Math.min(minX, x); maxX = Math.max(maxX, x);
169 minY = Math.min(minY, y); maxY = Math.max(maxY, y);
170 };
164 const box = emptyBox();
165 const see = (x: number, y: number): void => grow(box, x, y);
171166 let body = "";
172167 for (const it of items) {
173168 if (it.t === "box") {
@@ -193,7 +188,8 @@ export function draw(items: readonly Item[]): { width: number; height: number; b
193188 .join("")}</text>`;
194189 }
195190 }
196 if (!Number.isFinite(minX)) { minX = minY = 0; maxX = maxY = 1; }
191 if (!Number.isFinite(box.minX)) Object.assign(box, { minX: 0, minY: 0, maxX: 1, maxY: 1 });
192 const { minX, minY, maxX, maxY } = box;
197193 return { width: Math.ceil(maxX - minX + 2 * PAD), height: Math.ceil(maxY - minY + 2 * PAD), body: `<g transform="translate(${f(PAD - minX)} ${f(PAD - minY)})">${body}</g>` };
198194 }
199195
src/web/render/dxf.ts +2 −5
@@ -16,6 +16,7 @@ import { html, raw } from "../html.ts";
1616 import type { Rendered, RenderInput } from "./renderers.ts";
1717 import { RENDER_CAP } from "./kinds.ts";
1818 import { fileSize } from "../ui.ts";
19 import { within } from "./bounds.ts";
1920
2021 /** Entities drawn in all; the rest are counted but not drawn. */
2122 export const ENTITY_CAP = 50_000;
@@ -42,11 +43,7 @@ export interface Drawing {
4243
4344 const DRAWN = new Set(["LINE", "CIRCLE", "ARC", "LWPOLYLINE"]);
4445
45 const num = (s: string | undefined): number | undefined => {
46 if (s === undefined || s.trim() === "") return undefined;
47 const n = Number(s);
48 return Number.isFinite(n) && Math.abs(n) <= LIMIT ? n : undefined;
49 };
46 const num = (s: string | undefined): number | undefined => within(s, LIMIT);
5047
5148 /** Parse DXF text. Pure. An error string when it cannot be drawn. */
5249 export function parseDxf(text: string): Drawing | { error: string } {
src/web/render/kicad.ts added +378
@@ -0,0 +1,378 @@
1 /**
2 * A KiCad board (`.kicad_pcb`: an s-expression opening `(kicad_pcb`) drawn as
3 * inline SVG of its Edge.Cuts outline, with its layer list and counts of
4 * footprints, tracks and vias. Format per the KiCad "PCB file format"
5 * documentation (dev-docs.kicad.org, file formats): every coordinate is in
6 * millimetres, y grows downward (as on the screen, so no flip), `(layers (N
7 * "name" type))` declares the stack, `gr_line`/`gr_arc`/`gr_circle`/`gr_rect`/
8 * `gr_poly` on layer "Edge.Cuts" are the outline. An arc is `(start)(mid)(end)`
9 * (KiCad 7 and later) or, in older files, `(start centre)(end)(angle degrees)`.
10 *
11 * Drawn: the Edge.Cuts graphics only. Counted and not drawn: footprints,
12 * segments, arcs (tracks), vias and zones; outline graphics inside footprints.
13 * The file is read in one pass that keeps only the nodes it needs and skips the
14 * rest by depth; depth, layers and drawn items are capped, and the size cap
15 * bounds the loop first. Every number is finite and clamped, every string escaped.
16 */
17
18 import { html, raw } from "../html.ts";
19 import type { Rendered, RenderInput } from "./renderers.ts";
20 import { RENDER_CAP } from "./kinds.ts";
21 import { fileSize } from "../ui.ts";
22 import { emptyBox, grow, within } from "./bounds.ts";
23
24 /** Outline items drawn in all; the rest are counted. */
25 export const OUTLINE_CAP = 20_000;
26 /** Layers kept and listed. */
27 export const LAYER_CAP = 64;
28 /** Nesting kept for a node we read; deeper is a malformed file. */
29 const DEPTH_CAP = 32;
30 /** Coordinates beyond this many millimetres are treated as corrupt. */
31 const LIMIT = 1e5;
32
33 type Node = string | Node[];
34 type Pt = readonly [number, number];
35
36 export type Shape =
37 | { readonly t: "line"; readonly a: Pt; readonly b: Pt }
38 | { readonly t: "arc"; readonly a: Pt; readonly m: Pt; readonly b: Pt }
39 | { readonly t: "circle"; readonly c: Pt; readonly r: number }
40 | { readonly t: "poly"; readonly pts: Pt[] };
41
42 export interface Board {
43 readonly version: string;
44 readonly layers: { readonly name: string; readonly type: string }[];
45 readonly footprints: number;
46 readonly tracks: number;
47 readonly vias: number;
48 readonly zones: number;
49 readonly outline: Shape[];
50 /** Edge.Cuts graphics left out past OUTLINE_CAP, or with unreadable numbers. */
51 readonly dropped: number;
52 }
53
54 const WANTED = new Set(["version", "layers", "gr_line", "gr_arc", "gr_circle", "gr_rect", "gr_poly"]);
55
56 /** Read the top-level children of `(kicad_pcb …)`; skipped ones are only counted by name. */
57 function scan(text: string): { top: Node[]; counts: Map<string, number> } | { error: string } {
58 const counts = new Map<string, number>();
59 const top: Node[] = [];
60 const n = text.length;
61 let pos = 0;
62 if (text.charCodeAt(0) === 0xfeff) pos = 1;
63 // token: "(" ")" or a string/atom; undefined at the end
64 const next = (): string | undefined => {
65 while (pos < n && text.charCodeAt(pos) <= 32) pos++;
66 if (pos >= n) return undefined;
67 const c = text[pos]!;
68 if (c === "(" || c === ")") {
69 pos++;
70 return c;
71 }
72 if (c === '"') {
73 let out = "";
74 pos++;
75 while (pos < n && text[pos] !== '"') {
76 if (text[pos] === "\\" && pos + 1 < n) pos++;
77 out += text[pos++];
78 }
79 if (pos >= n) return undefined;
80 pos++;
81 return `"${out}`;
82 }
83 const s = pos;
84 while (pos < n && text.charCodeAt(pos) > 32 && text[pos] !== "(" && text[pos] !== ")") pos++;
85 return text.slice(s, pos);
86 };
87 const atom = (t: string): string => (t.startsWith('"') ? t.slice(1) : t);
88 if (next() !== "(" || next() !== "kicad_pcb") return { error: "it does not open on (kicad_pcb" };
89 const stack: Node[][] = [];
90 let skipping = 0; // depth to unwind while skipping an unwanted child
91 let depth = 1;
92 for (let t = next(); t !== undefined; t = next()) {
93 if (skipping > 0) {
94 if (t === "(") skipping++;
95 else if (t === ")") {
96 skipping--;
97 if (skipping === 0) depth = 1;
98 }
99 continue;
100 }
101 if (t === "(") {
102 if (depth === 1) {
103 const head = next();
104 if (head === undefined) return { error: "it ends inside a list" };
105 if (head === "(" || head === ")") return { error: "it is not a KiCad board" };
106 const name = atom(head);
107 counts.set(name, (counts.get(name) ?? 0) + 1);
108 if (!WANTED.has(name)) {
109 skipping = 1;
110 continue;
111 }
112 stack.push([name]);
113 depth = 2;
114 } else {
115 if (stack.length >= DEPTH_CAP) return { error: "it nests lists too deeply" };
116 stack.push([]);
117 depth++;
118 }
119 } else if (t === ")") {
120 if (depth === 1) return { top, counts };
121 const done = stack.pop()!;
122 depth--;
123 if (depth === 1) top.push(done);
124 else stack[stack.length - 1]!.push(done);
125 } else if (depth > 1) stack[stack.length - 1]!.push(atom(t));
126 }
127 return { error: "it ends before the board's closing parenthesis" };
128 }
129
130 const child = (node: Node[], name: string): Node[] | undefined => node.find((c): c is Node[] => Array.isArray(c) && c[0] === name);
131 const num = (v: Node | undefined): number | undefined => (typeof v === "string" ? within(v, LIMIT) : undefined);
132 const pt = (node: Node[] | undefined): Pt | undefined => {
133 if (!node) return undefined;
134 const x = num(node[1]), y = num(node[2]);
135 return x === undefined || y === undefined ? undefined : [x, y];
136 };
137 const onEdge = (node: Node[]): boolean => {
138 const l = child(node, "layer");
139 return typeof l?.[1] === "string" && l[1] === "Edge.Cuts";
140 };
141
142 /** The point a sweep of `deg` degrees from `a` about `c` reaches, and the one halfway. */
143 function arcFromAngle(c: Pt, a: Pt, deg: number): { m: Pt; b: Pt } {
144 const r = Math.hypot(a[0] - c[0], a[1] - c[1]);
145 const a0 = Math.atan2(a[1] - c[1], a[0] - c[0]);
146 const at = (k: number): Pt => [c[0] + r * Math.cos(a0 + k), c[1] + r * Math.sin(a0 + k)];
147 const rad = (deg * Math.PI) / 180;
148 return { m: at(rad / 2), b: at(rad) };
149 }
150
151 function shapeOf(node: Node[]): Shape | undefined {
152 const kind = node[0];
153 const a = pt(child(node, "start"));
154 const b = pt(child(node, "end"));
155 if (kind === "gr_line") return a && b ? { t: "line", a, b } : undefined;
156 if (kind === "gr_rect") {
157 return a && b ? { t: "poly", pts: [a, [b[0], a[1]], b, [a[0], b[1]]] } : undefined;
158 }
159 if (kind === "gr_circle") {
160 const c = pt(child(node, "center"));
161 return c && b ? { t: "circle", c, r: Math.hypot(b[0] - c[0], b[1] - c[1]) } : undefined;
162 }
163 if (kind === "gr_arc") {
164 const m = pt(child(node, "mid"));
165 if (a && m && b) return { t: "arc", a, m, b };
166 const ang = num(child(node, "angle")?.[1]);
167 if (a && b && ang !== undefined) {
168 // the old form: start is the centre, end the first point
169 const r = arcFromAngle(a, b, ang);
170 return { t: "arc", a: b, m: r.m, b: r.b };
171 }
172 return undefined;
173 }
174 if (kind === "gr_poly") {
175 const pts: Pt[] = [];
176 for (const p of child(node, "pts")?.slice(1) ?? []) {
177 if (!Array.isArray(p) || p[0] !== "xy") continue;
178 const q = pt(p);
179 if (q === undefined) return undefined;
180 pts.push(q);
181 }
182 return pts.length >= 3 ? { t: "poly", pts } : undefined;
183 }
184 return undefined;
185 }
186
187 /** Parse a board. Pure. An error string when it is not a readable KiCad board. */
188 export function parseKicad(text: string): Board | { error: string } {
189 const s = scan(text);
190 if ("error" in s) return s;
191 const layers: { name: string; type: string }[] = [];
192 const outline: Shape[] = [];
193 let version = "", dropped = 0;
194 for (const node of s.top) {
195 if (!Array.isArray(node)) continue;
196 const kind = node[0];
197 if (kind === "version") version = typeof node[1] === "string" ? node[1].slice(0, 20) : "";
198 else if (kind === "layers") {
199 for (const l of node.slice(1)) {
200 if (!Array.isArray(l) || typeof l[1] !== "string") continue;
201 if (layers.length < LAYER_CAP) layers.push({ name: l[1].slice(0, 60), type: typeof l[2] === "string" ? l[2].slice(0, 20) : "" });
202 }
203 } else if (onEdge(node)) {
204 const sh = shapeOf(node);
205 if (sh === undefined || outline.length >= OUTLINE_CAP) dropped++;
206 else outline.push(sh);
outdated

Clean: num duplicates the one in dxf.ts. Reuse a shared helper.

207 }
208 }
209 const c = (k: string): number => s.counts.get(k) ?? 0;
210 return {
211 version,
212 layers,
213 footprints: c("footprint") + c("module"),
214 tracks: c("segment") + c("arc"),
215 vias: c("via"),
216 zones: c("zone"),
217 outline,
218 dropped,
219 };
220 }
221
222 const W = 640;
223 const MAX_H = 480;
224 const PAD = 12;
225
226 /** Circle through three points: centre and radius, or undefined when they are in line. */
227 function circle3(a: Pt, m: Pt, b: Pt): { c: Pt; r: number } | undefined {
228 const d = 2 * (a[0] * (m[1] - b[1]) + m[0] * (b[1] - a[1]) + b[0] * (a[1] - m[1]));
229 if (Math.abs(d) < 1e-12) return undefined;
230 const sa = a[0] ** 2 + a[1] ** 2, sm = m[0] ** 2 + m[1] ** 2, sb = b[0] ** 2 + b[1] ** 2;
231 const x = (sa * (m[1] - b[1]) + sm * (b[1] - a[1]) + sb * (a[1] - m[1])) / d;
232 const y = (sa * (b[0] - m[0]) + sm * (a[0] - b[0]) + sb * (m[0] - a[0])) / d;
233 const r = Math.hypot(a[0] - x, a[1] - y);
234 return Number.isFinite(r) && r <= LIMIT * 10 ? { c: [x, y], r } : undefined;
235 }
236
237 /**
238 * An arc's circle and signed sweep in radians (positive: increasing angle, clockwise on screen).
239 */
240 function arcSweep(a: Pt, m: Pt, b: Pt): { k: { c: Pt; r: number }; a0: number; span: number } | undefined {
241 const k = circle3(a, m, b);
242 if (!k) return undefined;
243 const ang = (p: Pt): number => Math.atan2(p[1] - k.c[1], p[0] - k.c[0]);
244 const TAU = Math.PI * 2;
245 const mod = (v: number): number => ((v % TAU) + TAU) % TAU;
246 const fwd = mod(ang(b) - ang(a));
247 // going forward from a we meet m before b, else the sweep runs the other way round
248 return { k, a0: ang(a), span: mod(ang(m) - ang(a)) <= fwd ? fwd : fwd - TAU };
249 }
250
251 /** Points along an arc, for its extent: 24 steps of the sweep from a through m to b. */
252 function arcPoints(a: Pt, m: Pt, b: Pt): Pt[] {
253 const w = arcSweep(a, m, b);
254 if (!w) return [a, m, b];
255 const out: Pt[] = [];
256 for (let i = 0; i <= 24; i++) {
257 const t = w.a0 + (w.span * i) / 24;
258 out.push([w.k.c[0] + w.k.r * Math.cos(t), w.k.c[1] + w.k.r * Math.sin(t)]);
259 }
260 return out;
261 }
262
263 export interface Extent {
264 readonly minX: number;
265 readonly minY: number;
266 readonly maxX: number;
267 readonly maxY: number;
268 }
269
270 /** Bounds of the outline, in millimetres. */
271 export function extentOf(shapes: readonly Shape[]): Extent {
272 const box = emptyBox();
273 const at = (x: number, y: number): void => grow(box, x, y);
274 for (const s of shapes) {
275 if (s.t === "line") [s.a, s.b].forEach((p) => at(p[0], p[1]));
276 else if (s.t === "poly") s.pts.forEach((p) => at(p[0], p[1]));
277 else if (s.t === "circle") {
278 at(s.c[0] - s.r, s.c[1] - s.r);
279 at(s.c[0] + s.r, s.c[1] + s.r);
280 } else arcPoints(s.a, s.m, s.b).forEach((p) => at(p[0], p[1]));
281 }
282 return box;
283 }
284
285 /** The SVG body and size, the outline fitted to the page. */
286 export function draw(shapes: readonly Shape[]): { width: number; height: number; body: string } {
287 const e = extentOf(shapes);
288 const spanX = Math.max(e.maxX - e.minX, 1e-9);
289 const spanY = Math.max(e.maxY - e.minY, 1e-9);
outdated

Clean: grow is the same as in diagram.ts. Reuse a shared helper.

290 let scale = (W - 2 * PAD) / spanX;
291 let height = spanY * scale + 2 * PAD;
292 if (height > MAX_H) {
293 scale = (MAX_H - 2 * PAD) / spanY;
294 height = MAX_H;
295 }
296 const width = Math.max(spanX * scale + 2 * PAD, 2 * PAD + 1);
297 const f = (v: number): string => (Number.isFinite(v) ? v : 0).toFixed(2);
298 const X = (v: number): string => f(PAD + (v - e.minX) * scale);
299 const Y = (v: number): string => f(PAD + (v - e.minY) * scale);
300 let d = "";
301 let circles = "";
302 for (const s of shapes) {
303 if (s.t === "line") d += `M${X(s.a[0])} ${Y(s.a[1])}L${X(s.b[0])} ${Y(s.b[1])}`;
304 else if (s.t === "poly") d += s.pts.map((p, i) => `${i === 0 ? "M" : "L"}${X(p[0])} ${Y(p[1])}`).join("") + "Z";
305 else if (s.t === "circle") circles += `<circle cx="${X(s.c[0])}" cy="${Y(s.c[1])}" r="${f(s.r * scale)}"/>`;
306 else {
307 const w = arcSweep(s.a, s.m, s.b);
308 if (!w) d += `M${X(s.a[0])} ${Y(s.a[1])}L${X(s.b[0])} ${Y(s.b[1])}`;
309 else {
310 // SVG sweep-flag 1 turns toward increasing angle, which is clockwise with y down
311 const R = f(w.k.r * scale);
312 d += `M${X(s.a[0])} ${Y(s.a[1])}A${R} ${R} 0 ${Math.abs(w.span) > Math.PI ? 1 : 0} ${w.span > 0 ? 1 : 0} ${X(s.b[0])} ${Y(s.b[1])}`;
313 }
314 }
315 }
316 const body =
317 `<g fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">` +
318 (d === "" ? "" : `<path d="${d}"/>`) +
319 `${circles}</g>`;
320 return { width: Math.round(width), height: Math.round(height), body };
321 }
outdated

Format, strip commas, then parse is a roundabout way to round. Use Math.round(x*1000)/1000.

322
323 const fmt = (n: number): string => Number(n.toFixed(3)).toLocaleString("en", { maximumFractionDigits: 3 });
324 const round3 = (n: number): number => Math.round(n * 1000) / 1000;
325 const plural = (n: number, one: string): string => `${n.toLocaleString("en")} ${one}${n === 1 ? "" : "s"}`;
326
327 const COPPER = new Set(["signal", "power", "mixed", "jumper"]);
328
329 /** The facts a reader (a page or the MCP file tool) wants, as plain data. */
330 export function kicadFacts(b: Board): Record<string, unknown> {
331 const e = extentOf(b.outline);
332 const size = b.outline.length === 0 ? undefined : { width: round3(e.maxX - e.minX), height: round3(e.maxY - e.minY), unit: "mm" };
333 return {
334 kind: "kicad_pcb",
335 version: b.version,
336 layers: b.layers.map((l) => l.name),
337 copperLayers: b.layers.filter((l) => COPPER.has(l.type)).length,
338 footprints: b.footprints,
339 tracks: b.tracks,
340 vias: b.vias,
341 outlineItems: b.outline.length,
342 ...(size ? { size } : {}),
343 };
344 }
345
346 export function kicad(input: RenderInput): Rendered {
347 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
348 if (input.size > RENDER_CAP.kicad || input.body.length > RENDER_CAP.kicad) return fall("it is too large to draw");
349 let board: Board | { error: string };
350 try {
351 board = parseKicad(new TextDecoder().decode(input.body));
352 } catch {
353 return fall("it could not be read as a KiCad board");
354 }
355 if ("error" in board) return fall(board.error);
356 const has = board.outline.length > 0;
357 const e = extentOf(board.outline);
358 const size = has ? `${fmt(e.maxX - e.minX)} × ${fmt(e.maxY - e.minY)} mm` : "";
359 const facts: [string, string][] = [["Units", "millimetres"]];
360 if (has) facts.push(["Board size", size]);
361 else facts.push(["Outline", "none"]);
362 const copper = board.layers.filter((l) => COPPER.has(l.type)).length;
363 facts.push(["Layers", `${plural(board.layers.length, "layer")}, ${plural(copper, "copper layer")}`]);
364 facts.push(["Parts", `${plural(board.footprints, "footprint")}, ${plural(board.tracks, "track")}, ${plural(board.vias, "via")}, ${plural(board.zones, "zone")}`]);
365 if (board.dropped > 0) facts.push(["Not drawn", `${plural(board.dropped, "outline graphic")} unreadable or past the first ${OUTLINE_CAP.toLocaleString("en")}`]);
outdated

Principle 1/8: the parenthetical re-explains the label. Drop it: the value is 30 × 20 mm.

366 const drawn = has ? draw(board.outline) : undefined;
367 const svg = drawn ? html`<svg viewBox="0 0 ${drawn.width} ${drawn.height}" role="img" aria-label="${`Board outline, ${size}`}">${raw(drawn.body)}</svg>` : html``;
368 const layerRows =
369 board.layers.length === 0
370 ? html``
outdated

Principle 2/7: the layers are one comma string in a dd. Render them as rows (name, type).

371 : html`<dl class="status-rows" aria-label="Layers">${board.layers.map((l) => html`<div class="status-row"><dt>${l.name}</dt><dd>${l.type === "" ? "unspecified" : l.type}</dd></div>`)}</dl>`;
372 const content = html`<figure class="gerber-view">
373 ${svg}
374 <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>
375 ${layerRows}
376 </figure>`;
377 return { content, lines: 0, summary: `${has ? size + " · " : ""}${fileSize(input.size)}` };
378 }
src/web/render/kinds.ts +7
@@ -67,6 +67,7 @@ export type FileKind =
6767 | "gcode"
6868 | "dxf"
6969 | "gerber"
70 | "kicad"
7071 | "mermaid"
7172 | "drawio"
7273 | "excalidraw"
@@ -176,6 +177,7 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
176177 gcode: 50 * MB,
177178 dxf: 5 * MB,
178179 gerber: 5 * MB,
180 kicad: 5 * MB,
179181 mermaid: 1 * MB,
180182 drawio: 1 * MB,
181183 excalidraw: 1 * MB,
@@ -468,6 +470,9 @@ const isDxfHead = (head: Uint8Array): boolean =>
468470 const isGerberHead = (head: Uint8Array): boolean =>
469471 /%(FS[LT]?[AI]?X\d\dY\d\d|MO(MM|IN))|^\uFEFF?\s*G04/.test(new TextDecoder().decode(head.subarray(0, 1024)));
470472
473 /** A KiCad board opens on a `(kicad_pcb` list. */
474 const isKicadHead = (head: Uint8Array): boolean => /^\uFEFF?\s*\(\s*kicad_pcb[\s(]/.test(new TextDecoder().decode(head.subarray(0, 256)));

Missing blank line between isKicadHead and the next doc comment.

475
471476 /** A USD text layer opens on `#usda` and a version. */
472477 export const isUsdaHead = (head: Uint8Array): boolean =>
473478 /^\uFEFF?#usda\s+\d/.test(new TextDecoder().decode(head.subarray(0, 32)));
@@ -625,6 +630,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
625630 if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text";
626631 if (ext === "iges" || ext === "igs") return isIgesHead(head) ? "iges" : "text";
627632 if (ext === "gbr" || ext === "gtl" || ext === "gbl") return isGerberHead(head) ? "gerber" : "text";
633 if (ext === "kicad_pcb") return isKicadHead(head) ? "kicad" : "text";
628634 // A USD text layer opens on `#usda`: a `.usda` that does not is only text.
629635 if (ext === "usda") return isUsdaHead(head) ? "usd" : "text";
630636 // RTF opens on `{\rtf`: a `.rtf` whose bytes say otherwise is only text.
@@ -776,6 +782,7 @@ const SNIFFED_EXTENSIONS: Readonly<Partial<Record<FileKind, readonly string[]>>>
776782 wasm: ["wasm"],
777783 cad: [...FACTS_EXTENSIONS],
778784 prproj: ["prproj"],
785 kicad: ["kicad_pcb"],
779786 };
780787
781788 /** What names a kind, for the guide: extensions and file names, each once, to show as code. */
src/web/render/renderers.ts +2
@@ -30,6 +30,7 @@ import { geojson } from "./geojson.ts";
3030 import { kml } from "./kml.ts";
3131 import { dxf } from "./dxf.ts";
3232 import { gerber } from "./gerber.ts";
33 import { kicad } from "./kicad.ts";
3334 import { drawio, excalidraw, mermaid } from "./diagram.ts";
3435 import { step } from "./step.ts";
3536 import { iges } from "./iges.ts";
@@ -164,6 +165,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
164165 gcode,
165166 dxf,
166167 gerber,
168 kicad,
167169 mermaid,
168170 drawio,
169171 excalidraw,
test/fuzz-renderers.test.ts +4
@@ -131,6 +131,10 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
131131 path: "top.gtl",
132132 files: ["%FSLAX24Y24*%\n%MOMM*%\n%ADD10C,0.5*%\n%ADD11R,1X<script>*%\nD10*\nX0Y0D02*\nG01X10000Y0D01*\nD11*\nX5000Y5000D03*\nG36*\nX0Y0D02*\nX1000Y0D01*\nX1000Y1000D01*\nG37*\nM02*\n"],
133133 },
134 kicad: {
135 path: "a.kicad_pcb",
136 files: ['(kicad_pcb (version 20221018) (layers (0 "F.Cu<script>" signal) (44 "Edge.Cuts" user)) (footprint "<b>") (via (at 1 1)) (gr_line (start 0 0) (end 10 0) (layer "Edge.Cuts")) (gr_arc (start 10 0) (mid 12 2) (end 10 4) (layer "Edge.Cuts")) (gr_circle (center 5 5) (end 6 5) (layer "Edge.Cuts")))'],
137 },
134138 drawio: {
135139 path: "a.drawio",
136140 files: [
test/mcp-read-file.test.ts +15
@@ -68,6 +68,10 @@ beforeAll(async () => {
6868 { path: "bad.json", content: '{\n "a": }' },
6969 { path: "good.json", content: "{}" },
7070 ] }));
71 ok(await commitToBranch(app, owner, pub, { message: "kicad", files: [
72 { path: "board.kicad_pcb", content: '(kicad_pcb (version 20221018) (layers (0 "F.Cu" signal) (44 "Edge.Cuts" user)) (footprint "R") (via (at 1 1)) (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts")))' },
73 { path: "bad.kicad_pcb", content: "(kicad_pcb (version 1)" },
74 ] }));
7175 ok(await commitToBranch(app, owner, pub, { message: "gimp", files: [{ path: "art.xcf", content: xcfFile([["Sky", { w: 200, h: 100, x: 3, y: 4 }]]) }, { path: "bad.xcf", content: "gimp xcf nope" }] }));
7276 const movie = concat(ftyp(), box("moov", mvhd0(600, 600 * 92), box("trak", tkhd(0, 1920, 1080))));
7377 ok(await commitToBranch(app, owner, pub, { message: "movie", files: [{ path: "clip.mp4", content: movie }] }));
@@ -173,6 +177,17 @@ test("a .xcf file carries its canvas and layers as about, or says it is unreadab
173177 expect((await read(tok["stranger"]!, { repo: "ada/pub", path: "bad.xcf" })).value.about.says).toBe("GIMP, unreadable");
174178 });
175179
180 test("a KiCad board is described by its layers, counts and outline size", async () => {
181 const t = tok["stranger"]!;
182 const good = (await read(t, { repo: "ada/pub", path: "board.kicad_pcb" })).value;
183 expect(good.about).toEqual({
184 kind: "kicad_pcb", version: "20221018", layers: ["F.Cu", "Edge.Cuts"], copperLayers: 1,
185 footprints: 1, tracks: 0, vias: 1, outlineItems: 1, size: { width: 30, height: 20, unit: "mm" },
186 });
187 const bad = (await read(t, { repo: "ada/pub", path: "bad.kicad_pcb" })).value;
188 expect(bad.about.parses).toBe(false);
189 });
190
176191 test("a .tfstate file carries about with its secrets masked", async () => {
177192 const file = (await read(tok["stranger"]!, { repo: "ada/pub", path: "infra/terraform.tfstate" })).value;
178193 expect(file.about.kind).toBe("tfstate");
test/render-kicad.test.ts added +146
@@ -0,0 +1,146 @@
1 /** KiCad boards (.kicad_pcb): the Edge.Cuts outline as inline SVG, with layers and counts. */
2 import { describe, expect, test } from "bun:test";
3 import { draw, extentOf, kicad, kicadFacts, LAYER_CAP, OUTLINE_CAP, parseKicad } from "../src/web/render/kicad.ts";
4 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
5 import { RENDERERS } from "../src/web/render/renderers.ts";
6
7 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
8 // A 30 x 20 mm board: four lines, a half-round notch (arc) is left out so the size is exact.
9 const GOOD = `(kicad_pcb (version 20221018) (generator "pcbnew")
10 (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (36 "B.SilkS" user "B.Silkscreen") (44 "Edge.Cuts" user))
11 (footprint "R_0603" (layer "F.Cu") (at 5 5) (fp_line (start 0 0) (end 1 1) (layer "Edge.Cuts")))
12 (footprint "C_0603" (layer "F.Cu") (at 9 5))
13 (segment (start 1 1) (end 2 2) (width 0.25) (layer "F.Cu") (net 1))
14 (via (at 3 3) (size 0.8) (drill 0.4) (layers "F.Cu" "B.Cu") (net 1))
15 (gr_line (start 0 0) (end 30 0) (layer "Edge.Cuts") (width 0.1))
16 (gr_line (start 30 0) (end 30 20) (layer "Edge.Cuts") (width 0.1))
17 (gr_line (start 30 20) (end 0 20) (layer "Edge.Cuts") (width 0.1))
18 (gr_line (start 0 20) (end 0 0) (layer "Edge.Cuts") (width 0.1))
19 (gr_line (start -50 -50) (end 50 50) (layer "F.SilkS") (width 0.1)))`;
20 const run = (text: string) => kicad({ path: "b.kicad_pcb", size: text.length, body: enc(text), media: "/m", download: "/d" });
21
22 describe("kicad", () => {
23 test("registered by extension, confirmed by the first bytes", () => {
24 expect(fileKind("a.kicad_pcb", enc(GOOD))).toBe("kicad");
25 expect(fileKind("a.kicad_pcb", enc("hello\n"))).toBe("text");
26 expect(fileKind("a.kicad_pcb", enc("(kicad_sch (version 1))"))).toBe("text");
27 expect(RENDERERS.kicad).toBe(kicad);
28 expect(RENDER_CAP.kicad).toBeGreaterThan(0);
29 });
30
31 test("parses by hand: layers, counts, a 30 x 20 mm outline", () => {
32 const b = parseKicad(GOOD);
33 if ("error" in b) throw new Error(b.error);
34 expect(b.version).toBe("20221018");
35 expect(b.layers.map((l) => l.name)).toEqual(["F.Cu", "B.Cu", "B.SilkS", "Edge.Cuts"]);
36 expect([b.footprints, b.tracks, b.vias]).toEqual([2, 1, 1]);
37 expect(b.outline.length).toBe(4); // the silkscreen line and the footprint's own graphic are not the outline
38 const e = extentOf(b.outline);
39 expect([e.minX, e.minY, e.maxX, e.maxY]).toEqual([0, 0, 30, 20]);
40 expect(kicadFacts(b)).toMatchObject({ copperLayers: 2, size: { width: 30, height: 20, unit: "mm" } });
41 });
42
43 test("draws svg with the size, layers and counts as text", () => {
44 const out = String(run(GOOD).content);
45 expect(out.match(/<svg/g)?.length).toBe(1);
46 expect(out).toContain("<path");
47 expect(out).toContain("30 × 20 mm");
48 expect(out).toContain("2 footprints, 1 track, 1 via");
49 expect(out).toContain("<dt>Edge.Cuts</dt><dd>user</dd>");
50 expect(out).not.toContain("width × height");
51 expect(out).not.toContain("<script");
52 });
53
54 test("an arc is drawn as an A command, a circle as a circle", () => {
55 const t = '(kicad_pcb (gr_arc (start 10 0) (mid 0 10) (end -10 0) (layer "Edge.Cuts")) (gr_circle (center 0 0) (end 3 0) (layer "Edge.Cuts")))';
56 const b = parseKicad(t);
57 if ("error" in b) throw new Error(b.error);
outdated

Tests: no case covers the old angle-form arc, gr_rect, gr_poly (including under 3 points) or the zone count. Each is claimed in the docs.

58 const d = draw(b.outline).body;
59 expect(d).toMatch(/A[\d.]+ [\d.]+ 0 0 1 /); // a half turn is not "large"; (10,0)→(0,10)→(-10,0) runs toward increasing angle, clockwise on screen with y down: sweep 1
60 expect(d).toContain("<circle");
61 const e = extentOf(b.outline);
62 expect(e.maxY).toBeCloseTo(10, 6); // the arc bulges to y=10
63 expect(e.maxX).toBeCloseTo(10, 6);
64 });
65
66 test("the older angle-form arc is drawn about its centre", () => {
67 const b = parseKicad('(kicad_pcb (gr_arc (start 0 0) (end 10 0) (angle 90) (layer "Edge.Cuts")))');
68 if ("error" in b) throw new Error(b.error);
69 expect(b.outline.length).toBe(1);
70 const e = extentOf(b.outline);
71 expect([e.minX, e.maxX, e.maxY].map((v) => Math.round(v * 1e6) / 1e6)).toEqual([0, 10, 10]); // centre (0,0), 10 mm radius, a quarter turn
72 expect(draw(b.outline).body).toContain("A");
73 });
74
75 test("gr_rect is a closed four-corner outline", () => {
76 const b = parseKicad('(kicad_pcb (gr_rect (start 2 3) (end 12 8) (layer "Edge.Cuts")))');
77 if ("error" in b) throw new Error(b.error);
78 const e = extentOf(b.outline);
79 expect([e.minX, e.minY, e.maxX, e.maxY]).toEqual([2, 3, 12, 8]);
80 expect(kicadFacts(b)).toMatchObject({ size: { width: 10, height: 5 } });
81 });
82
83 test("gr_poly is drawn from its points; under 3 points it is dropped and counted", () => {
84 const ok = parseKicad('(kicad_pcb (gr_poly (pts (xy 0 0) (xy 4 0) (xy 4 6)) (layer "Edge.Cuts")))');
85 if ("error" in ok) throw new Error(ok.error);
86 expect([ok.outline.length, ok.dropped]).toEqual([1, 0]);
87 expect(extentOf(ok.outline).maxY).toBe(6);
88 const bad = parseKicad('(kicad_pcb (gr_poly (pts (xy 0 0) (xy 4 0)) (layer "Edge.Cuts")))');
89 if ("error" in bad) throw new Error(bad.error);
90 expect([bad.outline.length, bad.dropped]).toEqual([0, 1]);
91 expect(String(run('(kicad_pcb (gr_poly (pts (xy 0 0) (xy 4 0)) (layer "Edge.Cuts")))').content)).toContain("1 outline graphic");
92 });
93
94 test("zones are counted and shown", () => {
95 const t = '(kicad_pcb (zone (net 1)) (zone (net 2)) (gr_line (start 0 0) (end 1 1) (layer "Edge.Cuts")))';
96 const b = parseKicad(t);
97 if ("error" in b) throw new Error(b.error);
98 expect(b.zones).toBe(2);
99 expect(String(run(t).content)).toContain("2 zones");
100 });
101
102 test("the size is stated once and a missing outline in one word", () => {
103 expect(String(run('(kicad_pcb (layers (0 "F.Cu" signal)))').content)).toContain("<dt>Outline</dt><dd>none</dd>");
104 });
105
106 test("every value from the file is escaped", () => {
107 const t = '(kicad_pcb (layers (0 "<img src=x onerror=alert(1)>" signal)) (gr_line (start 0 0) (end 1 1) (layer "Edge.Cuts")))';
108 const out = String(run(t).content);
109 expect(out).not.toContain("<img");
110 expect(out).toContain("&lt;img");
111 });
112
113 test("a file over the cap keeps the source and says why", () => {
114 const r = kicad({ path: "b.kicad_pcb", size: RENDER_CAP.kicad + 1, body: enc(GOOD), media: "/m", download: "/d" });
115 expect(r.fallback).toContain("too large");
116 });
117
118 test("malformed files fall back with one line", () => {
119 for (const t of ["", "(kicad_sch)", "(kicad_pcb (layers (0 ", "(kicad_pcb (a (b)", '(kicad_pcb (a "unterminated)']) {
120 const r = run(t);
121 expect(r.fallback).toMatch(/^This file is shown as text because .+\.$/);
122 }
123 });
124
125 test("hostile counts and depth are bounded", () => {
126 expect("error" in parseKicad("(kicad_pcb (layers " + "(".repeat(100_000) + ")".repeat(100_000) + "))")).toBe(true);
127 const layers = Array.from({ length: LAYER_CAP * 3 }, (_, i) => `(${i} "L${i}" signal)`).join(" ");
128 const many = Array.from({ length: OUTLINE_CAP + 50 }, () => '(gr_line (start 0 0) (end 1 1) (layer "Edge.Cuts"))').join("");
129 const b = parseKicad(`(kicad_pcb (layers ${layers}) ${many} ${"(via (at 0 0))".repeat(5000)})`);
130 if ("error" in b) throw new Error(b.error);
131 expect(b.layers.length).toBe(LAYER_CAP);
132 expect(b.outline.length).toBe(OUTLINE_CAP);
133 expect(b.dropped).toBe(50);
134 expect(b.vias).toBe(5000);
135 // lying numbers are dropped, not drawn
136 const lie = parseKicad('(kicad_pcb (gr_line (start 0 0) (end 1e999 1) (layer "Edge.Cuts")) (gr_line (start 0 0) (end 4 4) (layer "Edge.Cuts")))');
137 if ("error" in lie) throw new Error(lie.error);
138 expect([lie.outline.length, lie.dropped]).toEqual([1, 1]);
139 });
140
141 test("a board with no outline still lists its facts", () => {
142 const r = run('(kicad_pcb (layers (0 "F.Cu" signal)))');
143 expect(r.fallback).toBeUndefined();
144 expect(String(r.content)).toContain("<dt>Outline</dt><dd>none</dd>");
145 });
146 });
test/render-kinds.test.ts +1
@@ -110,6 +110,7 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
110110 gbr: [enc("%FSLAX24Y24*%\n%MOMM*%\n"), "gerber", "application/octet-stream"],
111111 gtl: [enc("G04 x*\n"), "gerber", "application/octet-stream"],
112112 gbl: [enc("%MOIN*%\n"), "gerber", "application/octet-stream"],
113 kicad_pcb: [enc("(kicad_pcb (version 20221018)\n"), "kicad", "application/octet-stream"],
113114 mmd: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
114115 mermaid: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
115116 drawio: [enc("<mxfile/>"), "drawio", "application/octet-stream"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs