Connect SVG clipboard source to explicit Paste modes

Read bounded original SVG through the platform clipboard service for native
Paste options and action playback. Preserve a newer internal copy when an
older OS source remains unchanged, and report failed or panicking reads
without losing the existing copy. Retain ordinary raster clipboard routes.

Add source replacement, mode/output, Undo, action playback, stale-source,
size-bound and panic/retry regressions. Completes the app intake for the
source-backed backend adapted from Skyfuller1303's PR #3409.

Validation: 104 unique UI/Actions/native-service passes, one existing manual
clipboard ignore; actual app-model Pixels/Shape renders and saved Path;
2921 engine package passes (22 ignores), adversarial pass, all-target strict
engine/UI/app Clippy, full format, 31-crate layers and standard wasm/HEIF.
This commit is contained in:
yoriswind committed 2026-11-01 11:06:36 -08:00
1 parent 46fb7822c9
commit a547bdcb30
9 files changed
+275 -8

No files matched your search

+28
View File
@@ -497,6 +497,11 @@ fn guarded_clipboard_get(mut read: impl FnMut() -> Result<Option<(u32, u32, Vec<
Box::new(move || crate::crash_guard::guard("Paste", &mut read))
}
/// SVG reads use the same recovery boundary as raster clipboard reads.
fn guarded_clipboard_svg(mut read: impl FnMut() -> Result<Option<Vec<u8>>, 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<String, arboard::Error>) -> Result<Option<String>
}
}
/// Keep SVG source for Paste As without accepting an unbounded clipboard string as a new copy.
fn svg_clipboard_source(text: Option<String>) -> Result<Option<Vec<u8>>, 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<photocraft_automation::AuthorizedWorkspace>) ->
)
})
}),
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)))),
+27
View File
@@ -709,6 +709,33 @@ fn from_text(text: &str) -> Option<(u32, u32, Vec<u8>)> {
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("<p>text</p>".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<u8>), x: u32, y: u32) -> [u8; 4] {
let at = ((y * img.0 + x) * 4) as usize;
img.2[at..at + 4].try_into().unwrap()
+1
View File
@@ -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,
+65 -2
View File
@@ -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<bool, String> {
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<u8> = 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;
+122
View File
@@ -58,6 +58,128 @@ fn os_clipboard_honours_export_clipboard_preference() {
type OsClip = Arc<Mutex<Option<(u32, u32, Vec<u8>)>>>;
const CLIP_SVG: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" width="8" height="6"><path d="M1 1 C2 0 6 0 7 1 L7 5 L1 5 Z" fill="#e03020"/></svg>"##;
#[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"<svg invalid".to_vec()))] {
*response.lock().unwrap() = failure;
assert!(app.run("edit.paste", json!({"as": "path"})).is_err());
assert!(app.ui.status_error);
assert_eq!(app.session.active().unwrap().doc, before);
assert!(Arc::ptr_eq(&source, app.session.clipboard.as_ref().unwrap().svg.as_ref().unwrap()));
}
let changed = CLIP_SVG.replace("<path", "<!-- new copy --><path");
*response.lock().unwrap() = Ok(Some(changed.as_bytes().to_vec()));
app.run("edit.paste", json!({"as": "path"})).unwrap();
assert_eq!(app.session.clipboard.as_ref().unwrap().svg.as_ref().unwrap().as_slice(), changed.as_bytes());
let before = app.session.active().unwrap().doc.clone();
*response.lock().unwrap() = Ok(None);
assert!(app.run("edit.paste", json!({"as": "path"})).is_err(), "missing vectors must not become a successful no-op");
assert_eq!(app.session.active().unwrap().doc, before);
assert!(app.session.clipboard.is_none());
}
#[test]
fn explicit_pixel_paste_still_reads_raster_clipboards() {
let services = Services {
clipboard_get_svg: Some(Box::new(|| Ok(None))),
clipboard_get_image: Some(Box::new(|| Ok(Some((2, 1, vec![255; 8]))))),
..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": "pixels"})).unwrap();
let state = app.session.active().unwrap();
assert!(matches!(state.doc.layer(state.active_layer.unwrap()).unwrap().content, photocraft_doc::LayerContent::Raster(_)));
assert!(app.session.clipboard.as_ref().unwrap().svg.is_none());
}
#[test]
fn newer_internal_copies_survive_an_unchanged_external_svg() {
const SOURCE: &str =
r##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="40" height="20" fill="#335577" opacity="0.5"/></svg>"##;
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};
+18 -2
View File
@@ -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);
+6 -4
View File
@@ -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<u64>,
/// Last observed SVG bytes, to distinguish an unchanged OS source from a newer internal copy.
os_clip_svg: Option<std::sync::Arc<Vec<u8>>>,
/// 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,
+3
View File
@@ -177,6 +177,9 @@ fn play_owned(app: &mut PhotocraftApp, params: &Value, suspended: Option<Value>)
} 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())
};
+5
View File
@@ -247,6 +247,9 @@ pub type ClipboardSetFn = Box<dyn FnMut(u32, u32, &[u8]) -> Result<(), String>>;
/// `Err` means the contents could not be read and must not invalidate the internal copy.
pub type ClipboardGetFn = Box<dyn FnMut() -> Result<Option<(u32, u32, Vec<u8>)>, String>>;
/// Read original SVG markup for an explicit Paste As. A read error preserves the internal copy.
pub type ClipboardGetSvgFn = Box<dyn FnMut() -> Result<Option<Vec<u8>>, String>>;
/// Whether the last clipboard read found no way to reach the OS clipboard at all.
pub type ClipboardUnreadableFn = Box<dyn Fn() -> 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<ClipboardSetFn>,
pub clipboard_get_image: Option<ClipboardGetFn>,
/// SVG text copied by another app, read only for an explicit pixels/path/shape paste.
pub clipboard_get_svg: Option<ClipboardGetSvgFn>,
/// 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<ClipboardUnreadableFn>,