feat: gerbview WASM port

This commit is contained in:
Balint Ipkovich 2026-06-03 14:23:57 +02:00
commit 4467bcd2c4
17 changed files with 433 additions and 12 deletions

View file

@ -11,6 +11,7 @@
# calculator PCB calculator
# pl_editor drawing-sheet editor
# symbol_editor symbol editor (eeschema kiface, FRAME_SCH_SYMBOL_EDITOR)
# gerbview Gerber viewer
# all build all of the above sequentially
#
# Any extra args are forwarded to scripts/kicad/build-<app>.sh (e.g. -j 8,
@ -48,7 +49,7 @@ trap 'kw_fail 130; exit 130' INT TERM
cd "$(dirname "$0")/.."
VALID_APPS="pcbnew | eeschema | calculator | pl_editor | symbol_editor | all"
VALID_APPS="pcbnew | eeschema | calculator | pl_editor | symbol_editor | gerbview | all"
usage() {
echo "Usage: ./docker/build.sh <app> [args...]" >&2
@ -71,7 +72,7 @@ APP_NAME="$1"
shift
case "$APP_NAME" in
pcbnew|eeschema|calculator|pl_editor|symbol_editor|all) ;;
pcbnew|eeschema|calculator|pl_editor|symbol_editor|gerbview|all) ;;
*)
echo "Error: unknown app '$APP_NAME' (expected: ${VALID_APPS})" >&2
usage
@ -187,11 +188,12 @@ build_app() {
}
if [[ "${APP_NAME}" == "all" ]]; then
build_app pcbnew 1 5
build_app eeschema 2 5
build_app calculator 3 5
build_app pl_editor 4 5
build_app symbol_editor 5 5
build_app pcbnew 1 6
build_app eeschema 2 6
build_app calculator 3 6
build_app pl_editor 4 6
build_app symbol_editor 5 6
build_app gerbview 6 6
else
build_app "${APP_NAME}" 1 1
fi

View file

@ -0,0 +1,74 @@
# Gerber Viewer (gerbview) WASM port — design notes
## Goal
Bring up KiCad's Gerber Viewer (`gerbview`, `FRAME_GERBER`) in the browser to the
"boots, canvas visible, click around" level the other ported apps reached. Scope is
launch-only — loading actual Gerber/drill files is out of scope for now.
## Approach
gerbview is its own standalone program + kiface (unlike symbol_editor, which lived
inside the eeschema kiface), so it follows the **pl_editor/pcbnew pattern** almost
verbatim: gate the native dynamic-kiface logic behind `if( EMSCRIPTEN )` and link the
kiface objects statically into the `gerbview` executable. `gerbview.cpp` (the
`KIFACE_GETTER`) is already part of `gerbview_kiface_objects`, so no source hoisting
was needed (unlike eeschema). There was no `#ifdef __EMSCRIPTEN__` frame stub to
remove (gerbview was never gated out, unlike the symbol editor).
## Changes (kicad submodule)
- **`kicad/gerbview/CMakeLists.txt`** — mirror pl_editor's WASM static-link block:
- On EMSCRIPTEN, compile `common/single_top.cpp` with `TOP_FRAME=FRAME_GERBER`
(no `BUILD_KIWAY_DLL`); wrap the native minimal exe link in `if( NOT EMSCRIPTEN )`.
- Hoist the kiface deps into `GERBVIEW_KIFACE_LIBRARIES`; on EMSCRIPTEN link them
directly into the `gerbview` exe with `LINKER:--allow-multiple-definition`.
- Gate `gerbview.cpp` defs: EMSCRIPTEN → `COMPILING_DLL` (no `BUILD_KIWAY_DLL`, so
`KIFACE_GETTER` links statically); else `BUILD_KIWAY_DLL;COMPILING_DLL`.
- **`kicad/gerbview/navlib/CMakeLists.txt`** — add an `if( EMSCRIPTEN )` branch that
builds `gerbview_navlib` from the WASM stub instead of the real 3Dconnexion plugin
(no SpaceMouse driver in the browser). The frame's navlib member uses
`NL_GERBVIEW_PLUGIN` under WASM (`#ifndef __linux__`; emscripten doesn't define it).
- **`#include <wx/choice.h>`** added to three files that use `wxChoice` (the
Cmp/Net/Attr/DCode aux-toolbar combo boxes) but only had the forward declaration:
`gerbview/events_called_functions.cpp`, `gerbview/toolbars_gerber.cpp`,
`gerbview/tools/gerbview_control.cpp`. Native builds pull `wx/choice.h` transitively;
the WASM wxWidgets header config does not, so these failed with "member access into
incomplete type 'wxChoice'". Include-what-you-use fix — behavior-neutral, upstream-safe.
(`gerbview_frame.cpp` already gets it transitively; the generated `_base.cpp` carries
its own includes — both left untouched to keep the fork minimal.)
## Changes (root repo)
- **`wasm/stubs/nl_gerbview_plugin_stub.cpp`** (NEW) — no-op `NL_GERBVIEW_PLUGIN`
ctor/dtor + `SetCanvas`/`SetFocus`, mirroring `nl_pl_editor_plugin_stub.cpp`.
- **`scripts/kicad/build-gerbview.sh`** (NEW) — thin wrapper → `build-kicad-target.sh gerbview`.
- **`scripts/kicad/build-kicad-target.sh`** — add `gerbview` to the `pcbnew|eeschema)`
case arm (target = subdir = `gerbview`); update usage strings.
- **`docker/build.sh`** — add `gerbview` to valid apps, dispatch case, and the `all`
loop (now 6 apps).
- **`tests/scripts/setup-kicad-wasm.sh`** — `copy_app gerbview`.
- **`tests/apps/kicad/gerbview.html`** (NEW) — browser shell (copy of pl_editor.html;
title, `thisProgram=/usr/bin/gerbview`, `gerbview.js`).
- **`tests/kicad/gerbview.spec.ts`** (NEW) + **`tests/package.json`** — launch-only
smoke test (wizard, canvas visible, registry populated, ≥1 toolbar, no abort).
## Build & verify
```
./docker/build.sh gerbview # seed fresh-branch cache from main first (see build-quirks memory)
cd tests && npm run setup:kicad && npm run test:gerbview
```
Expect: the viewer opens — menu bar, top + aux toolbars (with the Cmp/Net/Attr/DCode
combos), left tool toolbar, dark gerber canvas with grid + origin crosshair, and the
Layers/Items manager pane. `gerbview.spec.ts` passes (2/2, no abort).
## Known limitations
- No Gerber/drill files are loaded; the canvas is empty until a file is opened
(file loading untested / out of scope).
- Symbol-editor-style drawing tools that require an open document behave per native
KiCad (some are inactive with no layers loaded).
- No persistent storage (MEMFS only).
</content>

2
kicad

@ -1 +1 @@
Subproject commit 3ced43c0b471b607ce263f78216f7e6cf4e834ed
Subproject commit 933c2fda02712169fd418f70225d2637f0b8c2f8

View file

@ -0,0 +1,7 @@
#!/bin/bash
# Build KiCad Gerber Viewer (gerbview) for WebAssembly.
# Thin wrapper around build-kicad-target.sh — see that script for options.
set -e
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
exec "${SCRIPT_DIR}/build-kicad-target.sh" gerbview "$@"

View file

@ -31,7 +31,7 @@
set -e
if [ -z "$1" ]; then
echo "Error: missing <app> argument (pcbnew | eeschema | calculator | pl_editor | symbol_editor)" >&2
echo "Error: missing <app> argument (pcbnew | eeschema | calculator | pl_editor | symbol_editor | gerbview)" >&2
exit 1
fi
APP_NAME="$1"
@ -44,7 +44,7 @@ shift
# - pl_editor: subdir is pagelayout_editor (upstream source dir name)
# - symbol_editor: served by the eeschema kiface, so it builds in eeschema/
case "$APP_NAME" in
pcbnew|eeschema)
pcbnew|eeschema|gerbview)
KICAD_TARGET="$APP_NAME"
KICAD_SUBDIR="$APP_NAME"
;;
@ -61,7 +61,7 @@ case "$APP_NAME" in
KICAD_SUBDIR="eeschema"
;;
*)
echo "Error: unknown app '$APP_NAME' (expected: pcbnew | eeschema | calculator | pl_editor | symbol_editor)" >&2
echo "Error: unknown app '$APP_NAME' (expected: pcbnew | eeschema | calculator | pl_editor | symbol_editor | gerbview)" >&2
exit 1
;;
esac

View file

@ -0,0 +1,200 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>KiCad Gerber Viewer WASM</title>
<style>
.emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
div.emscripten { text-align: center; }
/* the canvas *must not* have any border or padding, or mouse coords will be wrong */
canvas.emscripten { border: 0px none; }
.window {
position: absolute;
pointer-events: none;
z-index: 10;
background-color: black;
overflow: hidden;
width: 0;
height: 0;
}
.window-canvas {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
#status {
position: fixed;
bottom: 10px;
left: 10px;
color: #fff;
font-family: monospace;
z-index: 1000;
background: rgba(0,0,0,0.7);
padding: 10px;
border-radius: 5px;
}
#progress {
width: 300px;
height: 20px;
background: #333;
margin-top: 5px;
}
#progress-bar {
height: 100%;
background: #4CAF50;
width: 0%;
transition: width 0.3s;
}
</style>
</head>
<body style="margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a2e;">
<div id="main-window" style="width: 100vw; height: 100vh; position: absolute; top: 0; left: 0;"></div>
<div id="status">
<div id="status-text">Initializing...</div>
<div id="progress"><div id="progress-bar"></div></div>
</div>
<div id="window-container"></div>
<script>
var mainWindow = document.getElementById('main-window');
var statusText = document.getElementById('status-text');
var progressBar = document.getElementById('progress-bar');
var showError = function(msg) {
console.error('[KICAD_ERROR] ' + msg);
statusText.textContent = 'Error: ' + msg;
statusText.style.color = 'red';
};
var createCanvas = function() {
var canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.style.display = 'none';
var width = window.innerWidth;
var height = window.innerHeight;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
canvas.oncontextmenu = function() { event.preventDefault(); };
canvas.addEventListener("webglcontextlost", function(e) {
showError('WebGL context lost. You will need to reload the page.');
e.preventDefault();
}, false);
mainWindow.appendChild(canvas);
Module.canvas = canvas;
console.log('[KICAD] preRun complete, canvas created: ' + width + 'x' + height);
};
var onRuntimeInitialized = function() {
console.log('[KICAD] Runtime initialized');
var canvas = Module.canvas;
canvas.style.display = 'block';
document.getElementById('status').style.display = 'none';
};
// Pre-fetched resource data (fetched before pl_editor.js loads)
var resourceData = null;
fetch('images.tar.gz')
.then(function(response) {
if (!response.ok) throw new Error('HTTP ' + response.status);
return response.arrayBuffer();
})
.then(function(buffer) {
resourceData = new Uint8Array(buffer);
console.log('[KICAD] Prefetched images.tar.gz (' + resourceData.length + ' bytes)');
})
.catch(function(err) {
console.warn('[KICAD] Could not prefetch images.tar.gz:', err.message);
});
var writeResources = function() {
var resourcePath = '/workspace/build-wasm/sysroot/share/kicad/resources';
FS.mkdirTree(resourcePath);
if (resourceData) {
FS.writeFile(resourcePath + '/images.tar.gz', resourceData);
console.log('[KICAD] Wrote images.tar.gz to ' + resourcePath);
} else {
console.warn('[KICAD] images.tar.gz not ready yet (WASM loaded faster than fetch)');
}
};
// Land the user in a sane, writable directory instead of MEMFS root (where
// the only visible entries are /dev, /proc, /tmp, /workspace, /home).
// The Open/Save dialogs default to cwd when no explicit defaultDir is set.
var setupHomeDir = function() {
var home = '/home/kicad';
FS.mkdirTree(home);
FS.chdir(home);
console.log('[KICAD] cwd set to ' + home);
};
var Module = {
thisProgram: '/usr/bin/gerbview', // Fake absolute path for argv[0]
preRun: [createCanvas, writeResources, setupHomeDir],
postRun: [],
print: function(text) {
if (arguments.length > 1)
text = Array.prototype.slice.call(arguments).join(' ');
console.log('[KICAD_OUT] ' + text);
},
printErr: function(text) {
if (arguments.length > 1)
text = Array.prototype.slice.call(arguments).join(' ');
console.error('[KICAD_ERR] ' + text);
},
setStatus: function(text) {
console.log('[KICAD_STATUS] ' + text);
statusText.textContent = text;
var match = text.match(/(\d+)\/(\d+)/);
if (match) {
var pct = (parseInt(match[1]) / parseInt(match[2])) * 100;
progressBar.style.width = pct + '%';
}
},
totalDependencies: 0,
monitorRunDependencies: function(left) {
this.totalDependencies = Math.max(this.totalDependencies, left);
Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
},
onRuntimeInitialized: onRuntimeInitialized,
locateFile: function(path) {
return path;
}
};
Module.setStatus('Downloading...');
window.onerror = function(msg, url, line) {
showError(msg + ' at ' + url + ':' + line);
Module.setStatus = function(text) {
if (text) Module.printErr('[post-exception status] ' + text);
};
return false;
};
</script>
<!-- wxWidgets WASM glue code (defines getConfigEntryLength, etc.) -->
<script src="wx.js"></script>
<script async src="gerbview.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

View file

@ -0,0 +1,104 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { clickByLabel } from '../e2e/utils/element-tracker';
/**
* Gerber Viewer (gerbview) WASM E2E Tests
*
* gerbview is its own standalone kiface (FRAME_GERBER), launched via single_top
* like pcbnew/pl_editor. It runs the same shared first-run setup wizard, so the
* launch flow mirrors symbol_editor.spec.ts: wait for the canvas, click through the
* wizard, then assert the viewer chrome built. Scope is launch-only the viewer
* must start, paint a canvas + toolbars (incl. the layers manager), populate the
* element registry, and produce no WASM abort. Loading actual Gerber files is out
* of scope here.
*/
async function completeWizard(page: Page): Promise<void> {
await expect(page.locator('#canvas')).toBeVisible({ timeout: 90000 });
await page.waitForFunction(() => !!window.wxElementRegistry, null, { timeout: 90000 });
// The frame builds its UI a beat after the registry object appears; wait for
// the registry to actually have entries before driving it.
await page.waitForFunction(() => {
const registry = window.wxElementRegistry;
return !!registry && registry.findAll({}).length > 0;
}, null, { timeout: 90000 });
await page.waitForTimeout(2000);
await page.screenshot({ path: 'test-results/gerbview-wizard-00-initial.png', scale: 'device' });
for (let i = 1; i <= 10; i++) {
let clicked = await clickByLabel(page, 'Next >');
if (!clicked) {
clicked = await clickByLabel(page, 'Finish');
if (clicked) {
await page.waitForTimeout(500);
await page.screenshot({
path: `test-results/gerbview-wizard-${String(i).padStart(2, '0')}-finish.png`,
scale: 'device'
});
}
break;
}
await page.waitForTimeout(500);
await page.screenshot({
path: `test-results/gerbview-wizard-${String(i).padStart(2, '0')}.png`,
scale: 'device'
});
}
await page.waitForTimeout(2000);
}
function hasAbort(testLogger: { consoleLogs: string[]; errors: string[] }): boolean {
return [...testLogger.consoleLogs, ...testLogger.errors].some(line => line.includes('Aborted('));
}
test.describe('gerbview WASM', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/kicad/gerbview.html');
});
test('app loads, canvas visible, no WASM abort', async ({ page, testLogger }) => {
await completeWizard(page);
await page.screenshot({ path: 'test-results/gerbview-01-loaded.png', scale: 'device' });
expect(hasAbort(testLogger), 'no WASM abort during load').toBe(false);
const canvasCount = await page.locator('canvas').count();
expect(canvasCount).toBeGreaterThan(0);
});
test('canvas + toolbar metrics look sane', async ({ page, testLogger }) => {
await completeWizard(page);
const metrics = await page.evaluate(() => {
const registry = window.wxElementRegistry;
const all = registry ? registry.findAll({ visible: true }) : [];
const toolbars = all.filter((el: { typeName: string }) => /ToolBar/.test(el.typeName));
const glCanvas = document.querySelector('canvas[id^="glcanvas-"]') as HTMLCanvasElement | null;
return {
registryTotal: all.length,
toolbarCount: toolbars.length,
mainCanvasOk: (() => {
const c = document.getElementById('canvas') as HTMLCanvasElement | null;
return !!c && c.width > 0 && c.height > 0;
})(),
glCanvasOk: !!glCanvas && glCanvas.width > 0 && glCanvas.height > 0,
};
});
await page.screenshot({ path: 'test-results/gerbview-02-metrics.png', scale: 'device' });
expect(metrics.registryTotal, 'registry should be populated').toBeGreaterThan(10);
expect(metrics.toolbarCount, 'at least one toolbar should be visible').toBeGreaterThanOrEqual(1);
expect(metrics.mainCanvasOk, 'main canvas has nonzero dimensions').toBe(true);
expect(metrics.glCanvasOk, 'GL canvas has nonzero dimensions').toBe(true);
expect(hasAbort(testLogger)).toBe(false);
});
});

View file

@ -29,6 +29,10 @@
"test:symbol_editor:chrome": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=chromium --headed kicad/symbol_editor.spec.ts",
"test:symbol_editor": "npm run test:symbol_editor:firefox",
"test:symbol_editor:headed": "npm run test:symbol_editor:chrome",
"test:gerbview:firefox": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=firefox kicad/gerbview.spec.ts",
"test:gerbview:chrome": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=chromium --headed kicad/gerbview.spec.ts",
"test:gerbview": "npm run test:gerbview:firefox",
"test:gerbview:headed": "npm run test:gerbview:chrome",
"test:coroutine:firefox": "playwright test --config=playwright-coroutine.config.ts --project=firefox",
"test:coroutine:chrome": "playwright test --config=playwright-coroutine.config.ts --project=chromium --headed"
},

View file

@ -84,9 +84,10 @@ copy_app eeschema && found_any=1
copy_app calculator && found_any=1
copy_app pl_editor && found_any=1
copy_app symbol_editor && found_any=1
copy_app gerbview && found_any=1
if [ "$found_any" -eq 0 ]; then
echo "Error: no pcbnew/eeschema/calculator/pl_editor/symbol_editor artifacts found in output/ or docker volume" >&2
echo "Error: no pcbnew/eeschema/calculator/pl_editor/symbol_editor/gerbview artifacts found in output/ or docker volume" >&2
exit 1
fi

View file

@ -0,0 +1,29 @@
/*
* 3Dconnexion SpaceMouse plugin stubs for KiCad gerbview WASM build.
* The 3DxWare driver is unavailable in the browser; these stubs satisfy the
* symbols referenced from gerbview_frame.cpp without doing anything.
*/
// Minimal definition for NL_GERBVIEW_PLUGIN_IMPL — required because the
// unique_ptr<NL_GERBVIEW_PLUGIN_IMPL> destructor needs a complete type.
class NL_GERBVIEW_PLUGIN_IMPL {};
#include <navlib/nl_gerbview_plugin.h>
NL_GERBVIEW_PLUGIN::NL_GERBVIEW_PLUGIN()
{
}
NL_GERBVIEW_PLUGIN::~NL_GERBVIEW_PLUGIN()
{
}
void NL_GERBVIEW_PLUGIN::SetCanvas( EDA_DRAW_PANEL_GAL* aViewport )
{
(void) aViewport;
}
void NL_GERBVIEW_PLUGIN::SetFocus( bool aFocus )
{
(void) aFocus;
}