RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+179
View File
@@ -0,0 +1,179 @@
// Embedded browser sharpness with the real Electron engine: frames map one page pixel to one host pixel at each display scale,
// a display scale change (a move to another monitor) updates the frame scale, and pointer input lands on the page point under it.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scales = process.env.BROWSER_TEST_SCALE ? [Number(process.env.BROWSER_TEST_SCALE)] : [1, 1.25, 1.5, 2];
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-scale-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/**
* Serve a page and return the markup of the scale fixture. The engine gateway blocks local addresses, so the test writes the markup into the page.
* The fixture has 1-device-pixel black and white columns in its top-left 200 by 100 CSS pixels, and text below them.
* `draw()` draws the columns again for the current pixel ratio. The page records the position of each click.
*/
async function startFixture() {
const html = `<!doctype html><title>Scale fixture</title><body style="margin:0;background:#fff;color:#111;font:14px sans-serif">
<canvas id="stripes" style="display:block;width:200px;height:100px"></canvas><p style="margin:8px">Sharp text: The quick brown fox jumps over the lazy dog. 0123456789</p>
<script>
function draw(){const c=document.getElementById('stripes'),r=devicePixelRatio;c.width=Math.round(200*r);c.height=Math.round(100*r);const g=c.getContext('2d');g.fillStyle='#fff';g.fillRect(0,0,c.width,c.height);g.fillStyle='#000';for(let x=0;x<c.width;x+=2)g.fillRect(x,0,1,c.height);}
draw();window.clicks=[];addEventListener('mousedown',e=>clicks.push([e.clientX,e.clientY]));
</script>`;
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end(html); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { html, url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
/**
* Return the mean absolute difference between horizontal neighbours in the stripe area of the frame image, read from a screenshot of the whole host page.
* The value is 255 for an exact copy of the page pixels. Resampling blends neighbours and lowers it.
* The test does not measure an element screenshot, because a clip at a fractional device pixel resamples the screenshot itself.
*/
async function stripeContrast(page, png, scale) {
return page.evaluate(async ({ data, scale }) => {
const box = document.querySelector('.surface img').getBoundingClientRect();
const left = Math.round(box.left * devicePixelRatio), top = Math.round(box.top * devicePixelRatio);
const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode();
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
const width = Math.round(180 * scale), row = context.getImageData(left, top + Math.round(50 * scale), width, 1).data;
let sum = 0;
for (let x = 0; x < width - 1; x++) sum += Math.abs(row[x * 4] - row[x * 4 + 4]);
return sum / (width - 1);
}, { data: png.toString('base64'), scale });
}
await runSmoke('browser/scale', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const output = await outputDir('browser/scale');
const report = {};
try {
for (const scale of scales) {
const context = await browser.newContext({ viewport: { width: 1000, height: 700 }, deviceScaleFactor: scale });
const page = engine.page = await openPage(context, { timeout: 30000 });
await page.exposeFunction('browserRpc', (command, args) => engine.rpc(command, args));
// Keep each resolution media query list of the host, so the test can report a scale change to the host page.
await page.addInitScript(() => { const native = matchMedia.bind(window); window.__resolutionQueries = []; window.matchMedia = query => { const list = native(query); if (query.includes('resolution')) window.__resolutionQueries.push(list); return list; }; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => engine.rpc('testEvaluate', { tabId, code });
await engine.rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
await evaluate(`document.open();document.write(${JSON.stringify(fixture.html)});document.close();true;`);
await page.locator('.browser:not(.blank)[data-browser-state="ready"] .surface img').waitFor();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
/**
* Wait for the lossless frame of the current scale, then measure and save the host pixels of the surface.
* `cdp` takes the screenshot through a CDP session with its own scale override, because a Playwright screenshot applies the context scale again.
*/
async function measure(expected, name, cdp) {
for (let attempt = 0; attempt < 100 && await evaluate('devicePixelRatio') !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate('devicePixelRatio'), expected, `The page pixel ratio follows the host at ${name}`);
// Emulation in the engine also changes the ratio without a media query event, so draw the columns again.
await evaluate('draw();true;');
await page.waitForTimeout(400);
await page.waitForFunction(() => document.querySelector('.surface img')?.src.startsWith('data:image/png'));
let png;
if (cdp) png = Buffer.from((await cdp.send('Page.captureScreenshot', { format: 'png' })).data, 'base64');
else {
await surface.screenshot({ path: path.join(output, `surface-${name}.png`) });
png = await page.screenshot();
}
await writeFile(path.join(output, `window-${name}.png`), png);
return stripeContrast(page, png, expected);
}
const contrast = await measure(scale, `${scale}x`);
assert.ok(contrast > 240, `Frames must not be resampled at ${scale}x: neighbour contrast ${contrast.toFixed(1)}`);
const box = await surface.boundingBox();
await evaluate('clicks.length=0;true;');
for (const [x, y] of [[37, 61], [412, 233]]) await page.mouse.click(box.x + x, box.y + y);
for (let attempt = 0; attempt < 100 && (await evaluate('clicks.length')) < 2; attempt++) await page.waitForTimeout(50);
const clicks = await evaluate('clicks');
// Native input uses whole device pixels, and the frame can start up to one device pixel inside the surface. Allow one CSS pixel.
assert.ok(clicks.length === 2 && clicks.every(([x, y], index) => Math.abs(x - [37, 412][index]) <= 1 && Math.abs(y - [61, 233][index]) <= 1),
`Clicks land on the page point under the pointer at ${scale}x: ${JSON.stringify(clicks)}`);
report[`${scale}x`] = { contrast, clicks };
if (scale === 1.5) {
// A move to a monitor with a different scale changes devicePixelRatio but not the CSS size of the surface.
// Emulation changes the pixel ratio without a media query change event, so the test sends the event that a real display change sends.
const cdp = await page.context().newCDPSession(page);
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 700, deviceScaleFactor: 1.25, mobile: false });
await page.evaluate(() => { for (const list of [...window.__resolutionQueries]) list.dispatchEvent(new Event('change')); });
const moved = await measure(1.25, '1.5x-to-1.25x', cdp);
assert.ok(moved > 240, `Frames must follow a display scale change: neighbour contrast ${moved.toFixed(1)}`);
report['1.5x-to-1.25x'] = { contrast: moved };
}
assert.deepEqual(page.errors, []);
engine.page = undefined;
await engine.rpc('closeTab', { tabId });
await context.close();
}
await writeFile(path.join(output, 'browser-scale.json'), JSON.stringify(report, null, 2));
console.log(`PASS browser frames are sharp at ${scales.join(', ')}x, follow a scale change, and keep pointer positions`);
} finally {
await engine.stop();
await fixture.close();
}
});