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

A Gerber .gbr file draws its copper layer as an SVG #14468

Merged opened this

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

Merged

torque/forge:torque/14449-a-gerber-gbr-file-draws-its-copper-layer → main 5 commits fork 2 threads · 2 unresolved

  • Merged. torque/14449-a-gerber-gbr-file-draws-its-copper-layer was merged into main as ef11bd4.

Review

Sign in to review this change.
12 files changed +565 −1
docs/design/areas/render.md +4
@@ -86,3 +86,7 @@ A .zip, .tar or .tar.gz is drawn by `src/web/render/archive-view.ts` as the exis
8686 `src/web/render/xml.ts` draws the element tree as nested `ul.xml-tree` (`src/web/style/content.ts`): no bullets, 8px of indent per level with a `--border` rule beside it, so the 24 levels it draws at most still fit 360px, and names, attributes and text wrap (`overflow-wrap: anywhere`) instead of scrolling the page. Tokens only, both themes. An `.rtf` file's text is plain `p` inside the existing `.prose`; an `.ini` is the existing `.table`; neither adds a class.
8787
8888 - `.pdf-facts`: the page count, title and author above a PDF's viewer, one line of label and value pairs.
89
90 ## Copper layer (.gbr)
91
92 `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`.
docs/features/file-gerber.md added +20
@@ -0,0 +1,20 @@
1 ---
2 topic: Files in the browser
3 row: A .gbr file as a picture
4 ---
5 # A .gbr file as a picture
6
7 A Gerber RS-274X layer (`.gbr`, `.gtl`, `.gbl`) opens on its blob page as an SVG
8 of the copper, with its units and board size as text. Source is one tap away.
9
10 - `src/web/render/gerber.ts` parses and draws; `kinds.ts` maps the extensions to
11 the `gerber` kind (the head must carry `%FS`, `%MO` or open on `G04`, else the
12 file stays text); `renderers.ts` names the renderer.
13 - Drawn: flashes of circle, rectangle, obround and polygon apertures, straight
14 and arc tracks, and regions, y up, fitted to the copper's extent.
15 - Counted, not drawn: macro apertures, clear polarity, single-quadrant arcs
16 (G74), step and repeat, other extended commands. Regions draw arcs straight.
17 - At most 50,000 objects are drawn; the page says how many were left out, and the board size still covers them. No
18 units (`%MO`), no format (`%FS`), nothing drawable, or a file over 5 MB: the
19 source view, with the reason.
20 - Try it: commit a `.gbr` file to a repository and open its file page.
docs/features/file-kinds.md +1
@@ -44,6 +44,7 @@ The forge draws a file on its page when its kind is below and it is within the s
4444 - **Email**, drawn up to 5 MB: `.eml`
4545 - **G-code**, drawn up to 50 MB: `.gcode`, `.gco`
4646 - **DXF drawing**, drawn up to 5 MB: `.dxf`, a file that opens on 0 then SECTION
47 - **Gerber layer**, drawn up to 5 MB: `.gbr`, `.gtl`, `.gbl`
4748 - **Mermaid diagram**, drawn up to 1 MB: `.mmd`, `.mermaid`
4849 - **draw.io diagram**, drawn up to 1 MB: `.drawio`
4950 - **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", 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",
17 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
17 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
1818 excalidraw: "Excalidraw", step: "STEP model", 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", makefile: "Makefile",
2020 dockerfile: "Dockerfile", workflow: "GitHub workflow", compose: "Compose file", sql: "SQL", graphql: "GraphQL",
src/web/render/gerber.ts added +365
@@ -0,0 +1,365 @@
1 /**
2 * A Gerber RS-274X file (`.gbr`, `.gtl`, `.gbl`: one copper layer of a printed
3 * circuit board) drawn as inline SVG. Format per the Ucamco "Gerber Layer
4 * Format Specification": `%FS` sets the coordinate format (section 4.2),
5 * `%MO` the units (4.3), `%AD` defines round, rectangle, obround and polygon
6 * apertures (4.4), D01 draws, D02 moves, D03 flashes (4.5), G01/G02/G03 pick
7 * linear or clockwise/counter-clockwise circular interpolation with I/J the
8 * centre offset from the start (4.7), G36/G37 bracket a region (4.10).
9 * Coordinates are absolute; omitted leading zeros (the default) or trailing
10 * zeros are both read. The y axis is flipped for the screen.
11 *
12 * Drawn: flashes of standard apertures, straight and arc tracks (a track is as
13 * wide as its aperture; a non-round one is stroked by its smaller side, an
14 * approximation), and regions. Counted and not drawn: macro apertures, clear
15 * polarity (`%LPC`), single-quadrant arcs (G74) and every other extended command. Arcs in a region
16 * are drawn straight to their end point. Hole parameters are ignored. The size on the page is the
17 * extent of the copper, stroke and aperture half-widths included, in the file's own units. A file
18 * with no `%MO`, no `%FS` or nothing drawable falls back to the source view. Every loop runs over
19 * the file, which the size cap bounds first; every number is finite and clamped, every string
20 * escaped.
21 */
22
23 import { html, raw } from "../html.ts";
24 import type { Rendered, RenderInput } from "./renderers.ts";
25 import { RENDER_CAP } from "./kinds.ts";
26 import { fileSize } from "../ui.ts";
27
28 /** Objects drawn in all; the rest are counted. */
29 export const OBJECT_CAP = 50_000;
30 /** Coordinates and sizes beyond this magnitude are treated as corrupt. */
31 const LIMIT = 1e7;
32
33 type Pt = readonly [number, number];
34 type Aperture =
35 | { readonly s: "C"; readonly d: number }
36 | { readonly s: "R" | "O"; readonly w: number; readonly h: number }
37 | { readonly s: "P"; readonly d: number; readonly n: number; readonly rot: number }
38 | { readonly s: "M" };
39
40 export type Item =
41 | { readonly t: "flash"; readonly at: Pt; readonly ap: Aperture }
42 | { readonly t: "line"; readonly a: Pt; readonly b: Pt; readonly w: number }
43 | { readonly t: "arc"; readonly a: Pt; readonly b: Pt; readonly c: Pt; readonly cw: boolean; readonly w: number }
44 | { readonly t: "region"; readonly pts: Pt[] };
45
46 export interface Layer {
47 readonly unit: "mm" | "in";
48 readonly items: Item[];
49 readonly apertures: number;
50 readonly flashes: number;
51 readonly tracks: number;
52 readonly regions: number;
53 /** Things read but not drawn, by name. */
54 readonly ignored: Map<string, number>;
55 /** Drawable objects left out past OBJECT_CAP. */
56 readonly dropped: number;
57 /** Bounds of everything parsed, dropped objects included. */
58 readonly extent: Extent;
59 }
60
61 export interface Extent {
62 readonly minX: number;
63 readonly minY: number;
64 readonly maxX: number;
65 readonly maxY: number;
66 }
67
68 const finite = (n: number): number | undefined => (Number.isFinite(n) && Math.abs(n) <= LIMIT ? n : undefined);
69
70 /** Parse Gerber text. Pure. An error string when it cannot be drawn. */
71 export function parseGerber(text: string): Layer | { error: string } {
72 let intDigits = 0, decDigits = 0, trailing = false, haveFs = false;
73 let unit: "mm" | "in" | undefined;
74 const apertures = new Map<number, Aperture>();
75 const ignored = new Map<string, number>();
76 const ignore = (what: string): void => void ignored.set(what, (ignored.get(what) ?? 0) + 1);
77 const items: Item[] = [];
78 let flashes = 0, tracks = 0, regions = 0, dropped = 0;
79 let cur: Aperture | undefined;
80 let x = 0, y = 0;
81 let mode: 1 | 2 | 3 = 1;
82 let single = false;
83 let inRegion = false;
84 let contour: Pt[] = [];
85 let clear = false;
86 let sawEnd = false;
87
88 const coord = (s: string): number | undefined => {
89 const neg = s.startsWith("-");
90 let d = s.replace(/^[+-]/, "");
91 if (d === "" || d.length > 20) return undefined;
92 if (trailing) d = d.padEnd(intDigits + decDigits, "0");
93 return finite((neg ? -1 : 1) * (Number(d) / 10 ** decDigits));
94 };
95 let extent: Extent = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
96 const add = (it: Item): void => {
97 const e = extentOf([it]);
98 extent = { minX: Math.min(extent.minX, e.minX), minY: Math.min(extent.minY, e.minY), maxX: Math.max(extent.maxX, e.maxX), maxY: Math.max(extent.maxY, e.maxY) };
99 if (items.length >= OBJECT_CAP) dropped++;
100 else items.push(it);
101 };
102 const closeContour = (): void => {
103 if (contour.length >= 3) {
104 regions++;
105 add({ t: "region", pts: contour });
106 }
107 contour = [];
108 };
109 const width = (a: Aperture | undefined): number =>
110 a === undefined || a.s === "M" ? 0 : a.s === "C" || a.s === "P" ? a.d : Math.min(a.w, a.h);
111
112 const extended = (block: string): void => {
113 for (const cmd of block.split("*")) {
114 const c = cmd.trim();
115 if (c === "") continue;
116 let m: RegExpExecArray | null;
117 if ((m = /^FS([LT]?)([AI]?)X(\d)(\d)Y(\d)(\d)$/.exec(c))) {
118 if (m[2] === "I") return void ignore("incremental coordinates");
119 trailing = m[1] === "T";
120 intDigits = Number(m[3]);
121 decDigits = Number(m[4]);
122 haveFs = intDigits + decDigits > 0;
123 } else if ((m = /^MO(MM|IN)$/.exec(c))) unit = m[1] === "MM" ? "mm" : "in";
124 else if ((m = /^ADD(\d+)([A-Za-z_.$][\w.$]*)(?:,(.*))?$/.exec(c))) {
125 const code = Number(m[1]);
126 const p = (m[3] ?? "").split("X").map((v) => finite(Number(v)));
127 const ok = (...i: number[]): boolean => i.every((k) => p[k] !== undefined && p[k]! >= 0);
128 let ap: Aperture = { s: "M" };
129 if (m[2] === "C" && ok(0)) ap = { s: "C", d: p[0]! };
130 else if ((m[2] === "R" || m[2] === "O") && ok(0, 1)) ap = { s: m[2], w: p[0]!, h: p[1]! };
131 else if (m[2] === "P" && ok(0, 1) && p[1]! >= 3 && p[1]! <= 12) ap = { s: "P", d: p[0]!, n: Math.floor(p[1]!), rot: p[2] ?? 0 };
132 if (apertures.size < 100_000) apertures.set(code, ap);
133 } else if (c === "LPC") clear = true;
134 else if (c === "LPD") clear = false;
135 else if (/^(AM|AB|SR|TF|TA|TO|TD|LM|LR|LS|IP|OF|SF|MI|AS|IN|LN)/.test(c)) ignore(c.slice(0, 2));
136 else ignore("other command");
137 }
138 };
139
140 const word = (block: string): void => {
141 if (/^G0?4/.test(block)) return;
142 let d: number | undefined;
143 let nx: number | undefined, ny: number | undefined, i = 0, j = 0;
144 for (const m of block.matchAll(/([GDMXYIJ])([+-]?\d+)/g)) {
145 const k = m[1]!, v = m[2]!;
146 if (k === "G") {
147 const g = Number(v);
148 if (g === 1 || g === 2 || g === 3) mode = g;
149 else if (g === 74) single = true;
150 else if (g === 75) single = false;
151 else if (g === 36) {
152 inRegion = true;
153 contour = [];
154 } else if (g === 37) {
155 closeContour();
156 inRegion = false;
157 }
158 } else if (k === "M") {
159 if (Number(v) === 2) sawEnd = true;
160 } else if (k === "D") d = Number(v);
161 else if (k === "X") nx = coord(v);
162 else if (k === "Y") ny = coord(v);
163 else if (k === "I") i = coord(v) ?? 0;
164 else j = coord(v) ?? 0;
165 }
166 const px = x, py = y;
167 if (nx !== undefined) x = nx;
168 if (ny !== undefined) y = ny;
169 if (d === undefined) return;
170 if (d >= 10) {
171 cur = apertures.get(d);
172 return;
173 }
174 if (d === 2) {
175 if (inRegion) {
176 closeContour();
177 contour = [[x, y]];
178 }
179 } else if (d === 1) {
180 if (inRegion) {
181 if (contour.length === 0) contour.push([px, py]);
182 if (contour.length < 100_000) contour.push([x, y]);
183 } else if (clear) ignore("clear-polarity object");
184 else if (cur === undefined) ignore("draw with no aperture");
185 else if (mode !== 1 && single) ignore("single-quadrant arc (G74)");
186 else {
187 tracks++;
188 const w = width(cur);
189 add(mode === 1 ? { t: "line", a: [px, py], b: [x, y], w } : { t: "arc", a: [px, py], b: [x, y], c: [px + i, py + j], cw: mode === 2, w });
190 }
191 } else if (d === 3 && !inRegion) {
192 if (clear) ignore("clear-polarity object");
193 else if (cur === undefined) ignore("flash with no aperture");
194 else if (cur.s === "M") ignore("macro flash");
195 else {
196 flashes++;
197 add({ t: "flash", at: [x, y], ap: cur });
198 }
199 }
200 };
201
202 let pos = 0;
203 while (pos < text.length) {
204 const c = text.charCodeAt(pos);
205 if (c <= 32 || c === 0xfeff) {
206 pos++;
207 continue;
208 }
209 if (c === 37) {
210 const end = text.indexOf("%", pos + 1);
211 if (end < 0) break;
212 extended(text.slice(pos + 1, end));
213 pos = end + 1;
214 } else {
215 const end = text.indexOf("*", pos);
216 if (end < 0) break;
217 word(text.slice(pos, end).replace(/\s+/g, ""));
218 pos = end + 1;
219 }
220 }
221 if (inRegion) closeContour();
222 if (unit === undefined) return { error: "it does not say its units (%MO)" };
223 if (!haveFs) return { error: "it has no coordinate format (%FS)" };
224 if (!sawEnd && items.length === 0) return { error: "it has nothing to draw" };
225 if (items.length === 0) return { error: "it has no pad, track or region to draw" };
226 const aps = [...apertures.values()].length;
227 return { unit, items, apertures: aps, flashes, tracks, regions, ignored, dropped, extent };
228 }
229
230 const W = 640;
231 const MAX_H = 480;
232 const PAD = 12;
233 const TAU = Math.PI * 2;
234 const mod = (a: number): number => ((a % TAU) + TAU) % TAU;
235
236 /** Half the extent of an aperture on each axis. */
237 const half = (a: Aperture): Pt => ("w" in a ? [a.w / 2, a.h / 2] : "d" in a ? [a.d / 2, a.d / 2] : [0, 0]);
238
239 /** Arc geometry: centre, radius and the sweep in radians (a full turn when start meets end). */
240 function arcOf(a: Extract<Item, { t: "arc" }>): { r: number; a0: number; span: number } {
241 const r = Math.hypot(a.a[0] - a.c[0], a.a[1] - a.c[1]);
242 const a0 = Math.atan2(a.a[1] - a.c[1], a.a[0] - a.c[0]);
243 const a1 = Math.atan2(a.b[1] - a.c[1], a.b[0] - a.c[0]);
244 const raw = a.cw ? mod(a0 - a1) : mod(a1 - a0);
245 return { r, a0, span: raw < 1e-9 ? TAU : raw };
246 }
247
248 /** Bounds of all copper, in file units. */
249 export function extentOf(items: readonly Item[]): Extent {
250 let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
251 const grow = (x: number, y: number, hx: number, hy: number): void => {
252 minX = Math.min(minX, x - hx);
253 maxX = Math.max(maxX, x + hx);
254 minY = Math.min(minY, y - hy);
255 maxY = Math.max(maxY, y + hy);
256 };
257 for (const it of items) {
258 if (it.t === "flash") grow(it.at[0], it.at[1], ...half(it.ap));
259 else if (it.t === "region") for (const p of it.pts) grow(p[0], p[1], 0, 0);
260 else {
261 const h = it.w / 2;
262 grow(it.a[0], it.a[1], h, h);
263 grow(it.b[0], it.b[1], h, h);
264 if (it.t === "arc") {
265 const { r, a0, span } = arcOf(it);
266 for (let q = 0; q < 4; q++) {
267 const ang = (q * Math.PI) / 2;
268 const along = it.cw ? mod(a0 - ang) : mod(ang - a0);
269 if (along <= span) grow(it.c[0] + r * Math.cos(ang), it.c[1] + r * Math.sin(ang), h, h);
270 }
271 }
272 }
273 }
274 return { minX, minY, maxX, maxY };
275 }
276
277 /** The SVG body and size, fitted to the copper's extent. */
278 export function draw(items: readonly Item[]): { width: number; height: number; body: string } {
279 const { minX, minY, maxX, maxY } = extentOf(items);
280 const spanX = Math.max(maxX - minX, 1e-9);
281 const spanY = Math.max(maxY - minY, 1e-9);
282 let scale = (W - 2 * PAD) / spanX;
283 let height = spanY * scale + 2 * PAD;
284 if (height > MAX_H) {
285 scale = (MAX_H - 2 * PAD) / spanY;
286 height = MAX_H;
287 }
288 const width = Math.max(spanX * scale + 2 * PAD, 2 * PAD + 1);
289 const f = (n: number): string => (Number.isFinite(n) ? n : 0).toFixed(2);
290 const X = (v: number): string => f(PAD + (v - minX) * scale);
291 const Y = (v: number): string => f(PAD + (maxY - v) * scale);
292 const strokes = new Map<string, string>();
293 let fills = "";
294 const stroke = (w: number, d: string): void => {
295 const k = f(Math.max(w * scale, 0.5));
296 strokes.set(k, (strokes.get(k) ?? "") + d);
297 };
298 for (const it of items) {
299 if (it.t === "line") stroke(it.w, `M${X(it.a[0])} ${Y(it.a[1])}L${X(it.b[0])} ${Y(it.b[1])}`);
300 else if (it.t === "arc") {
301 const { r, span } = arcOf(it);
302 const R = f(r * scale);
303 const sweep = it.cw ? 1 : 0;
304 let d = `M${X(it.a[0])} ${Y(it.a[1])}`;
305 if (span >= TAU - 1e-9) {
306 // a full circle: two half arcs through the opposite point
307 const ox = 2 * it.c[0] - it.a[0], oy = 2 * it.c[1] - it.a[1];
308 d += `A${R} ${R} 0 0 ${sweep} ${X(ox)} ${Y(oy)}A${R} ${R} 0 0 ${sweep} ${X(it.b[0])} ${Y(it.b[1])}`;
309 } else d += `A${R} ${R} 0 ${span > Math.PI ? 1 : 0} ${sweep} ${X(it.b[0])} ${Y(it.b[1])}`;
310 stroke(it.w, d);
311 } else if (it.t === "region") fills += `<path d="${it.pts.map((p, i) => `${i === 0 ? "M" : "L"}${X(p[0])} ${Y(p[1])}`).join("")}Z"/>`;
312 else {
313 const ap = it.ap;
314 const [cx, cy] = [X(it.at[0]), Y(it.at[1])];
315 if (ap.s === "C") fills += `<circle cx="${cx}" cy="${cy}" r="${f((ap.d / 2) * scale)}"/>`;
316 else if (ap.s === "R" || ap.s === "O") {
317 const w = ap.w * scale, h = ap.h * scale;
318 const rx = ap.s === "O" ? Math.min(w, h) / 2 : 0;
319 fills += `<rect x="${f(Number(cx) - w / 2)}" y="${f(Number(cy) - h / 2)}" width="${f(w)}" height="${f(h)}" rx="${f(rx)}"/>`;
320 } else if (ap.s === "P") {
321 const pts: string[] = [];
322 for (let k = 0; k < ap.n; k++) {
323 const ang = ((ap.rot + (360 * k) / ap.n) * Math.PI) / 180;
324 pts.push(`${f(Number(cx) + (ap.d / 2) * scale * Math.cos(ang))},${f(Number(cy) - (ap.d / 2) * scale * Math.sin(ang))}`);
325 }
326 fills += `<polygon points="${pts.join(" ")}"/>`;
327 }
328 }
329 }
330 let body = fills === "" ? "" : `<g fill="currentColor" stroke="none">${fills}</g>`;
331 for (const [w, d] of strokes) body += `<path d="${d}" fill="none" stroke="currentColor" stroke-width="${w}" stroke-linecap="round" stroke-linejoin="round"/>`;
332 return { width: Math.round(width), height: Math.round(height), body };
333 }
334
335 const num = (n: number): string => Number(n.toFixed(4)).toLocaleString("en", { maximumFractionDigits: 4 });
336 const plural = (n: number, one: string): string => `${n.toLocaleString("en")} ${one}${n === 1 ? "" : "s"}`;
337
338 export function gerber(input: RenderInput): Rendered {
339 const fall = (why: string): Rendered => ({ content: html``, lines: 0, fallback: `This file is shown as text because ${why}.` });
outdated

The extent comes from layer.items, which excludes objects past OBJECT_CAP, so the board size is wrong for large files. Compute the bounds over everything parsed, or label it as the drawn extent, and test it.

340 if (input.size > RENDER_CAP.gerber || input.body.length > RENDER_CAP.gerber) return fall("it is too large to draw");
341 let layer: Layer | { error: string };
342 try {
343 layer = parseGerber(new TextDecoder().decode(input.body));
344 } catch {
345 return fall("it could not be read as Gerber");
346 }
outdated

Principles 1 and 8: this paragraph repeats the Not drawn row below it and uses jargon (y up, macro apertures, step-and-repeat). Remove it and fold the dropped-objects sentence into the Not drawn row.

347 if ("error" in layer) return fall(layer.error);
348 const drawn = draw(layer.items);
349 const e = layer.extent;
350 const name = layer.unit === "mm" ? "millimetres" : "inches";
351 const size = `${num(e.maxX - e.minX)} × ${num(e.maxY - e.minY)} ${layer.unit}`;
352 const facts: [string, string][] = [
353 ["Units", name],
354 ["Board size", `${size} (width × height of the copper)`],
355 ["Objects", `${plural(layer.flashes, "pad")}, ${plural(layer.tracks, "track")}, ${plural(layer.regions, "region")}; ${plural(layer.apertures, "aperture")} defined`],
356 ];
357 const skipped = [...layer.ignored].map(([k, n]) => `${n.toLocaleString("en")} × ${k}`);
358 if (layer.dropped > 0) skipped.push(`${layer.dropped.toLocaleString("en")} objects past the first ${OBJECT_CAP.toLocaleString("en")}`);
359 if (skipped.length > 0) facts.push(["Not drawn", `${skipped.join(", ")} (shapes this page cannot draw yet)`]);
360 const content = html`<figure class="gerber-view">
361 <svg viewBox="0 0 ${drawn.width} ${drawn.height}" role="img" aria-label="${`Copper layer, ${size}`}">${raw(drawn.body)}</svg>
362 <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl>
363 </figure>`;
364 return { content, lines: 0, summary: `${size} · ${fileSize(input.size)}` };
365 }
src/web/render/kinds.ts +10
@@ -50,6 +50,7 @@ export type FileKind =
5050 | "mail"
5151 | "gcode"
5252 | "dxf"
53 | "gerber"
5354 | "mermaid"
5455 | "drawio"
5556 | "excalidraw"
@@ -134,6 +135,7 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
134135 mail: 5 * MB,
135136 gcode: 50 * MB,
136137 dxf: 5 * MB,
138 gerber: 5 * MB,
137139 mermaid: 1 * MB,
138140 drawio: 1 * MB,
139141 excalidraw: 1 * MB,
@@ -290,6 +292,9 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
290292 gcode: "gcode",
291293 gco: "gcode",
292294 dxf: "dxf",
295 gbr: "gerber",
296 gtl: "gerber",
297 gbl: "gerber",
293298 mmd: "mermaid",
294299 mermaid: "mermaid",
295300 drawio: "drawio",
@@ -385,6 +390,10 @@ const isOffice = (path: string, head: Uint8Array): FileKind | undefined => {
385390 const isDxfHead = (head: Uint8Array): boolean =>
386391 /^\uFEFF?\s*0\r?\nSECTION\r?\n/.test(new TextDecoder().decode(head.subarray(0, 64)));
387392
393 /** A Gerber layer sets its format (`%FS`) or units (`%MO`), or opens on a `G04` comment. */
394 const isGerberHead = (head: Uint8Array): boolean =>
395 /%(FS[LT]?[AI]?X\d\dY\d\d|MO(MM|IN))|^\uFEFF?\s*G04/.test(new TextDecoder().decode(head.subarray(0, 1024)));
396
388397 /** A STEP file opens on `ISO-10303-21;`; a `.step` or `.stp` without it stays text. */
389398 const isStepHead = (head: Uint8Array): boolean =>
390399 /^\uFEFF?\s*ISO-10303-21\s*;/.test(new TextDecoder().decode(head.subarray(0, 64)));
@@ -482,6 +491,7 @@ export function fileKind(path: string, head: Uint8Array): FileKind {
482491 if (isComposeName(path)) return "compose";
483492 const ext = extension(path);
484493 if (ext === "step" || ext === "stp") return isStepHead(head) ? "step" : "text";
494 if (ext === "gbr" || ext === "gtl" || ext === "gbl") return isGerberHead(head) ? "gerber" : "text";
485495 // RTF opens on `{\rtf`: a `.rtf` whose bytes say otherwise is only text.
486496 if (ext === "rtf") return /^\uFEFF?\s*\{\\rtf/.test(new TextDecoder().decode(head.subarray(0, 16))) ? "rtf" : "text";
487497 return TEXTUAL[ext] ?? (isDxfHead(head) ? "dxf" : "text");
src/web/render/renderers.ts +2
@@ -23,6 +23,7 @@ import { csv } from "./csv.ts";
2323 import { geojson } from "./geojson.ts";
2424 import { kml } from "./kml.ts";
2525 import { dxf } from "./dxf.ts";
26 import { gerber } from "./gerber.ts";
2627 import { drawio, excalidraw, mermaid } from "./diagram.ts";
2728 import { step } from "./step.ts";
2829 import { gcode } from "./gcode.ts";
@@ -142,6 +143,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
142143 har,
143144 gcode,
144145 dxf,
146 gerber,
145147 mermaid,
146148 drawio,
147149 excalidraw,
src/web/style/content.ts +3
@@ -604,6 +604,9 @@ img.img-box, .prose img.img-box, .tell-picture.img-box { display: block; width:
604604 .dxf-view { margin: 0; }
605605 .dxf-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); }
606606 .dxf-view .status-rows { margin-top: 12px; }
607 .gerber-view { margin: 0; }
608 .gerber-view svg { display: block; max-width: 100%; height: auto; margin: 0 auto; color: var(--fg); }
609 .gerber-view .status-rows { margin-top: 12px; }
607610 .diagram-view { margin: 0; }
608611 .diagram-scroll { overflow-x: auto; max-width: 100%; }
609612 .diagram-scroll:focus-visible { outline: 1px solid var(--fg); outline-offset: 2px; }
test/fixtures/sample.gbr added +33
@@ -0,0 +1,33 @@
1 G04 Sample top copper: a 20 x 12 mm board, pads, tracks, an arc and a region*
2 %FSLAX24Y24*%
3 %MOMM*%
4 %ADD10C,0.4*%
5 %ADD11R,1.6X1.6*%
6 %ADD12O,2.4X1.2*%
7 %ADD13C,1.6*%
8 D11*
9 X20000Y20000D03*
10 X180000Y20000D03*
11 D12*
12 X100000Y100000D03*
13 D13*
14 X180000Y100000D03*
15 D10*
16 X20000Y20000D02*
17 X180000Y20000D01*
18 X20000Y20000D02*
19 X20000Y80000D01*
20 G75*
21 G03X60000Y80000I20000J0D01*
22 G01*
23 X60000Y80000D02*
24 X100000Y100000D01*
25 X100000Y100000D02*
26 X180000Y100000D01*
27 G36*
28 X120000Y40000D02*
29 X160000Y40000D01*
30 X160000Y70000D01*
31 X120000Y70000D01*
32 G37*
33 M02*
test/fuzz-renderers.test.ts +4
@@ -96,6 +96,10 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
9696 path: "part.dxf",
9797 files: ["0\nSECTION\n2\nENTITIES\n0\nLINE\n8\n<script>alert(1)</script>\n10\n0\n20\n0\n11\n5\n21\n5\n0\nCIRCLE\n10\n1\n20\n1\n40\n2\n0\nENDSEC\n0\nEOF\n"],
9898 },
99 gerber: {
100 path: "top.gtl",
101 files: ["%FSLAX24Y24*%\n%MOMM*%\n%ADD10C,0.5*%\n%ADD11R,1X<script>*%\nD10*\nX0Y0D02*\nG01X10000Y0D01*\nD11*\nX5000Y5000D03*\nG36*\nX0Y0D02*\nX1000Y0D01*\nX1000Y1000D01*\nG37*\nM02*\n"],
102 },
99103 drawio: {
100104 path: "a.drawio",
101105 files: [
test/render-gerber.test.ts added +119
@@ -0,0 +1,119 @@
1 /** Gerber copper layers as inline SVG. */
2 import { describe, expect, test } from "bun:test";
3 import { extentOf, gerber, OBJECT_CAP, parseGerber } from "../src/web/render/gerber.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 const head = "G04 test*\n%FSLAX24Y24*%\n%MOMM*%\n%ADD10C,0.5*%\n%ADD11R,2X1*%\n";
9 // A 10 x 5 mm board: a track along the bottom, a rectangular pad, a triangular region.
10 const GOOD =
11 head +
12 "D10*\nX0Y0D02*\nG01X100000Y0D01*\nD11*\nX50000Y25000D03*\n" +
13 "G36*\nX0Y0D02*\nX20000Y0D01*\nX20000Y20000D01*\nG37*\nM02*\n";
14 const draw = (text: string) => gerber({ path: "r/top.gtl", size: text.length, body: enc(text), media: "/m", download: "/d" });
15
16 describe("gerber", () => {
17 test("registered by extension, confirmed by the head", () => {
18 for (const n of ["a.gbr", "a.gtl", "a.gbl"]) expect(fileKind(n, enc(GOOD))).toBe("gerber");
19 expect(fileKind("a.gbr", enc("hello\n"))).toBe("text");
20 expect(RENDERERS.gerber).toBe(gerber);
21 expect(RENDER_CAP.gerber).toBeGreaterThan(0);
22 });
23
24 test("parses by hand: 2.4 format, a 10 mm track, a flash, a region", () => {
25 const l = parseGerber(GOOD);
26 if ("error" in l) throw new Error(l.error);
27 expect(l.unit).toBe("mm");
28 expect([l.flashes, l.tracks, l.regions, l.apertures]).toEqual([1, 1, 1, 2]);
29 // 100000 with 4 decimals = 10 mm; the 0.5 mm track adds 0.25 each side
30 const e = extentOf(l.items);
31 expect(e.minX).toBeCloseTo(-0.25, 9);
32 expect(e.maxX).toBeCloseTo(10.25, 9);
33 expect(e.minY).toBeCloseTo(-0.25, 9);
34 expect(e.maxY).toBeCloseTo(3, 9); // the pad: centred at 2.5, 1 mm high
35 });
36
37 test("draws svg with the units and board size as text", () => {
38 const out = String(draw(GOOD).content);
39 expect(out.match(/<svg/g)?.length).toBe(1);
40 expect(out).toContain("<rect");
41 expect(out).toContain("stroke-width=");
42 expect(out).toContain("<path");
43 expect(out).toContain("millimetres");
44 expect(out).toContain("10.5 × 3.25 mm");
45 expect(out).toContain("1 pad, 1 track, 1 region");
46 expect(out).not.toMatch(/<svg[^>]*\s(width|height)=/);
47 });
48
49 test("omitted trailing zeros and inches", () => {
50 const l = parseGerber("%FSTAX24Y24*%\n%MOIN*%\n%ADD10C,0.1*%\nD10*\nX1Y1D03*\nM02*\n");
51 if ("error" in l) throw new Error(l.error);
52 expect(l.unit).toBe("in");
53 const it = l.items[0]!;
54 expect(it.t === "flash" && it.at[0]).toBeCloseTo(10, 9); // "1" padded to 100000 -> 10 in
55 });
56
57 test("an arc is drawn as an A command", () => {
58 const t = head + "D10*\nX10000Y0D02*\nG75*\nG03X0Y10000I-10000J0D01*\nM02*\n";
59 const out = String(draw(t).content);
60 expect(out).toMatch(/A[\d.]+ [\d.]+ 0 0 0 /);
61 });
62
63 test("macros and clear polarity are counted, not drawn", () => {
64 const t = head + "%ADD12MYMACRO,1X2*%\nD12*\nX0Y0D03*\n%LPC*%\nD10*\nX1Y1D03*\n%LPD*%\nX2Y2D03*\nM02*\n";
65 const out = String(draw(t).content);
66 expect(out).toContain("1 × macro flash");
67 expect(out).toContain("1 × clear-polarity object");
68 expect(out).toContain("1 pad");
69 });
70
71 test("values from the file are escaped", () => {
72 const t = head + "%TF.FileFunction,<script>alert(1)</script>*%\n%ADD13<script>,1*%\nD10*\nX0Y0D03*\n";
73 const out = String(draw(t).content);
74 expect(out).not.toContain("<script");
75 });
76
77 test("malformed, empty or oversized files keep the source view and never throw", () => {
78 for (const bad of ["", "garbage", "%FSLAX24Y24*%\n", "%MOMM*%\nD10*\nX0Y0D03*\n", head + "M02*\n", "%", "X\0Y\0D03*"]) {
79 const r = draw(bad);
80 expect(r.fallback).toBeTruthy();
81 }
82 const big = { path: "a.gbr", size: RENDER_CAP.gerber + 1, body: enc(GOOD), media: "/m", download: "/d" };
83 expect(gerber(big).fallback).toContain("too large");
84 });
85
86 test("objects past the cap are counted and the size covers all of them", () => {
87 // OBJECT_CAP flashes at the origin, then one far pad that is dropped: the board is 10 mm wide
88 const t = head + "D10*\n" + "X0Y0D03*\n".repeat(OBJECT_CAP) + "X100000Y0D03*\n".repeat(5);
89 const l = parseGerber(t);
90 if ("error" in l) throw new Error(l.error);
91 expect(l.dropped).toBe(5);
92 expect(l.extent.maxX).toBeCloseTo(10.25, 9);
93 expect(l.extent.minX).toBeCloseTo(-0.25, 9);
94 const out = String(draw(t).content);
95 expect(out).toContain("5 objects past the first");
96 expect(out).toContain("10.5 × 0.5 mm");
97 });
98
99 test("single-quadrant arcs are counted, not drawn", () => {
100 const t = head + "D10*\nG74*\nX0Y0D02*\nG03X10000Y10000I10000J0D01*\nG75*\nG03X0Y0I0J-10000D01*\nM02*\n";
101 const l = parseGerber(t);
102 if ("error" in l) throw new Error(l.error);
103 expect(l.tracks).toBe(1);
104 expect(l.ignored.get("single-quadrant arc (G74)")).toBe(1);
105 });
106
107 test("the page does not repeat itself in jargon", () => {
108 const out = String(draw(GOOD).content);
109 expect(out).not.toMatch(/y up|step-and-repeat|macro apertures/);
110 });
111
112 test("the sample fixture draws", async () => {
113 const t = await Bun.file(new URL("./fixtures/sample.gbr", import.meta.url)).text();
114 const l = parseGerber(t);
115 if ("error" in l) throw new Error(l.error);
116 expect([l.flashes, l.regions]).toEqual([4, 1]);
117 expect(String(draw(t).content)).toContain("<svg");
118 });
119 });
test/render-kinds.test.ts +3
@@ -94,6 +94,9 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
9494 gcode: [enc("G28\nG1 X1 E1\n"), "gcode", "application/octet-stream"],
9595 gco: [enc("G28\n"), "gcode", "application/octet-stream"],
9696 dxf: [enc("0\nSECTION\n2\nENTITIES\n0\nENDSEC\n0\nEOF\n"), "dxf", "application/octet-stream"],
97 gbr: [enc("%FSLAX24Y24*%\n%MOMM*%\n"), "gerber", "application/octet-stream"],
98 gtl: [enc("G04 x*\n"), "gerber", "application/octet-stream"],
99 gbl: [enc("%MOIN*%\n"), "gerber", "application/octet-stream"],
97100 mmd: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
98101 mermaid: [enc("flowchart TD\n"), "mermaid", "application/octet-stream"],
99102 drawio: [enc("<mxfile/>"), "drawio", "application/octet-stream"],

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs