add calculator build

This commit is contained in:
Istvan Matejcsok 2026-05-28 17:21:26 +02:00
commit 0464470733
11 changed files with 948 additions and 14 deletions

View file

@ -0,0 +1,198 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>KiCad Calculator 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';
// wx.js owns the backing-store size via setWindowRect(); keep the HTML
// shell responsible only for the CSS size.
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 calculator.js loads)
var resourceData = null;
// Start fetching images.tar.gz immediately (runs in parallel with WASM loading)
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);
});
// Write pre-fetched resources to FS (called in preRun after FS is available)
var writeResources = function() {
// Create directory structure matching KiCad's compiled-in KICAD_DATA path.
// This path is baked in during CMake configuration and is shared with the
// pcbnew build (both use the same sysroot).
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)');
}
};
var Module = {
thisProgram: '/usr/bin/pcb_calculator', // argv[0]
preRun: [createCanvas, writeResources],
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,
// Required for locating .wasm and .worker.js files
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="calculator.js"></script>
</body>
</html>

View file

@ -0,0 +1,150 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { clickByLabel, clickTreeItem, findAllTreeItems } from '../e2e/utils/element-tracker';
/**
* PCB Calculator WASM E2E Tests
*
* The calculator is a wxFrame containing a wxTreebook with ~14 calculator
* panels grouped under four section pages. There's no GAL canvas, no
* toolbars-as-tested, and no setup wizard for the calculator itself.
*
* However, KiCad's first-run setup wizard pops up before *any* app's frame
* (same wizard pcbnew sees) because Emscripten's MEMFS starts empty each
* page load and KiCad finds no config. We click through it the same way
* pcbnew.spec.ts's completeWizard() does, then verify:
* 1. The calculator frame loads and registers its panels.
* 2. The treebook contains the panel labels we expect.
* 3. Clicking a leaf panel ("Color Code") switches the active page.
*
* Panel labels are sourced from pcb_calculator_frame.cpp:170-192 (kicad fork).
*/
async function waitForRegistry(page: Page): Promise<void> {
await page.waitForFunction(() => !!(window as any).wxElementRegistry, null, { timeout: 90000 });
// Give the C++ side a moment to register every panel after the frame
// first appears — the treebook is populated synchronously in the frame
// ctor, but wxElementRegistry registrations are flushed on idle.
await page.waitForTimeout(2000);
}
/**
* Click through KiCad's first-run setup wizard. Mirrors the intent of
* tests/kicad/pcbnew.spec.ts's completeWizard() but waits actively for each
* "Next >" / "Finish" button to appear in wxElementRegistry before clicking
* the calculator boots quickly enough that the wizard buttons can lag
* behind by a second or two, and a fixed sleep proved flaky.
*/
async function waitForLabel(page: Page, label: string, timeoutMs: number): Promise<boolean> {
try {
await page.waitForFunction(
(l) => {
const r = (window as any).wxElementRegistry;
return !!(r && r.findByLabel && r.findByLabel(l, {}).length > 0);
},
label,
{ timeout: timeoutMs }
);
return true;
} catch {
return false;
}
}
async function completeFirstRunWizard(page: Page): Promise<void> {
// The canvas becomes visible only after Module.onRuntimeInitialized fires,
// which is a reliable witness that the WASM has booted.
await expect(page.locator('#canvas')).toBeVisible({ timeout: 90000 });
await waitForRegistry(page);
for (let i = 1; i <= 12; i++) {
const haveNext = await waitForLabel(page, 'Next >', 15000);
if (haveNext) {
const clickedNext = await clickByLabel(page, 'Next >');
if (clickedNext) {
await page.waitForTimeout(400);
continue;
}
}
const haveFinish = await waitForLabel(page, 'Finish', 5000);
if (haveFinish) {
await clickByLabel(page, 'Finish');
await page.waitForTimeout(400);
}
break;
}
// Allow the wizard to dismiss and the calculator frame to register.
await page.waitForTimeout(2500);
}
async function getRegistryLabels(page: Page): Promise<string[]> {
return await page.evaluate(() => {
const registry = (window as any).wxElementRegistry;
if (!registry || !registry.findAll) return [];
const all = registry.findAll({});
return all
.map((el: any) => (el && el.label ? String(el.label) : ''))
.filter((l: string) => l.length > 0);
});
}
test.describe('PCB Calculator WASM', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/kicad/calculator.html');
});
test('loads calculator frame', async ({ page, testLogger }) => {
void testLogger;
await completeFirstRunWizard(page);
// The default panel (Regulator) renders its controls into the registry
// as soon as the frame is up. "Calculate" is a unique button label on
// panel_regulator and a reliable witness that the calculator is live.
const labels = await getRegistryLabels(page);
const hasRegulatorPanel = labels.some(l => l === 'Calculate');
expect(hasRegulatorPanel, `expected the calculator's default Regulator panel to be live (Calculate button registered). Got: ${JSON.stringify(labels.slice(0, 30))}`).toBe(true);
await page.screenshot({ path: 'test-results/calculator-loaded.png', scale: 'device' });
});
test('treebook lists expected panels', async ({ page, testLogger }) => {
void testLogger;
await completeFirstRunWizard(page);
const treeItems = await findAllTreeItems(page);
const treeLabels = treeItems.map(i => i.label).filter((l): l is string => typeof l === 'string');
const requiredSubset = [
'Regulators',
'Resistor Calculator',
'Via Size',
'Track Width',
'Color Code',
'RF Attenuators',
'Transmission Lines',
];
const missing = requiredSubset.filter(req => !treeLabels.includes(req));
expect(missing, `treebook is missing expected panels: ${JSON.stringify(missing)} (tree items: ${JSON.stringify(treeLabels)})`).toEqual([]);
});
test('switch to Color Code panel', async ({ page, testLogger }) => {
void testLogger;
await completeFirstRunWizard(page);
await page.screenshot({ path: 'test-results/calculator-before-switch.png', scale: 'device' });
const clicked = await clickTreeItem(page, 'Color Code');
expect(clicked, 'expected to find and click the Color Code tree item').toBe(true);
// Allow the panel to swap in. The Color Code panel exposes a unique
// "Tolerance" label that the Regulator panel does not — use it as a
// proof-of-switch.
await page.waitForTimeout(800);
const labelsAfter = await getRegistryLabels(page);
const onColorCodePanel = labelsAfter.some(l => /Tolerance/i.test(l));
expect(onColorCodePanel, `expected Color Code panel to be active after click; labels: ${JSON.stringify(labelsAfter.slice(0, 40))}`).toBe(true);
await page.screenshot({ path: 'test-results/calculator-color-code.png', scale: 'device' });
});
});

View file

@ -13,6 +13,11 @@
"test:kicad:chrome": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=chromium --headed",
"test:kicad": "npm run test:kicad:firefox",
"test:kicad:headed": "npm run test:kicad:chrome",
"setup:calculator": "./scripts/setup-calculator-wasm.sh",
"test:calculator:firefox": "npm run setup:calculator && playwright test --config=playwright-calculator.config.ts --project=firefox",
"test:calculator:chrome": "npm run setup:calculator && playwright test --config=playwright-calculator.config.ts --project=chromium --headed",
"test:calculator": "npm run test:calculator:firefox",
"test:calculator:headed": "npm run test:calculator: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

@ -0,0 +1,90 @@
import { defineConfig, devices } from '@playwright/test';
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
// Mirrors playwright-kicad.config.ts. The only structural difference is
// testMatch — calculator.spec.ts lives next to pcbnew.spec.ts under ./kicad,
// and we filter to it so running `npm run test:calculator` doesn't drag in
// the pcbnew suite.
const PORT_FILE = path.join(__dirname, '.test-port');
// NOTE: Chrome headless crashes on ARM Mac due to SwiftShader WebGL bug
// (Chromium issues #1416283, #338414704). Firefox headless works reliably.
// Use --project=firefox for headless, --project=chromium for headed debugging.
function getOrFindPort(): number {
try {
const stat = fs.statSync(PORT_FILE);
const age = Date.now() - stat.mtimeMs;
if (age < 60000) {
const port = parseInt(fs.readFileSync(PORT_FILE, 'utf-8').trim());
if (port > 0 && port < 65536) {
return port;
}
}
} catch {
// File doesn't exist or can't be read
}
const port = findFreePort();
fs.writeFileSync(PORT_FILE, port.toString());
return port;
}
function findFreePort(): number {
try {
const result = execSync(
'python3 -c "import socket; s=socket.socket(); s.bind((\'\',0)); print(s.getsockname()[1]); s.close()"',
{ encoding: 'utf-8' }
);
return parseInt(result.trim());
} catch {
return 9000 + Math.floor(Math.random() * 1000);
}
}
const port = getOrFindPort();
export default defineConfig({
globalSetup: './global-setup.ts',
testDir: './kicad',
testMatch: 'calculator.spec.ts',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
timeout: 180000, // KiCad WASM needs more time to load (3 minutes)
use: {
baseURL: `http://localhost:${port}`,
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
},
projects: [
{
name: 'firefox',
use: {
...devices['Desktop Firefox'],
viewport: { width: 1280, height: 720 },
},
},
{
// Uses system Chrome (not bundled Chromium) so WebGL runs on the real GPU.
name: 'chromium',
use: {
channel: 'chrome',
viewport: { width: 1280, height: 720 },
},
},
],
webServer: {
command: `npx serve apps -p ${port} -c ../serve.json`,
port: port,
reuseExistingServer: !process.env.CI,
},
});

View file

@ -0,0 +1,58 @@
#!/bin/bash
# Copy PCB Calculator WASM build output to the test directory.
# Mirrors setup-kicad-wasm.sh; differences:
# - copies calculator.{js,wasm,wasm.map,worker.js} instead of pcbnew.*
#
# Priority: use local output/ (populated by docker/build-calculator.sh).
# Fallback: copy from the Docker volume directly.
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
KICAD_TEST="$PROJECT_ROOT/tests/apps/kicad"
OUTPUT_DIR="$PROJECT_ROOT/output"
mkdir -p "$KICAD_TEST"
if [ -f "$OUTPUT_DIR/calculator.js" ] && [ -f "$OUTPUT_DIR/calculator.wasm" ]; then
echo "Copying Calculator WASM files from output directory..."
cp "$OUTPUT_DIR/calculator.js" "$KICAD_TEST/"
cp "$OUTPUT_DIR/calculator.wasm" "$KICAD_TEST/"
# Source map for debug symbols (optional)
cp "$OUTPUT_DIR/calculator.wasm.map" "$KICAD_TEST/" 2>/dev/null || true
# Worker file for pthreads (optional)
cp "$OUTPUT_DIR/calculator.worker.js" "$KICAD_TEST/" 2>/dev/null || true
# Bitmap resources for KiCad icons (shared with pcbnew; optional)
cp "$OUTPUT_DIR/images.tar.gz" "$KICAD_TEST/" 2>/dev/null || true
else
echo "Output directory not found, copying from Docker build..."
SRC=/workspace/build-wasm/kicad-calculator/pcb_calculator
docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
"kicad-wasm-builder:${SRC}/pcb_calculator.js" "$KICAD_TEST/calculator.js"
docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
"kicad-wasm-builder:${SRC}/pcb_calculator.wasm" "$KICAD_TEST/calculator.wasm"
# Optional artifacts (best-effort).
docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
"kicad-wasm-builder:${SRC}/pcb_calculator.wasm.map" "$KICAD_TEST/calculator.wasm.map" 2>/dev/null || true
docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
"kicad-wasm-builder:${SRC}/pcb_calculator.worker.js" "$KICAD_TEST/calculator.worker.js" 2>/dev/null || true
docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
kicad-wasm-builder:/workspace/build-wasm/kicad-calculator/resources/images.tar.gz "$KICAD_TEST/" 2>/dev/null || true
fi
# wxWidgets WASM glue code (shared with pcbnew).
echo "Copying wxWidgets WASM glue code..."
if [ -f "$OUTPUT_DIR/wx.js" ]; then
cp "$OUTPUT_DIR/wx.js" "$KICAD_TEST/"
else
if docker compose -f "$PROJECT_ROOT/docker/docker-compose.yml" cp \
kicad-wasm-builder:/workspace/build-wasm/wxwidgets/build/wasm/wx.js "$KICAD_TEST/" 2>/dev/null; then
:
else
cp "$PROJECT_ROOT/wxwidgets/build/wasm/wx.js" "$KICAD_TEST/"
fi
fi
echo "Calculator WASM files copied to $KICAD_TEST"
ls -lh "$KICAD_TEST"