Skip to content

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

Report channel copy allocation failures without losing the clipboard. (#4587)

Vikram Bhaskaran79e2107f71cb
diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs
index fc52cf0a4..fea104823 100644
--- a/crates/engine/src/channel_clip.rs
+++ b/crates/engine/src/channel_clip.rs
@@ -59,15 +59,16 @@ pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {
return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
}
let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, true);
- let values = src.read_region(area);
- let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1)));
- let mut px = Vec::with_capacity(values.len() / n * 2);
+ let values = crate::allocation::read_region(src, area, "copying a channel")?;
+ let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?;
+ let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?;
+ let mut px = crate::allocation::capacity(len, "copying a channel")?;
for (i, p) in values.chunks_exact(n).enumerate() {
px.push(p.get(k).copied().unwrap_or(0.0));
px.push(cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)));
}
let mut surface = Surface::new(fmt);
- surface.write_region(area, &px);
+ surface.try_write_region(area, &px)?;
surface.prune();
let bounds = surface.content_bounds();
if bounds.is_empty() {
diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs
index 39cb029b3..be7e51dfd 100644
--- a/crates/engine/src/channel_clip/tests.rs
+++ b/crates/engine/src/channel_clip/tests.rs
@@ -163,3 +163,22 @@ fn clearing_a_channel_reports_allocation_failure_without_editing() {
assert_eq!(s.active().unwrap().history.entries(), history);
}
}
+
+#[test]
+fn channel_copy_allocation_failure_keeps_clipboard_and_document() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ s.execute("edit.copy", json!({})).unwrap();
+ s.execute("channel.target", json!({"channel": "red"})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let clip = s.clipboard.as_ref().unwrap().surface.clone();
+ let history = s.active().unwrap().history.entries();
+ crate::allocation::fail_next_for_test();
+ let result = copy(&mut s);
+ let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
+ assert!(result.is_err());
+ assert_eq!(*s.active().unwrap().doc, *before);
+ assert_eq!(s.active().unwrap().history.entries(), history);
+ assert_eq!(s.clipboard.as_ref().unwrap().surface, clip);
+ }
+}