Skip to content

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

Free Transform: refuse outputs over a pixel budget instead of building them (#4293)

Fabio Lussi8157d1a8517b
diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs
index 1480ec2b3..2584a877d 100644
--- a/crates/algo/src/transform.rs
+++ b/crates/algo/src/transform.rs
@@ -192,6 +192,30 @@ pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option<Homography> {
Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse()
}
+/// The destination rectangle [`warp_surface`] fills for `src_rect` under `h`: the warped corners
+/// plus a pixel for filter support, each side clamped to ±2²⁰. `None` when a corner maps to
+/// infinity (the result is then empty). Lets a caller price a warp before allocating it.
+pub fn warp_output_bounds(src_rect: Rect, h: &Homography) -> Option<Rect> {
+ if src_rect.is_empty() || h.inverse().is_none() {
+ return None;
+ }
+ let corners = [(src_rect.x0, src_rect.y0), (src_rect.x1, src_rect.y0), (src_rect.x1, src_rect.y1), (src_rect.x0, src_rect.y1)]
+ .map(|(x, y)| h.apply(x as f64, y as f64));
+ corner_bounds(&corners)
+}
+
+fn corner_bounds(corners: &[(f64, f64); 4]) -> Option<Rect> {
+ if !corners.iter().all(|c| c.0.is_finite() && c.1.is_finite()) {
+ return None;
+ }
+ let lim = (1 << 20) as f64;
+ let bx0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor().max(-lim) as i32 - 1;
+ let by0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor().max(-lim) as i32 - 1;
+ let bx1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil().min(lim) as i32 + 1;
+ let by1 = corners.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil().min(lim) as i32 + 1;
+ Some(Rect::new(bx0, by0, bx1, by1))
+}
+
fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Option<Rect>) -> Result<Surface, photocraft_raster::AllocationError> {
let mut fmt = src.format();
let converted;
@@ -234,21 +258,13 @@ fn warp(src: &Surface, src_rect: Rect, h: &Homography, interp: Interp, clip: Opt
let fwd_w = [(sx0, sy0), (sx1, sy0), (sx1, sy1), (sx0, sy1)].map(|(x, y)| h.0[6] * x + h.0[7] * y + h.0[8]);
let side = [1.0, -1.0].into_iter().find(|&s| fwd_w.iter().all(|&c| s * c > 0.0));
let w_lo = 1.0 / fwd_w.iter().fold(0.0f64, |m, c| m.max(c.abs()));
- let finite = corners.iter().all(|c| c.0.is_finite() && c.1.is_finite());
- let lim = 1 << 20;
- let bounds = || {
- let bx0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor().max(-(lim as f64)) as i32 - 1;
- let by0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor().max(-(lim as f64)) as i32 - 1;
- let bx1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil().min(lim as f64) as i32 + 1;
- let by1 = corners.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil().min(lim as f64) as i32 + 1;
- Rect::new(bx0, by0, bx1, by1)
- };
- let dst = match clip {
+ let bounds = corner_bounds(&corners);
+ let dst = match (clip, bounds) {
// The warped corners only bound the result while the whole source is in front of the horizon.
- Some(c) if finite && side.is_some() => bounds().intersect(&c),
- Some(c) => c,
- None if finite => bounds(),
- None => return Ok(out),
+ (Some(c), Some(b)) if side.is_some() => b.intersect(&c),
+ (Some(c), _) => c,
+ (None, Some(b)) => b,
+ (None, None) => return Ok(out),
};
if dst.is_empty() {
return Ok(out);
diff --git a/crates/engine/src/allocation.rs b/crates/engine/src/allocation.rs
index 322e3ebd2..7c29ecc8e 100644
--- a/crates/engine/src/allocation.rs
+++ b/crates/engine/src/allocation.rs
@@ -48,7 +48,7 @@ pub(crate) fn read_region(surface: &photocraft_raster::Surface, area: photocraft
Ok(out)
}
-fn error(purpose: &str, detail: &str) -> EngineError {
+pub(crate) fn error(purpose: &str, detail: &str) -> EngineError {
EngineError::Other(format!("not enough memory for {purpose} ({detail}); the document was not changed"))
}
diff --git a/crates/engine/src/select_extra_cmds.rs b/crates/engine/src/select_extra_cmds.rs
index e2c9e7059..5feae1a75 100644
--- a/crates/engine/src/select_extra_cmds.rs
+++ b/crates/engine/src/select_extra_cmds.rs
@@ -195,6 +195,7 @@ fn transform_selection(s: &mut Session, p: &Value) -> Result<Value> {
}
let selected = s.edit("Transform Selection", |doc, _| {
if let Some(sel) = &doc.selection {
+ crate::transform_cmds::check_budget(sel.content_bounds(), &h, "selection")?;
doc.selection = Some(crate::transform_cmds::warp_gray(sel, &h, interp)?).filter(|s| !s.content_bounds().is_empty());
}
Ok(doc.selection.is_some())
diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs
index 44926b09f..a09366e6f 100644
--- a/crates/engine/src/transform_cmds.rs
+++ b/crates/engine/src/transform_cmds.rs
@@ -1,6 +1,6 @@
//! Edit › Free Transform / Transform: projective transforms of layers (and the selection).
-use photocraft_algo::transform::{Homography, Interp, warp_surface};
+use photocraft_algo::transform::{Homography, Interp, warp_output_bounds, warp_surface};
use photocraft_color::PixelFormat;
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks};
use photocraft_geom::{Affine, Rect};
@@ -234,9 +234,81 @@ pub fn locked_for_transform(doc: &Document, id: LayerId) -> bool {
false
}
+/// The largest result (px) a single Free Transform warp may build: 2³⁰, the bound Puppet Warp uses
+/// too ([`photocraft_algo::puppet::MAX_WARP_PIXELS`]). Only the size of the result counts, not
+/// where it lands, so moving a layer far off the canvas stays allowed. A scale past it is refused
+/// rather than clipped (#3773): the warp would otherwise fill every tile of a result up to 2²¹ px
+/// on a side before anything could fail.
+pub const MAX_TRANSFORM_PIXELS: u64 = 1 << 30;
+
+/// Tests use a far lower budget, so proving a refusal never comes near allocating the real one.
+#[cfg(not(test))]
+const BUDGET: u64 = MAX_TRANSFORM_PIXELS;
+#[cfg(test)]
+const BUDGET: u64 = 1 << 20;
+
+/// Refuse a warp of the content inside `src` by `h` whose result would exceed the pixel budget,
+/// before anything is built. `what` names the surface in the message.
+pub(crate) fn check_budget(src: Rect, h: &Homography, what: &str) -> Result<()> {
+ let Some(b) = warp_output_bounds(src, h) else { return Ok(()) };
+ let (w, ht) = (u64::from(b.width()), u64::from(b.height()));
+ if w.saturating_mul(ht) > BUDGET {
+ let detail = format!("the transformed {what} would be {w} x {ht} px, more than the {BUDGET} px limit");
+ return Err(crate::allocation::error("transforming pixels", &detail));
+ }
+ Ok(())
+}
+
+/// [`check_budget`] for every warp [`transform_layer`] would make of `l` (for a group, of every
+/// layer inside it), so a transform that doesn't fit is refused before any layer is built and a
+/// group that partly fits isn't half-transformed.
+fn check_layer_budget(doc_sel: Option<&Surface>, l: &Layer, h: &Homography) -> Result<()> {
+ if h.is_identity() {
+ return Ok(());
+ }
+ // An explicit stack rather than recursion: documents can nest deeply.
+ let mut stack = vec![(l, doc_sel)];
+ while let Some((l, sel)) = stack.pop() {
+ match &l.content {
+ LayerContent::Group(g) => stack.extend(g.children.iter().map(|c| (c, None))),
+ LayerContent::Text(_) | LayerContent::Shape(_) => {}
+ LayerContent::Smart(sm) => {
+ if let Some(c) = &sm.cache {
+ check_budget(c.content_bounds(), h, "smart object")?;
+ }
+ if let Some(m) = &sm.filter_mask {
+ check_budget(m.surface.content_bounds(), h, "smart filter mask")?;
+ }
+ }
+ _ => {
+ if let Some(surf) = l.surface() {
+ check_budget(surf.content_bounds(), h, &format!("layer \"{}\"", l.name))?;
+ }
+ }
+ }
+ if let Some(m) = &l.mask
+ && m.linked
+ {
+ // With a selection only its region of the mask moves (`warp_gray_selected`).
+ let src = match sel.filter(|_| !moves_whole(l)) {
+ Some(sel) => sel.content_bounds(),
+ None => m.surface.content_bounds(),
+ };
+ check_budget(src, h, "layer mask")?;
+ }
+ }
+ Ok(())
+}
+
/// `group` holds the locks `l` inherits from the groups around it ([`group_locks`]). A Background
/// is turned into a normal layer by the caller first ([`crate::extra_cmds::background_to_layer`]).
+/// Refused, with `l` untouched, when a result would exceed [`MAX_TRANSFORM_PIXELS`].
pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {
+ check_layer_budget(doc_sel, l, h)?;
+ apply_transform(doc_sel, group, l, h, affine, interp)
+}
+
+fn apply_transform(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, h: &Homography, affine: Option<Affine>, interp: Interp) -> Result<()> {
crate::allocation::checkpoint("transforming pixels")?;
let locks = transform_locks(l, group, false);
if locks.position || locks.all {
@@ -245,7 +317,7 @@ pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut L
if h.is_identity() {
if let LayerContent::Group(g) = &mut l.content {
for c in g.children.iter_mut() {
- transform_layer(None, locks, c, h, affine, interp)?;
+ apply_transform(None, locks, c, h, affine, interp)?;
}
}
return Ok(());
@@ -256,7 +328,7 @@ pub(crate) fn transform_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut L
match &mut l.content {
LayerContent::Group(g) => {
for c in g.children.iter_mut() {
- transform_layer(None, locks, c, h, affine, interp)?;
+ apply_transform(None, locks, c, h, affine, interp)?;
}
}
LayerContent::Text(t) => {
@@ -501,10 +573,16 @@ fn transform(s: &mut Session, p: &Value) -> Result<Value> {
let lone = lone.is_some();
s.edit("Free Transform", |doc, _| {
let sel = doc.selection.clone();
+ // The selection outline moves too: price it before anything is built.
+ if let Some(sel) = sel.as_ref().filter(|_| !h.is_identity()) {
+ check_budget(sel.content_bounds(), &h, "selection")?;
+ }
if lone {
// A targeted unlinked mask, alpha channel or Quick Mask transforms by itself.
if !h.is_identity() {
let (surf, _) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let src = sel.as_ref().map_or_else(|| surf.content_bounds(), Surface::content_bounds);
+ check_budget(src, &h, "mask or channel")?;
*surf = match &sel {
Some(sel) => warp_gray_selected(surf, sel, &h, interp)?,
None => warp_gray(surf, &h, interp)?,
@@ -577,6 +655,112 @@ mod tests {
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()
}
+ // ---- Pixel budget (#3773). Tests run with a 2²⁰ px budget, so nothing here comes near the real one. ----
+
+ /// A 16 x 16 document whose active layer is a 1 x 8 column at x = 10.
+ fn column() -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 16, "height": 16})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("paint", |doc, active| {
+ doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 2, 11, 10), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s
+ }
+
+ /// Stretch x by `k` about x = 10 (the column's left edge).
+ fn stretch(k: f64) -> Value {
+ json!({"matrix": [k, 0, 0, 1, -10.0 * k, 0], "interpolation": "nearest"})
+ }
+
+ #[test]
+ fn a_scale_past_the_pixel_budget_is_refused_and_changes_nothing() {
+ let mut s = column();
+ let st = s.active().unwrap();
+ let (before, revision, steps) = (st.doc.clone(), st.revision, st.history.past_len());
+ // 200000 x 10 px of output: twice the test budget.
+ let err = s.execute("edit.transform", stretch(2e5)).unwrap_err().to_string();
+ assert!(err.starts_with("not enough memory for transforming pixels"), "{err}");
+ assert!(err.contains("would be 200002 x 10 px") && err.ends_with("the document was not changed"), "{err}");
+ let st = s.active().unwrap();
+ assert!(st.doc == before, "the document is untouched");
+ assert_eq!((st.revision, st.history.past_len()), (revision, steps));
+ // Within the budget the same stretch still works, nothing clipped.
+ s.execute("edit.transform", stretch(1e4)).unwrap();
+ assert_eq!(active_bounds(&s), Rect::new(0, 2, 10_000, 10));
+ }
+
+ #[test]
+ fn a_group_with_one_layer_past_the_budget_is_not_half_transformed() {
+ let mut s = column();
+ let wide = s.active().unwrap().active_layer.unwrap();
+ // Over the column: a 1 px dot, which fits the budget stretched by the same amount.
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let dot = s.active().unwrap().active_layer.unwrap();
+ s.edit("paint", |doc, _| {
+ doc.layer_mut(dot).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 12, 11, 13), &[0.0, 1.0, 0.0, 1.0]);
+ // Widen the column to 8 px (x 2..10), so it alone needs 400002 x 10 px.
+ doc.layer_mut(wide).unwrap().surface_mut().unwrap().fill_rect(Rect::new(2, 2, 10, 10), &[1.0, 0.0, 0.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.execute("layer.select", json!({"layer": wide.0})).unwrap();
+ s.execute("layer.select", json!({"layer": dot.0, "mode": "add"})).unwrap();
+ let group = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap());
+ let st = s.active().unwrap();
+ assert!(matches!(&st.doc.layer(group).unwrap().content, LayerContent::Group(g) if g.children.len() == 2));
+ let (before, revision) = (st.doc.clone(), st.revision);
+ let k = 5e4;
+ assert!(s.execute("edit.transform", json!({"layer": group.0, "matrix": [k, 0, 0, 1, -10.0 * k, 0]})).is_err());
+ let st = s.active().unwrap();
+ assert!(st.doc == before && st.revision == revision, "nothing changed");
+ // The layer-level check runs before any child is warped, so even the layer itself
+ // (not just the edit's copy of the document) is left as it was.
+ let mut l = st.doc.layer(group).unwrap().clone();
+ let h = Homography([k, 0.0, -10.0 * k, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
+ assert!(transform_layer(None, Locks::default(), &mut l, &h, None, Interp::Nearest).is_err());
+ assert!(&l == st.doc.layer(group).unwrap(), "no child was transformed");
+ }
+
+ #[test]
+ fn moving_a_small_layer_far_off_the_canvas_is_within_budget() {
+ let mut s = session();
+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, 900_000, -900_000]})).unwrap();
+ assert_eq!(active_bounds(&s), Rect::new(900_010, -899_990, 900_030, -899_980));
+ s.execute("edit.transform", json!({"matrix": [1, 0, 0, 1, -900_000, 900_000]})).unwrap();
+ assert_eq!(active_bounds(&s), Rect::new(10, 10, 30, 20), "and back, every pixel kept");
+ }
+
+ #[test]
+ fn selections_masks_and_channels_have_the_same_budget() {
+ // The selection outline of a layer transform.
+ let mut s = column();
+ s.execute("select.rect", json!({"x": 10, "y": 2, "width": 1, "height": 8})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let err = s.execute("edit.transform", stretch(2e5)).unwrap_err().to_string();
+ assert!(err.contains("transformed selection would be"), "{err}");
+ // Transform Selection.
+ let err = s.execute("select.transformSelection", stretch(2e5)).unwrap_err().to_string();
+ assert!(err.contains("transformed selection would be"), "{err}");
+ assert!(s.active().unwrap().doc == before);
+ // A targeted alpha channel.
+ let mut s = column();
+ s.execute("channel.new", json!({})).unwrap();
+ s.edit("paint channel", |doc, _| {
+ doc.channels[0].surface.fill_rect(Rect::new(10, 2, 11, 10), &[1.0]);
+ Ok(())
+ })
+ .unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let mut p = stretch(2e5);
+ p["target"] = json!({"channel": 0});
+ let err = s.execute("edit.transform", p).unwrap_err().to_string();
+ assert!(err.contains("transformed mask or channel would be"), "{err}");
+ assert!(s.active().unwrap().doc == before);
+ }
+
#[test]
fn scale_via_quad_and_undo() {
let mut s = session();
diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs
index ecb19fff7..0af28a81c 100644
--- a/crates/ui-egui/src/transform_tool.rs
+++ b/crates/ui-egui/src/transform_tool.rs
@@ -669,6 +669,9 @@ pub fn warps_type(app: &PhotocraftApp) -> bool {
fn enter_type_warp(app: &mut PhotocraftApp, ctx: &egui::Context) {
if app.ui.transform.as_ref().is_some_and(|t| t.quad != corners(t.rect)) {
commit(app);
+ if app.ui.transform.is_some() {
+ return; // refused: the box stays as it was
+ }
if let Err(e) = begin(app, ctx) {
app.ui.status = e;
return;
@@ -954,7 +957,7 @@ pub fn commit(app: &mut PhotocraftApp) {
}
let type_layer = warps_type(app);
let Some(t) = app.ui.transform.take() else { return };
- app.transform_preview = None;
+ let preview = app.transform_preview.take();
if let Some(options) = &t.content_aware {
crate::cas_transform::commit(app, &t, options);
return;
@@ -968,12 +971,12 @@ pub fn commit(app: &mut PhotocraftApp) {
None => p["quad"] = json!(t.quad),
}
if let Err(e) = app.run("select.transformSelection", p) {
- app.ui.status = e;
+ keep_open(app, t, preview, e);
}
return;
}
- if let Some(target) = t.path {
- let mut p = target;
+ if let Some(target) = &t.path {
+ let mut p = target.clone();
match &t.warp {
Some(w) if w.is_identity() => return,
Some(w) => p["warp"] = json!(w),
@@ -988,7 +991,7 @@ pub fn commit(app: &mut PhotocraftApp) {
},
}
if let Err(e) = app.run("path.transform", p) {
- app.ui.status = e;
+ keep_open(app, t, preview, e);
}
return;
}
@@ -1004,8 +1007,8 @@ pub fn commit(app: &mut PhotocraftApp) {
return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays
}
let mut p = json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation});
- if let Some(target) = t.target {
- p["target"] = target;
+ if let Some(target) = &t.target {
+ p["target"] = target.clone();
}
app.run("edit.transform", p)
};
@@ -1015,17 +1018,19 @@ pub fn commit(app: &mut PhotocraftApp) {
fold_made(app, made);
}
}
- Err(e) => {
- if made.is_some()
- && let Some(document) = document
- {
- take_back_made(app, document, LayerId(t.layer));
- }
- app.ui.status = e;
- }
+ Err(e) => keep_open(app, t, preview, e),
}
}
+/// A commit the engine refused (a result over the pixel budget, #3773): the box stays open as it
+/// was, with the reason in the status bar, so the transform can be changed or cancelled. A copy or
+/// a placed layer it made goes only when it is cancelled.
+fn keep_open(app: &mut PhotocraftApp, t: TransformSession, preview: Option<TransformPreview>, e: String) {
+ app.ui.transform = Some(t);
+ app.transform_preview = preview;
+ app.ui.status = e;
+}
+
/// A transform whose layer or document went away (undo, close) ends silently; picking another tool
/// or selecting another layer (Layers panel, ⌘-click, the control channel) applies it, so the box
/// never stays on a layer that is no longer the active one (#1400). Checked every frame and before
@@ -1055,6 +1060,10 @@ pub fn end_if_left(app: &mut PhotocraftApp) {
|| (!selection && st.active_layer.is_some_and(|active| active.0 != layer.0))
{
commit(app);
+ // Picking another tool or layer can't leave a refused transform open: it ends, as Esc would.
+ if app.ui.transform.is_some() {
+ cancel(app);
+ }
}
}
@@ -3413,6 +3422,30 @@ mod tests {
assert!(app.ui.transform.is_none() && app.transform_preview.is_none());
}
+ /// A commit the engine refuses (here a collapsed box; a result over the pixel budget, #3773, is
+ /// refused the same way) shows the reason and keeps the box open, unchanged; picking another
+ /// tool then ends it.
+ #[test]
+ fn a_refused_commit_keeps_the_box_open() {
+ let ctx = egui::Context::default();
+ let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));
+ let (revision, steps) = (app.session.active().unwrap().revision, app.session.active().unwrap().history.past_len());
+ begin(&mut app, &ctx).unwrap();
+ if let Some(t) = app.ui.transform.as_mut() {
+ t.quad = [[16.0, 16.0]; 4];
+ }
+ commit(&mut app);
+ let t = app.ui.transform.as_ref().expect("the box stays open");
+ assert_eq!(t.quad, [[16.0, 16.0]; 4], "as the user left it");
+ assert!(app.transform_preview.is_some(), "with its preview");
+ assert!(app.ui.status.contains("collapses"), "{}", app.ui.status);
+ let st = app.session.active().unwrap();
+ assert_eq!((st.revision, st.history.past_len()), (revision, steps), "the document was not changed");
+ app.ui.tool = if app.ui.tool == Tool::Brush { Tool::Move } else { Tool::Brush };
+ end_if_left(&mut app);
+ assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "another tool ends it");
+ }
+
/// #352: ⌥⌘T transforms a copy. OK leaves the original and a moved copy as one history step;
/// Cancel leaves no copy and nothing to redo; with a selection the copy holds the selected
/// pixels only.