feat(gfx): integrate wasi-gfx for loading and presenting GUI
CI / test (push) Successful in 24s

This commit is contained in:
Antigravity committed 2026-11-25 02:54:03 +00:00
1 parent ccb809bdc3
commit 7caadb3f7f
59 files changed
+7495 -16

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
// Pure JS host implementation of the wasi-gfx WIT interfaces:
// - wasi-gfx:frame-buffer/frame-buffer@0.2.0
// - wasi-gfx:surface/surface@0.2.0
// - wasi-gfx:surface/surface-frame-buffer@0.2.0
//
// Works in both Browser (HTMLCanvasElement + Canvas2D ImageData) and Node/headless.
export class WasiGfxBuffer {
constructor(width = 1, height = 1) {
this.width = Math.max(1, width | 0);
this.height = Math.max(1, height | 0);
this._data = new Uint8Array(this.width * this.height * 4);
}
getWithCopy() {
return new Uint8Array(this._data);
}
setWithCopy(val) {
if (!(val instanceof Uint8Array)) {
this._data = new Uint8Array(val);
} else {
this._data = new Uint8Array(val);
}
}
}
function makeEventStream(subscribe) {
let unsubscribe = null;
return new ReadableStream({
start(controller) {
unsubscribe = subscribe((ev) => controller.enqueue(ev));
},
cancel() {
if (unsubscribe) unsubscribe();
},
});
}
export class WasiGfxSurface {
constructor(desc = {}, options = {}) {
this._width = Math.max(1, (desc.width ?? options.width ?? 1280) | 0);
this._height = Math.max(1, (desc.height ?? options.height ?? 720) | 0);
this.canvas = options.canvas ?? null;
this.onPresent = options.onPresent ?? null;
this.presentedFrames = 0;
this.lastPresented = null;
this._listeners = {
resize: new Set(),
frame: new Set(),
pointerUp: new Set(),
pointerDown: new Set(),
pointerMove: new Set(),
keyUp: new Set(),
keyDown: new Set(),
};
if (this.canvas) {
this.canvas.width = this._width;
this.canvas.height = this._height;
this._ctx2d = this.canvas.getContext('2d');
this._bindCanvasEvents();
} else {
this._ctx2d = null;
}
}
_bindCanvasEvents() {
const c = this.canvas;
const pos = (e) => {
const r = c.getBoundingClientRect();
return {
x: (e.clientX - r.left) * (c.width / (r.width || c.width)),
y: (e.clientY - r.top) * (c.height / (r.height || c.height)),
};
};
c.addEventListener('pointerup', (e) => this._emit('pointerUp', pos(e)));
c.addEventListener('pointerdown', (e) => this._emit('pointerDown', pos(e)));
c.addEventListener('pointermove', (e) => this._emit('pointerMove', pos(e)));
if (typeof window !== 'undefined') {
window.addEventListener('keyup', (e) => this._emit('keyUp', {
key: undefined,
text: e.key,
altKey: e.altKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
shiftKey: e.shiftKey,
}));
window.addEventListener('keydown', (e) => this._emit('keyDown', {
key: undefined,
text: e.key,
altKey: e.altKey,
ctrlKey: e.ctrlKey,
metaKey: e.metaKey,
shiftKey: e.shiftKey,
}));
}
}
_emit(channel, event) {
for (const fn of this._listeners[channel]) fn(event);
}
_subscribe(channel, fn) {
this._listeners[channel].add(fn);
return () => this._listeners[channel].delete(fn);
}
height() { return this._height; }
width() { return this._width; }
requestSetSize(height, width) {
const nw = width != null ? Math.max(1, width | 0) : this._width;
const nh = height != null ? Math.max(1, height | 0) : this._height;
if (nw !== this._width || nh !== this._height) {
this._width = nw;
this._height = nh;
if (this.canvas) {
this.canvas.width = nw;
this.canvas.height = nh;
}
this._emit('resize', { width: nw, height: nh });
}
}
onResize() { return makeEventStream((fn) => this._subscribe('resize', fn)); }
onFrame() { return makeEventStream((fn) => this._subscribe('frame', fn)); }
onPointerUp() { return makeEventStream((fn) => this._subscribe('pointerUp', fn)); }
onPointerDown() { return makeEventStream((fn) => this._subscribe('pointerDown', fn)); }
onPointerMove() { return makeEventStream((fn) => this._subscribe('pointerMove', fn)); }
onKeyUp() { return makeEventStream((fn) => this._subscribe('keyUp', fn)); }
onKeyDown() { return makeEventStream((fn) => this._subscribe('keyDown', fn)); }
_commitFrame(rgbaBytes) {
this.lastPresented = new Uint8Array(rgbaBytes);
this.presentedFrames += 1;
if (this._ctx2d && typeof ImageData !== 'undefined') {
const expected = this._width * this._height * 4;
if (this.lastPresented.length === expected) {
const img = new ImageData(
new Uint8ClampedArray(this.lastPresented.buffer, this.lastPresented.byteOffset, expected),
this._width,
this._height,
);
this._ctx2d.putImageData(img, 0, 0);
}
}
if (this.onPresent) this.onPresent(this.lastPresented, this._width, this._height);
}
}
export class WasiGfxFrameBufferContext {
constructor(surface) {
this.surface = surface;
this._buffer = new WasiGfxBuffer(surface.width(), surface.height());
}
getCurrentBuffer() {
if (this._buffer.width !== this.surface.width() || this._buffer.height !== this.surface.height()) {
this._buffer = new WasiGfxBuffer(this.surface.width(), this.surface.height());
}
return this._buffer;
}
present() {
this.surface._commitFrame(this._buffer.getWithCopy());
}
}
/**
* Create a wasi-gfx host state & import table for jco-transpiled components.
* Tracks all created surfaces and contexts so hosts/tests can inspect presented frames.
*/
export function createWasiGfxHost(options = {}) {
const surfaces = [];
const contexts = [];
class Surface extends WasiGfxSurface {
constructor(desc) {
super(desc, options);
surfaces.push(this);
}
}
class Context extends WasiGfxFrameBufferContext {
constructor(surface) {
super(surface);
contexts.push(this);
}
}
const imports = {
'wasi-gfx:frame-buffer/frame-buffer': { Buffer: WasiGfxBuffer },
'wasi-gfx:frame-buffer/frame-buffer@0.2.0': { Buffer: WasiGfxBuffer },
'wasi-gfx:surface/surface': { Surface },
'wasi-gfx:surface/surface@0.2.0': { Surface },
'wasi-gfx:surface/surface-frame-buffer': { Context },
'wasi-gfx:surface/surface-frame-buffer@0.2.0': { Context },
};
return {
Surface,
Context,
Buffer: WasiGfxBuffer,
surfaces,
contexts,
imports,
};
}
+79
View File
@@ -0,0 +1,79 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createWasiGfxHost } from '../src/wasi-gfx.mjs';
const HERE = dirname(fileURLToPath(import.meta.url));
const BUILD = join(HERE, '..', '..', 'build');
test('wasi-gfx host: Surface, Buffer, Context, and event streams', async () => {
const gfx = createWasiGfxHost();
const surf = new gfx.Surface({ width: 100, height: 50 });
assert.equal(surf.width(), 100);
assert.equal(surf.height(), 50);
const resizes = [];
const reader = surf.onResize().getReader();
surf.requestSetSize(80, 120);
const { value } = await reader.read();
resizes.push(value);
await reader.cancel();
assert.deepEqual(resizes, [{ width: 120, height: 80 }]);
const ctx = new gfx.Context(surf);
const buf = ctx.getCurrentBuffer();
const pixels = new Uint8Array(120 * 80 * 4);
pixels[0] = 0x11;
pixels[1] = 0x22;
pixels[2] = 0x33;
pixels[3] = 0xff;
buf.setWithCopy(pixels);
ctx.present();
assert.equal(surf.presentedFrames, 1);
assert.equal(surf.lastPresented[0], 0x11);
assert.equal(surf.lastPresented[3], 0xff);
});
test('wasi-gfx component (gfx-gui.wasm): loads GUI, handles pointer/resize/key, presents RGBA frames', async () => {
const gfx = createWasiGfxHost();
const jcoDir = join(BUILD, 'jco', 'gfx-gui');
const mod = await import(pathToFileURL(join(jcoDir, 'gfx-gui.js')).href);
const getCoreModule = async (p) => WebAssembly.compile(await readFile(join(jcoDir, p)));
const inst = await mod.instantiate(getCoreModule, gfx.imports);
await inst.initGui(320, 180);
assert.equal(gfx.surfaces.length, 1);
assert.equal(gfx.contexts.length, 1);
const surf = gfx.surfaces[0];
assert.equal(surf.width(), 320);
assert.equal(surf.height(), 180);
assert.equal(surf.presentedFrames, 1);
assert.equal(surf.lastPresented.length, 320 * 180 * 4);
// Verify non-empty rendered GUI pixels (alpha=255 and multiple distinct colors).
const colors = new Set();
for (let i = 0; i < surf.lastPresented.length; i += 4) {
assert.equal(surf.lastPresented[i + 3], 255);
colors.add((surf.lastPresented[i] << 16) | (surf.lastPresented[i + 1] << 8) | surf.lastPresented[i + 2]);
}
assert.ok(colors.size > 5, `expected rich GUI palette, got ${colors.size} colors`);
// Pointer click on launcher area -> opens launcher popup and presents new frame.
await inst.onPointer(1, 20, 170);
assert.equal(surf.presentedFrames, 2);
// Resize -> updates surface size and presents resized frame.
await inst.onResize(400, 240);
assert.equal(surf.width(), 400);
assert.equal(surf.height(), 240);
assert.equal(surf.presentedFrames, 3);
assert.equal(surf.lastPresented.length, 400 * 240 * 4);
// Escape key -> dismisses launcher and presents frame.
await inst.onKey(true, 'Escape');
assert.equal(surf.presentedFrames, 4);
});
+53 -12
View File
@@ -2,6 +2,7 @@ import { Desktop } from '../src/desktop.mjs';
import { createPlatform } from '../src/platform.mjs';
import { tokensFromJson } from '../src/theme.mjs';
import { webLoader } from '../src/loader-web.mjs';
import { WasiGfxSurface, WasiGfxFrameBufferContext } from '../src/wasi-gfx.mjs';
import { paint } from './canvas.mjs';
const base = new URL('../../', import.meta.url).href.replace(/\/$/, '');
@@ -12,6 +13,15 @@ const getJson = async (p) => {
return r.json();
};
async function drainStream(stream, handler) {
const reader = stream.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
handler(value);
}
}
const status = document.getElementById('status');
try {
const config = await getJson(`config/${q.get('config') ?? 'desktop.json'}`);
@@ -21,23 +31,54 @@ try {
const platform = createPlatform({ apps, tokens, now: fixed ? () => fixed : undefined });
const desktop = await new Desktop({ config, loader: webLoader(base), platform }).start();
// Present the desktop GUI through a wasi-gfx Surface + FrameBuffer Context.
const canvas = document.getElementById('screen');
canvas.width = desktop.screen.w; canvas.height = desktop.screen.h;
const ctx = canvas.getContext('2d');
const redraw = () => paint(ctx, desktop.frame().ops, desktop.screen);
const pos = (e) => { const r = canvas.getBoundingClientRect(); return [Math.round((e.clientX - r.left) * canvas.width / r.width), Math.round((e.clientY - r.top) * canvas.height / r.height)]; };
for (const [ev, kind] of [['pointermove', 'move'], ['pointerdown', 'down'], ['pointerup', 'up']]) {
canvas.addEventListener(ev, (e) => { const [x, y] = pos(e); if (desktop.pointer(kind, x, y)) redraw(); });
}
window.addEventListener('keydown', (e) => {
const k = e.key.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.key) ? e.key : null;
if (k && desktop.key(k)) { e.preventDefault(); redraw(); }
const gfxSurface = new WasiGfxSurface(
{ width: desktop.screen.w, height: desktop.screen.h },
{ canvas },
);
const gfxContext = new WasiGfxFrameBufferContext(gfxSurface);
const offscreen = document.createElement('canvas');
offscreen.width = desktop.screen.w;
offscreen.height = desktop.screen.h;
const offCtx = offscreen.getContext('2d');
const redraw = () => {
paint(offCtx, desktop.frame().ops, desktop.screen);
const img = offCtx.getImageData(0, 0, desktop.screen.w, desktop.screen.h);
const buf = gfxContext.getCurrentBuffer();
buf.setWithCopy(new Uint8Array(img.data.buffer, img.data.byteOffset, img.data.byteLength));
gfxContext.present();
};
// Route input events from wasi-gfx Surface streams into Desktop.
drainStream(gfxSurface.onPointerMove(), (e) => {
if (desktop.pointer('move', Math.round(e.x), Math.round(e.y))) redraw();
});
drainStream(gfxSurface.onPointerDown(), (e) => {
if (desktop.pointer('down', Math.round(e.x), Math.round(e.y))) redraw();
});
drainStream(gfxSurface.onPointerUp(), (e) => {
if (desktop.pointer('up', Math.round(e.x), Math.round(e.y))) redraw();
});
drainStream(gfxSurface.onKeyDown(), (e) => {
const k = e.text && (e.text.length === 1 || ['Backspace', 'Enter', 'Escape'].includes(e.text)) ? e.text : null;
if (k && desktop.key(k)) redraw();
});
redraw();
if (!fixed) setInterval(redraw, 1000);
status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name}`;
status.textContent = `${desktop.widgets.map((w) => `${w.id}=${w.componentName}`).join(' ')} | theme: ${platform.tokens.name} | wasi-gfx`;
// Handle for automation / the browser console.
window.moonPlasma = { desktop, platform, redraw, swap: async (id, c) => { await desktop.swap(id, c); redraw(); }, ready: true };
window.moonPlasma = {
desktop,
platform,
gfxSurface,
gfxContext,
redraw,
swap: async (id, c) => { await desktop.swap(id, c); redraw(); },
ready: true,
};
} catch (e) {
status.textContent = `ERROR: ${e.message}`;
status.style.color = '#f66';