Show browser frames at one frame pixel for each screen pixel

The built-in browser looked blurry at Windows display scaling above 100%.
The engine rendered sharp frames, but the host stretched each frame to the
surface. The stretch resampled every pixel and blended text and images.

- The engine crops the extra frame edge and sends the frame scale.
- The view shows each frame at its CSS size, at a device pixel edge, on its
  own compositor layer, with nearest-pixel sampling.
- Pointer input subtracts the frame offset.
- The view sends a new scale when the display scale changes.
- A new smoke test, browser/scale, measures stripe contrast at 100%, 125%,
  150%, and 200%, and after a scale change. It also tests click positions.

Measured contrast at 150%: 92 of 255 before, 255 after.

(cherry picked from commit e98a65de536111b5365d1c6f863a897a8e38e505)
This commit is contained in:
Knotty Wyvern
2026-10-28 12:32:41 -07:00
parent 1c19da25ba
commit af68d92969
4 changed files with 217 additions and 12 deletions
+7 -3
View File
@@ -115,7 +115,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
webPreferences: { ...REMOTE_PREFERENCES, session: ses, offscreen: { deviceScaleFactor: 1 }, backgroundThrottling: false } }); webPreferences: { ...REMOTE_PREFERENCES, session: ses, offscreen: { deviceScaleFactor: 1 }, backgroundThrottling: false } });
win.setMenu(null); win.setMenu(null);
const item = { id, profileId, epoch: 0, view: win, title: 'Browser', favicon: null, iconRequest: null, blocked: 0, find: null, findRequest: 0, const item = { id, profileId, epoch: 0, view: win, title: 'Browser', favicon: null, iconRequest: null, blocked: 0, find: null, findRequest: 0,
delivery: new FrameDelivery(), context: null, downloads: new Set(), settle: null, retryFrame: null, latestImage: null, scale: 1 }; delivery: new FrameDelivery(), context: null, downloads: new Set(), settle: null, retryFrame: null, latestImage: null, latestScale: 1, scale: 1 };
tabs.set(item.id, item); tabs.set(item.id, item);
const wc = win.webContents; const wc = win.webContents;
wc.setFrameRate(60); wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp'); wc.setFrameRate(60); wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp');
@@ -158,7 +158,11 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
wc.on('did-finish-load', () => emulateViewport(item)); wc.on('did-finish-load', () => emulateViewport(item));
wc.on('did-fail-load', (_event, code, _description, _url, main) => { if (main && code !== -3) emit({ event: 'error', tabId: item.id, message: `Page load failed (${code}).` }); }); wc.on('did-fail-load', (_event, code, _description, _url, main) => { if (main && code !== -3) emit({ event: 'error', tabId: item.id, message: `Page load failed (${code}).` }); });
wc.on('paint', (_event, _dirty, image) => { wc.on('paint', (_event, _dirty, image) => {
item.latestImage = image; // Offscreen frames can be one pixel larger than the viewport. The host shows each frame pixel on one screen pixel, so crop the extra edge.
const size = image.getSize(), width = Math.min(size.width, Math.round((item.viewport?.width ?? size.width) * item.scale)),
height = Math.min(size.height, Math.round((item.viewport?.height ?? size.height) * item.scale));
item.latestImage = width < size.width || height < size.height ? image.crop({ x: 0, y: 0, width, height }) : image;
item.latestScale = item.scale;
clearTimeout(item.settle); clearTimeout(item.settle);
clearTimeout(item.retryFrame); clearTimeout(item.retryFrame);
const frame = (lossless = false) => { const frame = (lossless = false) => {
@@ -170,7 +174,7 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
} }
const data = lossless ? item.latestImage.toPNG() : item.latestImage.toJPEG(90); const data = lossless ? item.latestImage.toPNG() : item.latestImage.toJPEG(90);
if (data.length && data.length <= 4_000_000) emit({ event: 'frame', tabId: item.id, frameId: item.delivery.sent(), if (data.length && data.length <= 4_000_000) emit({ event: 'frame', tabId: item.id, frameId: item.delivery.sent(),
mime: lossless ? 'image/png' : 'image/jpeg', data: data.toString('base64'), ...item.latestImage.getSize() }); mime: lossless ? 'image/png' : 'image/jpeg', data: data.toString('base64'), scale: item.latestScale, ...item.latestImage.getSize() });
}; };
frame(); frame();
// Send a lossless final frame for sharp text when the page stops changing. // Send a lossless final frame for sharp text when the page stops changing.
+30 -8
View File
@@ -17,7 +17,7 @@
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId)); const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
const blank = $derived(!current?.url || current.url === 'about:blank'); const blank = $derived(!current?.url || current.url === 'about:blank');
let address = $state(''); let editing = $state(false); let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement; let image = $state(''), imageBox = $state({ width: 0, height: 0, x: 0, y: 0, exact: false }); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false; let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
let inputQueue = Promise.resolve(); let inputQueue = Promise.resolve();
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args)); const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
@@ -74,7 +74,9 @@
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) { if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
displayedFrame = frame; displayedFrame = frame;
if (blank) { image = ''; acknowledgeFrame(); } if (blank) { image = ''; acknowledgeFrame(); }
else image = `data:${frame.mime};base64,${frame.data}`; else {
image = `data:${frame.mime};base64,${frame.data}`; imageBox = frameBox(frame);
}
} }
}); });
pageEvents.set(id, event => { pageEvents.set(id, event => {
@@ -83,6 +85,20 @@
}); });
return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); }; return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); };
}); });
/**
* Return the CSS box that shows each frame pixel on one screen pixel: the frame size in CSS pixels, and the offset
* from the surface edge to the next device pixel edge. A stretched or misaligned frame is resampled and blurs text.
* `exact` is true when the frame scale is the display scale. Then the image uses nearest-pixel sampling, because
* layout rounds the CSS size to 1/64 pixel and a scale of 0.99998 still blends neighbour pixels.
* Chromium uses nearest-pixel sampling only to scale up, so the size rounds up to the next 1/64 pixel.
* The image has its own compositor layer. A shared layer can start at a fractional device pixel and blend the frame again.
*/
function frameBox(frame: BrowserFrame) {
const scale = frame.scale || 1, ratio = devicePixelRatio || 1, rect = surface.getBoundingClientRect();
const align = (edge: number) => (Math.ceil(edge * ratio - 0.001) - edge * ratio) / ratio;
const size = (pixels: number) => Math.ceil(pixels / scale * 64) / 64;
return { width: size(frame.width), height: size(frame.height), x: align(rect.left), y: align(rect.top), exact: scale === ratio };
}
function acknowledgeFrame() { function acknowledgeFrame() {
const frame = displayedFrame; displayedFrame = undefined; const frame = displayedFrame; displayedFrame = undefined;
if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {}); if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {});
@@ -115,7 +131,7 @@
{ label: $t('Reload'), icon: 'refresh', run: () => void send('reload') }, { label: $t('Reload'), icon: 'refresh', run: () => void send('reload') },
{ label: $t('Find in page'), icon: 'search', shortcut: 'Ctrl+F', run: () => void find() }); { label: $t('Find in page'), icon: 'search', shortcut: 'Ctrl+F', run: () => void find() });
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + context.x * rect.width / width, y: rect.top + context.y * rect.height / height, const menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y,
items, label: $t('Browser page actions') }); items, label: $t('Browser page actions') });
closeMenu = menu.close; closeMenu = menu.close;
} }
@@ -140,7 +156,12 @@
timer = setTimeout(syncSize, 100); timer = setTimeout(syncSize, 100);
}); });
resize.observe(surface); resize.observe(surface);
return () => { mounted = false; stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); }; // A move to a monitor with a different display scale changes the pixel ratio but not always the surface size.
let pixelRatio: MediaQueryList;
const watchPixelRatio = () => { pixelRatio = matchMedia(`(resolution: ${devicePixelRatio}dppx)`); pixelRatio.addEventListener('change', changePixelRatio, { once: true }); };
const changePixelRatio = () => { watchPixelRatio(); syncSize(); };
watchPixelRatio();
return () => { mounted = false; pixelRatio.removeEventListener('change', changePixelRatio); stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
}); });
function syncSize() { function syncSize() {
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
@@ -158,7 +179,7 @@
const rect = surface.getBoundingClientRect(); const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); return; } if (!rect.width || !rect.height) { stopScroll(); return; }
const anchor = autoScroll.anchor; const anchor = autoScroll.anchor;
wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y }); wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x - imageBox.x)), y: Math.min(height - 1, Math.round(anchor.y - imageBox.y)), deltaX: -delta.x, deltaY: -delta.y });
} }
scrollFrame = requestAnimationFrame(scrollStep); scrollFrame = requestAnimationFrame(scrollStep);
} }
@@ -186,7 +207,8 @@
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); } if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
if (type === 'mouseWheel') stopScroll(); else return; if (type === 'mouseWheel') stopScroll(); else return;
} }
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x * width / rect.width))), y: Math.max(0, Math.min(height - 1, Math.round(point.y * height / rect.height))), // The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event), button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) }; ...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; } if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
@@ -261,7 +283,7 @@
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }} oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }} oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea> onblur={stopScroll}></textarea>
{#if image && ready && !blank}<img src={image} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if} {#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if} {#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div> </div>
</div> </div>
@@ -275,7 +297,7 @@
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)} .surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent} .browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006} .surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px} img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)} .error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer} .reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
.reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer} .reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer}
+1 -1
View File
@@ -13,7 +13,7 @@ export type Snapshot = {
}; };
export const state = writable<Snapshot | null>(null); export const state = writable<Snapshot | null>(null);
export const pageErrors = writable<Record<string, string>>({}); export const pageErrors = writable<Record<string, string>>({});
export type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number }; export type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number; scale?: number };
export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string }; export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string };
export const frames = new Map<string, (frame: BrowserFrame) => void>(); export const frames = new Map<string, (frame: BrowserFrame) => void>();
export const pageEvents = new Map<string, (event: PageMenu) => void>(); export const pageEvents = new Map<string, (event: PageMenu) => void>();
+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();
}
});