From 94c8dfaed5491ce4fd71ce09e2d9462afb8f61db Mon Sep 17 00:00:00 2001 From: mnmlyw <36081657+mnmlyw@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:25:01 -0700 Subject: [PATCH] Content-Aware fill returns the size error for a huge selection extent instead of panicking (#963) The automatic sampling margin was three quarters of the selection's larger side, computed as `ext * 3` in u32 (edit.fill) or i32 (edit.contentAwareFill) before the window cap, so a loaded document with a far-flung selection overflowed and panicked. edit.contentAwareFill also had no window cap at all and could try to allocate a canvas-sized window. The margin is now one shared function computed in u64 and saturated to i32, and both commands check the window against the same 400 M-pixel cap before reading or allocating. Content-Aware Move uses the shared margin too. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/edit_menu_cmds.rs | 8 +- crates/engine/src/edit_menu_cmds/tests.rs | 59 ++++++++++++ crates/engine/src/fill_cmds.rs | 91 +++++++++++++++++-- .../src/retouch_cmds/content_aware_move.rs | 3 +- 4 files changed, 149 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs index 0862ddca9b..c545824ab5 100644 --- a/crates/engine/src/edit_menu_cmds.rs +++ b/crates/engine/src/edit_menu_cmds.rs @@ -341,12 +341,13 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: & if hb.is_empty() { return Err(bad(cmd, "the selection is outside the canvas")); } - let ext = hb.width().max(hb.height()) as i32; + // The canvas is at most i32 wide, so the extent fits; saturate anyway rather than wrap (#963). + let ext = i32::try_from(hb.width().max(hb.height())).unwrap_or(i32::MAX); let sampling = str_or(p, "sampling", "auto").to_string(); let custom_mask: Option = p.get("channel").and_then(|v| channel_mask(&doc, v)).cloned(); let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None }; let window = match sampling.as_str() { - "auto" => hb.inflate((ext * 3 / 4).max(32)), + "auto" => hb.inflate(crate::fill_cmds::sampling_margin(hb)), "rectangular" => hb.inflate(int(p, "margin").map_or(ext.max(16), |m| m.clamp(0, 100_000) as i32)), "custom" => { let r = match (custom_rect, custom_mask.as_ref()) { @@ -373,7 +374,8 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: & let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?; let fmt = surf.format(); let n = fmt.channels(); - let (w, h) = (window.width() as usize, window.height() as usize); + // Refuse a window too large to read before allocating for it, whatever the sampling (#963). + let (w, h) = crate::fill_cmds::window_size(window)?; // A background job when started with `Session::start` (#210): reading the window and the // PatchMatch fill run on a worker against the document snapshot, cancellable per row band. crate::jobs::run( diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs index 921a8a49c5..c17f475331 100644 --- a/crates/engine/src/edit_menu_cmds/tests.rs +++ b/crates/engine/src/edit_menu_cmds/tests.rs @@ -116,6 +116,65 @@ fn content_aware_fill_huge_area_neither_panics_nor_wraps() { } } +/// `blob_session` with the canvas declared as `size` and a sparse selection of `rects`, as a +/// loaded `.pcraft` can hold (#963). Nothing here allocates more than a few tiles. +fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { + let mut s = blob_session(8); + let st = s.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + doc.size = photocraft_geom::Size::new(size.0, size.1); + let mut sel = Surface::new(PixelFormat::GRAY8); + for r in rects { + sel.fill_rect(*r, &[1.0]); + } + doc.selection = Some(sel); + s +} + +/// A sampling window too large to read, or whose margin overflows, is the size error: no panic, +/// no huge allocation, the document and history untouched (#963). +#[test] +fn content_aware_fill_huge_window_is_an_error() { + // Largest extent whose `ext * 3` still fits in i32. + const EDGE: i32 = i32::MAX / 3; + let max = i32::MAX; + let big = (2_000_000_000, 2_000_000_000); + let dot = Rect::new(0, 0, 1, 1); + let cases = [ + ("auto, wide, just above", big, vec![dot, Rect::new(EDGE, 0, EDGE + 1, 1)], json!({})), + ("auto, tall, just above", big, vec![dot, Rect::new(0, EDGE, 1, EDGE + 1)], json!({})), + ("auto, wide, just below", big, vec![dot, Rect::new(EDGE - 1, 0, EDGE, 1)], json!({})), + ( + "auto, extreme coordinates", + (max as u32, max as u32), + vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), dot, Rect::new(max - 2, max - 2, max - 1, max - 1)], + json!({}), + ), + ( + "rectangular, small selection", + (300_000, 300_000), + vec![Rect::new(150_000, 150_000, 150_001, 150_001)], + json!({"sampling": "rectangular", "margin": 100_000}), + ), + ("rectangular, huge extent", big, vec![dot, Rect::new(EDGE + 1, 0, EDGE + 2, 1)], json!({"sampling": "rectangular"})), + ("custom, whole canvas", big, vec![dot], json!({"sampling": "custom", "area": [0, 0, 2_000_000_000, 2_000_000_000]})), + ]; + for (name, size, rects, p) in cases { + let mut s = huge_selection(size, &rects); + let before = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let err = s.execute("edit.contentAwareFill", p).expect_err(name).to_string(); + assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); + assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); + } + // Control: an ordinary selection still fills. + let mut s = huge_selection((64, 48), &[Rect::new(26, 16, 38, 30)]); + let r = s.execute("edit.contentAwareFill", json!({"colorAdaptation": "none"})).unwrap(); + assert!(r["filled"].as_u64().unwrap() > 100); +} + #[test] fn content_aware_fill_removes_object_at_all_depths() { for depth in [8, 16, 32] { diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs index a988f113fc..a6fb412753 100644 --- a/crates/engine/src/fill_cmds.rs +++ b/crates/engine/src/fill_cmds.rs @@ -176,15 +176,10 @@ fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, color_adaptation: if hole_bounds.is_empty() { return Err(EngineError::Other("the selection is outside the canvas".into())); } - let ext = hole_bounds.width().max(hole_bounds.height()); - let window = hole_bounds.inflate(i32::try_from(ext * 3 / 4).unwrap_or(i32::MAX).max(32)).intersect(&canvas); + let window = hole_bounds.inflate(sampling_margin(hole_bounds)).intersect(&canvas); let fmt = surf.format(); let n = fmt.channels(); - let (w, h) = (window.width() as usize, window.height() as usize); - // Same cap as other whole-image operations: refuse absurd windows instead of allocating. - if w.saturating_mul(h) > 400_000_000 { - return Err(EngineError::Other("the selection is too large for Content-Aware fill".into())); - } + let (w, h) = window_size(window)?; let img = surf.read_region(window); let mut hole = vec![false; w * h]; for (i, hv) in hole.iter_mut().enumerate() { @@ -209,6 +204,25 @@ fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, color_adaptation: Ok(Source::Pixels(window, px)) } +/// The automatic Content-Aware sampling margin around `hole`: three quarters of its larger side, +/// at least 32 pixels. Worked out in u64 because a loaded document can declare a selection whose +/// extent times three overflows u32 (#963); a margin beyond i32 saturates, as `Rect::inflate` does. +pub(crate) fn sampling_margin(hole: Rect) -> i32 { + let ext = u64::from(hole.width().max(hole.height())); + i32::try_from(ext * 3 / 4).unwrap_or(i32::MAX).max(32) +} + +/// The size of a Content-Aware sampling window, or an error for a window too large to read and +/// fill (#963). Same cap as other whole-image operations: refuse absurd windows instead of +/// allocating. +pub(crate) fn window_size(window: Rect) -> Result<(usize, usize)> { + let (w, h) = (window.width(), window.height()); + if u64::from(w) * u64::from(h) > 400_000_000 { + return Err(EngineError::Other("the selection is too large for Content-Aware fill".into())); + } + Ok((w as usize, h as usize)) +} + /// How the source goes onto the target. #[derive(Clone, Copy)] struct Blend { @@ -499,4 +513,67 @@ mod tests { // Out-of-range opacity is clamped. s.execute(CMD, json!({"contents": "white", "opacity": 1e300})).unwrap(); } + + /// A session whose canvas is `size` and whose selection is the given (sparse) rectangles, as + /// a loaded `.pcraft` can declare (#963): the canvas size is not capped on load and the + /// selection tiles can lie far apart. Nothing here allocates more than a few tiles. + fn huge_selection(size: (u32, u32), rects: &[Rect]) -> Session { + let mut s = session(); + s.execute(CMD, json!({"contents": "color", "color": "#336699"})).unwrap(); + let st = s.active_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + doc.size = photocraft_geom::Size::new(size.0, size.1); + let mut sel = Surface::new(photocraft_color::PixelFormat::GRAY8); + for r in rects { + sel.fill_rect(*r, &[1.0]); + } + doc.selection = Some(sel); + s + } + + /// Content-Aware fill on a selection whose extent overflows the sampling-window arithmetic + /// (#963) returns the size error and leaves the document and history untouched. + #[test] + fn content_aware_huge_extent_is_an_error() { + // Largest extent whose `ext * 3` still fits in u32. + const EDGE: i32 = (u32::MAX / 3) as i32; + let max = i32::MAX; + let cases: [(&str, (u32, u32), Vec); 7] = [ + // The issue's repro: a second selection tile 5 600 000 tiles to the right. + ("issue repro", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 8, 8), Rect::new(5_600_000 * TILE_SIZE, 0, 5_600_000 * TILE_SIZE + 8, 8)]), + ("wide, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE, 0, EDGE + 1, 1)]), + ("tall, just above", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE, 1, EDGE + 1)]), + ("wide, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(EDGE - 1, 0, EDGE, 1)]), + ("tall, just below", (2_000_000_000, 2_000_000_000), vec![Rect::new(0, 0, 1, 1), Rect::new(0, EDGE - 1, 1, EDGE)]), + // The largest canvas a Rect can hold, selected corner to corner, plus a piece off the + // canvas at the most negative coordinate. + ( + "extreme coordinates", + (max as u32, max as u32), + vec![Rect::new(i32::MIN, i32::MIN, i32::MIN + 1, i32::MIN + 1), Rect::new(0, 0, 1, 1), Rect::new(max - 2, max - 2, max - 1, max - 1)], + ), + // A canvas wider than a Rect can hold is treated as empty, never as a panic. + ("canvas beyond i32", (u32::MAX, u32::MAX), vec![Rect::new(0, 0, 1, 1), Rect::new(max - 2, 0, max - 1, 1)]), + ]; + for (name, size, rects) in cases { + let mut s = huge_selection(size, &rects); + let before = s.active().unwrap().doc.clone(); + let past = s.active().unwrap().history.past_len(); + let r = s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})); + let err = r.expect_err(name).to_string(); + assert!(!err.contains("internal error"), "{name}: {err}"); + if name != "canvas beyond i32" { + assert!(err.contains("too large for Content-Aware fill"), "{name}: {err}"); + } + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&before, &st.doc), "{name}: the document changed"); + assert_eq!(st.history.past_len(), past, "{name}: a history step was recorded"); + assert!(close(px(&s, 5, 5), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{name}"); + } + // Control: an ordinary selection still fills from its surroundings. + let mut s = huge_selection((40, 30), &[Rect::new(15, 10, 21, 16)]); + s.execute(CMD, json!({"contents": "white"})).unwrap(); + s.execute(CMD, json!({"contents": "contentAware", "colorAdaptation": false})).unwrap(); + assert!(close(px(&s, 17, 12), [0x33 as f32 / 255.0, 0x66 as f32 / 255.0, 0x99 as f32 / 255.0, 1.0]), "{:?}", px(&s, 17, 12)); + } } diff --git a/crates/engine/src/retouch_cmds/content_aware_move.rs b/crates/engine/src/retouch_cmds/content_aware_move.rs index 38a81362af..5b31bd1bff 100644 --- a/crates/engine/src/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/retouch_cmds/content_aware_move.rs @@ -150,8 +150,7 @@ fn erode(w: usize, h: usize, m: &[bool], r: usize) -> Vec { /// Where a fill samples from around `r`: as Edit › Content-Aware Fill's automatic sampling area, /// three quarters of the extent around it (at least 32, at most [`MAX_MARGIN`] pixels). fn window(r: Rect, canvas: Rect) -> Rect { - let ext = r.width().max(r.height()) as i32; - r.inflate((ext * 3 / 4).clamp(32, MAX_MARGIN)).intersect(&canvas) + r.inflate(crate::fill_cmds::sampling_margin(r).min(MAX_MARGIN)).intersect(&canvas) } /// The pixels a step works on: the targeted surface, or with Sample All Layers the visible