Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix: reconcile PR with upstream changes

jonathanwxh-cell40130ae99eec
diff --cc apps/photocraft/src/services.rs
index 6dfcd4bbc,fcacf81b2..88fe7622a
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@@ -530,38 -567,35 +567,47 @@@ pub fn native(automation: Option<photoc
}),
clipboard_get_image: Some({
let clip = clip.clone();
+ let unreadable = clip_unreadable.clone();
Box::new(move || {
- let mut slot = clip.try_borrow_mut().ok()?;
+ 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())?),
+ None => {
+ // arboard opens only when some backend works. In a Flatpak on Wayland none
+ // does (#5031): the sandbox hides the data-control protocol from it, and
+ // `--socket=fallback-x11` gives no X server while a compositor runs.
+ let opened = arboard::Clipboard::new();
+ unreadable.set(opened.is_err());
- slot.insert(opened.ok()?)
++ 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.
- if let Some(img) = cb.get().file_list().ok().and_then(|paths| image_from_files(&paths)) {
- return Some(img);
+ match cb.get().file_list() {
+ Ok(paths) => {
+ if let Some(img) = image_from_files(&paths) {
+ return Ok(Some(img));
+ }
+ }
+ Err(error @ arboard::Error::ClipboardOccupied) => return Err(error.to_string()),
+ Err(_) => {}
}
- if let Ok(img) = cb.get_image() {
- return Some((img.width as u32, img.height as u32, img.bytes.into_owned()));
+ 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()),
+ }
+ }
}
- #[cfg(target_os = "linux")]
- return wayland_clipboard_image();
- #[cfg(not(target_os = "linux"))]
- None
})
}),
+ 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)))),
save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),
diff --cc crates/ui-egui/src/lib.rs
index 372d0d0d5,89f293a2c..9355e80ab
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -377,9 -401,10 +401,11 @@@ pub type OpenUrlFn = Box<dyn Fn(&str) -
pub type EncodePngFn = Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, String>>;
/// Put an RGBA8 image (width, height, pixels) on the OS clipboard.
pub type ClipboardSetFn = Box<dyn FnMut(u32, u32, &[u8]) -> Result<(), String>>;
-/// Read an RGBA8 image from the OS clipboard.
-pub type ClipboardGetFn = Box<dyn FnMut() -> Option<(u32, u32, Vec<u8>)>>;
+/// Read an RGBA8 image from the OS clipboard. `Ok(None)` means no image is available;
+/// `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>>;
+ /// Whether the last clipboard read found no way to reach the OS clipboard at all.
+ pub type ClipboardUnreadableFn = Box<dyn Fn() -> bool>;
/// Shared queue of (file name, bytes) delivered asynchronously.
pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;
/// Read the saved preferences text (`None` when there is none yet).
@@@ -1085,9 -1138,14 +1139,14 @@@ impl PhotocraftApp
// 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 {
- self.import_os_clipboard();
+ self.import_os_clipboard()?;
}
if 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);
+ return Ok(serde_json::json!({"pasted": false}));
+ }
// Enabled on the strength of the OS clipboard, which held no image: a quiet no-op.
let message = "Nothing to paste: the clipboard holds no image";
self.ui.status = tl!(message).into();
@@@ -2625,36 -2719,18 +2728,40 @@@ impl PhotocraftApp
/// If the OS clipboard holds an image that isn't the one we put there, make it the session
/// clipboard (so ⌘V pastes screenshots and images copied in other apps, like Photoshop).
- /// Returns true when a new external image was imported. Once the OS clipboard no longer holds
+ /// Returns `Ok(true)` when a new external image was imported. Once the OS clipboard no longer holds
/// the image we mirrored or imported (text or a file was copied since), that image is stale:
- /// it is dropped rather than pasted.
- pub(crate) fn import_os_clipboard(&mut self) -> bool {
- let Some(get) = self.services.clipboard_get_image.as_mut() else { return false };
- let image = get().filter(|(w, h, bytes)| *w > 0 && *h > 0 && bytes.len() == *w as usize * *h as usize * 4);
+ /// it is dropped rather than pasted. Unexported internal copies survive unavailable or empty
+ /// system clipboards.
+ pub(crate) fn import_os_clipboard(&mut self) -> Result<bool, String> {
+ let Some(get) = self.services.clipboard_get_image.as_mut() else { return Ok(false) };
+ // A read failure says nothing about the clipboard contents. Keep our editable copy and
+ // its signature rather than treating the failure as an empty image.
+ let image = match get() {
+ Ok(image) => image,
+ Err(error) => {
+ // An unexported copy remains usable without an OS clipboard (for example, in
+ // a Wayland sandbox). Mirrored/imported copies still require a successful read
+ // before pasting, because their system contents may have changed.
+ if self.clip_unmirrored && !self.clip_external && self.session.clipboard.is_some() {
+ return Ok(false);
+ }
++ if self.session.clipboard.is_none() && self.services.clipboard_unreadable.as_ref().is_some_and(|unreadable| unreadable()) {
++ // Let paste explain the unavailable backend without treating a saved copy as empty.
++ return Ok(false);
++ }
+ self.ui.status = error.clone();
+ self.ui.status_error = true;
+ return Err(error);
+ }
+ };
+ 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() {
+ if self.os_clip_sig.take().is_some() && !self.clip_unmirrored {
self.session.clipboard = None;
self.clip_external = false;
+ self.clip_unmirrored = true;
}
- return false;
+ return Ok(false);
};
let sig = clip_signature(w, h, &bytes);
if self.os_clip_sig == Some(sig) && self.session.clipboard.is_some() {
diff --cc crates/ui-egui/src/notices.rs
index cd974fbbe,76cdc7b9b..08de9f16a
--- a/crates/ui-egui/src/notices.rs
+++ b/crates/ui-egui/src/notices.rs
@@@ -278,6 -303,37 +303,37 @@@ mod tests
assert_eq!(crate::i18n::tr(crate::i18n::Lang::EN, &notice.title), "Native file drag-and-drop is unavailable");
}
+ /// #5031: a paste that can't reach the clipboard (a Flatpak on Wayland) says why and how to
+ /// paste anyway, once while shown; a clipboard that simply holds no image stays a quiet no-op.
+ #[test]
+ fn unreadable_clipboard_paste_explains_the_sandbox() {
+ let command = "flatpak run --nosocket=wayland --socket=x11 ai.storyteller.photocraft";
+ let services = |unreadable: bool| Services {
- clipboard_get_image: Some(Box::new(|| None)),
++ clipboard_get_image: Some(Box::new(move || if unreadable { Err("no clipboard backend".into()) } else { Ok(None) })),
+ clipboard_unreadable: Some(Box::new(move || unreadable)),
+ xwayland_command: Some(command.to_string()),
+ ..Default::default()
+ };
+ let ctx = egui::Context::default();
+ let mut app = PhotocraftApp::new(Session::new(), services(true));
+ for _ in 0..2 {
+ let r = crate::menus::invoke(&mut app, &ctx, "edit.paste", serde_json::json!({})).unwrap();
+ assert_eq!(r["pasted"], serde_json::json!(false));
+ }
+ assert_eq!(app.ui.status, "Nothing to paste: PhotoCraft can't read the system clipboard here");
+ let shown: Vec<_> = app.ui.notices.iter().filter(|notice| notice.title == CLIPBOARD_UNREADABLE).collect();
+ assert_eq!(shown.len(), 1, "a second paste doesn't stack another notice");
+ let guidance = english(shown[0]);
+ assert!(guidance.contains(&format!("under XWayland: `{command}`")), "{guidance}");
+ let es = crate::i18n::Lang::from_code("es").unwrap();
+ assert!(shown[0].lines.iter().chain([&shown[0].title]).all(|line| crate::i18n::tr(es, line) != *line), "every line is a catalog template");
+
+ let mut empty = PhotocraftApp::new(Session::new(), services(false));
+ crate::menus::invoke(&mut empty, &ctx, "edit.paste", serde_json::json!({})).unwrap();
+ assert_eq!(empty.ui.status, "Nothing to paste: the clipboard holds no image");
+ assert!(empty.ui.notices.iter().all(|notice| notice.title != CLIPBOARD_UNREADABLE));
+ }
+
/// A notice's lines in English with their arguments filled in.
fn english(notice: &Notice) -> String {
let args: Vec<(&str, &str)> = notice.args.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();