Skip to content

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

Live strokes: reject out-of-range coordinates before the preview changes (#1652)

Jason Xiangc88dbd26cd27
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 49a752369..32581b69f 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -330,6 +330,7 @@ pub struct LiveStroke {
pub doc: std::sync::Arc<photocraft_doc::Document>,
/// Jitter seed to pass to `paint.stroke`.
pub seed: u64,
+ cmd: String,
renderer: StrokeRenderer,
mirror: Option<(crate::symmetry_cmds::SymmetryAxis, StrokeRenderer)>,
mirror_distinct: bool,
@@ -371,8 +372,20 @@ impl LiveStroke {
let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom);
let mirror = s.active().and_then(|st| st.symmetry_path.clone()).map(|axis| (axis, StrokeRenderer::new(&brush, Some(surf.format()), zoom)));
let pre = surf.clone();
- let mut live =
- Self { doc: std::sync::Arc::new(doc), seed, renderer, mirror, mirror_distinct: false, pre, sel, lock, layer, params: p.clone(), tail: Rect::EMPTY };
+ let mut live = Self {
+ doc: std::sync::Arc::new(doc),
+ seed,
+ cmd: cmd.into(),
+ renderer,
+ mirror,
+ mirror_distinct: false,
+ pre,
+ sel,
+ lock,
+ layer,
+ params: p.clone(),
+ tail: Rect::EMPTY,
+ };
live.push(&pts)?;
Ok(live)
}
@@ -387,7 +400,9 @@ impl LiveStroke {
/// committing it now would: with smoothing, the brush lags behind the pointer and catches up
/// when the stroke ends, so that catch-up tail is drawn too (and redrawn on every step), and
/// nothing new appears on release.
+ /// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
+ check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
if let Some((axis, mirror)) = &mut self.mirror {
let reflected = axis.reflect_points(pts);
diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rs
index e963ac70f..ed8ccb181 100644
--- a/crates/engine/src/brush_cmds/tests.rs
+++ b/crates/engine/src/brush_cmds/tests.rs
@@ -336,6 +336,57 @@ fn live_stroke_matches_the_committed_stroke() {
assert!(LiveStroke::begin(&Session::new(), &json!({"points": [[1, 1]]})).is_err());
}
+#[test]
+fn stroke_coordinate_validation_keeps_the_existing_bounds() {
+ let edges = [StrokePoint::new(-MAX_COORD, MAX_COORD, 1.0), StrokePoint::new(MAX_COORD, -MAX_COORD, 1.0)];
+ assert!(check_coords(&edges, "paint.stroke").is_ok());
+ assert!(check_coords(&[], "paint.stroke").is_ok(), "an empty live update is allowed");
+ for (x, y) in [(MAX_COORD + 1.0, 0.0), (0.0, -MAX_COORD - 1.0), (f64::NAN, 0.0), (0.0, f64::INFINITY)] {
+ assert!(check_coords(&[StrokePoint::new(x, y, 1.0)], "paint.stroke").is_err());
+ }
+ // The command parser still rejects empty strokes and shares the same inclusive boundary.
+ assert!(parse_points(&json!({"points": []}), "paint.stroke").is_err());
+ assert!(parse_points(&json!({"points": [[MAX_COORD, -MAX_COORD]]}), "paint.stroke").is_ok());
+}
+
+#[test]
+fn live_brush_and_pencil_reject_invalid_batches_without_changing_the_preview() {
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 32, "height": 32, "depth": depth, "background": "transparent"})).unwrap();
+ let st = s.active().unwrap();
+ let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.past_len());
+ let id = st.active_layer.unwrap();
+ for (cmd, erase) in [("paint.stroke", false), ("paint.stroke", true), ("paint.pencil", false)] {
+ let p = json!({"points": [[8, 16]], "size": 4, "erase": erase, "seed": 7});
+ let mut live = LiveStroke::begin_with(&s, cmd, &p).unwrap();
+ let mut control = LiveStroke::begin_with(&s, cmd, &p).unwrap();
+ // NaN first: on an unguarded renderer this fails without starting the enormous segment.
+ for (x, y) in [(f64::NAN, 16.0), (16.0, f64::NAN), (f64::INFINITY, 16.0), (16.0, f64::NEG_INFINITY), (1e300, 16.0), (16.0, -MAX_COORD - 1.0)] {
+ let shown = live.doc.clone();
+ let bounds = live.bounds();
+ let batch = [StrokePoint::new(12.0, 18.0, 1.0), StrokePoint::new(x, y, 1.0)];
+ let err = live.push(&batch).unwrap_err();
+ assert!(matches!(err, EngineError::BadParams { cmd: ref actual, ref msg }
+ if actual == cmd && msg.contains("point coordinates must be finite")));
+ assert!(std::sync::Arc::ptr_eq(&shown, &live.doc), "reject the whole batch before touching the preview");
+ assert_eq!(live.bounds(), bounds);
+ }
+ // A rejected batch must not advance the renderer; resuming is identical to never
+ // receiving it. Ordinary off-canvas points remain valid too.
+ let next = [StrokePoint::new(-4.0, 16.0, 1.0), StrokePoint::new(24.0, 16.0, 1.0)];
+ assert_eq!(live.push(&next).unwrap(), control.push(&next).unwrap());
+ assert_eq!(live.bounds(), control.bounds());
+ let (got, want) = (live.doc.layer(id).unwrap().surface().unwrap(), control.doc.layer(id).unwrap().surface().unwrap());
+ assert!(same_pixels(got, want, live.bounds()));
+ assert_eq!(got.content_bounds(), want.content_bounds());
+ }
+ let st = s.active().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&doc, &st.doc));
+ assert_eq!((st.revision, st.history.past_len()), (revision, history));
+ }
+}
+
#[test]
fn live_pencil_matches_the_committed_pencil_and_auto_erases() {
let mut s = session(80, 40);
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 348ce94a7..242bba76b 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -315,6 +315,7 @@ enum LivePaint {
pub struct LiveRetouch {
/// The active document with the stroke so far.
pub doc: std::sync::Arc<Document>,
+ cmd: String,
renderer: photocraft_paint::StrokeRenderer,
pre: std::sync::Arc<Document>,
pre_surf: Surface,
@@ -361,8 +362,21 @@ impl LiveRetouch {
LivePaint::History(src) if src.format() != pre_surf.format() => LivePaint::History(src.convert(pre_surf.format())),
other => other,
};
- let mut live =
- Self { doc: std::sync::Arc::new(doc), renderer, pre, pre_surf, id, params: p.clone(), paint, mode, opacity, sel, lock, tail: Rect::EMPTY };
+ let mut live = Self {
+ doc: std::sync::Arc::new(doc),
+ cmd: cmd.into(),
+ renderer,
+ pre,
+ pre_surf,
+ id,
+ params: p.clone(),
+ paint,
+ mode,
+ opacity,
+ sel,
+ lock,
+ tail: Rect::EMPTY,
+ };
live.push(&stroke.points)?;
Ok(live)
}
@@ -377,7 +391,9 @@ impl LiveRetouch {
/// the commit, and pixels painted earlier in the stroke are never re-cloned. What finishing
/// the stroke now would add is drawn too (a lone first dab shows on the press), and redrawn on
/// every step.
+ /// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
+ crate::brush_cmds::check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
let old = std::mem::replace(&mut self.tail, Rect::EMPTY);
let mut dmg = Rect::EMPTY;
@@ -864,6 +880,7 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
pub struct LiveDab {
/// The active document with the stroke so far.
pub doc: std::sync::Arc<Document>,
+ cmd: String,
renderer: photocraft_paint::StrokeRenderer,
done: usize,
effect: DabEffect,
@@ -896,6 +913,7 @@ impl LiveDab {
let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs();
let mut live = Self {
doc: std::sync::Arc::new(doc),
+ cmd: cmd.into(),
renderer,
done: 0,
effect,
@@ -919,7 +937,9 @@ impl LiveDab {
}
/// Render more points; returns the rectangle that changed.
+ /// Invalid coordinates reject the whole batch without changing the preview.
pub fn push(&mut self, pts: &[StrokePoint]) -> Result<Rect> {
+ crate::brush_cmds::check_coords(pts, &self.cmd)?;
self.renderer.push(pts);
let ctx = self.renderer.ctx.clone();
let new: Vec<_> = self.renderer.dabs().get(self.done..).unwrap_or_default().to_vec();
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index 87f3e77e9..bb13463e2 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -1133,6 +1133,68 @@ fn live_clone_matches_the_commit() {
}
}
+// Both preview implementations must reject an entire pointer batch before their renderer,
+// coverage, tail or working surface changes. Compare a resumed stroke with a clean control.
+macro_rules! live_coordinate_regression {
+ ($name:ident, $live:ty, [$($cmd:literal),+]) => {
+ #[test]
+ fn $name() {
+ for depth in DEPTHS {
+ let mut s = session(32, 32, depth, "rgb");
+ paint_layer(&mut s, texture);
+ let st = s.active().unwrap();
+ let (doc, revision, history) = (st.doc.clone(), st.revision, st.history.past_len());
+ let id = st.active_layer.unwrap();
+ for cmd in [$($cmd),+] {
+ let p = json!({"points": [[8, 16]], "source": [4, 8], "size": 4, "hardness": 100});
+ let mut live = <$live>::begin(&s, cmd, &p).unwrap();
+ let mut control = <$live>::begin(&s, cmd, &p).unwrap();
+ // The first regression case fails fast even without the guard, before any
+ // enormous coordinate reaches the path walker.
+ for (x, y) in [
+ (f64::NAN, 16.0),
+ (16.0, f64::NAN),
+ (f64::INFINITY, 16.0),
+ (16.0, f64::NEG_INFINITY),
+ (1e300, 16.0),
+ (16.0, -crate::brush_cmds::MAX_COORD - 1.0),
+ ] {
+ let shown = live.doc.clone();
+ let bounds = live.bounds();
+ let batch = [StrokePoint::new(12.0, 18.0, 1.0), StrokePoint::new(x, y, 1.0)];
+ let err = live.push(&batch).unwrap_err();
+ assert!(matches!(err, EngineError::BadParams { cmd: ref actual, ref msg }
+ if actual == cmd && msg.contains("point coordinates must be finite")));
+ assert!(std::sync::Arc::ptr_eq(&shown, &live.doc), "{cmd}: invalid batch changed the preview");
+ assert_eq!(live.bounds(), bounds, "{cmd}");
+ }
+ let next = [StrokePoint::new(-4.0, 16.0, 1.0), StrokePoint::new(24.0, 16.0, 1.0)];
+ assert_eq!(live.push(&next).unwrap(), control.push(&next).unwrap(), "{cmd}");
+ assert_eq!(live.bounds(), control.bounds(), "{cmd}");
+ let got = live.doc.layer(id).unwrap().surface().unwrap();
+ let want = control.doc.layer(id).unwrap().surface().unwrap();
+ assert_eq!(got.read_region(live.bounds()), want.read_region(control.bounds()), "{cmd}");
+ assert_eq!(got.content_bounds(), want.content_bounds(), "{cmd}");
+ }
+ let st = s.active().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&doc, &st.doc));
+ assert_eq!((st.revision, st.history.past_len()), (revision, history));
+ }
+ }
+ };
+}
+
+live_coordinate_regression!(
+ live_retouch_rejects_invalid_batches_without_changing_the_preview,
+ LiveRetouch,
+ ["paint.cloneStamp", "paint.healingBrush", "paint.historyBrush"]
+);
+live_coordinate_regression!(
+ live_dab_rejects_invalid_batches_without_changing_the_preview,
+ LiveDab,
+ ["paint.dodge", "paint.burn", "paint.sponge", "paint.blur", "paint.sharpen", "paint.smudge"]
+);
+
/// The live Dodge shows what the commit paints, also where a stroke doubles back across the
/// cells that remember each pixel's original colour (the live stroke edits one dab at a time).
/// 32-bit, so the live working copy isn't quantised between dabs.