diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index 675996c5d0d..cabd2196d62 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -497,6 +497,11 @@ fn guarded_clipboard_get(mut read: impl FnMut() -> Result Result>, String> + 'static) -> photocraft_ui_egui::ClipboardGetSvgFn { + Box::new(move || crate::crash_guard::guard("Paste", &mut read)) +} + fn guarded_clipboard_set(mut write: impl FnMut(u32, u32, &[u8]) -> Result<(), String> + 'static) -> photocraft_ui_egui::ClipboardSetFn { Box::new(move |w: u32, h: u32, px: &[u8]| crate::crash_guard::guard("Copy", || write(w, h, px))) } @@ -616,6 +621,18 @@ fn clipboard_text(read: Result) -> Result } } +/// Keep SVG source for Paste As without accepting an unbounded clipboard string as a new copy. +fn svg_clipboard_source(text: Option) -> Result>, String> { + let Some(text) = text else { return Ok(None) }; + if !photocraft_io::svg::is_svg(text.as_bytes()) { + return Ok(None); + } + if text.len() > 16 << 20 { + return Err("SVG clipboard data exceeds the 16 MiB limit".into()); + } + Ok(Some(text.into_bytes())) +} + /// 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. @@ -748,6 +765,17 @@ pub fn native(automation: Option) -> ) }) }), + clipboard_get_svg: Some({ + let clip = clip.clone(); + guarded_clipboard_svg(move || { + let mut slot = clip.try_borrow_mut().map_err(|_| "clipboard is busy".to_string())?; + let cb = match slot.as_mut() { + Some(c) => c, + None => slot.insert(arboard::Clipboard::new().map_err(|e| e.to_string())?), + }; + svg_clipboard_source(clipboard_text(cb.get_text())?) + }) + }), clipboard_unreadable: Some(Box::new(move || clip_unreadable.get())), load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())), photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))), diff --git a/apps/photocraft/src/services/tests.rs b/apps/photocraft/src/services/tests.rs index 8f12fee908f..a0a91aa118e 100644 --- a/apps/photocraft/src/services/tests.rs +++ b/apps/photocraft/src/services/tests.rs @@ -709,6 +709,33 @@ 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") } +#[test] +fn svg_clipboard_source_preserves_markup_and_bounds_its_size() { + let bytes = svg_clipboard_source(Some(HALF_RED.into())).unwrap().unwrap(); + assert_eq!(bytes, HALF_RED.as_bytes()); + for text in [None, Some("plain text".into()), Some("

text

".into())] { + assert_eq!(svg_clipboard_source(text), Ok(None)); + } + let mut oversized = HALF_RED.to_string(); + oversized.extend(std::iter::repeat_n(' ', (16 << 20) + 1)); + assert!(svg_clipboard_source(Some(oversized)).is_err()); +} + +#[test] +fn a_panicking_svg_clipboard_read_is_reported_and_can_be_retried() { + let panics = Rc::new(Cell::new(true)); + let fail = panics.clone(); + let mut get = guarded_clipboard_svg(move || { + if fail.get() { + panic!("SVG clipboard reader bug"); + } + Ok(Some(HALF_RED.as_bytes().to_vec())) + }); + assert!(get().unwrap_err().contains("Paste failed")); + panics.set(false); + assert_eq!(get().unwrap().unwrap(), HALF_RED.as_bytes()); +} + 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() diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 14038b10de4..3015f0214d6 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -143,6 +143,7 @@ impl PhotocraftApp { clone_preview: None, info_sample: None, os_clip_sig: None, + os_clip_svg: None, clip_unmirrored: true, clip_external: false, clip_read_for_paste: false, diff --git a/crates/ui-egui/src/app/clipboard.rs b/crates/ui-egui/src/app/clipboard.rs index a553cc932cb..ade57b1c250 100644 --- a/crates/ui-egui/src/app/clipboard.rs +++ b/crates/ui-egui/src/app/clipboard.rs @@ -8,7 +8,67 @@ fn clip_signature(w: u32, h: u32, px: &[u8]) -> u64 { sig } +/// Match the bitmap signature by sampling the bounded SVG mirror, without another full pixel buffer. +fn svg_clip_signature(clip: &photocraft_engine::edit_cmds::Clip) -> u64 { + let b = clip.bounds; + let (w, h) = (b.width(), b.height()); + let mut sig = (u64::from(w) << 32) | u64::from(h); + if w == 0 || h == 0 { + return sig; + } + for i in (0..b.size().area().saturating_mul(4)).step_by(997) { + let x = b.x0.saturating_add((i / 4 % u64::from(w)) as i32); + let y = b.y0.saturating_add((i / 4 / u64::from(w)) as i32); + let mut pixel = [[0; 4]]; + clip.surface.read_rgba8_into(photocraft_geom::Rect::from_xywh(x, y, 1, 1), &mut pixel); + let value = pixel[0].get((i % 4) as usize).copied().unwrap_or_default(); + sig = sig.rotate_left(5) ^ u64::from(value); + } + sig +} + impl PhotocraftApp { + /// Capture SVG and its raster mirror together; failures leave the previous copy intact. + pub(super) fn import_os_svg_clipboard(&mut self) -> Result { + let Some(get) = self.services.clipboard_get_svg.as_mut() else { return Ok(false) }; + let source = match get() { + Ok(source) => source, + Err(_) if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() => return Ok(false), + Err(error) => { + self.ui.status = error.clone(); + self.ui.status_error = true; + return Err(error); + } + }; + let Some(source) = source else { + self.os_clip_svg = None; + // Bitmap equality cannot prove that an earlier external vector source is current. + if self.clip_external && self.session.clipboard.as_ref().is_some_and(|clip| clip.svg.is_some()) { + self.session.clipboard = None; + self.os_clip_sig = None; + self.clip_external = false; + self.clip_unmirrored = true; + } + return Ok(false); + }; + if self.os_clip_svg.as_deref().is_some_and(|old| old == &source) && self.session.clipboard.is_some() { + // A newer internal copy remains authoritative until the external bytes change. + return Ok(true); + } + let clip = photocraft_engine::edit_cmds::Clip::from_svg(&source).map_err(|error| { + let error = error.to_string(); + self.ui.status = error.clone(); + self.ui.status_error = true; + error + })?; + self.os_clip_sig = Some(svg_clip_signature(&clip)); + self.os_clip_svg = clip.svg.clone(); + self.session.clipboard = Some(clip); + self.clip_external = true; + self.clip_unmirrored = false; + Ok(true) + } + /// Mirror the session clipboard onto the OS clipboard (RGBA8). pub(super) fn export_os_clipboard(&mut self) { self.clip_unmirrored = true; @@ -24,6 +84,7 @@ impl PhotocraftApp { clip.surface.read_rgba8_into(b, &mut px); let bytes: Vec = px.into_iter().flatten().collect(); if set(b.width(), b.height(), &bytes).is_ok() { + self.os_clip_svg = None; self.os_clip_sig = Some(clip_signature(b.width(), b.height(), &bytes)); self.clip_unmirrored = false; } @@ -59,7 +120,8 @@ impl PhotocraftApp { }; let image = image.filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4); let Some((w, h, bytes)) = image else { - if self.os_clip_sig.take().is_some() && !self.clip_unmirrored { + self.os_clip_svg = None; + if (self.os_clip_sig.take().is_some() || self.clip_external) && !self.clip_unmirrored { self.session.clipboard = None; self.clip_external = false; self.clip_unmirrored = true; @@ -74,7 +136,8 @@ impl PhotocraftApp { let mut surface = photocraft_raster::Surface::from_interleaved(photocraft_color::PixelFormat::RGBA8, r, &bytes); surface.prune(); self.session.clipboard = - Some(photocraft_engine::edit_cmds::Clip { components: None, surface, bounds: r, layers: None, resolution: None, source: None }); + Some(photocraft_engine::edit_cmds::Clip { components: None, surface, bounds: r, layers: None, resolution: None, source: None, svg: None }); + self.os_clip_svg = None; self.os_clip_sig = Some(sig); self.clip_external = true; self.clip_unmirrored = false; diff --git a/crates/ui-egui/src/app/clipboard_tests.rs b/crates/ui-egui/src/app/clipboard_tests.rs index 65318b174f7..e0cb4eb1384 100644 --- a/crates/ui-egui/src/app/clipboard_tests.rs +++ b/crates/ui-egui/src/app/clipboard_tests.rs @@ -58,6 +58,128 @@ fn os_clipboard_honours_export_clipboard_preference() { type OsClip = Arc)>>>; +const CLIP_SVG: &str = r##""##; + +#[test] +fn svg_clipboard_paste_as_keeps_source_and_creates_the_requested_content() { + for mode in ["pixels", "path", "shape"] { + let services = Services { clipboard_get_svg: Some(Box::new(|| Ok(Some(CLIP_SVG.as_bytes().to_vec())))), ..Default::default() }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 24, "height": 20})).unwrap(); + let (layers, paths) = { + let doc = &app.session.active().unwrap().doc; + (doc.layers.len(), doc.paths.len()) + }; + app.run("edit.paste", json!({"as": mode})).unwrap(); + let state = app.session.active().unwrap(); + if mode == "path" { + assert_eq!(state.doc.paths.len(), paths + 1); + assert_eq!(state.doc.layers.len(), layers); + } else { + let content = &state.doc.layer(state.active_layer.unwrap()).unwrap().content; + assert!(match mode { + "pixels" => matches!(content, photocraft_doc::LayerContent::Raster(_)), + _ => matches!(content, photocraft_doc::LayerContent::Shape(_)), + }); + } + let source = app.session.clipboard.as_ref().unwrap().svg.clone().unwrap(); + assert_eq!(source.as_slice(), CLIP_SVG.as_bytes()); + app.run("edit.undo", json!({})).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.layers.len(), doc.paths.len()), (layers, paths)); + app.run("edit.redo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&source, app.session.clipboard.as_ref().unwrap().svg.as_ref().unwrap())); + } +} + +#[test] +fn svg_clipboard_errors_preserve_the_copy_and_empty_reads_invalidate_external_source() { + let response = Arc::new(Mutex::new(Ok(Some(CLIP_SVG.as_bytes().to_vec())))); + let read = response.clone(); + let services = Services { clipboard_get_svg: Some(Box::new(move || read.lock().unwrap().clone())), ..Default::default() }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 24, "height": 20})).unwrap(); + app.run("edit.paste", json!({"as": "path"})).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let source = app.session.clipboard.as_ref().unwrap().svg.clone().unwrap(); + for failure in [Err("clipboard is busy".into()), Ok(Some(b""##; + for params in [json!({}), json!({"as":"pixels"})] { + let image = OsClip::default(); + let read = image.clone(); + let services = Services { + clipboard_get_svg: Some(Box::new(|| Ok(Some(SOURCE.as_bytes().to_vec())))), + clipboard_get_image: Some(Box::new(move || Ok(read.lock().unwrap().clone()))), + ..Default::default() + }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width":64,"height":64})).unwrap(); + app.import_os_svg_clipboard().unwrap(); + let clip = app.session.clipboard.as_ref().unwrap(); + let b = clip.bounds; + let mut pixels = vec![[0; 4]; b.size().area() as usize]; + clip.surface.read_rgba8_into(b, &mut pixels); + let bytes: Vec<_> = pixels.into_iter().flatten().collect(); + let signature = bytes.iter().step_by(997).fold((u64::from(b.width()) << 32) | u64::from(b.height()), |sig, byte| sig.rotate_left(5) ^ u64::from(*byte)); + assert_eq!(app.os_clip_sig, Some(signature), "match the image signature across all four RGBA components"); + *image.lock().unwrap() = Some((b.width(), b.height(), bytes)); + app.session.edit_prefs(|prefs| prefs.general.export_clipboard = false); + app.run("file.new", json!({"width":8,"height":6})).unwrap(); + app.run("edit.fill", json!({"color":"#0000ff"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("edit.paste", params).unwrap(); + assert_eq!(app.session.clipboard.as_ref().unwrap().surface.rgba(0, 0), [0.0, 0.0, 1.0, 1.0]); + assert!(!app.clip_external, "the unchanged older SVG must not replace the newer internal copy"); + } +} + +#[test] +fn action_vector_paste_reads_the_current_svg_source() { + let services = Services { clipboard_get_svg: Some(Box::new(|| Ok(Some(CLIP_SVG.as_bytes().to_vec())))), ..Default::default() }; + let mut app = PhotocraftApp::new(Session::new(), services); + app.run("file.new", json!({"width": 24, "height": 20})).unwrap(); + app.session.actions.list.push(photocraft_engine::actions_cmds::Action::new("SVG", vec![("edit.paste".into(), json!({"as": "shape"}))])); + let result = app.run("actions.play", json!({"action": "SVG"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + let state = app.session.active().unwrap(); + assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Shape(_))); +} + #[test] fn failed_clipboard_reads_preserve_editable_contents_until_retry() { use std::sync::atomic::{AtomicBool, Ordering}; diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 39d17bf493d..d17fb2ad265 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -85,10 +85,26 @@ impl PhotocraftApp { let t0 = gpu_canvas::now_ms(); // The OS clipboard is read only on an explicit paste, never in the background (privacy, CPU). if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "file.newFromClipboard") { - if !clip_read { + let paste_as = if id == "edit.paste" { + match params.get("as") { + None => None, + Some(value) => match value.as_str() { + Some(mode @ ("pixels" | "path" | "shape")) => Some(mode), + _ => return Err("`as` must be pixels, path or shape".into()), + }, + } + } else { + None + }; + if let Some(mode) = paste_as { + let imported = self.import_os_svg_clipboard()?; + if mode == "pixels" && !imported && !clip_read { + self.import_os_clipboard()?; + } + } else if !clip_read { self.import_os_clipboard()?; } - if self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { + if paste_as.is_none() && self.session.clipboard.is_none() && self.services.clipboard_get_image.is_some() { if self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) { // The clipboard may well hold an image that can't be reached: say why. notices::clipboard_unreadable(self); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e17b2bc80dd..8165b8a41d6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -253,10 +253,10 @@ pub(crate) use services::SAVE_OPTIONS_OPEN; pub(crate) use services::saved_revision_after_write; pub use services::{ AdoptAutosaveFn, AppendTextFn, AutomationCommandFn, AutomationOpenPcraftFn, AutomationReadFn, AutomationWriteFn, AutosaveFn, AutosaveResultsFn, CapsLockFn, - CaptionStyleFn, ClipboardGetFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, ExportSettings, - ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, LoadTextFn, - OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, SaveTextFn, - Services, SystemThemeFn, WindowFrameFn, WriteFn, + CaptionStyleFn, ClipboardGetFn, ClipboardGetSvgFn, ClipboardSetFn, ClipboardUnreadableFn, CursorPosFn, DiscardAutosaveFn, EncodePngFn, ExportFn, + ExportSettings, ExternalSvgEditor, ExternalSvgSession, ExternalVectorSave, ExternalVectorSource, FileStamp, FileStampFn, FormatChoices, ImportFn, Inbox, + LoadTextFn, OpenExternalSvgFn, OpenUrlFn, OsEventsFn, PhotoshopShortcutsFn, QuitFn, RecoverFn, Recoverable, RightButtonDownFn, SameFileFn, SaveFileFn, + SaveTextFn, Services, SystemThemeFn, WindowFrameFn, WriteFn, }; pub use text::bidi_text; pub use text::cjk_fonts; @@ -593,6 +593,8 @@ pub struct PhotocraftApp { pub(crate) pending_after_prompt: Option<(String, serde_json::Value)>, /// Last mirrored or imported OS image; this can predate the current internal copy. os_clip_sig: Option, + /// Last observed SVG bytes, to distinguish an unchanged OS source from a newer internal copy. + os_clip_svg: Option>>, /// The session copy, if any, need not track the OS clipboard. An older OS signature is kept /// to recognize unchanged system contents when exporting a newer copy failed or was disabled. clip_unmirrored: bool, diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index c1ba436d226..42ad89fa304 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -177,6 +177,9 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option) } else if actions_cmds::shell_view_command(id) { app.sync_views(); app.run(id, p.clone()) + } else if id == "edit.paste" && p.get("as").is_some() { + // An explicit vector paste needs the original OS source, not just an old pixel copy. + app.run(id, p.clone()) } else { app.session.execute(id, p.clone()).map_err(|e| e.to_string()) }; diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 1bcaf89e328..11fc27119b7 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -247,6 +247,9 @@ pub type ClipboardSetFn = Box Result<(), String>>; /// `Err` means the contents could not be read and must not invalidate the internal copy. pub type ClipboardGetFn = Box Result)>, String>>; +/// Read original SVG markup for an explicit Paste As. A read error preserves the internal copy. +pub type ClipboardGetSvgFn = Box Result>, String>>; + /// Whether the last clipboard read found no way to reach the OS clipboard at all. pub type ClipboardUnreadableFn = Box bool>; @@ -433,6 +436,8 @@ pub struct Services { /// OS clipboard images: copies go out, screenshots and images from other apps come in. pub clipboard_set_image: Option, pub clipboard_get_image: Option, + /// SVG text copied by another app, read only for an explicit pixels/path/shape paste. + pub clipboard_get_svg: Option, /// True when the last `clipboard_get_image` read had no clipboard to read, as in a Flatpak on /// Wayland (#5031), rather than a clipboard that holds no image. `None` where that can't happen. pub clipboard_unreadable: Option,