Skip to content

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

fix(algo,engine): refuse a Select and Mask refine too large to allocate

Khawar Zamman Wanif58e2f42753f
diff --git a/crates/algo/src/matting.rs b/crates/algo/src/matting.rs
index f9f3036eb..f4bfccb0b 100644
--- a/crates/algo/src/matting.rs
+++ b/crates/algo/src/matting.rs
@@ -413,6 +413,22 @@ where
lo.into_iter().zip(hi).map(|(a, b)| a + (b - a) * frac).collect()
}
+/// Most pixels one refine should cover. Its result is a dense [`Region`] over [`refine_area`]
+/// (about two bytes a pixel while it is assembled), so callers refuse a larger refine up front
+/// rather than allocate it: 2³⁰ pixels, a 32k × 32k selection.
+pub const MAX_REFINE_AREA: u64 = 1 << 30;
+
+/// The area [`refine_mask`] and [`refine_mask_brushed`] compute and allocate their result over:
+/// `content` grown by how far `p` can spread it, plus where `brush` adds, within `canvas`. Empty
+/// when `content` misses the canvas.
+pub fn refine_area(content: Rect, canvas: Rect, p: &RefineParams, brush: Option<&EdgeBrush>) -> Rect {
+ let content = content.intersect(&canvas);
+ if content.is_empty() {
+ return Rect::EMPTY;
+ }
+ content.inflate(p.spread()).union(&brush.map_or(Rect::EMPTY, EdgeBrush::added_bounds)).intersect(&canvas)
+}
+
/// Refines a selection mask. `mask(r)` returns coverage over `r` (row-major); `content` bounds
/// its non-zero pixels; the result is clipped to `canvas`. `sampler` supplies the guide image
/// (only read when `radius > 0`). Returns `None` when nothing remains selected.
@@ -446,11 +462,10 @@ fn refine_mask_with<F>(
where
F: Fn(&[f32], usize, usize, usize, bool) -> Vec<f32> + Copy + Sync + Send,
{
- let content = content.intersect(&canvas);
- if content.is_empty() {
+ let bbox = refine_area(content, canvas, p, brush);
+ if bbox.is_empty() {
return None;
}
- let bbox = content.inflate(p.spread()).union(&brush.map_or(Rect::EMPTY, EdgeBrush::added_bounds)).intersect(&canvas);
let halo = p.halo() + brush.map_or(0, |b| i32::try_from(b.window() * 4).unwrap_or(i32::MAX));
let mut tiles = Vec::new();
let mut y = bbox.y0;
diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rs
index 8d6366360..cfd1b333e 100644
--- a/crates/engine/src/smartselect_cmds.rs
+++ b/crates/engine/src/smartselect_cmds.rs
@@ -431,10 +431,20 @@ fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {
let start = if target_mask { mask_surf.or(doc.selection.as_ref()) } else { doc.selection.as_ref().or(mask_surf) };
// The workspace's tool edits change the selection before its edge is refined.
let edited = if edits.is_empty() { None } else { select_mask_edits::apply(doc, active, start.cloned(), &edits) };
- let sel = if edits.is_empty() { start } else { edited.as_ref() }?;
+ let Some(sel) = (if edits.is_empty() { start } else { edited.as_ref() }) else { return Ok(None) };
let brush = matting::EdgeBrush::new(&strokes, doc.bounds());
- matting::refine_mask_brushed(smp, &matting::surface_reader(sel), sel.content_bounds(), doc.bounds(), &params, brush.as_ref())
- })?;
+ // The refined result is dense over the selection's bounds: refuse what would not fit
+ // rather than allocate it (a thin edit across a huge canvas; the #8783 review).
+ let content = sel.content_bounds();
+ let area = matting::refine_area(content, doc.bounds(), &params, brush.as_ref());
+ if u64::from(area.width()) * u64::from(area.height()) > matting::MAX_REFINE_AREA {
+ return Err(bad(
+ "select.refineEdge",
+ &format!("the selection is too large to refine ({} × {} px; at most {} px in all)", area.width(), area.height(), matting::MAX_REFINE_AREA),
+ ));
+ }
+ Ok(matting::refine_mask_brushed(smp, &matting::surface_reader(sel), content, doc.bounds(), &params, brush.as_ref()))
+ })??;
let d = s.active().ok_or(EngineError::NoDocument)?;
let active = d.active_layer.filter(|id| d.doc.layer(*id).is_some());
match output.as_str() {
@@ -1079,6 +1089,34 @@ mod tests {
(0..h).flat_map(|y| (0..w).map(move |x| (cov(s, x, y) * 255.0).round() as u8)).collect()
}
+ /// The #8783 review: a refine whose result would be dense over more than
+ /// [`matting::MAX_REFINE_AREA`] pixels is refused, not allocated: a thin Brush edit across a
+ /// huge canvas (its edited selection spans the canvas) and a selection of the whole canvas.
+ /// The selection stays as it was.
+ #[test]
+ fn refine_edge_refuses_a_selection_too_large_to_refine() {
+ let mut s = Session::new();
+ s.add_document(
+ Document::new("huge", photocraft_doc::Size::new(100_000, 100_000), photocraft_doc::ColorMode::Rgb, photocraft_color::SampleType::U8),
+ None,
+ );
+ s.execute("select.rect", json!({"x": 10, "y": 60, "width": 10, "height": 10})).unwrap();
+ let small = s.active().and_then(|d| d.doc.selection.clone()).expect("selected");
+ let diagonal = json!({"edits": [{"tool": "brush", "points": [[0, 0], [99_999, 99_999]], "size": 1}]});
+ let t = std::time::Instant::now();
+ let e = s.execute("select.refineEdge", diagonal).expect_err("too large to refine");
+ assert!(e.to_string().contains("too large to refine"), "{e}");
+ assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&small), "the selection is unchanged");
+ // The small selection itself still refines.
+ s.execute("select.refineEdge", json!({"radius": 4})).unwrap();
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("select.all", json!({})).unwrap();
+ let all = s.active().and_then(|d| d.doc.selection.clone()).expect("selected");
+ assert!(s.execute("select.refineEdge", json!({"radius": 4})).is_err());
+ assert!(s.active().and_then(|d| d.doc.selection.as_ref()) == Some(&all));
+ assert!(t.elapsed() < std::time::Duration::from_secs(20), "{:?}", t.elapsed());
+ }
+
/// The #8783 review: Brush and Lasso edits and Refine Edge Brush strokes that would paint
/// too many tiles of a huge canvas are refused before anything is painted, and the selection
/// stays as it was.