Skip to content

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

Check unclamped transform dimensions against the pixel budget (#6493)

denstu47368dfaf1ae6d9
diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs
index 050d08c32..3e67f1cde 100644
--- a/crates/algo/src/transform.rs
+++ b/crates/algo/src/transform.rs
@@ -231,14 +231,37 @@ pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option<Homography> {
/// 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.
+/// infinity (the result is then empty). Use [`warp_output_size`] to price the full result before
+/// admitting a transform: clipping these bounds must not hide an excessive scale.
pub fn warp_output_bounds(src_rect: Rect, h: &Homography) -> Option<Rect> {
+ corner_bounds(&warp_corners(src_rect, h)?)
+}
+
+/// Unclipped output dimensions, including the same filter support as [`warp_output_bounds`].
+/// Position does not affect the price, so translating a small layer far away stays cheap.
+/// Unrepresentable or non-finite dimensions saturate at `u64::MAX`, allowing a caller to refuse
+/// the warp with a saturating pixel-budget comparison. Empty and singular inputs have no output.
+pub fn warp_output_size(src_rect: Rect, h: &Homography) -> Option<(u64, u64)> {
+ let corners = warp_corners(src_rect, h)?;
+ if !corners.iter().all(|(x, y)| x.is_finite() && y.is_finite()) {
+ return Some((u64::MAX, u64::MAX));
+ }
+ let x0 = corners.iter().map(|c| c.0).fold(f64::MAX, f64::min).floor();
+ let y0 = corners.iter().map(|c| c.1).fold(f64::MAX, f64::min).floor();
+ let x1 = corners.iter().map(|c| c.0).fold(f64::MIN, f64::max).ceil();
+ let y1 = corners.iter().map(|c| c.1).fold(f64::MIN, f64::max).ceil();
+ // Float-to-integer casts saturate, including when the finite endpoints' difference overflows.
+ Some((((x1 - x0) as u64).saturating_add(2), ((y1 - y0) as u64).saturating_add(2)))
+}
+
+fn warp_corners(src_rect: Rect, h: &Homography) -> Option<[(f64, f64); 4]> {
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)
+ Some(
+ [(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)),
+ )
}
fn corner_bounds(corners: &[(f64, f64); 4]) -> Option<Rect> {
@@ -510,6 +533,31 @@ fn warp(
mod tests {
use super::*;
+ #[test]
+ fn output_size_prices_the_unclipped_extent_independently_of_position() {
+ let src = Rect::new(0, 0, 24, 16);
+ for dx in [0.0, 900_000.0, 10_000_000.0] {
+ let h = Homography([1.0, 0.0, dx, 0.0, 1.0, -dx, 0.0, 0.0, 1.0]);
+ assert_eq!(warp_output_size(src, &h), Some((26, 18)));
+ }
+ for sx in [1e7, -1e7] {
+ let h = Homography([sx, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
+ assert_eq!(warp_output_size(src, &h), Some((240_000_002, 18)));
+ }
+ }
+
+ #[test]
+ fn output_size_saturates_overflows_and_preserves_filter_support() {
+ let src = Rect::new(0, 0, 24, 16);
+ let fractional = Homography([0.5, 0.0, 0.25, 0.0, 1.0, 0.75, 0.0, 0.0, 1.0]);
+ let bounds = warp_output_bounds(src, &fractional).unwrap();
+ assert_eq!(warp_output_size(src, &fractional), Some((u64::from(bounds.width()), u64::from(bounds.height()))));
+ let huge = Homography([1e308, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0]);
+ assert_eq!(warp_output_size(src, &huge), Some((u64::MAX, u64::MAX)));
+ assert_eq!(warp_output_size(Rect::EMPTY, &Homography::IDENTITY), None);
+ assert_eq!(warp_output_size(src, &Homography([0.0; 9])), None);
+ }
+
#[test]
fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() {
let mut s = Surface::new(PixelFormat::RGBA8);
diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs
index 310bb13bb..2fafc222f 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_output_bounds, warp_surface, warp_surface_with};
+use photocraft_algo::transform::{Homography, Interp, warp_output_size, warp_surface, warp_surface_with};
use photocraft_color::PixelFormat;
use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks};
use photocraft_geom::{Affine, Rect};
@@ -273,10 +273,13 @@ 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");
+ check_budget_with_limit(src, h, what, BUDGET)
+}
+
+fn check_budget_with_limit(src: Rect, h: &Homography, what: &str, budget: u64) -> Result<()> {
+ let Some((w, ht)) = warp_output_size(src, h) else { return Ok(()) };
+ 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(())
@@ -735,6 +738,24 @@ mod tests {
// ---- Pixel budget (#3773). Tests run with a 2²⁰ px budget, so nothing here comes near the real one. ----
+ #[test]
+ fn huge_transform_scales_exceed_the_production_budget_before_clipping() {
+ let src = Rect::new(0, 0, 24, 16);
+ for scale in [1e7, 1e28, 1e306] {
+ for (sx, sy) in [(scale, 1.0), (1.0, scale), (-scale, 1.0)] {
+ let h = Homography([sx, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 1.0]);
+ assert!(check_budget_with_limit(src, &h, "layer", MAX_TRANSFORM_PIXELS).is_err(), "{sx} x {sy} must be refused");
+ }
+ }
+ }
+
+ #[test]
+ fn an_ordinary_transform_remains_within_the_production_budget() {
+ let src = Rect::new(0, 0, 24, 16);
+ let h = Homography([10_000.0, 0.0, 900_000.0, 0.0, 1.0, -900_000.0, 0.0, 0.0, 1.0]);
+ assert!(check_budget_with_limit(src, &h, "layer", MAX_TRANSFORM_PIXELS).is_ok());
+ }
+
/// 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();
diff --git a/crates/engine/tests/transform_budget_unclamped.rs b/crates/engine/tests/transform_budget_unclamped.rs
new file mode 100644
index 000000000..c603bee7b
--- /dev/null
+++ b/crates/engine/tests/transform_budget_unclamped.rs
@@ -0,0 +1,49 @@
+//! #6430: integration tests use the production pixel budget, not the unit tests' reduced one.
+use photocraft_engine::Session;
+use photocraft_geom::Rect;
+use serde_json::{Value, json};
+
+fn painted() -> Session {
+ let mut session = Session::new();
+ session.execute("file.new", json!({"width": 24, "height": 16})).unwrap();
+ session.execute("layer.new.layer", json!({})).unwrap();
+ session
+ .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();
+ session
+}
+
+fn assert_refused_without_changes(session: &mut Session, command: &str, params: Value) {
+ let state = session.active().unwrap();
+ let (document, revision, history) = (state.doc.clone(), state.revision, state.history.past_len());
+ let error = session.execute(command, params).unwrap_err().to_string();
+ assert!(error.contains("limit"), "{error}");
+ let state = session.active().unwrap();
+ assert!(state.doc == document, "refusal changed the document");
+ assert_eq!((state.revision, state.history.past_len()), (revision, history));
+}
+
+#[test]
+fn extreme_layer_scales_are_refused_before_a_clipped_strip_is_warped() {
+ let mut session = painted();
+ session.execute("filter.render.clouds", json!({})).unwrap();
+ for scale in [1e9, 1e30, 1e308, -1e308] {
+ for axis in ["scaleX", "scaleY"] {
+ assert_refused_without_changes(&mut session, "edit.transform", json!({(axis): scale}));
+ }
+ }
+}
+
+#[test]
+fn extreme_selection_scales_are_refused_without_losing_the_selection() {
+ let mut session = painted();
+ session.execute("select.rect", json!({"x": 10, "y": 2, "width": 1, "height": 8})).unwrap();
+ for scale in [1e30, 1e308] {
+ for axis in ["scaleX", "scaleY"] {
+ assert_refused_without_changes(&mut session, "select.transformSelection", json!({(axis): scale}));
+ }
+ }
+}