Skip to content

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

Merge main into feat/tool-213-7-live-retouch

David Mann8c7a2de4a7eb
diff --cc crates/engine/src/eraser_cmds.rs
index 0d6af8770,3fb546de4..7d415a39c
--- a/crates/engine/src/eraser_cmds.rs
+++ b/crates/engine/src/eraser_cmds.rs
@@@ -144,48 -132,27 +133,49 @@@ fn background_eraser_setup(s: &Session
background: s.tools.background,
};
let id = active_pixel_layer(s, CMD)?;
- {
- let d = s.active().ok_or(EngineError::NoDocument)?;
- let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
- if let Some(e) = pixels_locked(&d.doc, l) {
- return Err(e);
- }
- if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) {
- return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
- }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ if let Some(e) = pixels_locked(&d.doc, l) {
+ return Err(e);
+ }
- if d.doc.effective_locks(id).transparency && !is_background(l) {
++ if d.doc.effective_locks(id).transparency && !d.doc.is_background(id) {
+ return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
}
- let stroke = Stroke { brush, points: pts };
+ Ok((Stroke { brush, points: pts }, bs, id))
+}
+
+/// `paint.backgroundEraser`: a stroke erasing colours similar to the sampled one.
+fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "paint.backgroundEraser";
+ let (stroke, bs, id) = background_eraser_setup(s, p)?;
let dmg = s.edit("Background Eraser", |doc, _| {
let selection = doc.selection.clone();
+ crate::extra_cmds::background_to_layer(doc, id);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
- unlock_background(l);
let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?;
Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref()))
})?;
Ok(damage(s, dmg, true))
}
+/// A `paint.backgroundEraser` stroke shown while it is drawn: the same params, checks and
+/// erasing per dab as the commit (on a Background already turned into a normal layer), so the
+/// preview at the last point is the committed result.
+pub fn live_background_eraser(s: &Session, p: &Value) -> Result<crate::retouch_cmds::LiveDab> {
+ const CMD: &str = "paint.backgroundEraser";
+ let (stroke, bs, id) = background_eraser_setup(s, p)?;
+ let mut doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone();
- unlock_background(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
++ doc.layer(id).ok_or(EngineError::NoLayer(id))?;
++ crate::extra_cmds::background_to_layer(&mut doc, id);
+ let stroke = background_eraser_stroke(&stroke);
+ crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, true, |pre| match background_eraser_effect(pre.format(), &bs) {
+ Some(effect) => Box::new(effect),
+ // No alpha: the commit erases nothing either.
+ None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}),
+ })?
+ .with_tail_preview()
+}
+
/// Eraser-group command specs.
pub fn specs() -> Vec<CommandSpec> {
vec![
diff --cc crates/engine/src/retouch_cmds/pattern_stamp.rs
index 3c0772baf,0dc9f102a..3908e27b1
--- a/crates/engine/src/retouch_cmds/pattern_stamp.rs
+++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs
@@@ -29,80 -29,44 +29,80 @@@ pub(super) fn enabled(s: &Session) -> s
if crate::pattern_cmds::resolve(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) }
}
-pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
- const CMD: &str = "paint.patternStamp";
- let (mut stroke, id) = parse_brush(s, p, CMD)?;
- let mode = blend_param(p, CMD)?;
- let aligned = flag(p, "aligned", true);
- let impressionist = flag(p, "impressionist", false);
- let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
- if pat.is_empty() {
- return Err(bad(CMD, "the pattern is empty"));
+/// A parsed `paint.patternStamp`: shared by the command and its live preview, so both paint the
+/// same stroke (seeded the same way) with the same tile and placement.
+pub(super) struct Setup {
+ pub(super) stroke: Stroke,
+ pub(super) id: Option<LayerId>,
+ pub(super) mode: BlendMode,
+ aligned: bool,
+ pub(super) impressionist: bool,
+ pat: Pattern,
+ pub(super) tile: std::sync::Arc<Tile>,
+ phase: (f32, f32),
+ scale: f32,
+ angle: f32,
+ seed: u64,
+}
+
+impl Setup {
+ pub(super) fn parse(s: &Session, p: &Value) -> Result<Self> {
+ const CMD: &str = "paint.patternStamp";
+ let (mut stroke, id) = parse_brush(s, p, CMD)?;
+ let mode = blend_param(p, CMD)?;
+ let aligned = flag(p, "aligned", true);
+ let impressionist = flag(p, "impressionist", false);
+ let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
+ if pat.is_empty() {
+ return Err(bad(CMD, "the pattern is empty"));
+ }
+ let scale = stamp_scale(p, CMD)?;
+ let angle = stamp_angle(p, CMD)?;
+ let Some(first) = stroke.points.first() else {
+ return Err(bad(CMD, "`points` is empty"));
+ };
+ let phase = stamp_phase(p, CMD, aligned, first)?;
- let tile = std::sync::Arc::new(Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty"))?);
++ let tile = std::sync::Arc::new(Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty or too large to paint"))?);
+ reject_huge_stroke(CMD, &stroke)?;
+ let seed = p.get("seed").and_then(Value::as_u64).unwrap_or_else(|| {
+ let bytes = p.get("points").map(std::string::ToString::to_string).unwrap_or_default();
+ photocraft_paint::rng::seed_from_bytes(bytes.as_bytes())
+ });
+ stroke.brush.seed = seed;
+ Ok(Self { stroke, id, mode, aligned, impressionist, pat, tile, phase, scale, angle, seed })
+ }
+
+ /// Where the pattern sits (aligned strokes; Impressionist jitters it per dab).
+ pub(super) fn placement(&self) -> Placement {
+ placement(self.phase, self.scale, self.angle)
}
- let scale = stamp_scale(p, CMD)?;
- let angle = stamp_angle(p, CMD)?;
- let Some(first) = stroke.points.first() else {
- return Err(bad(CMD, "`points` is empty"));
- };
- let phase = stamp_phase(p, CMD, aligned, first)?;
- let tile = Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty or too large to paint"))?;
- reject_huge_stroke(CMD, &stroke)?;
- let seed = p.get("seed").and_then(Value::as_u64).unwrap_or_else(|| {
- let bytes = p.get("points").map(std::string::ToString::to_string).unwrap_or_default();
- photocraft_paint::rng::seed_from_bytes(bytes.as_bytes())
- });
- stroke.brush.seed = seed;
+ /// One Impressionist dab's edit of a working copy in `fmt`.
+ fn impressionist_effect(&self, fmt: PixelFormat) -> super::DabEffect {
+ let (tile, phase, scale, angle, seed, mode) = (self.tile.clone(), self.phase, self.scale, self.angle, self.seed, self.mode);
+ let (tw, th) = (self.pat.width as f32 * scale, self.pat.height as f32 * scale);
+ Box::new(move |work, fp| stamp_dab(work, &fmt, &tile, fp, phase, scale, angle, seed, tw, th, mode))
+ }
+}
+pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "paint.patternStamp";
+ let st = Setup::parse(s, p)?;
let dmg = s.edit("Pattern Stamp", |doc, _| {
- crate::pattern_cmds::ensure_in_doc(doc, &pat);
+ crate::pattern_cmds::ensure_in_doc(doc, &st.pat);
let pre = doc.clone();
- let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, st.id, p)?;
let sel = pre.selection.as_ref();
- if impressionist {
- paint_impressionist(surf, &stroke, sel, lock, &tile, &pat, phase, scale, angle, seed, mode)
+ if st.impressionist {
+ // Halo is the dab footprint only: Impressionist jitters phase, it does not blur.
+ let effect = st.impressionist_effect(surf.format());
+ Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect))
} else {
- paint_aligned(surf, &stroke, sel, lock, &tile, phase, scale, angle, mode, CMD)
+ paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD)
}
})?;
- if let Some(st) = s.active_mut() {
- st.last_damage = Some(dmg);
+ if let Some(state) = s.active_mut() {
+ state.last_damage = Some(dmg);
}
Ok(json!({
"damage": damage_json(dmg),
diff --cc crates/engine/src/retouch_cmds/tests.rs
index 5b677bd93,a0fac91b2..760abce25
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@@ -1581,71 -1581,62 +1581,131 @@@ fn spot_healing_keeps_film_grain_throug
}
}
+/// The live Pattern Stamp shows exactly what the commit paints, fed point by point, at 8 and 16
+/// bits: aligned strokes through their coverage (`LiveRetouch`), Impressionist ones dab by dab
+/// (`LiveDab` with float working pixels, as the commit's).
+#[test]
+fn live_pattern_stamp_matches_the_commit() {
+ let all = [[20.0, 30.0], [34.0, 36.0], [50.0, 28.0], [70.0, 34.0]];
+ for depth in [8, 16] {
+ for (impressionist, aligned) in [(false, true), (false, false), (true, true)] {
+ let mut s = session(96, 64, depth, "rgb");
+ paint_layer(&mut s, texture);
+ let opts = |pts: &[[f64; 2]]| {
+ json!({"points": pts, "size": 14, "hardness": 40, "opacity": 70, "pattern": "Checkerboard", "scale": 150, "angle": 20,
+ "aligned": aligned, "impressionist": impressionist, "mode": "multiply", "seed": 11})
+ };
+ let (doc, h) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len());
+ let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>();
+ let shown = if impressionist {
+ assert!(LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).is_err(), "Impressionist is laid dab by dab");
+ let mut live = live_pattern_impressionist(&s, &opts(&all[..1])).unwrap();
+ live.push(&pts(&all[1..3])).unwrap();
+ live.push(&pts(&all[3..])).unwrap();
+ live.doc.clone()
+ } else {
+ assert!(live_pattern_impressionist(&s, &opts(&all[..1])).is_err());
+ let mut live = LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap();
+ live.push(&pts(&all[1..3])).unwrap();
+ live.push(&pts(&all[3..])).unwrap();
+ live.doc.clone()
+ };
+ assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "the preview leaves the document alone");
+ s.execute("paint.patternStamp", opts(&all)).unwrap();
+ assert_eq!(s.active().unwrap().history.past_len(), h + 1, "one History step");
+ let id = s.active().unwrap().active_layer.unwrap();
+ let (a, b) = (shown.layer(id).unwrap().surface().unwrap(), s.active().unwrap().doc.layer(id).unwrap().surface().unwrap());
+ let mut changed = false;
+ for y in 0..64 {
+ for x in 0..96 {
+ let (got, want) = (a.rgba(x, y), b.rgba(x, y));
+ changed |= (0..3).any(|c| (want[c] - texture(x, y)[c]).abs() > 0.02);
+ assert_eq!(got, want, "impressionist {impressionist} aligned {aligned} {depth}-bit ({x}, {y})");
+ }
+ }
+ assert!(changed, "the stroke painted");
+ }
+ }
+}
+
+/// A live Pattern Stamp on the layer mask paints the mask, as the commit does, and leaves the
+/// layer's pixels alone.
+#[test]
+fn live_pattern_stamp_paints_the_targeted_mask() {
+ let mut s = session(64, 48, 8, "rgb");
+ paint_layer(&mut s, texture);
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ let all = [[16.0, 20.0], [40.0, 24.0]];
+ let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 12, "pattern": "Checkerboard", "target": "mask", "seed": 3});
+ let mut live = LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap();
+ live.push(&[StrokePoint::new(40.0, 24.0, 1.0)]).unwrap();
+ let shown = live.doc.clone();
+ s.execute("paint.patternStamp", opts(&all)).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ let (lv, cm) = (shown.layer(id).unwrap(), s.active().unwrap().doc.layer(id).unwrap());
+ let (lm, cmask) = (&lv.mask.as_ref().unwrap().surface, &cm.mask.as_ref().unwrap().surface);
+ let b = Rect::new(0, 0, 64, 48);
+ assert_eq!(lm.read_region(b), cmask.read_region(b), "the live mask is the committed mask");
+ assert!((0..64).any(|x| cmask.rgba(x, 22)[0] < 0.99), "the mask was painted");
+ assert_eq!(lv.surface().unwrap().read_region(b), cm.surface().unwrap().read_region(b), "pixels untouched");
+}
++
+ #[test]
+ fn remove_several_strokes_apply_as_one_job_and_one_undo_step() {
+ let mut s = square_session(8, "rgb");
+ let bg = rgba(&s, 10, 10);
+ let past = s.active().unwrap().history.past_len();
+ // Each stroke covers half of the square; together they remove it.
+ let r = s.execute("paint.remove", json!({"strokes": [[[38, 30], [45, 30]], [[47, 30], [54, 30]]], "size": 16})).unwrap();
+ assert!(r["damage"].is_array(), "{r}");
+ for (x, y) in [(41, 30), (46, 30), (51, 30)] {
+ assert!(near(rgba(&s, x, y), bg, 0.03), "({x}, {y}): {:?} vs {bg:?}", rgba(&s, x, y));
+ }
+ assert_eq!(s.active().unwrap().history.past_len(), past + 1, "one undo step for both strokes");
+ for p in [
+ json!({"strokes": [], "size": 16}),
+ json!({"strokes": "x", "size": 16}),
+ json!({"strokes": [[]], "size": 16}),
+ json!({"strokes": [[[1, 1]], "x"], "size": 16}),
+ ] {
+ assert!(s.execute("paint.remove", p).is_err());
+ }
+ }
+
+ #[test]
+ fn remove_to_a_new_layer_leaves_the_target_untouched() {
+ let mut s = square_session(8, "rgb");
+ let target = s.active().unwrap().active_layer.unwrap();
+ let bg = rgba(&s, 10, 10);
+ let square = rgba(&s, 46, 30);
+ let past = s.active().unwrap().history.past_len();
+ let r = s.execute("paint.remove", json!({"points": [[38, 30], [54, 30]], "size": 16, "newLayer": true})).unwrap();
+ let nid = LayerId(r["layer"].as_u64().expect("the new layer's id"));
+ let d = s.active().unwrap();
+ assert_eq!(d.active_layer, Some(nid), "the new layer is active");
+ assert_ne!(nid, target);
+ let order: Vec<LayerId> = d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ assert_eq!(order, vec![target, nid], "the new layer sits above the target");
+ assert_eq!(d.doc.layer(nid).unwrap().name, "Layer 1");
+ // The target keeps its pixels; the new layer carries the fill inside the hole only.
+ let old = d.doc.layer(target).unwrap().surface().unwrap();
+ assert!(near(old.rgba(46, 30), square, 0.001));
+ let new = d.doc.layer(nid).unwrap().surface().unwrap();
+ assert!(near(new.rgba(46, 30), bg, 0.03), "{:?}", new.rgba(46, 30));
+ assert_eq!(new.rgba(10, 10)[3], 0.0, "transparent away from the hole");
+ assert_eq!(d.history.past_len(), past + 1);
+ s.execute("edit.undo", json!({})).unwrap();
+ let d = s.active().unwrap();
+ assert!(d.doc.layer(nid).is_none(), "undo removes the layer");
+ assert_eq!(d.active_layer, Some(target));
+ // On an empty layer with Sample All Layers, the composite is what gets filled, onto a new layer.
+ s.execute("layer.new.layer", json!({})).unwrap();
+ let empty = s.active().unwrap().active_layer.unwrap();
+ let r = s.execute("paint.remove", json!({"points": [[38, 30], [54, 30]], "size": 16, "sampleAllLayers": true, "newLayer": true})).unwrap();
+ let nid = LayerId(r["layer"].as_u64().unwrap());
+ let d = s.active().unwrap();
+ let order: Vec<LayerId> = d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect();
+ assert_eq!(order, vec![target, empty, nid]);
+ assert!(near(d.doc.layer(nid).unwrap().surface().unwrap().rgba(46, 30), bg, 0.03));
+ assert!(near(d.doc.layer(target).unwrap().surface().unwrap().rgba(46, 30), square, 0.001));
+ }
diff --cc crates/ui-egui/src/lib.rs
index a424f459c,025c19eb7..684b8e74b
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -2261,9 -2293,11 +2293,13 @@@ mod pen_variants_tests
#[cfg(test)]
mod color_replacement_tests;
#[cfg(test)]
+ mod layer_shortcut_tests;
+ #[cfg(test)]
+mod live_retouch_tests;
+#[cfg(test)]
mod pencil_tests;
+ #[cfg(test)]
+ mod tool_shortcut_tests;
#[cfg(test)]
mod pixel_aspect_tests;
diff --cc crates/ui-egui/src/retouch_ui.rs
index fc35a6d28,a9e1241e0..78073e080
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@@ -116,10 -84,32 +116,16 @@@ pub fn finish_stroke(app: &mut Photocra
let pts = json!(points);
let (cmd, mut p): (&str, Value) = match tool {
Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type, "sampleAllLayers": o.sample_all_layers})),
- Tool::Remove => ("paint.remove", json!({"sampleAllLayers": o.sample_all_layers})),
+ Tool::Remove => {
+ if !o.remove_after_each_stroke {
+ remove_pending_add(app, points);
+ return true;
+ }
+ ("paint.remove", remove_params(&o))
+ }
Tool::MixerBrush => ("paint.mixerBrush", json!({})),
Tool::ColorReplacement => ("paint.colorReplacement", color_replacement_params(app)),
- Tool::PatternStamp => {
- let mut p = json!({
- "aligned": o.pattern_stamp_aligned,
- "impressionist": o.pattern_stamp_impressionist,
- "scale": o.pattern_stamp_scale,
- "angle": o.pattern_stamp_angle,
- });
- if o.pattern_stamp_aligned
- && let Some(ph) = app.ui.pattern_stamp_phase
- {
- p["phase"] = json!(ph);
- }
- if let Some(id) = photocraft_engine::presets::patterns::current(&app.session).or(app.session.patterns.items.first()).map(|x| x.id.clone()) {
- p["pattern"] = json!(id);
- }
- ("paint.patternStamp", p)
- }
+ Tool::PatternStamp => ("paint.patternStamp", pattern_stamp_params(app, points)),
Tool::Healing | Tool::CloneStamp => {
let Some(p) = clone_params(app) else {
// Option-click on the Mac, Alt-click on Windows.