fix: 🐛 hide print preview

This commit is contained in:
Istvan Matejcsok 2026-06-19 10:24:41 +02:00
commit 5c6e426b00
8 changed files with 449 additions and 1 deletions

3
.gitignore vendored
View file

@ -50,6 +50,9 @@ wxwidgets-clean/
/tests/apps/standalone/*/*.wasm
/tests/apps/kicad/*.js
/tests/apps/kicad/*.wasm
# Demo board for the gerbview print test — provisioned at setup from
# site/public/gerber-demo/board (see tests/scripts/setup-kicad-wasm.sh), not committed.
/tests/apps/kicad/board/
# DOM-port test bundles (mirrored + built by scripts/build-wasm-test.sh --dom)

2
kicad

@ -1 +1 @@
Subproject commit 793c26bbb4377c31ec32ff182ee06deb27edd3d9
Subproject commit f7a15ade476dec8615b864cbb90ef40662537b7e

View file

@ -0,0 +1,284 @@
<!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 — Print test harness</title>
<style>
.emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block; }
div.emscripten { text-align: center; }
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>
// Print-dialog test harness for gerbview. Identical boot to gerbview.html,
// but it ALSO auto-opens the tiny_tapeout demo board (so the Print dialog has
// layers to list) and seeds config to suppress the first-run wizard — same
// approach as the blog demo (site/public/gerber-demo/boot.js).
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';
};
// KiCad config dir baked into the WASM build (see boot.js / constants.ts).
var KICAD_CONFIG_DIR = '/home/kicad/.config/kicad/kicad/9.99';
// A lightweight subset of the tiny_tapeout demo board: enough layers/drill
// files to enable the Print action and populate the dialog's layer list,
// without the multi-MB copper/silkscreen layers (the Print Preview button is
// hidden regardless of board content, so the heavy layers add nothing here).
var BOARD_DIR = '/home/kicad/demo';
var BOARD_FILES = [
'tinytapeout-demo-Edge_Cuts.gbr',
'tinytapeout-demo-B_Mask.gbr',
'tinytapeout-demo-F_Mask.gbr',
'tinytapeout-demo-B_Paste.gbr',
'tinytapeout-demo-F_Paste.gbr',
'tinytapeout-demo-User_2.gbr',
'tinytapeout-demo-PTH.drl',
'tinytapeout-demo-NPTH.drl'
];
var OPEN_ARGS = BOARD_FILES.map(function(f) { return BOARD_DIR + '/' + f; });
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 gerbview.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);
});
// Prefetch the demo board layers (served from ./board/, copied from
// site/public/gerber-demo/board) in parallel with the wasm download.
var boardData = null;
var boardPromise = Promise.all(
BOARD_FILES.map(function(name) {
return fetch('./board/' + name)
.then(function(r) {
if (!r.ok) throw new Error('HTTP ' + r.status + ' for ' + name);
return r.arrayBuffer();
})
.then(function(buf) { return [name, new Uint8Array(buf)]; });
})
).then(function(pairs) {
boardData = {};
pairs.forEach(function(p) { boardData[p[0]] = p[1]; });
console.log('[KICAD] prefetched ' + pairs.length + ' board files');
}).catch(function(err) {
console.error('[KICAD] board prefetch failed:', 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)');
}
};
// Suppress the first-run setup wizard (its modal loop is noise for this test):
// pre-seed the config so settings providers report NeedsUserInput()==false.
var seedKicadConfig = function() {
FS.mkdirTree(KICAD_CONFIG_DIR);
var seed = function(path, contents) {
if (FS.analyzePath(path).exists) return;
FS.writeFile(path, contents);
};
seed(KICAD_CONFIG_DIR + '/kicad_common.json', JSON.stringify({
do_not_show_again: { update_check_prompt: true, data_collection_prompt: true }
}, null, 2));
seed(KICAD_CONFIG_DIR + '/sym-lib-table', '(sym_lib_table\n (version 7)\n)\n');
seed(KICAD_CONFIG_DIR + '/fp-lib-table', '(fp_lib_table\n (version 7)\n)\n');
seed(KICAD_CONFIG_DIR + '/design-block-lib-table', '(design_block_lib_table\n (version 7)\n)\n');
console.log('[KICAD] seeded config (wizard suppressed)');
};
// Land in a writable home dir (Open/Save dialogs default to cwd).
var setupHomeDir = function() {
var home = '/home/kicad';
FS.mkdirTree(home);
FS.chdir(home);
console.log('[KICAD] cwd set to ' + home);
};
// Write the board into MEMFS and point argv at it so gerbview auto-opens it.
// argv must be set before main(); a run dependency keeps main() waiting if the
// board fetch hasn't landed yet.
var preloadBoard = function() {
Module.arguments = OPEN_ARGS;
var writeBoard = function() {
if (!boardData) return;
FS.mkdirTree(BOARD_DIR);
Object.keys(boardData).forEach(function(name) {
FS.writeFile(BOARD_DIR + '/' + name, boardData[name]);
});
console.log('[KICAD] wrote board into ' + BOARD_DIR + '; argv=' + OPEN_ARGS.length + ' files');
};
if (boardData) { writeBoard(); return; }
var add = window.addRunDependency;
var rm = window.removeRunDependency;
if (typeof add === 'function' && typeof rm === 'function') {
add('board-files');
boardPromise.then(function() { writeBoard(); rm('board-files'); });
} else {
boardPromise.then(writeBoard);
}
};
var Module = {
thisProgram: '/usr/bin/gerbview', // Fake absolute path for argv[0]
arguments: OPEN_ARGS,
preRun: [createCanvas, writeResources, seedKicadConfig, setupHomeDir, preloadBoard],
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 src="wx-dom.js"></script>
<script async src="gerbview.js"></script>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View file

@ -0,0 +1,146 @@
import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import {
clickByLabel,
clickByTooltip,
clickMenuBarItem,
clickMenuItem,
findByLabel,
} from '../e2e/utils/element-tracker';
/**
* Gerber Viewer Print dialog — regression for emergence-engineering/pcbjam#14.
*
* In the browser, KiCad's generic Print dialog used to show a "Print Preview"
* button (wxID_APPLY) that the DOM/WASM port can't honor: the in-app
* wxPreviewFrame is opened window-modal from inside the already-modal Print
* dialog, which the port can't render over an active modal — clicking it did
* nothing and wedged the dialog so it would not reopen.
*
* The fix hides that button in the browser build (the same way native KiCad
* already hides it on macOS/GTK), since the browser provides its own print
* preview. This test loads the tiny_tapeout demo board, opens the Print dialog,
* and asserts (a) there is no visible "Print Preview" button and (b) the dialog
* can be closed and reopened — i.e. the modal state is no longer wedged.
*/
function hasAbort(testLogger: { consoleLogs: string[]; errors: string[] }): boolean {
return [...testLogger.consoleLogs, ...testLogger.errors].some(line => line.includes('Aborted('));
}
// The Print dialog is detected by its unique OK button, labelled exactly
// "Print" (wxID_OK). Toolbar/menu print entries are rendered tools / menu items
// (a separate registry) or carry the "..." ellipsis, so they don't match here —
// a visible exact-"Print" element means the modal Print dialog is open.
async function printDialogIsOpen(page: Page): Promise<boolean> {
return (await findByLabel(page, 'Print', { visible: true, exact: true })) !== null;
}
async function waitForPrintDialog(page: Page, open: boolean, timeout = 8000): Promise<void> {
await page.waitForFunction(
(wantOpen: boolean) => {
const registry = window.wxElementRegistry;
if (!registry) return false;
const isOpen = registry.findByLabel('Print', { visible: true, exact: true }).length > 0;
return isOpen === wantOpen;
},
open,
{ timeout },
);
}
async function waitForGerbview(page: Page): Promise<void> {
await expect(page.locator('#canvas')).toBeVisible({ timeout: 90000 });
await page.waitForFunction(() => !!window.wxElementRegistry, null, { timeout: 90000 });
await page.waitForFunction(() => {
const registry = window.wxElementRegistry;
return !!registry && registry.findAll({}).length > 0;
}, null, { timeout: 90000 });
// The config is seeded to suppress the first-run wizard, but dismiss it
// defensively in case it still appears (harmless when there is none).
for (let i = 0; i < 6; i++) {
if (!(await clickByLabel(page, 'Next >'))) {
await clickByLabel(page, 'Finish');
break;
}
await page.waitForTimeout(300);
}
// Let the demo board load and the viewer chrome settle. The Print Preview
// button is hidden unconditionally in the WASM build, so the assertions
// don't actually depend on the layers being fully parsed — this is mostly
// for a faithful screenshot.
await page.waitForTimeout(4000);
}
// Open the Print dialog. In gerbview, Print is a top-toolbar tool (not a File
// menu item), so click that; fall back to a File -> Print… menu path in case the
// UI changes ("..." vs unicode "…").
async function openPrintDialog(page: Page): Promise<void> {
if (!(await clickByTooltip(page, 'Print'))) {
await clickMenuBarItem(page, 'File');
await page.waitForTimeout(500);
let opened = await clickMenuItem(page, 'Print...');
if (!opened) opened = await clickMenuItem(page, 'Print…');
if (!opened) await clickMenuItem(page, 'Print');
}
await waitForPrintDialog(page, true);
}
// Close the modal Print dialog. Escape cancels a wxDialog; fall back to the
// Close button if needed. Poll for the dialog to actually disappear.
async function closePrintDialog(page: Page): Promise<void> {
for (const how of ['escape', 'close', 'escape'] as const) {
if (how === 'escape') {
await page.keyboard.press('Escape').catch(() => {});
} else {
await clickByLabel(page, 'Close', { visible: true, exact: true });
}
try {
await waitForPrintDialog(page, false, 3000);
return;
} catch {
// try the next method
}
}
// Final assertion happens in the test; surface the still-open state there.
await waitForPrintDialog(page, false, 1000);
}
test.describe('gerbview Print dialog (WASM)', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/kicad/gerbview-print.html');
});
test('no Print Preview button, and the dialog reopens (no wedge)', async ({ page, testLogger }) => {
await waitForGerbview(page);
await page.screenshot({ path: 'test-results/gerbview-print-00-loaded.png', scale: 'device' });
// --- Open the Print dialog ---
await openPrintDialog(page);
expect(await printDialogIsOpen(page), 'Print dialog should be open').toBe(true);
await page.screenshot({ path: 'test-results/gerbview-print-01-dialog.png', scale: 'device' });
// --- The broken "Print Preview" button must be gone in the browser ---
const preview = await findByLabel(page, 'Print Preview', { visible: true, exact: true });
expect(preview, 'Print Preview button must be hidden in the browser build').toBeNull();
// Sanity: this really is the Print dialog (Close + Page Setup present too).
expect(await findByLabel(page, 'Close', { visible: true, exact: true }),
'Close button present').not.toBeNull();
// --- Close it ---
await closePrintDialog(page);
expect(await printDialogIsOpen(page), 'dialog should close').toBe(false);
// --- Regression: reopening Print must work (it used to wedge) ---
await openPrintDialog(page);
expect(await printDialogIsOpen(page), 'Print dialog should reopen (no wedge)').toBe(true);
await page.waitForTimeout(2500); // let the reopened dialog finish painting before capture
await page.screenshot({ path: 'test-results/gerbview-print-02-reopened.png', scale: 'device' });
expect(hasAbort(testLogger), 'no WASM abort during the flow').toBe(false);
});
});

View file

@ -115,5 +115,20 @@ else
smart_cp "$PROJECT_ROOT/wxwidgets/build/wasm/wx-dom.js" "$KICAD_TEST"
fi
# Demo board for the gerbview print test (tests/apps/kicad/gerbview-print.html).
# Provisioned (not committed; gitignored) from the canonical demo board, same
# pattern as the wasm artifacts above. gerbview-print.html fetches the subset of
# layers it needs from ./board/, so copying the whole set is harmless.
BOARD_SRC="$PROJECT_ROOT/site/public/gerber-demo/board"
if [ -d "$BOARD_SRC" ]; then
echo "Provisioning gerbview demo board..."
mkdir -p "$KICAD_TEST/board"
for f in "$BOARD_SRC"/tinytapeout-demo-*; do
smart_cp "$f" "$KICAD_TEST/board"
done
else
echo " (demo board source $BOARD_SRC not found — skipping)"
fi
echo "KiCad WASM files synced to $KICAD_TEST"
ls -lh "$KICAD_TEST"