Compare commits

...
5 Commits
Author SHA1 Message Date
Knotty Wyvern 33495d2bf7 Set the version to 0.1.53 2026-10-31 18:31:37 -07:00
Knotty Wyvern e4be352a2b Pin browser engine 0.1.9
Engine 0.1.9 keeps the original bytes for Copy image. The pin names its ZIP on the RuneStone releases page.
2026-10-31 18:24:37 -07:00
Knotty Wyvern 6e1b24e40f 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.
2026-10-31 17:33:08 -07:00
Knotty Wyvern 31ce7e73ce Close the workspace menu on a second click of its button
The menu is an automatic popover. A press on the button closed the open
menu, and the click that followed opened it again. The picker now
records an open menu when the press starts on the button. The click
then leaves the menu closed.

The workspace smoke test clicks the button two times. Card 53db89fc.
2026-10-31 17:33:07 -07:00
Knotty Wyvern 8e2df5544a Show the label colors in Manage labels again
The default field rule of Project Management excluded the find bar with
:not(.rs-find-bar input). That exclusion raised the specificity of the
rule above the rule of each control. Thus the color swatches, the card
title field, the switches, and the date field got the default field
background.

:where() inside :not() keeps the exclusion and adds no specificity.
A new smoke test checks the 16 swatch colors and the card title field in
both themes. Card 0efb6b6e.
2026-10-31 17:33:07 -07:00
40 changed files with 729 additions and 57 deletions
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.9",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.9",
"dependencies": {
"@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone-browser",
"version": "0.1.8",
"version": "0.1.9",
"private": true,
"description": "Isolated browser runtime included with RuneStone",
"type": "module",
+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; });
} });
+2
View File
@@ -10,6 +10,8 @@ This guide explains how to insert and edit images, read diagrams, edit Markdown
| --- | --- |
| Drag an image from the navigator into a Markdown editor | RuneStone inserts a relative link to the existing file. Press Escape to cancel the drag. |
| Drop an image from your system file manager, or paste an image | RuneStone copies the image into the workspace `attachments/` folder with a unique name, then inserts a link. |
| Paste an image that you copied with **Copy image** in the RuneStone browser | RuneStone saves the original file that the page loaded. A GIF keeps its animation, also from a website that refuses downloads. |
| Paste a GIF, WebP, or AVIF image that you copied in another web browser | That browser copies only the first frame. RuneStone downloads the original file from the image address, so the animation stays. If the website refuses the download, RuneStone saves the first frame and shows a message. |
Undo removes the inserted link. It keeps the image file.
+6
View File
@@ -116,6 +116,12 @@ To add an image to a card, paste it or drop it into the description, or select *
Use a PNG, JPEG, GIF, or WebP image of at most 50 MiB.
To show an image on the board, add **Card cover** and choose one of the images of the card.
A web browser copies only the first frame of an image. When you paste a GIF or WebP image from a browser, RuneStone downloads the original file.
Then the animation stays.
Some websites refuse that download. Then the card gets the first frame, and RuneStone shows a message.
To keep the animation, use **Copy image** in the RuneStone browser. That copy keeps the original file that the page loaded.
**More actions** → **Customize background** sets an image behind the open board, or behind All tasks.
To show the Background slideshow on the boards, see [Choose where the background shows](themes.md#choose-where-the-background-shows).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.52",
"version": "0.1.53",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.52"
version = "0.1.53"
dependencies = [
"base64 0.23.1",
"dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "runestone"
version = "0.1.52"
version = "0.1.53"
description = "Writing workspace plus script editor"
authors = ["Knotty Wyvern"]
edition = "2021"
@@ -46,4 +46,4 @@ opt-level = 3
strip = true
[package.metadata.runestone]
version = "0.1.52"
version = "0.1.53"
+4 -4
View File
@@ -1,11 +1,11 @@
{
"version": "0.1.8",
"version": "0.1.9",
"protocol": 1,
"platforms": {
"windows-x86_64": {
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.8/RuneStone-Browser_0.1.8_win32-x64.zip",
"bytes": 163632595,
"sha256": "d704003bf5fe047b100a3cf0ab84f3321fd272510cf287a229e50d1653d0856b"
"url": "https://git.knottywyvern.com/kwyvern/RuneStone/releases/download/browser-engine-v0.1.9/RuneStone-Browser_0.1.9_win32-x64.zip",
"bytes": 163623491,
"sha256": "040fbc671a061331a031de280879d5a455f6cda679e9e2c75c8bc4a21e101121"
}
}
}
+2
View File
@@ -71,6 +71,8 @@ fn main() {
"workspace_delete",
"workspace_read_data_url",
"workspace_write_bytes",
"workspace_save_image_url",
"workspace_download_image",
"workspace_copy",
"workspace_abs_path",
"workspace_reveal",
+2
View File
@@ -69,6 +69,8 @@
"allow-workspace-delete",
"allow-workspace-read-data-url",
"allow-workspace-write-bytes",
"allow-workspace-save-image-url",
"allow-workspace-download-image",
"allow-workspace-copy",
"allow-workspace-abs-path",
"allow-workspace-reveal",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-download-image"
description = "Enables the workspace_download_image command without any pre-configured scope."
commands.allow = ["workspace_download_image"]
[[permission]]
identifier = "deny-workspace-download-image"
description = "Denies the workspace_download_image command without any pre-configured scope."
commands.deny = ["workspace_download_image"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-save-image-url"
description = "Enables the workspace_save_image_url command without any pre-configured scope."
commands.allow = ["workspace_save_image_url"]
[[permission]]
identifier = "deny-workspace-save-image-url"
description = "Denies the workspace_save_image_url command without any pre-configured scope."
commands.deny = ["workspace_save_image_url"]
+2 -1
View File
@@ -34,6 +34,7 @@ const COMMANDS: &[&str] = &[
"insertText",
"edit",
"contextAction",
"copiedImage",
"frameAck",
"createProfile",
"renameProfile",
@@ -480,7 +481,7 @@ impl BrowserState {
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock()?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "focus", "input", "insertText", "edit", "contextAction", "copiedImage", "frameAck", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock()?.owners.get(id) {
Some(window) if window == owner => {},
+2
View File
@@ -107,6 +107,8 @@ pub fn run() {
workspace::workspace_delete,
workspace::workspace_read_data_url,
workspace::workspace_write_bytes,
workspace::workspace_save_image_url,
workspace::workspace_download_image,
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
+152 -2
View File
@@ -967,10 +967,14 @@ fn read_data_url(root: &Path, rel: &str) -> Result<String> {
}
let bytes = fsutil::read_to_limit(file, MAX_IMAGE_BYTES as u64)?
.ok_or_else(|| Error::new("image is too large"))?;
Ok(format!(
Ok(data_url(mime, &bytes))
}
fn data_url(mime: &str, bytes: &[u8]) -> String {
format!(
"data:{mime};base64,{}",
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes)
))
)
}
fn copy_destination(path: &Path, number: u32) -> PathBuf {
@@ -1244,6 +1248,108 @@ fn write_image(root: &Path, rel: &str, base64: &str) -> Result<()> {
fsutil::write_bytes(&path, &bytes)
}
/// Save the original of an image that a web page copied. The clipboard has only a still copy,
/// so an animated GIF needs its source file. `rel` has no extension. The format of the
/// downloaded file sets it. Returns the path of the new file.
#[tauri::command]
pub async fn workspace_save_image_url(
window: tauri::Window,
state: State<'_, WorkspaceState>,
url: String,
rel: String,
) -> Result<String> {
let root = current_root(&state, window.label())?;
blocking(move || {
let bytes = download_image(&url)?;
save_image(&root, &rel, &bytes)
})
.await
}
/// Download a web image and return it as a data URL. Project Management keeps card images
/// as data URLs, so this gives a card the original of a copied image.
#[tauri::command]
pub async fn workspace_download_image(url: String) -> Result<String> {
blocking(move || image_data_url(&download_image(&url)?)).await
}
fn image_data_url(bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let mime = mime_from_path(Path::new(&format!("image.{extension}")))
.ok_or_else(|| Error::new("file is not an image"))?;
Ok(data_url(mime, bytes))
}
fn download_image(url: &str) -> Result<Vec<u8>> {
use std::io::Read;
let web = |url: &reqwest::Url| matches!(url.scheme(), "http" | "https");
let url = reqwest::Url::parse(url).map_err(|_| Error::new("invalid image address"))?;
if !web(&url) {
return Err(Error::new("image address is not http or https"));
}
let client = reqwest::blocking::Client::builder()
.user_agent(concat!("RuneStone/", env!("CARGO_PKG_VERSION")))
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.redirect(reqwest::redirect::Policy::custom(move |attempt| {
if attempt.previous().len() >= 5 || !web(attempt.url()) {
attempt.stop()
} else {
attempt.follow()
}
}))
.build()
.map_err(Error::from_display)?;
let response = client.get(url).send().map_err(Error::from_display)?;
if !response.status().is_success() {
return Err(Error::new(format!("image server answered {}", response.status())));
}
let mut bytes = Vec::new();
response.take(MAX_IMAGE_BYTES as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > MAX_IMAGE_BYTES {
return Err(Error::new("image is too large"));
}
Ok(bytes)
}
fn save_image(root: &Path, rel: &str, bytes: &[u8]) -> Result<String> {
let extension = image_extension(bytes).ok_or_else(|| Error::new("file is not an image"))?;
let rel = format!("{rel}.{extension}");
let path = resolve_for_write(root, &rel)?;
check_new_components(root, &rel)?;
if path.exists() {
return Err(Error::new("a file with that name already exists"));
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fsutil::write_bytes(&path, bytes)?;
Ok(rel)
}
/// The extension of a raster image format from its first bytes. A web server can send a
/// wrong type, and an SVG file can contain scripts, so the type header and SVG do not count.
fn image_extension(bytes: &[u8]) -> Option<&'static str> {
let at = |start: usize, value: &[u8]| bytes.get(start..start + value.len()) == Some(value);
if at(0, b"GIF87a") || at(0, b"GIF89a") {
Some("gif")
} else if at(0, b"\x89PNG\r\n\x1a\n") {
Some("png")
} else if at(0, b"\xff\xd8\xff") {
Some("jpg")
} else if at(0, b"RIFF") && at(8, b"WEBP") {
Some("webp")
} else if at(4, b"ftypavif") || at(4, b"ftypavis") {
Some("avif")
} else if at(0, b"BM") {
Some("bmp")
} else if at(0, b"\0\0\x01\0") {
Some("ico")
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1598,6 +1704,50 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn image_formats_come_from_the_file_contents() {
assert_eq!(image_extension(b"GIF89a\x01\0"), Some("gif"));
assert_eq!(image_extension(b"GIF87a"), Some("gif"));
assert_eq!(image_extension(b"\x89PNG\r\n\x1a\n\0"), Some("png"));
assert_eq!(image_extension(b"\xff\xd8\xff\xe0"), Some("jpg"));
assert_eq!(image_extension(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
assert_eq!(image_extension(b"\0\0\0\x1cftypavif"), Some("avif"));
assert_eq!(image_extension(b"BM\0\0"), Some("bmp"));
assert_eq!(image_extension(b"\0\0\x01\0\x01\0"), Some("ico"));
assert_eq!(image_extension(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"), None);
assert_eq!(image_extension(b"<!doctype html>"), None);
assert_eq!(image_extension(b"RIFF"), None);
assert_eq!(image_extension(b""), None);
}
#[test]
fn web_images_keep_their_original_format() {
let root = workspace_fixture("image-url");
let gif = b"GIF89a\x01\0\x01\0\0\0\0;".to_vec();
let (base, server) = crate::plugin_sources::tests::server(vec![
("302 Found\r\nLocation: /cat.gif".into(), Vec::new()),
("200 OK\r\nContent-Type: image/png".into(), gif.clone()),
("200 OK\r\nContent-Type: image/gif".into(), b"<!doctype html>".to_vec()),
("404 Not Found".into(), Vec::new()),
]);
let bytes = download_image(&format!("{base}/image")).unwrap();
assert_eq!(save_image(&root, "attachments/pasted", &bytes).unwrap(), "attachments/pasted.gif");
assert_eq!(fs::read(root.join("attachments/pasted.gif")).unwrap(), gif);
assert_eq!(image_data_url(&bytes).unwrap(), "data:image/gif;base64,R0lGODlhAQABAAAAADs=");
let page = download_image(&format!("{base}/page")).unwrap();
assert_eq!(save_image(&root, "attachments/page", &page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(&page).unwrap_err().to_string(), "file is not an image");
assert_eq!(image_data_url(b"\xff\xd8\xff\xe0").unwrap(), "data:image/jpeg;base64,/9j/4A==");
assert!(download_image(&format!("{base}/missing")).unwrap_err().to_string().contains("404"));
let requests = server.join().unwrap();
assert!(requests[1].starts_with("GET /cat.gif "));
assert!(download_image("file:///C:/cat.gif").is_err());
assert!(save_image(&root, "attachments/pasted", &gif).is_err(), "an existing file stays");
assert!(save_image(&root, "../outside", &gif).is_err());
assert_eq!(names(&root.join("attachments")), ["pasted.gif"]);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn permanent_delete_removes_files_and_folders_but_never_the_root() {
let root = workspace_fixture("delete");
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.52",
"version": "0.1.53",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
+19 -1
View File
@@ -11,6 +11,7 @@
import { TabSession, type TabStatus } from './tabSession';
import { engine } from './engine';
import { AutoScroll } from './autoScroll';
import { keepCopiedImage } from '$lib/workspace/copiedImage';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('Opening browser…') });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
@@ -117,7 +118,7 @@
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push(
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
@@ -142,6 +143,23 @@
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args);
}
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
// A paste can come before the reply, so the copy is known at once by its address.
function copyImage(context: PageMenu) {
const owner = tabId;
const data = (async () => {
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
const copied = reply?.copied;
if (!copied) return undefined;
let data = '';
for (let offset: number | null = 0; offset !== null;) {
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
data += part.data; offset = part.next;
}
return `data:${copied.mime};base64,${data}`;
})().catch(() => undefined);
if (context.srcURL) keepCopiedImage(context.srcURL, data);
}
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
if (opening) return;
opening = true;
+4 -2
View File
@@ -75,12 +75,14 @@ export class TabSession {
}
}
}
async send(command: string, args: Record<string, unknown> = {}) {
/** Returns the reply of the engine, or undefined when the request did not complete. */
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
if (this.closed || this.value.phase !== 'ready') return;
const tabId = this.value.tabId;
try {
await this.transport(command, { ...args, tabId });
const reply = await this.transport(command, { ...args, tabId });
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
return reply;
} catch (error) {
// Replies from the previous connection cannot replace the current error.
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
+7 -5
View File
@@ -15,7 +15,7 @@
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle } from "$lib/workspace/media";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { savedEditor, saveEditor } from "./editorStates";
@@ -48,7 +48,7 @@
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
focusLine?: number | null;
/** The line and the column of the cursor, from 1. */
onSelectionLine?: (line: number, column: number) => void;
@@ -126,10 +126,12 @@
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
// Read the HTML now. The clipboard data is empty after the paste event.
const source = event instanceof ClipboardEvent && files.length === 1 ? pastedImageSource(data?.getData("text/html") ?? "") : undefined;
await importImages(view, files, position, undefined, source);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string, source?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
@@ -137,7 +139,7 @@
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
const snippet = await onInsertImage?.(file, source);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
+42 -12
View File
@@ -11,6 +11,30 @@ import {
parseImage,
saveImages,
} from "../storage/images.ts";
import { workspaceDownloadImage } from "../../../workspace/api.ts";
import { copiedImage } from "../../../workspace/copiedImage.ts";
import { mayAnimate, pastedImageSource } from "../../../workspace/media.ts";
async function fileDataUrl(file: File) {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
return `data:${file.type};base64,${btoa(binary)}`;
}
/**
* The original of a copied web image. The RuneStone browser keeps the bytes of the image that it copied.
* For a copy from another browser, download the original of a format with frames.
* Undefined keeps the still copy. "refused" means that the website did not give the original.
*/
async function webImage(source: string): Promise<{ data: string; type: string } | "refused" | undefined> {
const data = await copiedImage(source) ?? (mayAnimate(source) ? await workspaceDownloadImage(source).catch(() => "") : undefined);
if (data === undefined) return undefined;
if (!data) return "refused";
const type = /^data:([^;]+);/.exec(data)?.[1] ?? "";
return imageTypes.includes(type) ? { data, type } : undefined;
}
/** The image data stays outside the card Markdown and loads only in the open editor. */
export function createCardImages(
@@ -226,7 +250,8 @@ export function createCardImages(
}
}
}
async function addFiles(files: File[], attachOnly = false) {
/** `source` is the web address of the original of a copied image. `files` holds its still copy. */
async function addFiles(files: File[], attachOnly = false, source?: string) {
if (disposed || loading || description.disabled || !files.length) return;
loading = true;
updateControls();
@@ -237,18 +262,20 @@ export function createCardImages(
end = description.selectionEnd;
try {
const staged: { id: string; name: string; data: string }[] = [];
let refused = false;
for (const file of files) {
if (!imageTypes.includes(file.type))
// A browser copies only the first frame of a web image. The original keeps all of its frames.
const web = source ? await webImage(source) : undefined;
refused ||= web === "refused";
const original = typeof web === "object" ? web : undefined;
if (!original && !imageTypes.includes(file.type))
throw new Error(message("Use a PNG, JPEG, GIF, or WebP image."));
if (!file.size || file.size > maxImageBytes)
if (!original && !file.size)
throw new Error(message("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file."));
if (!original && file.size > maxImageBytes)
throw new Error(message("Use an image between 1 byte and 50 MiB."));
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = "";
for (let offset = 0; offset < bytes.length; offset += 8192)
binary += String.fromCharCode(
...bytes.subarray(offset, offset + 8192),
);
const data = `data:${file.type};base64,${btoa(binary)}`;
const data = original?.data ?? await fileDataUrl(file);
const name = original ? `${(file.name || "image").replace(/\.\w+$/, "")}.${original.type.slice(6)}` : file.name;
// Decode the image before the reference goes in, so that an invalid clipboard file keeps the draft.
const image = new Image();
image.src = data;
@@ -257,7 +284,7 @@ export function createCardImages(
});
staged.push({
id: crypto.randomUUID(),
name: (file.name || tr("Pasted image")).slice(0, 255),
name: (name || tr("Pasted image")).slice(0, 255),
data,
});
}
@@ -269,6 +296,7 @@ export function createCardImages(
description.setRangeText(`\n${markdown}\n`, start, end, "end");
}
description.dispatchEvent(new Event("input", { bubbles: true }));
if (refused) error.textContent = tr("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
} catch (reason) {
if (!disposed)
(attachOnly ? attachmentError : error).textContent = errorText(reason);
@@ -288,7 +316,9 @@ export function createCardImages(
if (!files.length) return;
event.preventDefault();
event.stopPropagation();
void addFiles(files);
// Read the HTML now. The clipboard data is empty after the paste event.
const source = files.length === 1 ? pastedImageSource(event.clipboardData?.getData("text/html") ?? "") : undefined;
void addFiles(files, false, source);
};
const dragOver = (event: DragEvent) => {
if (event.dataTransfer?.types.includes("Files")) {
+4 -3
View File
@@ -67,7 +67,7 @@
cursor: default;
}
.rs-pm button:not(.rs-picker-row):not([role^="menuitem"]):focus-visible,
.rs-pm input:not(.rs-find-bar input):focus-visible,
.rs-pm input:not(:where(.rs-find-bar input)):focus-visible,
.rs-pm select:focus-visible,
.rs-pm textarea:focus-visible {
outline: 1px solid var(--pm-accent);
@@ -196,7 +196,8 @@
.pm-search-row input {
width: min(340px, 100%);
}
.rs-pm input:not(.rs-find-bar input),
/* The find bar exclusion adds no specificity, so the rules of each control can replace these defaults. */
.rs-pm input:not(:where(.rs-find-bar input)),
.rs-pm select,
.rs-pm textarea {
background: var(--pm-field-surface);
@@ -205,7 +206,7 @@
padding: 6px 8px;
min-height: 30px;
}
.rs-pm input[type="checkbox"]:not(.rs-find-bar input) {
.rs-pm input[type="checkbox"]:not(:where(.rs-find-bar input)) {
min-height: 0;
width: 16px;
height: 16px;
+2
View File
@@ -4065,6 +4065,8 @@ export const messageRows: [string, string, string, string][] = [
["Unlink {name}", "Délier {name}", "{name} のリンクを解除", "取消关联 {name}"],
["Unsaved changes", "Modifications non enregistrées", "未保存の変更", "未保存的更改"],
["Use a PNG, JPEG, GIF, or WebP image.", "Utilisez une image PNG, JPEG, GIF ou WebP.", "PNG、JPEG、GIF、WebP のいずれかの画像を使用してください。", "请使用 PNG、JPEG、GIF 或 WebP 图片。"],
["The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.", "Le site web a refusé l’image d’origine. RuneStone n’en a donc ajouté que la première trame. Pour conserver l’animation, copiez l’image dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "Web サイトが元の画像を拒否したため、RuneStone は最初のフレームだけを追加しました。アニメーションを保つには、RuneStone のブラウザーで画像をコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "网站拒绝提供原始图片,因此 RuneStone 只添加了第一帧。要保留动画,请在 RuneStone 浏览器中复制图片。也可以保存图片,然后添加保存的文件。"],
["The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.", "Le fichier image est vide. Un navigateur peut fournir un fichier vide quand le site web refuse un téléchargement. Pour ajouter l’image, copiez-la dans le navigateur de RuneStone. Vous pouvez aussi enregistrer l’image, puis ajouter le fichier enregistré.", "画像ファイルが空です。Web サイトがダウンロードを拒否すると、ブラウザーが空のファイルを渡すことがあります。画像を追加するには、RuneStone のブラウザーでコピーしてください。画像を保存して、保存したファイルを追加することもできます。", "图片文件为空。网站拒绝下载时,浏览器可能会提供空文件。要添加图片,请在 RuneStone 浏览器中复制它。也可以保存图片,然后添加保存的文件。"],
["Use an image between 1 byte and 50 MiB.", "Utilisez une image entre 1 octet et 50 Mio.", "1 バイトから 50 MiB までの画像を使用してください。", "请使用 1 字节到 50 MiB 之间的图片。"],
["View image {name}", "Afficher l’image {name}", "画像 {name} を表示", "查看图片 {name}"],
["When you save, RuneStone removes each deleted label from all cards.", "Lors de l’enregistrement, RuneStone retire chaque étiquette supprimée de toutes les cartes.", "保存すると、RuneStone は削除したラベルをすべてのカードから外します。", "保存时,RuneStone 会从所有卡片中移除每个已删除的标签。"],
+2 -2
View File
@@ -37,7 +37,7 @@
onQuickOpen: () => void;
onOpenBrowser?: () => void;
onChange: EditorProps["onChange"];
onInsertImage: (file: File, buffer: OpenBuffer | null) => Promise<string | null>;
onInsertImage: (file: File, buffer: OpenBuffer | null, source?: string) => Promise<string | null>;
onRenameTitle: EditorProps["onRenameTitle"];
tableActions: (pane: DocumentView) => EditorProps["tableActions"];
linkActions: (pane: DocumentView) => EditorProps["linkActions"];
@@ -108,7 +108,7 @@
split={pane.split}
focusLine={activePane === pane.id ? focusLine : null}
{onChange}
onInsertImage={file => onInsertImage(file, pane.buffer)}
onInsertImage={(file, source) => onInsertImage(file, pane.buffer, source)}
{onRenameTitle}
tableActions={tableActions(pane)}
linkActions={linkActions(pane)}
+1 -1
View File
@@ -29,7 +29,7 @@
focusLine: number | null;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File) => Promise<string | null>;
onInsertImage?: (file: File, source?: string) => Promise<string | null>;
onView?: (view: ViewMode) => void;
onSplit?: (split: boolean) => void;
onCursor?: (line: number, column: number) => void;
+21 -5
View File
@@ -65,10 +65,12 @@
workspaceReveal,
workspaceWrite,
workspaceWriteBytes,
workspaceSaveImageUrl,
} from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
import { attachmentRel, dataUrlExtension, isImagePath, isMarkdownPath, mayAnimate } from "$lib/workspace/media";
import { copiedImage } from "$lib/workspace/copiedImage";
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
@@ -775,21 +777,35 @@
});
}
async function insertImage(file: File, note = buffer): Promise<string | null> {
/** `source` is the web address of the original of a copied image. `file` is its still copy. */
async function insertImage(file: File, note = buffer, source?: string): Promise<string | null> {
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null;
}
const noteRel = note.relPath;
const current = documents;
try {
const rel = attachmentRel(file.name);
const dataUrl = await readFileDataUrl(file);
let rel = attachmentRel(file.name);
const stem = rel.replace(/\.[^./]+$/, "");
// The RuneStone browser keeps the bytes of the image that it copied. For a copy from another browser, download the original of a format with frames.
const copied = source ? await copiedImage(source) : undefined;
const copiedExtension = copied ? dataUrlExtension(copied) : undefined;
const download = !copiedExtension && !!source && mayAnimate(source);
// The host sets the extension from the downloaded file. A failed download keeps the still copy.
const downloaded = download && source ? await workspaceSaveImageUrl(source, stem).catch(() => null) : null;
if (downloaded) rel = downloaded;
else {
if (copiedExtension) rel = `${stem}.${copiedExtension}`;
const dataUrl = copied && copiedExtension ? copied : await readFileDataUrl(file);
const base64 = dataUrl.split(",")[1];
if (!base64) {
error = $t("The image file is empty. A browser can give an empty file when the website refuses a download. To add the image, copy it in the RuneStone browser. You can also save the image and add the saved file.");
return null;
}
if (documents !== current || switching) return null;
await workspaceWriteBytes(rel, base64);
if (download) error = $t("The website refused the original image, so RuneStone added only its first frame. To keep the animation, copy the image in the RuneStone browser. You can also save the image and add the saved file.");
}
if (documents !== current) return null;
session.changed([rel]);
return `![](${"../".repeat(noteRel.split("/").length - 1)}${rel})`;
@@ -1379,7 +1395,7 @@
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{onChange}
onInsertImage={(file, tab) => insertImage(file, tab)}
onInsertImage={(file, tab, source) => insertImage(file, tab, source)}
onRenameTitle={renameNoteTitle}
tableActions={(pane) => ({ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) })}
linkActions={(pane) => ({
+15
View File
@@ -23,9 +23,24 @@
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
// A press on the anchor closes the open menu before the click. Then the click must not open it again.
let pressedOpen = false;
$effect(() => {
const target = anchor;
if (!target) return;
const press = () => {
pressedOpen = menu.matches(":popover-open");
// The click comes in the same task as the release. A drag away from the anchor gives no click.
if (pressedOpen) window.addEventListener("pointerup", () => setTimeout(() => { pressedOpen = false; }), { once: true });
};
target.addEventListener("pointerdown", press);
return () => target.removeEventListener("pointerdown", press);
});
export async function show() {
if (busy || creating) return;
if (pressedOpen) { pressedOpen = false; return; }
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true;
+10
View File
@@ -83,6 +83,16 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise<void>
return invoke("workspace_write_bytes", { rel, base64 });
}
/** Download a web image to `rel` plus the extension of its format. Returns the path of the new file. */
export function workspaceSaveImageUrl(url: string, rel: string): Promise<string> {
return invoke("workspace_save_image_url", { url, rel });
}
/** Download a web image. Returns it as a data URL. */
export function workspaceDownloadImage(url: string): Promise<string> {
return invoke("workspace_download_image", { url });
}
export type CopyResult = {
name: string;
rel_path: string;
+16
View File
@@ -0,0 +1,16 @@
/**
* The original of the last image that Copy image took in the RuneStone browser.
* The browser takes the bytes that the page loaded, so a pasted GIF keeps its frames.
* This also works when the website refuses a second download of the image.
*/
let last: { url: string; data: Promise<string | undefined> } | undefined;
/** Keep the original of a copied image. `data` gives its data URL. */
export function keepCopiedImage(url: string, data: Promise<string | undefined>) {
last = { url, data: data.catch(() => undefined) };
}
/** The data URL of the original of `url`, when the RuneStone browser copied that image last. */
export async function copiedImage(url: string): Promise<string | undefined> {
return last?.url === url ? last.data : undefined;
}
+33
View File
@@ -96,6 +96,39 @@ export function attachmentRel(fileName: string): string {
return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`;
}
const ENTITIES: Record<string, string> = { amp: "&", quot: '"', apos: "'", "#39": "'", lt: "<", gt: ">" };
/**
* The web address of a copied image. A browser puts only the first frame on the clipboard,
* with HTML that names the original file.
*/
export function pastedImageSource(html: string): string | undefined {
const images = [...html.matchAll(/<img\b[^>]*?\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/gi)];
if (images.length !== 1) return undefined;
const [, double, single, bare] = images[0];
const source = (double ?? single ?? bare).trim().replace(/&(amp|quot|apos|#39|lt|gt);/g, (_, name: string) => ENTITIES[name]);
try {
const url = new URL(source);
return /^https?:$/.test(url.protocol) ? url.href : undefined;
} catch {
return undefined;
}
}
/** A GIF, WebP, or AVIF address. These formats can have more frames, so the original is worth a download. */
export function mayAnimate(source: string): boolean {
return /\.(?:gif|webp|avif)$/i.test(new URL(source).pathname);
}
const EXTENSIONS: Record<string, string> = {
"image/gif": "gif", "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp", "image/avif": "avif", "image/bmp": "bmp",
};
/** The file extension of an image data URL, or undefined for another type. */
export function dataUrlExtension(data: string): string | undefined {
return EXTENSIONS[/^data:([^;,]+)[;,]/.exec(data)?.[1] ?? ""];
}
export function imageFiles(data: DataTransfer | null): File[] {
return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
}
+5
View File
@@ -88,6 +88,11 @@ function pmCommands(test) {
else workspace.folders.add(rel);
return null;
}),
// The download of a copied web image: a 1 by 1 GIF. An address with "offline" fails.
workspace_download_image: ({ url }) => {
if (url.includes("offline")) throw new Error("Cannot reach the image server");
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
},
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
spelling_menu_install: () => null,
"plugin:window|is_maximized": () => false,
+20 -1
View File
@@ -52,9 +52,19 @@ async function startEngine() {
return engine;
}
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
@@ -120,6 +130,15 @@ await runSmoke('browser/interaction', async ({ browser }) => {
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
+52 -1
View File
@@ -28,6 +28,13 @@ await runSmoke("editor/images", async ({ page }) => {
if (test.failWrite) throw new Error("Image write failed");
workspace.files.set(args.rel, args.base64);
},
// The download of a copied web image. The host adds the extension of the downloaded format.
workspace_save_image_url: args => {
if (args.url.includes("offline")) throw new Error("Cannot reach the image server");
const rel = args.rel + ".gif";
workspace.files.set(rel, btoa('<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'));
return rel;
},
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
@@ -196,5 +203,49 @@ await runSmoke("editor/images", async ({ page }) => {
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
await page.keyboard.press("Control+s");
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
// A browser copies the still first frame of a GIF. RuneStone saves the original file from the address in the HTML.
async function pasteWebImage(src) {
await page.locator(".cm-content").evaluate((element, src) => {
const data = new DataTransfer();
data.items.add(new File(["png"], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
const writes = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_write_bytes").length);
const writesBefore = await writes();
await pasteWebImage("https://media.example.com/cat.gif?size=large&amp;v=2");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.gif\)/.test(window.__CM__.state.doc.toString()));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_save_image_url").args);
assert.equal(download.url, "https://media.example.com/cat.gif?size=large&v=2");
assert.match(download.rel, /^attachments\/[\w-]+-image$/);
assert.equal(await writes(), writesBefore);
// When the download fails, the still copy stays.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /attachments\/[\w-]+-image\.png\)/.test(window.__CM__.state.doc.toString()));
assert.equal(await writes(), writesBefore + 1);
await page.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_save_image_url").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/-image\.gif\)/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.match(await page.evaluate(() => window.__TEST__.calls.findLast(call => call.command === "workspace_write_bytes").args.rel), /-image\.gif$/);
// An empty file from a browser drag gives a message, not a broken image.
await page.locator(".cm-content").evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
const rect = element.getBoundingClientRect();
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
});
await page.getByText("The image file is empty.", { exact: false }).waitFor();
assert.ok(!(await page.evaluate(() => window.__CM__.state.doc.toString())).includes("viprsr188"));
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode, undo, web GIF pastes, copied originals, and empty files passed.");
});
+66
View File
@@ -0,0 +1,66 @@
// Project Management card images: a GIF copied in a web browser keeps its original file. A failed download keeps the still copy.
import assert from "node:assert/strict";
import { runSmoke } from "../_harness/index.mjs";
import { cardPath, fileText, loadWorkspace, openBoard, pane, waitForFile } from "../_harness/pmFixture.mjs";
const imageFile = id => `.runestone/pm/images/${id}.json`;
await runSmoke("features/pmImages", async ({ page }) => {
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
await editor.getByRole("button", { name: "Edit", exact: true }).click();
const description = editor.locator('textarea[aria-label="Details (Markdown)"]');
await description.fill("");
// A browser puts a still PNG on the clipboard, with HTML that names the original GIF.
async function pasteWebImage(src) {
await description.evaluate((element, src) => {
const png = Uint8Array.from(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="), c => c.charCodeAt(0));
const data = new DataTransfer();
data.items.add(new File([png], "image.png", { type: "image/png" }));
data.setData("text/html", `<html><body><!--StartFragment--><img src="${src}"/><!--EndFragment--></body></html>`);
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
}, src);
}
const reference = name => new RegExp(`!\\[${name.replace(".", "\\.")}\\]\\(pm-image:([0-9a-f-]{36})\\)`);
await pasteWebImage("https://media.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.gif\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
const download = await page.evaluate(() => window.__TEST__.calls.find(call => call.command === "workspace_download_image").args);
assert.equal(download.url, "https://media.example.com/cat.gif");
// When the download fails, the card gets the still PNG.
await pasteWebImage("https://offline.example.com/cat.gif");
await page.waitForFunction(() => /!\[image\.png\]\(pm-image:/.test(document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value));
await editor.getByText("The website refused the original image, so RuneStone added only its first frame.", { exact: false }).waitFor();
// The RuneStone browser keeps the bytes of the image that it copied. The website gets no second request.
await page.evaluate(async () => (await import("/src/lib/workspace/copiedImage.ts")).keepCopiedImage("https://offline.example.com/copied.gif",
Promise.resolve("data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")));
const downloads = () => page.evaluate(() => window.__TEST__.calls.filter(call => call.command === "workspace_download_image").length);
const downloadsBefore = await downloads();
await pasteWebImage("https://offline.example.com/copied.gif");
await page.waitForFunction(() => (document.querySelector('dialog.pm-card-editor[open] textarea[aria-label="Details (Markdown)"]').value.match(/!\[image\.gif\]/g) || []).length === 2);
assert.equal(await downloads(), downloadsBefore);
assert.equal(await editor.getByText("The website refused the original image", { exact: false }).count(), 0, "A kept original clears the message");
// An empty file from a browser drag gives a message, not the size limit.
await description.evaluate(element => {
const data = new DataTransfer();
data.items.add(new File([], "viprsr188.gif", { type: "image/gif" }));
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data }));
});
await editor.getByText("The image file is empty.", { exact: false }).waitFor();
assert.equal(await editor.getByText("Use an image between 1 byte and 50 MiB.").count(), 0);
await editor.locator(".pm-description-actions").getByRole("button", { name: "Save", exact: true }).click();
await waitForFile(page, cardPath("card-a"), /pm-image:.*\n?[\s\S]*pm-image:/);
const body = await fileText(page, cardPath("card-a"));
const gif = reference("image.gif").exec(body)[1], png = reference("image.png").exec(body)[1];
assert.match(await fileText(page, imageFile(gif)), /"data":"data:image\/gif;base64,R0lGOD/);
assert.match(await fileText(page, imageFile(png)), /"data":"data:image\/png;base64,iVBOR/);
console.log("PASS: a pasted web GIF keeps its original file, a copied original needs no download, and failures explain the cause");
});
@@ -0,0 +1,38 @@
// Project Management label colors: each color choice of Manage labels shows its color, and the card title keeps its own field style, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { outputDir, runSmoke } from "../_harness/index.mjs";
import { loadWorkspace, openBoard, pane, setTheme } from "../_harness/pmFixture.mjs";
const rgb = hex => `rgb(${hex.slice(1).match(/../g).map(value => parseInt(value, 16)).join(", ")})`;
await runSmoke("features/pmLabelColors", async ({ page }) => {
const output = await outputDir("features/pmLabelColors");
await loadWorkspace(page);
await openBoard(page, "Roadmap");
await pane(page).locator(".pm-card-title", { hasText: /^Card A$/ }).click();
const editor = page.locator("dialog.pm-card-editor[open]");
await editor.waitFor();
// The card title is a transparent field. The default field rule of Project Management does not replace its background.
const title = editor.getByRole("textbox", { name: "Title", exact: true });
assert.equal(await title.evaluate(input => getComputedStyle(input).backgroundColor), "rgba(0, 0, 0, 0)");
await editor.getByRole("group", { name: "Card details", exact: true }).getByRole("button", { name: "Labels", exact: true }).click();
await page.getByRole("dialog", { name: "Choose labels", exact: true }).getByRole("button", { name: "Manage labels", exact: true }).click();
const manager = page.getByRole("dialog", { name: "Manage labels", exact: true });
await manager.waitFor();
const bug = manager.getByRole("group", { name: "Label Bug", exact: true });
const swatches = await bug.locator("input.pm-color-swatch").evaluateAll(inputs =>
inputs.map(input => ({ name: input.getAttribute("aria-label"), color: input.style.getPropertyValue("--pm-swatch-color"), shown: getComputedStyle(input).backgroundColor })));
assert.equal(swatches.length, 16);
for (const swatch of swatches) assert.equal(swatch.shown, rgb(swatch.color), `${swatch.name} shows its color`);
await bug.getByRole("radio", { name: "Blue", exact: true }).check();
await manager.locator(".pm-label-badge", { hasText: /^Bug$/ }).waitFor();
for (const theme of ["dark", "light"]) {
await setTheme(page, theme);
await bug.screenshot({ path: path.join(output, `label-colors-${theme}.png`) });
}
console.log("PASS: label color choices and the card title field");
});
@@ -66,7 +66,12 @@ await runSmoke("workspace/openAndCreate", async ({ page }) => {
assert.equal(await menu.locator('[aria-current="true"]').count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
await page.screenshot({ path: path.join(output, "workspaces-menu.png") });
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
// A second click on the switcher closes the menu. It does not open the menu again.
await trigger.click();
await menu.waitFor({ state: "hidden", timeout: 2000 });
await trigger.click();
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
const opened =await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
await menu.getByRole("button").filter({ hasText: "Current" }).click();
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
await page.keyboard.press("Control+o");
+47 -1
View File
@@ -1,7 +1,8 @@
import assert from "node:assert/strict";
import test from "node:test";
import { EditorState } from "@codemirror/state";
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { attachmentRel, dataUrlExtension, hasFileDrag, imageFiles, imageInsertion, mayAnimate, pastedImageSource, workspaceImageLink } from "../../../src/lib/workspace/media.ts";
import { copiedImage, keepCopiedImage } from "../../../src/lib/workspace/copiedImage.ts";
import { imageSource, editImageSource, imageSourceRanges } from "../../../src/lib/editor/imageSource.ts";
import { imageDrops, trackImageDrop } from "../../../src/lib/editor/imageDrop.ts";
@@ -18,6 +19,51 @@ test("protected file drags and files without MIME metadata are recognized", () =
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
});
test("a copied web image names its original file in the clipboard HTML", () => {
const copy = (src: string) => `<html><body>\r\n<!--StartFragment--><img src="${src}"/><!--EndFragment-->\r\n</body>\r\n</html>`;
assert.equal(pastedImageSource(copy("https://media.example.com/cat.gif")), "https://media.example.com/cat.gif");
assert.equal(pastedImageSource(copy("https://cdn.example.com/a/b.WEBP?width=200&amp;ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1");
assert.equal(pastedImageSource("<img alt='x' data-src='a.png' src='http://example.com/x.avif'>"), "http://example.com/x.avif");
assert.equal(pastedImageSource("<img src=https://example.com/x.gif>"), "https://example.com/x.gif");
assert.equal(pastedImageSource(copy("https://example.com/photo.jpg")), "https://example.com/photo.jpg");
// Firefox copies the element of the page with all of its attributes.
assert.equal(pastedImageSource('<img id="img" src="https://h.example.net/om/1/x.gif" style="width:640px" onload="update()">'), "https://h.example.net/om/1/x.gif");
// A missing address and other schemes keep the clipboard copy.
assert.equal(pastedImageSource(copy("data:image/gif;base64,R0lGODlh")), undefined);
assert.equal(pastedImageSource(copy("file:///C:/cat.gif")), undefined);
assert.equal(pastedImageSource(copy("cat.gif")), undefined);
assert.equal(pastedImageSource('<img srcset="https://example.com/x.gif 1x">'), undefined);
assert.equal(pastedImageSource(""), undefined);
// A copy of a page part with two images is not a copied image.
assert.equal(pastedImageSource(copy("https://example.com/a.gif") + copy("https://example.com/b.gif")), undefined);
});
test("only formats with frames get a download, and data URLs name their extension", () => {
assert.equal(mayAnimate("https://media.example.com/cat.gif"), true);
assert.equal(mayAnimate("https://cdn.example.com/a/b.WEBP?width=200"), true);
assert.equal(mayAnimate("http://example.com/x.avif"), true);
assert.equal(mayAnimate("https://example.com/photo.jpg"), false);
assert.equal(mayAnimate("https://example.com/image?format=gif"), false);
assert.equal(dataUrlExtension("data:image/gif;base64,R0lGODlh"), "gif");
assert.equal(dataUrlExtension("data:image/jpeg;base64,/9j/"), "jpg");
assert.equal(dataUrlExtension("data:image/webp;base64,UklG"), "webp");
assert.equal(dataUrlExtension("data:image/svg+xml;base64,PHN2Zz4="), undefined);
assert.equal(dataUrlExtension("data:text/html;base64,PGh0bWw+"), undefined);
});
test("a paste uses only the original of the image that the RuneStone browser copied last", async () => {
assert.equal(await copiedImage("https://example.com/a.gif"), undefined);
let finish: (value: string) => void = () => {};
keepCopiedImage("https://example.com/a.gif", new Promise(resolve => { finish = resolve; }));
const waiting = copiedImage("https://example.com/a.gif");
finish("data:image/gif;base64,R0lGODlh");
assert.equal(await waiting, "data:image/gif;base64,R0lGODlh");
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
keepCopiedImage("https://example.com/b.gif", Promise.reject(new Error("engine stopped")));
assert.equal(await copiedImage("https://example.com/b.gif"), undefined);
assert.equal(await copiedImage("https://example.com/a.gif"), undefined, "a newer copy replaces the older one");
});
test("image batches form independent Markdown blocks without extra blank lines", () => {
assert.equal(imageInsertion("beforeafter", 6, 6, ["![](a.png)", "![](b.png)"]), "\n\n![](a.png)\n\n![](b.png)\n\n");
assert.equal(imageInsertion("before\n\nafter", 8, 8, ["![](a.png)"]), "![](a.png)\n\n");