diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 47b4bbd34a..bf78919740 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -543,6 +543,61 @@ 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 || !text.trim_start_matches('\u{feff}').trim_start().starts_with('<') { + 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. A read that fails, such as one of a busy +/// clipboard, returns its error, and the reads after it don't run. +fn clipboard_image( + clipboard: &mut C, + files: impl FnOnce(&mut C) -> Result>, String>, + image: impl FnOnce(&mut C) -> Result)>, String>, + text: impl FnOnce(&mut C) -> Result, String>, +) -> Result)>, String> { + if let Some(img) = files(clipboard)?.and_then(|paths| image_from_files(&paths)) { + return Ok(Some(img)); + } + if let Some(img) = image(clipboard)? { + return Ok(Some(img)); + } + 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. @@ -660,30 +715,24 @@ pub fn native(automation: Option) -> slot.insert(opened.map_err(|e| e.to_string())?) } }; - // Copied files first: Finder also puts the file's icon on the clipboard as an - // image, which would otherwise paste instead of the file. - match cb.get().file_list() { - Ok(paths) => { - if let Some(img) = image_from_files(&paths) { - return Ok(Some(img)); + clipboard_image( + cb, + |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) => { + #[cfg(target_os = "linux")] + if let Some(image) = wayland_clipboard_image() { + return Ok(Some(image)); + } + match error { + arboard::Error::ContentNotAvailable => Ok(None), + _ => Err(error.to_string()), + } } - } - Err(error @ arboard::Error::ClipboardOccupied) => return Err(error.to_string()), - Err(_) => {} - } - match cb.get_image() { - Ok(img) => Ok(Some((img.width as u32, img.height as u32, img.bytes.into_owned()))), - Err(error) => { - #[cfg(target_os = "linux")] - if let Some(image) = wayland_clipboard_image() { - return Ok(Some(image)); - } - match error { - arboard::Error::ContentNotAvailable => Ok(None), - _ => Err(error.to_string()), - } - } - } + }, + |cb| clipboard_text(cb.get_text()), + ) }) }), clipboard_unreadable: Some(Box::new(move || clip_unreadable.get())), diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index f9bce2a367..c04b8171df 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -660,6 +660,175 @@ fn tga_is_trusted_only_with_its_extension() { 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 (), |_| Ok(None), |_| Ok(None), |_| Ok(Some(text.to_string()))).expect("no read fails") +} + +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 svg_clipboard_text_accepts_a_long_xml_preamble() { + let padding = "x".repeat(8192); + for prefix in [format!(""), format!("\n"), format!("")] { + let text = format!("{prefix}{HALF_RED}"); + let img = from_text(&text).expect("SVG after the XML preamble"); + 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]); + } + assert!(from_text(&format!("")).is_none()); + assert!(from_text(&format!("")).is_none()); +} + +#[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; + Ok(Some(COPIED_RECTANGLE.to_string())) + }; + let got = clipboard_image(&mut text_read, |_| Ok(Some(vec![png.clone()])), |_| Ok(Some(blue.clone())), svg_text); + assert_eq!(got.unwrap().map(|(w, h, _)| (w, h)), Some((3, 2)), "the copied file"); + let got = clipboard_image(&mut text_read, |_| Ok(None), |_| Ok(Some(blue.clone())), svg_text); + assert_eq!(got.unwrap().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 (), |_| Ok(Some(vec![svg.clone()])), |_| Ok(None), |_| Ok(Some(COPIED_RECTANGLE.to_string()))); + assert_eq!(got.unwrap().map(|(w, h, _)| (w, h)), Some((121, 81))); +} + +/// A failed read, such as one of a busy clipboard, is the paste's error: the reads after it, +/// the SVG text included, don't run. +#[test] +fn a_failed_clipboard_read_is_an_error_and_the_text_is_not_read() { + fn busy() -> Result { + Err("the clipboard is busy".to_string()) + } + let mut text_read = false; + let svg_text = |read: &mut bool| { + *read = true; + Ok(Some(COPIED_RECTANGLE.to_string())) + }; + let got = clipboard_image(&mut text_read, |_| busy(), |_| Ok(None), svg_text); + assert_eq!(got, Err("the clipboard is busy".to_string()), "the file list's error"); + let got = clipboard_image(&mut text_read, |_| Ok(None), |_| busy(), svg_text); + assert_eq!(got, Err("the clipboard is busy".to_string()), "the image's error"); + assert!(!text_read, "the text isn't read after a failed read"); + let got = clipboard_image(&mut (), |_| Ok(None), |_| Ok(None), |_| busy()); + 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] +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 (), |_| Ok(None), |_| Ok(None), |_| Ok(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); +} + /// #7582: a panic while reading the OS clipboard (in arboard, or decoding a copied file) is /// the paste's error in the status bar, not a crash: the document stays and the next paste /// works. The same for a panic while writing it. diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index b2b3dcd1a7..b4ff8fd138 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -498,14 +498,47 @@ fn import_parsed_with_budget(name: &str, parsed: Parsed, max_group_depth: usize, pub fn rasterize(bytes: &[u8], scale: f32) -> 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`]. diff --git a/crates/io/src/svg/tests.rs b/crates/io/src/svg/tests.rs index 7127738daa..e336810937 100644 --- a/crates/io/src/svg/tests.rs +++ b/crates/io/src/svg/tests.rs @@ -414,6 +414,28 @@ fn huge_drawings_scale_to_the_side_limit() { 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"