diff --git a/browser-runtime/scripts/test-engine.mjs b/browser-runtime/scripts/test-engine.mjs index 54e26cb..ddee4ee 100644 --- a/browser-runtime/scripts/test-engine.mjs +++ b/browser-runtime/scripts/test-engine.mjs @@ -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')); diff --git a/browser-runtime/src/engine.mjs b/browser-runtime/src/engine.mjs index 23a68bf..5a0401d 100644 --- a/browser-runtime/src/engine.mjs +++ b/browser-runtime/src/engine.mjs @@ -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; diff --git a/browser-runtime/test/engine-smoke.mjs b/browser-runtime/test/engine-smoke.mjs index 3716e9a..3c053ed 100644 --- a/browser-runtime/test/engine-smoke.mjs +++ b/browser-runtime/test/engine-smoke.mjs @@ -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', '');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'); diff --git a/browser-runtime/test/interaction-engine.mjs b/browser-runtime/test/interaction-engine.mjs index 43dd2f0..a7e85ce 100644 --- a/browser-runtime/test/interaction-engine.mjs +++ b/browser-runtime/test/interaction-engine.mjs @@ -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; }); } }); diff --git a/docs/guides/document-tools.md b/docs/guides/document-tools.md index aa4465f..b47e90c 100644 --- a/docs/guides/document-tools.md +++ b/docs/guides/document-tools.md @@ -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. diff --git a/docs/guides/project-management.md b/docs/guides/project-management.md index e7bfa70..cb53123 100644 --- a/docs/guides/project-management.md +++ b/docs/guides/project-management.md @@ -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). diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 7bb0651..e24c773 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -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", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 64db564..5f29849 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -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", diff --git a/src-tauri/permissions/autogenerated/workspace_download_image.toml b/src-tauri/permissions/autogenerated/workspace_download_image.toml new file mode 100644 index 0000000..92f4b60 --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_download_image.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/workspace_save_image_url.toml b/src-tauri/permissions/autogenerated/workspace_save_image_url.toml new file mode 100644 index 0000000..5a4532e --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_save_image_url.toml @@ -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"] diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 76036f3..274fae0 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -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 => {}, diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index bf58c7d..9c6c90b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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, diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index c0d74c7..add0c30 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -967,10 +967,14 @@ fn read_data_url(root: &Path, rel: &str) -> Result { } 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 { + 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 { + blocking(move || image_data_url(&download_image(&url)?)).await +} + +fn image_data_url(bytes: &[u8]) -> Result { + 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> { + 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 { + 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""), None); + assert_eq!(image_extension(b""), 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"".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"); diff --git a/src/lib/browser/Browser.svelte b/src/lib/browser/Browser.svelte index 23ff217..73e39b8 100644 --- a/src/lib/browser/Browser.svelte +++ b/src/lib/browser/Browser.svelte @@ -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 } = $props(); let status = $state({ 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; diff --git a/src/lib/browser/tabSession.ts b/src/lib/browser/tabSession.ts index b9bb1ac..5e96231 100644 --- a/src/lib/browser/tabSession.ts +++ b/src/lib/browser/tabSession.ts @@ -75,12 +75,14 @@ export class TabSession { } } } - async send(command: string, args: Record = {}) { + /** Returns the reply of the engine, or undefined when the request did not complete. */ + async send(command: string, args: Record = {}): Promise { 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; diff --git a/src/lib/editor/DocumentEditor.svelte b/src/lib/editor/DocumentEditor.svelte index 19dda1e..3bfc2bb 100644 --- a/src/lib/editor/DocumentEditor.svelte +++ b/src/lib/editor/DocumentEditor.svelte @@ -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; onOpenLink?: (kind: "md" | "wiki", target: string) => void; - onInsertImage?: (file: File) => Promise; + onInsertImage?: (file: File, source?: string) => Promise; 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; diff --git a/src/lib/features/pm/ui/images-ui.ts b/src/lib/features/pm/ui/images-ui.ts index c1c58f4..114b68b 100644 --- a/src/lib/features/pm/ui/images-ui.ts +++ b/src/lib/features/pm/ui/images-ui.ts @@ -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")) { diff --git a/src/lib/i18n/messages.ts b/src/lib/i18n/messages.ts index ab38a9b..16b9bd4 100644 --- a/src/lib/i18n/messages.ts +++ b/src/lib/i18n/messages.ts @@ -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 会从所有卡片中移除每个已删除的标签。"], diff --git a/src/lib/layout/DocumentArea.svelte b/src/lib/layout/DocumentArea.svelte index 5aaa33e..a45f455 100644 --- a/src/lib/layout/DocumentArea.svelte +++ b/src/lib/layout/DocumentArea.svelte @@ -37,7 +37,7 @@ onQuickOpen: () => void; onOpenBrowser?: () => void; onChange: EditorProps["onChange"]; - onInsertImage: (file: File, buffer: OpenBuffer | null) => Promise; + onInsertImage: (file: File, buffer: OpenBuffer | null, source?: string) => Promise; 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)} diff --git a/src/lib/layout/EditorPane.svelte b/src/lib/layout/EditorPane.svelte index 279e9a5..2e308be 100644 --- a/src/lib/layout/EditorPane.svelte +++ b/src/lib/layout/EditorPane.svelte @@ -29,7 +29,7 @@ focusLine: number | null; onChange: (value: string, id: string) => void; onRenameTitle?: (id: string, title: string) => Promise; - onInsertImage?: (file: File) => Promise; + onInsertImage?: (file: File, source?: string) => Promise; onView?: (view: ViewMode) => void; onSplit?: (split: boolean) => void; onCursor?: (line: number, column: number) => void; diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index e8b5334..adaf3f0 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -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 { + /** `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 { 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); - const base64 = dataUrl.split(",")[1]; - if (!base64) { - return null; + 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 || switching) return null; - await workspaceWriteBytes(rel, base64); 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) => ({ diff --git a/src/lib/workspace/api.ts b/src/lib/workspace/api.ts index 1e4cfae..2503cbc 100644 --- a/src/lib/workspace/api.ts +++ b/src/lib/workspace/api.ts @@ -83,6 +83,16 @@ export function workspaceWriteBytes(rel: string, base64: string): Promise 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 { + return invoke("workspace_save_image_url", { url, rel }); +} + +/** Download a web image. Returns it as a data URL. */ +export function workspaceDownloadImage(url: string): Promise { + return invoke("workspace_download_image", { url }); +} + export type CopyResult = { name: string; rel_path: string; diff --git a/src/lib/workspace/copiedImage.ts b/src/lib/workspace/copiedImage.ts new file mode 100644 index 0000000..f9a1864 --- /dev/null +++ b/src/lib/workspace/copiedImage.ts @@ -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 } | undefined; + +/** Keep the original of a copied image. `data` gives its data URL. */ +export function keepCopiedImage(url: string, data: Promise) { + 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 { + return last?.url === url ? last.data : undefined; +} diff --git a/src/lib/workspace/media.ts b/src/lib/workspace/media.ts index d7cf07f..b306342 100644 --- a/src/lib/workspace/media.ts +++ b/src/lib/workspace/media.ts @@ -96,6 +96,39 @@ export function attachmentRel(fileName: string): string { return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`; } +const ENTITIES: Record = { 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(/]*?\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 = { + "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)); } diff --git a/tests/smoke/_harness/pmFixture.mjs b/tests/smoke/_harness/pmFixture.mjs index 46889a8..7673710 100644 --- a/tests/smoke/_harness/pmFixture.mjs +++ b/tests/smoke/_harness/pmFixture.mjs @@ -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, diff --git a/tests/smoke/browser/interaction.smoke.mjs b/tests/smoke/browser/interaction.smoke.mjs index ae37c92..b5e5ea2 100644 --- a/tests/smoke/browser/interaction.smoke.mjs +++ b/tests/smoke/browser/interaction.smoke.mjs @@ -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('Fixture'); }); + 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('Fixture'); + }); 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='';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=''; 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++); }); diff --git a/tests/smoke/editor/images.smoke.mjs b/tests/smoke/editor/images.smoke.mjs index 104a443..a763f44 100644 --- a/tests/smoke/editor/images.smoke.mjs +++ b/tests/smoke/editor/images.smoke.mjs @@ -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('')); + 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", `\r\n\r\n\r\n`); + 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&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."); }); diff --git a/tests/smoke/features/pmImages.smoke.mjs b/tests/smoke/features/pmImages.smoke.mjs new file mode 100644 index 0000000..7739cc1 --- /dev/null +++ b/tests/smoke/features/pmImages.smoke.mjs @@ -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", ``); + 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"); +}); diff --git a/tests/unit/editor/images.spec.ts b/tests/unit/editor/images.spec.ts index 988c25b..f00e203 100644 --- a/tests/unit/editor/images.spec.ts +++ b/tests/unit/editor/images.spec.ts @@ -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) => `\r\n\r\n\r\n`; + 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&ex=1")), "https://cdn.example.com/a/b.WEBP?width=200&ex=1"); + assert.equal(pastedImageSource("x"), "http://example.com/x.avif"); + assert.equal(pastedImageSource(""), "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(''), "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(''), 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");