PhotoCraft: An open-source, photo editor written by scratch in pure Rust
fix(engine): reserve the define-brush tip and selection-mask buffers fallibly (#212) (#5469)
wwewdd69f0797dd2
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex b76f8c836..f2c9e28b2 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -863,9 +863,13 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {}// Paint amount = darkness × alpha × selection (black = full paint, like Photoshop).let (w, h) = (area.width() as usize, area.height() as usize);- let mut v = vec![0.0f32; w * h];+ // The sampled tip is one f32 buffer over the whole selection; a large selection must fail+ // gracefully instead of aborting the process on allocation, so reserve it fallibly.+ let mut v = crate::allocation::filled(w * h, 0.0, "defining a brush from the selection")?;let sc = sel.channels();- let sv = sel.read_region(area);+ // The selection mask is a second buffer of the same size; it must fail gracefully too+ // (review of #5469), so read it through the fallible allocator.+ let sv = crate::allocation::read_region(sel, area, "defining a brush from the selection")?;for y in 0..h {for x in 0..w {let c = surf.rgba(area.x0 + x as i32, area.y0 + y as i32);diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rsindex eaf69281b..5977603f9 100644--- a/crates/engine/src/brush_cmds/tests.rs+++ b/crates/engine/src/brush_cmds/tests.rs@@ -442,6 +442,26 @@ fn define_brush_from_selection() {assert!(rgba(&s, 30, 32)[3] > 0.9);}+#[test]+fn define_brush_from_selection_survives_allocation_failure() {+ // The sampled tip is one f32 buffer over the whole selection, and the selection mask is a+ // second of the same size. Both are reserved through the fallible allocator, so an allocation+ // failure must be a graceful error (brush, presets, history and document untouched), never a+ // panic or an OOM abort.+ let mut s = session(40, 40);+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();+ let brush_before = s.tools.brush.clone();+ let presets_before = s.tools.presets.clone();+ let history_before = s.active().unwrap().history.past_len();+ crate::allocation::fail_next_for_test();+ let result = s.execute("brush.defineFromSelection", json!({"name": "Blob"}));+ let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");+ assert!(result.is_err(), "an allocation failure must be reported, not panic");+ assert_eq!(s.tools.brush, brush_before, "the current brush is unchanged");+ assert_eq!(s.tools.presets, presets_before, "the preset list is unchanged");+ assert_eq!(s.active().unwrap().history.past_len(), history_before, "no history step was recorded");+}+#[test]fn works_on_cmyk_and_16_bit() {for (mode, depth) in [("cmyk", 8), ("rgb", 16), ("grayscale", 32)] {