From b06a02a3fa781f245e972cf1dc568b3d5f9297ce Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 17 Oct 2026 09:48:40 -0700 Subject: [PATCH 1/2] Paste: a drawing copied as SVG markup pastes its pixels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit › Paste, Paste in Place, File › New from Clipboard and New Document's Clipboard preset read only images from the OS clipboard: copied image files, then the clipboard's image, then on Wayland the other image/* types. When the clipboard held a drawing as SVG markup in plain text, the paste found nothing and the status bar read "Nothing to paste: the clipboard holds no image". On macOS and Linux, VectorCraft's Copy leaves only that markup on the clipboard while Include SVG Code is on, which is its default, so art copied there did not paste. When the clipboard holds no copied image file and no image, the reader now reads its text. Text that photocraft_io::svg::is_svg accepts is rendered at one pixel per SVG unit, scaled down to fit the SVG import's limits (16,384 px a side and 24,000,000 px in all), and pastes as a copied image does, with its transparency. An image on the clipboard still comes first. Other text, markup that does not parse and markup longer than 128 MiB paste nothing, as before. The render runs inside the crash guard that file import uses. The new photocraft_io::svg::rasterize_rgba8 renders a drawing at its own size within those limits and shares its render code with rasterize. The read order moved into clipboard_image, which takes the three clipboard reads as closures. Tests cover the SVG text paste, the scaling, the text that pastes nothing and the read order. --- apps/photocraft/src/services.rs | 172 +++++++++++++++++++++++++++++--- crates/io/src/svg.rs | 65 +++++++++++- 2 files changed, 220 insertions(+), 17 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index d4e7a01553..794bf0d982 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -443,6 +443,40 @@ fn image_from_offers(offers: &[String], mut fetch: impl FnMut(&str) -> Option Option<(u32, u32, Vec)> { + if u64::try_from(text.len()).ok()? > MAX_CLIPBOARD_SVG_BYTES || !photocraft_io::svg::is_svg(text.as_bytes()) { + return None; + } + crate::crash_guard::guard("Paste", || photocraft_io::svg::rasterize_rgba8(text.as_bytes()).map_err(|e| e.to_string())).ok() +} + +/// What a paste reads from the OS clipboard, in this order: the first copied file that is an +/// image (Finder also puts the file's icon on the clipboard as an image, which would otherwise +/// paste instead of the file), the clipboard's image, then a drawing copied as SVG markup. Each +/// read runs only when the ones before it found nothing. +fn clipboard_image( + clipboard: &mut C, + files: impl FnOnce(&mut C) -> Option>, + image: impl FnOnce(&mut C) -> Option<(u32, u32, Vec)>, + text: impl FnOnce(&mut C) -> Option, +) -> Option<(u32, u32, Vec)> { + if let Some(img) = files(clipboard).and_then(|paths| image_from_files(&paths)) { + return Some(img); + } + if let Some(img) = image(clipboard) { + return Some(img); + } + text(clipboard).and_then(|text| image_from_svg_text(&text)) +} + /// The shell command that starts this install under XWayland, where winit delivers file drops /// (winit 0.30 has none on Wayland, #386). A Flatpak gets the X11 socket only without the Wayland /// one, an AppImage relaunches by its own path, and anything else is `photocraft` on the PATH. @@ -543,18 +577,20 @@ pub fn native(automation: Option) -> Some(c) => c, None => slot.insert(arboard::Clipboard::new().ok()?), }; - // Copied files first: Finder also puts the file's icon on the clipboard as an - // image, which would otherwise paste instead of the file. - if let Some(img) = cb.get().file_list().ok().and_then(|paths| image_from_files(&paths)) { - return Some(img); - } - if let Ok(img) = cb.get_image() { - return Some((img.width as u32, img.height as u32, img.bytes.into_owned())); - } - #[cfg(target_os = "linux")] - return wayland_clipboard_image(); - #[cfg(not(target_os = "linux"))] - None + clipboard_image( + cb, + |cb| cb.get().file_list().ok(), + |cb| { + if let Ok(img) = cb.get_image() { + return Some((img.width as u32, img.height as u32, img.bytes.into_owned())); + } + #[cfg(target_os = "linux")] + return wayland_clipboard_image(); + #[cfg(not(target_os = "linux"))] + None + }, + |cb| cb.get_text().ok(), + ) }) }), load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())), @@ -1165,4 +1201,116 @@ mod tests { assert_eq!(image_from_files(&[tga]), Some((1, 1, vec![255, 0, 0, 255]))); assert!(image_from_files(&[bin]).is_none()); } + + /// A 121 × 81 white rectangle with a 1-unit black stroke, written as markup the way a vector + /// app's Copy puts it on the clipboard as text. + const COPIED_RECTANGLE: &str = r##" + + + +"##; + + /// A 40 × 20 drawing whose left half is a red square; the right half has no art. + const HALF_RED: &str = r##""##; + + /// The clipboard as `clipboard_image` reads it when it holds only `text`. + fn from_text(text: &str) -> Option<(u32, u32, Vec)> { + clipboard_image(&mut (), |_| None, |_| None, |_| Some(text.to_string())) + } + + fn pixel(img: &(u32, u32, Vec), x: u32, y: u32) -> [u8; 4] { + let at = ((y * img.0 + x) * 4) as usize; + img.2[at..at + 4].try_into().unwrap() + } + + #[test] + fn svg_markup_copied_as_text_pastes_its_pixels() { + let img = from_text(COPIED_RECTANGLE).expect("the drawing's pixels"); + assert_eq!((img.0, img.1, img.2.len()), (121, 81, 121 * 81 * 4), "one pixel per SVG unit"); + assert_eq!(pixel(&img, 60, 40), [255, 255, 255, 255], "the white fill"); + for (x, y) in [(0, 40), (120, 40), (60, 0), (60, 80)] { + let [r, g, b, a] = pixel(&img, x, y); + assert!(a == 255 && r < 8 && g < 8 && b < 8, "the black stroke at {x},{y}: {:?}", [r, g, b, a]); + } + let img = from_text(HALF_RED).expect("the drawing's pixels"); + assert_eq!((img.0, img.1), (40, 20)); + assert_eq!(pixel(&img, 5, 10), [255, 0, 0, 255]); + assert_eq!(pixel(&img, 30, 10), [0, 0, 0, 0], "transparent where there is no art"); + } + + #[test] + fn text_that_is_not_a_drawing_pastes_nothing() { + for text in ["", "hello", "

not a drawing

", ""] { + assert!(from_text(text).is_none(), "{text:?}"); + } + // Markup that doesn't parse, and markup past the read limit, paste nothing either. + assert!(from_text("").is_none()); + let mut huge = String::from(""); + huge.push_str(&" ".repeat(usize::try_from(MAX_CLIPBOARD_SVG_BYTES).unwrap())); + huge.push_str(""); + assert!(from_text(&huge).is_none(), "markup past the limit isn't parsed"); + } + + #[test] + fn a_drawing_past_the_pixel_limit_pastes_scaled_down() { + let wide = r##""##; + let img = from_text(wide).expect("scaled down, not dropped"); + let pixels = u64::from(img.0) * u64::from(img.1); + assert!(pixels <= 24_000_000 && pixels > 12_000_000, "{} × {}", img.0, img.1); + assert!(img.0.abs_diff(img.1 * 2) <= 2, "the proportions are kept: {} × {}", img.0, img.1); + assert_eq!(pixel(&img, img.0 / 2, img.1 / 2), [0, 0, 255, 255]); + } + + /// Copied files and an image come before SVG text, which is read only when neither is there. + #[test] + fn copied_files_and_images_come_before_svg_text() { + let dir = temp("svg-order"); + let png = dir.join("red.png"); + std::fs::write(&png, red_png(3, 2)).unwrap(); + let blue = (2, 2, [0u8, 0, 255, 255].repeat(4)); + let mut text_read = false; + let svg_text = |read: &mut bool| { + *read = true; + Some(COPIED_RECTANGLE.to_string()) + }; + let got = clipboard_image(&mut text_read, |_| Some(vec![png.clone()]), |_| Some(blue.clone()), svg_text); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((3, 2)), "the copied file"); + let got = clipboard_image(&mut text_read, |_| None, |_| Some(blue.clone()), svg_text); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((2, 2)), "the image, not the SVG text"); + assert!(!text_read, "the text isn't read while there is a file or an image"); + // A copied file that isn't an image (an .svg) falls through to the image, then the text. + let svg = dir.join("drawing.svg"); + std::fs::write(&svg, COPIED_RECTANGLE).unwrap(); + let got = clipboard_image(&mut (), |_| Some(vec![svg.clone()]), |_| None, |_| Some(COPIED_RECTANGLE.to_string())); + assert_eq!(got.map(|(w, h, _)| (w, h)), Some((121, 81))); + } + + /// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the + /// drawing's art; other text is still a quiet "nothing to paste". + #[test] + fn paste_turns_svg_text_on_the_clipboard_into_a_layer() { + let text: Rc> = Rc::new(RefCell::new(HALF_RED.to_string())); + let clip = text.clone(); + let services = Services { + clipboard_get_image: Some(Box::new(move || clipboard_image(&mut (), |_| None, |_| None, |_| Some(clip.borrow().clone())))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + let ctx = egui::Context::default(); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let layers = app.session.active().unwrap().doc.layers.len(); + let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap(); + assert_ne!(r["pasted"], json!(false), "{r}"); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.layers.len(), layers + 1); + let surface = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + let bounds = surface.content_bounds(); + assert_eq!((bounds.width(), bounds.height()), (20, 20), "the red half; the transparent half adds nothing"); + *text.borrow_mut() = "just words".to_string(); + let r = photocraft_ui_egui::menus::invoke(&mut app, &ctx, "edit.paste", json!({})).unwrap(); + assert_eq!(r["pasted"], json!(false)); + assert_eq!(app.ui.status, "Nothing to paste: the clipboard holds no image"); + assert_eq!(app.session.active().unwrap().doc.layers.len(), layers + 1); + } } diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index 72b2318675..c2a3694daf 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -244,14 +244,47 @@ fn import_parsed(name: &str, parsed: Parsed, max_group_depth: usize) -> Result Result { let tree = parse(bytes)?.tree; let cv = canvas(&tree, &mut Vec::new()); - let k = cv.scale * scale.clamp(1.0 / 64.0, 64.0); + let pixmap = render(&tree, cv.scale * scale.clamp(1.0 / 64.0, 64.0))?; + let rect = Rect::new(0, 0, pixmap.width() as i32, pixmap.height() as i32); + let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect(); + Ok(photocraft_compose::Buffer { rect, px }) +} + +/// The whole drawing at one pixel per SVG unit, scaled down to fit [`MAX_SIDE`] a side and +/// [`MAX_RASTER_PIXELS`] in all: its width, height and straight-alpha RGBA8 pixels. Paste uses it +/// for a drawing copied as SVG markup. +pub fn rasterize_rgba8(bytes: &[u8]) -> Result<(u32, u32, Vec), IoError> { + let tree = parse(bytes)?.tree; + let cv = canvas(&tree, &mut Vec::new()); + let (w, h) = (f64::from(tree.size().width() * cv.scale), f64::from(tree.size().height() * cv.scale)); + // The largest k ≤ 1 with (w·k + 2)(h·k + 2) ≤ the limit: `render` rounds each side up, and + // f32 rounding can add one more pixel. + let max = MAX_RASTER_PIXELS as f64; + let fit = if (w + 2.0) * (h + 2.0) <= max { + 1.0 + } else { + let (a, b) = (w * h, 2.0 * (w + h)); + (-b + (b * b - 4.0 * a * (4.0 - max)).sqrt()) / (2.0 * a) + }; + let pixmap = render(&tree, cv.scale * fit as f32)?; + let px = pixmap + .pixels() + .iter() + .flat_map(|p| { + let c = p.demultiply(); + [c.red(), c.green(), c.blue(), c.alpha()] + }) + .collect(); + Ok((pixmap.width(), pixmap.height(), px)) +} + +/// `tree` drawn at `k` pixels per SVG unit on a transparent pixmap whose sides round up. +fn render(tree: &usvg::Tree, k: f32) -> Result { let side = |v: f32| ((v * k).ceil() as u32).max(1); let (w, h) = (side(tree.size().width()), side(tree.size().height())); let mut pixmap = pixmap(w, h).ok_or_else(|| IoError::Svg(format!("{w} × {h} px is too large to rasterise")))?; - resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut()); - let rect = Rect::new(0, 0, w as i32, h as i32); - let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect(); - Ok(photocraft_compose::Buffer { rect, px }) + resvg::render(tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut()); + Ok(pixmap) } /// A transparent pixmap, or `None` past [`MAX_RASTER_PIXELS`]. @@ -792,4 +825,26 @@ mod tests { assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2)); assert_eq!(w.len(), 1); } + + /// A pasted drawing is one pixel per SVG unit, and a drawing past the pixel limit is scaled + /// down to fit it, keeping its proportions, instead of failing. + #[test] + fn rgba8_renders_at_its_own_size_within_the_pixel_limit() { + let svg = br##""##; + let (w, h, px) = rasterize_rgba8(svg).unwrap(); + assert_eq!((w, h, px.len()), (40, 20, 40 * 20 * 4)); + assert_eq!(px[..4], [255, 0, 0, 255], "the rectangle"); + assert_eq!(px[(10 * 40 + 30) * 4..][..4], [0, 0, 0, 0], "transparent beside it"); + for (side_w, side_h) in [(10_000u32, 5_000u32), (20_000, 20_000), (20_000, 2_000)] { + let svg = format!(""); + let (w, h, px) = rasterize_rgba8(svg.as_bytes()).unwrap(); + let pixels = u64::from(w) * u64::from(h); + assert!(pixels <= MAX_RASTER_PIXELS && pixels > MAX_RASTER_PIXELS / 2, "{side_w} × {side_h} became {w} × {h}"); + assert!(w <= MAX_SIDE && h <= MAX_SIDE, "{w} × {h}"); + let (aspect, want) = (f64::from(w) / f64::from(h), f64::from(side_w) / f64::from(side_h)); + assert!((aspect / want - 1.0).abs() < 0.01, "{w} × {h} keeps {side_w} × {side_h}"); + assert_eq!(px.len() as u64, pixels * 4); + } + assert!(rasterize_rgba8(b" Date: Thu, 22 Oct 2026 13:14:05 -0700 Subject: [PATCH 2/2] Paste: a failed clipboard read is an error, not nothing to paste The copied-file and text reads treated every arboard error except a busy clipboard as an empty clipboard, so a read that failed (a broken pipe on Wayland, for example) dropped a mirrored copy and reported "Nothing to paste". Now only ContentNotAvailable reads as nothing, as the image read already does; any other failure is the paste's error. Text that is not UTF-8 still reads as no SVG markup. --- apps/photocraft/src/services.rs | 54 +++++++++++++++++++++++++++------ 1 file changed, 44 insertions(+), 10 deletions(-) diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 3e87f48890..86819b39e3 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -576,6 +576,26 @@ fn clipboard_image( Ok(text(clipboard)?.and_then(|text| image_from_svg_text(&text))) } +/// One OS clipboard read as [`clipboard_image`] takes it: no content in the format asked for is +/// `None`, and any other failure, such as a busy clipboard or a broken pipe on Wayland, is the +/// read's error. +fn clipboard_read(read: Result) -> Result, String> { + match read { + Ok(value) => Ok(Some(value)), + Err(arboard::Error::ContentNotAvailable) => Ok(None), + Err(error) => Err(error.to_string()), + } +} + +/// Clipboard text as [`clipboard_image`] takes it: like [`clipboard_read`], except that text that +/// isn't UTF-8 is `None`, like other text that isn't SVG markup. +fn clipboard_text(read: Result) -> Result, String> { + match read { + Err(arboard::Error::ConversionFailure) => Ok(None), + read => clipboard_read(read), + } +} + /// The shell command that starts this install under XWayland, where winit delivers file drops /// (winit 0.30 has none on Wayland, #386). A Flatpak gets the X11 socket only without the Wayland /// one, an AppImage relaunches by its own path, and anything else is `photocraft` on the PATH. @@ -688,11 +708,7 @@ pub fn native(automation: Option) -> }; clipboard_image( cb, - |cb| match cb.get().file_list() { - Ok(paths) => Ok(Some(paths)), - Err(error @ arboard::Error::ClipboardOccupied) => Err(error.to_string()), - Err(_) => Ok(None), - }, + |cb| clipboard_read(cb.get().file_list()), |cb| match cb.get_image() { Ok(img) => Ok(Some((img.width as u32, img.height as u32, img.bytes.into_owned()))), Err(error) => { @@ -706,11 +722,7 @@ pub fn native(automation: Option) -> } } }, - |cb| match cb.get_text() { - Ok(text) => Ok(Some(text)), - Err(error @ arboard::Error::ClipboardOccupied) => Err(error.to_string()), - Err(_) => Ok(None), - }, + |cb| clipboard_text(cb.get_text()), ) }) }), @@ -1518,6 +1530,28 @@ mod tests { assert_eq!(got, Err("the clipboard is busy".to_string()), "the text's error"); } + /// Only a clipboard with nothing in the format asked for reads as nothing to paste. A read + /// that fails in any other way, such as a broken pipe on Wayland, is the paste's error, for + /// the copied files and the text alike. Text that isn't UTF-8 reads as no SVG markup. + #[test] + fn only_missing_content_reads_as_nothing_to_paste() { + use arboard::Error; + let failures = || [Error::ClipboardOccupied, Error::ClipboardNotSupported, Error::Unknown { description: "broken pipe".to_string() }]; + assert_eq!(clipboard_read(Ok::<_, Error>(vec![PathBuf::from("a.png")])), Ok(Some(vec![PathBuf::from("a.png")]))); + assert_eq!(clipboard_read::>(Err(Error::ContentNotAvailable)), Ok(None)); + for error in failures().into_iter().chain([Error::ConversionFailure]) { + let message = error.to_string(); + assert_eq!(clipboard_read::>(Err(error)), Err(message.clone()), "{message}"); + } + assert_eq!(clipboard_text(Ok("words".to_string())), Ok(Some("words".to_string()))); + assert_eq!(clipboard_text(Err(Error::ContentNotAvailable)), Ok(None)); + assert_eq!(clipboard_text(Err(Error::ConversionFailure)), Ok(None), "text that isn't UTF-8"); + for error in failures() { + let message = error.to_string(); + assert_eq!(clipboard_text(Err(error)), Err(message.clone()), "{message}"); + } + } + /// Edit › Paste with SVG markup as the clipboard's only content adds a new layer that holds the /// drawing's art; other text is still a quiet "nothing to paste". #[test]