PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Keep channel pastes transactional when pixel allocation fails. (#4588)
Vikram Bhaskarane34cdcbcca14
diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rsindex fea104823..86a49b0be 100644--- a/crates/engine/src/channel_clip.rs+++ b/crates/engine/src/channel_clip.rs@@ -96,10 +96,13 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit:return Err(EngineError::Other(format!("no colour channel {k} in this layer")));}if !area.is_empty() {- let mut rgba = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];+ let len = (area.width() as usize).checked_mul(area.height() as usize).ok_or_else(|| EngineError::Other("the channel paste is too large".into()))?;+ let mut rgba = crate::allocation::filled(len, [0.0f32; 4], "pasting into a channel")?;src.read_rgba_into(area, &mut rgba);- let weight = limit.map(|m| (m.read_region(area), m.format().channels().max(1)));- let mut px = surf.read_region(area);+ let weight = limit+ .map(|m| crate::allocation::read_region(m, area, "reading the channel paste selection").map(|v| (v, m.format().channels().max(1))))+ .transpose()?;+ let mut px = crate::allocation::read_region(surf, area, "pasting into a channel")?;for (i, (dst, s)) in px.chunks_exact_mut(n).zip(&rgba).enumerate() {let w = s[3] * weight.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0));let v = photocraft_color::convert::rgb_to_gray([s[0], s[1], s[2]]);@@ -107,7 +110,7 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit:*c += (v - *c) * w.clamp(0.0, 1.0);}}- surf.write_region(area, &px);+ surf.try_write_region(area, &px)?;surf.prune();}doc.selection = None;diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rsindex be7e51dfd..3d89c8f64 100644--- a/crates/engine/src/channel_clip/tests.rs+++ b/crates/engine/src/channel_clip/tests.rs@@ -164,6 +164,25 @@ fn clearing_a_channel_reports_allocation_failure_without_editing() {}}+#[test]+fn channel_paste_allocation_failure_is_transactional() {+ for depth in [8, 16, 32] {+ let mut s = session(depth);+ s.execute("edit.copy", json!({})).unwrap();+ let before = s.active().unwrap().doc.clone();+ let history = s.active().unwrap().history.entries();+ crate::allocation::fail_next_for_test();+ let result = paste(&mut s, &json!({}), 1, true, None, "Paste");+ 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);+ paste(&mut s, &json!({}), 1, true, None, "Paste").unwrap();+ assert!(s.undo());+ assert_eq!(*s.active().unwrap().doc, *before);+ }+}+#[test]fn channel_copy_allocation_failure_keeps_clipboard_and_document() {for depth in [8, 16, 32] {