Keep the frames of pasted GIF, WebP, and AVIF images

A browser puts only the first frame of an image on the clipboard, with
HTML that names the image address.

- Documents and cards download the original of a GIF, WebP, or AVIF
  address. The host commands workspace_save_image_url and
  workspace_download_image read the format from the file contents and
  refuse other data. A failed download keeps the first frame and shows
  a message.
- Copy image in the RuneStone browser keeps the bytes that the page
  loaded. The engine reads them through the DevTools Protocol, so the
  website gets no second request. The new copiedImage command gives
  them in parts below the line limit of the host. A paste uses them
  first.
- An empty dropped image file shows a message. Firefox gives such a
  file when the website refuses its download.

Copy image needs a new browser engine build. Card 0d5c18f7.
This commit is contained in:
Knotty Wyvern
2026-10-31 17:33:08 -07:00
parent 31ce7e73ce
commit 6e1b24e40f
29 changed files with 654 additions and 41 deletions
+20
View File
@@ -5,7 +5,27 @@ import os from 'node:os';
import path from 'node:path';
import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
// A two-frame GIF that the server gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
let onceGifServed = false;
// The same GIF with 7 MB of comment blocks, so that Copy image needs more than one part.
const comment = Buffer.concat([Buffer.from([255]), Buffer.alloc(255, 0x61)]);
const largeGif = Buffer.concat([onceGif.subarray(0, 32), Buffer.from([0x21, 0xfe]), ...Array(28_000).fill(comment), Buffer.from([0]), onceGif.subarray(32)]);
const server = http.createServer((req, res) => {
if (req.url === '/direct.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/large.gif') {
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(largeGif);
}
if (req.url === '/once.gif') {
if (onceGifServed) { res.writeHead(200, { 'Content-Type': 'text/html' }); return res.end('Invalid request'); }
onceGifServed = true;
res.writeHead(200, { 'Content-Type': 'image/gif' });
return res.end(onceGif);
}
if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
+40 -1
View File
@@ -31,6 +31,31 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
pageFocusStates.set(wc, enabled);
if (enabled) wc.focus();
}
// The last image that Copy image took from a page. RuneStone gets it in parts when the user pastes.
let copied = null;
const COPIED_PART = 3_000_000;
// The page holds the encoded image. Its bytes keep all frames of a GIF, and the website gets no second request.
async function loadedImage(wc, url) {
if (!wc.debugger.isAttached()) { wc.debugger.attach('1.3'); pageFocusStates.delete(wc); }
await wc.debugger.sendCommand('Page.enable');
try {
const href = value => { try { return new URL(value).href; } catch { return ''; } };
const nodes = [(await wc.debugger.sendCommand('Page.getResourceTree')).frameTree];
for (const node of nodes) {
// An image that opens as the page itself is the main resource of its frame.
const page = href(node.frame.url) === url && /^image\//.test(node.frame.mimeType) ? node.frame : undefined;
const resource = page ?? node.resources?.find(item => item.type === 'Image' && href(item.url) === url);
if (resource) {
const { content, base64Encoded } = await wc.debugger.sendCommand('Page.getResourceContent', { frameId: node.frame.id, url: resource.url });
const data = Buffer.from(content, base64Encoded ? 'base64' : 'utf8');
const valid = /^image\/(?:gif|png|jpeg|webp|avif|bmp)$/.test(resource.mimeType) && data.length > 0 && data.length <= 20_000_000;
return valid ? { mime: resource.mimeType, data } : null;
}
nodes.push(...(node.childFrames ?? []));
}
return null;
} finally { await wc.debugger.sendCommand('Page.disable').catch(() => {}); }
}
function emulateViewport(item) {
if (!item.viewport) return;
const { width, height } = item.viewport, scale = item.scale;
@@ -248,7 +273,13 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
switch (args.action) {
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
case 'copyImage': {
if (!context.hasImageContents) break;
wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale));
const image = context.srcURL ? await loadedImage(wc, context.srcURL).catch(() => null) : null;
copied = image && { token: randomUUID(), tabId: current.id, url: context.srcURL, ...image };
return copied && { copied: { token: copied.token, url: copied.url, mime: copied.mime, size: copied.data.length } };
}
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
case 'saveImage': case 'saveLink': {
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
@@ -259,6 +290,14 @@ export async function createEngine({ directory, emit = () => {}, canEmitFrame =
}
return null;
}
case 'copiedImage': {
// A part stays below the line limit of the host connection.
if (!copied || copied.token !== args.token || copied.tabId !== args.tabId || !Number.isSafeInteger(args.offset) || args.offset < 0 || args.offset >= copied.data.length) {
throw new Error('The copied image is no longer available.');
}
const end = Math.min(copied.data.length, args.offset + COPIED_PART);
return { data: copied.data.subarray(args.offset, end).toString('base64'), next: end < copied.data.length ? end : null };
}
case 'input': {
const current = tab(args.tabId), wc = current.view.webContents;
const input = args.input;
+50
View File
@@ -124,6 +124,56 @@ app.whenReady().then(async () => {
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
const menus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
const imageMenu = events.findLast(event => event.event === 'context-menu');
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
const bytes = Buffer.from(part.data, 'base64');
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
assert.equal(bytes.length, 85);
assert.equal(part.next, null);
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
// A large image comes in parts that stay below the line limit of the host.
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
const largeMenus = events.length;
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
const parts = [];
for (let offset = 0; offset !== null;) {
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
assert.ok(next.data.length <= 4_000_000);
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
}
const whole = Buffer.concat(parts);
assert.ok(parts.length >= 3);
assert.equal(whole.length, large.size);
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
assert.equal(whole.at(-1), 0x3b);
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
// An image that opens as the page itself is the main resource of the tab.
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
const directContents = engine.tabs.get(direct).view.webContents;
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
const directMenus = events.length;
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
await engine.command('closeTab', { tabId: direct });
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active');
+2 -1
View File
@@ -6,7 +6,8 @@ app.setPath('userData', process.env.RS_INTERACTION_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let framePending = false;
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
// The fixture server of the smoke test is on 127.0.0.1. The engine blocks local addresses for other hosts.
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, allowedTestHosts: new Set(['127.0.0.1']), canEmitFrame: () => !framePending, emit: value => {
if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
} });