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

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

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

Copy image needs a new browser engine build. Card 0d5c18f7.
This commit is contained in:
Knotty Wyvern
2026-10-31 17:33:08 -07:00
parent 31ce7e73ce
commit 6e1b24e40f
29 changed files with 654 additions and 41 deletions
+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");