Skip to content

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

undo/redo report the step's damage instead of recompositing the whole canvas (#810)

Elvis33LE9182f8f76d15
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 940bdf4ef..cb79ae53d 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -365,6 +365,252 @@ pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) {
st.last_damage = layers_damage(before, &st.doc, ids);
}
+/// Whether two surfaces hold identical pixels: same format and default pixel, and the same
+/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the
+/// comparison, so tile addresses cannot be reused under it.
+fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool {
+ a.format() == b.format()
+ && a.default_pixel() == b.default_pixel()
+ && a.tile_count() == b.tile_count()
+ && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb))
+}
+
+/// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical
+/// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them).
+fn blob_equal(x: &std::sync::Arc<Vec<u8>>, y: &std::sync::Arc<Vec<u8>>) -> bool {
+ std::sync::Arc::ptr_eq(x, y) || (x.len() == y.len() && x.as_slice() == y.as_slice())
+}
+
+fn blobs_equal(a: &Option<std::sync::Arc<Vec<u8>>>, b: &Option<std::sync::Arc<Vec<u8>>>) -> bool {
+ match (a, b) {
+ (None, None) => true,
+ (Some(x), Some(y)) => blob_equal(x, y),
+ _ => false,
+ }
+}
+
+/// Layer masks (also the smart-filter mask): scalars plus tile-pointer surface identity.
+fn masks_equal(a: &Option<photocraft_doc::LayerMask>, b: &Option<photocraft_doc::LayerMask>) -> bool {
+ match (a, b) {
+ (None, None) => true,
+ (Some(x), Some(y)) => {
+ x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface)
+ }
+ _ => false,
+ }
+}
+
+fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool {
+ a.text == b.text
+ && a.font_family == b.font_family
+ && a.size_pt == b.size_pt
+ && a.color == b.color
+ && a.transform == b.transform
+ && a.runs == b.runs
+ && a.paragraphs == b.paragraphs
+ && a.shape == b.shape
+ && a.orientation == b.orientation
+ && a.antialias == b.antialias
+ && a.warp == b.warp
+ && match (&a.cache, &b.cache) {
+ (None, None) => true,
+ (Some(x), Some(y)) => surfaces_equal(x, y),
+ _ => false,
+ }
+ && blobs_equal(&a.psd_raw, &b.psd_raw)
+}
+
+fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool {
+ a.filters_enabled == b.filters_enabled
+ && a.transform == b.transform
+ && a.smart_filters == b.smart_filters
+ && a.stack_mode == b.stack_mode
+ && a.perspective == b.perspective
+ && a.warp == b.warp
+ && match (&a.source, &b.source) {
+ (photocraft_doc::SmartSource::Embedded { file_name: x, bytes: xb }, photocraft_doc::SmartSource::Embedded { file_name: y, bytes: yb }) => {
+ x == y && blob_equal(xb, yb)
+ }
+ (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y,
+ _ => false,
+ }
+ && match (&a.cache, &b.cache) {
+ (None, None) => true,
+ (Some(x), Some(y)) => surfaces_equal(x, y),
+ _ => false,
+ }
+ && blobs_equal(&a.psd_raw, &b.psd_raw)
+ && masks_equal(&a.filter_mask, &b.filter_mask)
+}
+
+/// Extra alpha/spot channels (the image itself in Multichannel mode).
+fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::AlphaChannel) -> bool {
+ a.name == b.name && a.spot == b.spot && a.color == b.color && a.opacity == b.opacity && a.indicates == b.indicates && surfaces_equal(&a.surface, &b.surface)
+}
+
+/// Whether two layers render to identical pixels in place. Everything the compositor reads is
+/// compared structurally — no hashing, a hash collision would under-report damage; pixels are
+/// identified by their copy-on-write tile pointers. Group children are deliberately *not*
+/// compared here: the caller walks into them, so an edit inside a group damages only the
+/// edited child's extent, not the whole group's. The destructure is exhaustive, so a new
+/// `Layer` field fails to compile until it is classified: compared, or explicitly ignored
+/// (name, locks, label, `psd_blocks`, `psd_id`, link group — none of them composite; video
+/// bails out earlier in the walk).
+fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool {
+ let Layer {
+ id,
+ name: _,
+ visible,
+ locks: _,
+ blend,
+ opacity,
+ fill_opacity,
+ clipped,
+ mask,
+ vector_mask,
+ effects,
+ label: _,
+ content,
+ psd_blocks: _,
+ psd_id: _,
+ fill_cache,
+ link_group: _,
+ excluded_channels,
+ blend_if,
+ video: _,
+ } = a;
+ *id == b.id
+ && *visible == b.visible
+ && *blend == b.blend
+ && *opacity == b.opacity
+ && *fill_opacity == b.fill_opacity
+ && *clipped == b.clipped
+ && masks_equal(mask, &b.mask)
+ && *vector_mask == b.vector_mask
+ && *effects == b.effects
+ && *excluded_channels == b.excluded_channels
+ && *blend_if == b.blend_if
+ && match (content, &b.content) {
+ (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y),
+ // Children are walked separately; only the group's own clipping frame counts.
+ (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard,
+ (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y,
+ (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y,
+ (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y),
+ (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y,
+ (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y),
+ _ => false,
+ }
+ && match (fill_cache, &b.fill_cache) {
+ (None, None) => true,
+ (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface),
+ _ => false,
+ }
+}
+
+/// Document-level fields the compositor reads: all must match for a bounded damage claim. The
+/// destructure is exhaustive, so a new `Document` field fails to compile until it is classified
+/// here — compared when it composites, or explicitly ignored (the pixel-irrelevant allowlist:
+/// identity, name, selection, guides, paths, layer comps, annotations, automation state).
+fn doc_pixels_equal(a: &Document, b: &Document) -> bool {
+ let Document {
+ id: _,
+ name: _,
+ size,
+ resolution_dpi,
+ mode,
+ depth,
+ icc_profile,
+ layers: _,
+ channels,
+ guides: _,
+ selection: _,
+ metadata: _,
+ global_light,
+ paths: _,
+ work_path: _,
+ clipping_path: _,
+ quick_mask,
+ patterns,
+ color_table,
+ duotone,
+ layer_comps: _,
+ last_applied_comp: _,
+ last_document_state: _,
+ measurement: _,
+ notes: _,
+ text_styles: _,
+ slices: _,
+ variables: _,
+ timeline: _,
+ } = a;
+ *size == b.size
+ && resolution_dpi.to_bits() == b.resolution_dpi.to_bits()
+ && *mode == b.mode
+ && *depth == b.depth
+ && icc_profile.as_deref() == b.icc_profile.as_deref()
+ && channels.len() == b.channels.len()
+ && channels.iter().zip(&b.channels).all(|(x, y)| alpha_channels_equal(x, y))
+ && *global_light == b.global_light
+ && match (quick_mask, &b.quick_mask) {
+ (None, None) => true,
+ (Some(x), Some(y)) => alpha_channels_equal(x, y),
+ _ => false,
+ }
+ && *patterns == b.patterns
+ && *color_table == b.color_table
+ && *duotone == b.duotone
+}
+
+/// Pixels a single history step can have changed between `a` and `b` (the documents on either
+/// side of an undo or redo): the union of the change bounds of every layer whose pixels
+/// differ, so undoing a local edit recomposites only that area instead of the whole canvas.
+/// `None` (composite everything, as before) when the step touched anything the layer walk
+/// cannot bound: document-level fields the compositor reads (canvas size, mode, depth,
+/// profile, global light, patterns, channels, palettes), the layer structure (order,
+/// additions, removals, kind changes), layer properties that reach outside their own bounds
+/// (clipping, excluded channels — what `layer.setProps` already reports as unbounded), and
+/// video layers.
+pub fn step_damage(a: &Document, b: &Document) -> Option<Rect> {
+ if !doc_pixels_equal(a, b) {
+ return None;
+ }
+ fn walk(xs: &[Layer], ys: &[Layer], a: &Document, b: &Document, out: &mut Rect) -> bool {
+ if xs.len() != ys.len() {
+ return false;
+ }
+ for (x, y) in xs.iter().zip(ys) {
+ if x.id != y.id || x.video.is_some() || y.video.is_some() {
+ return false;
+ }
+ // Clipping and channel exclusion change how *other* layers render, outside this
+ // layer's own bounds; they have no bounded damage.
+ if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels {
+ return false;
+ }
+ if !layer_pixels_equal(x, y) {
+ // Both sides' extents: a move changes pixels where it left and where it landed.
+ let (Some(bx), Some(by)) = (photocraft_compose::change_bounds(x, a.bounds()), photocraft_compose::change_bounds(y, b.bounds())) else {
+ return false;
+ };
+ *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) };
+ }
+ match (x.children(), y.children()) {
+ (Some(xc), Some(yc)) => {
+ if !walk(xc, yc, a, b, out) {
+ return false;
+ }
+ }
+ (None, None) => {}
+ _ => return false,
+ }
+ }
+ true
+ }
+ let mut out = Rect::EMPTY;
+ if walk(&a.layers, &b.layers, a, b, &mut out) { Some(out) } else { None }
+}
+
/// Content bounds used by Align/Distribute: the layer's pixels (type and shape layers use their
/// rendered pixels), or the union of a group's children. Fill and adjustment layers have none.
pub fn layer_bounds(l: &Layer) -> Option<Rect> {
@@ -1427,6 +1673,75 @@ mod tests {
}
}
+ #[test]
+ fn undo_and_redo_report_only_the_edited_area() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ select_all(&mut s, &[a]);
+ // A pixel edit on one layer is bounded by that layer's extent on both sides.
+ s.edit("paint", |doc, _| {
+ doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(12, 12, 14, 14), &[0.0, 0.0, 1.0, 1.0]);
+ Ok(())
+ })
+ .unwrap();
+ s.undo();
+ assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)));
+ s.redo();
+ assert_eq!(damage(&s), Some(Rect::new(10, 10, 20, 20)));
+ // A move reports where the layer was and where it landed.
+ s.execute("layer.translate", json!({"dx": 5, "dy": 0})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)), "union of where the layer was and is");
+ s.redo();
+ assert_eq!(damage(&s), Some(Rect::new(10, 10, 25, 20)));
+ }
+
+ #[test]
+ fn undo_of_document_wide_steps_still_composites_everything() {
+ let mut s = session(8);
+ let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ // A canvas change has no bounded damage.
+ s.execute("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 25})).unwrap();
+ assert_ne!(doc(&s).size, photocraft_doc::Size::new(100, 80));
+ s.undo();
+ assert_eq!(damage(&s), None, "a size change recomposites the whole canvas");
+ // A structural change (a layer removed and restored) neither.
+ let b = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[b]);
+ s.execute("layer.delete", json!({})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), None);
+ }
+
+ #[test]
+ fn undo_of_compositor_read_document_fields_composites_everything() {
+ let mut s = session(8);
+ let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ // Global Light changes every effect's angle across the document.
+ s.execute("layer.layerStyle.globalLight", json!({"angle": 90.0})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), None, "a global-light change recomposites everything");
+ // A mode change that keeps the pixel format (RGB → Indexed maps to RGB) neither.
+ s.execute("image.mode.indexedColor", json!({})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), None, "a mode change recomposites everything");
+ }
+
+ #[test]
+ fn undo_of_clipping_or_channel_exclusion_composites_everything() {
+ let mut s = session(8);
+ let _ = rect_layer(&mut s, Rect::new(10, 10, 20, 20));
+ let b = rect_layer(&mut s, Rect::new(12, 12, 30, 30));
+ select_all(&mut s, &[b]);
+ // Clipping reaches the layers clipped above, outside this layer's bounds.
+ s.execute("layer.setProps", json!({"clipped": true})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), None, "a clipping change recomposites everything");
+ s.execute("layer.setProps", json!({"channels": [true, false, true]})).unwrap();
+ s.undo();
+ assert_eq!(damage(&s), None, "an excluded-channel change recomposites everything");
+ }
+
#[test]
fn linked_layers_move_together_and_undo() {
for depth in [8, 16, 32] {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 46cfd37f4..d7b93a52e 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -500,10 +500,13 @@ impl Session {
st.coalesce = None;
match st.history.undo(st.doc.clone()) {
Some((d, layers)) => {
+ // Pixels this step can have touched, so the canvas recomposites only that
+ // (it recomposited everything before).
+ let damage = layer_multi_cmds::step_damage(&d, &st.doc);
st.doc = d;
restore_target(st, layers);
st.revision += 1;
- st.last_damage = None;
+ st.last_damage = damage;
true
}
None => false,
@@ -518,10 +521,11 @@ impl Session {
st.coalesce = None;
match st.history.redo(st.doc.clone()) {
Some((d, layers)) => {
+ let damage = layer_multi_cmds::step_damage(&st.doc, &d);
st.doc = d;
restore_target(st, layers);
st.revision += 1;
- st.last_damage = None;
+ st.last_damage = damage;
true
}
None => false,
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index a77562d1d..9deeea251 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -557,8 +557,10 @@ fn damage_is_reported_for_strokes_only() {
s.execute("paint.stroke", json!({"points": [[10, 10], [20, 10]], "size": 4})).unwrap();
let d = s.active().unwrap().last_damage.unwrap();
assert!(d.contains(15, 10) && d.width() < 30);
+ // Undo reports the same bounded area back, not a whole-canvas recomposite.
s.execute("edit.undo", json!({})).unwrap();
- assert_eq!(s.active().unwrap().last_damage, None);
+ let d = s.active().unwrap().last_damage.unwrap();
+ assert!(d.contains(15, 10) && d.width() < 30);
}
#[test]