From b4487ee599980917b0407a165c484fd003bba9db Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:53:23 -0600 Subject: [PATCH 01/14] fix(paint): a bucket fill clicked on transparency fills the transparency in full (#11311) --- crates/algo/src/paint.rs | 104 +++++++++++++++++++++- crates/engine/src/cmd/paint_cmds/tests.rs | 74 +++++++++++++++ 2 files changed, 174 insertions(+), 4 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 4862304786..2070a59d42 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,7 +63,23 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. +/// `o`, the pixel `d` with `c` composited at coverage `k`, with what is left of `d`'s transparency +/// filled by `c` up to coverage `full` (≥ `k`) as well, behind the colour already there: the +/// transparent part of the pixel takes the fill at `full` while its colour keeps the softer `k`. +fn fill_transparency(o: [f32; 4], d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { + let add = ((full - k).max(0.0) * c[3].clamp(0.0, 1.0) * (1.0 - d[3]).max(0.0)).min((1.0 - o[3]).max(0.0)); + let a = o[3] + add; + if add.is_nan() || add <= 0.0 || a <= 0.0 { + return o; + } + let mix = |i: usize| (o[i] * o[3] + c[i] * add) / a; + [mix(0), mix(1), mix(2), a] +} + +/// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, +/// a covered pixel's transparency takes the fill at that coverage instead (see +/// [`fill_transparency`]); Lock Transparent Pixels and Clear ignore it. +#[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, area: Rect, @@ -72,6 +88,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, + transparency: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. @@ -99,7 +116,11 @@ fn composite_area( let d = photocraft_raster::to_rgba(&fmt, px); let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), + FillMode::Blend(m) => { + let c = color(x, y); + let o = blend::composite(m, d, c, k); + transparency.map_or(o, |full| fill_transparency(o, d, c, k, full(x, y))) + } // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], @@ -165,6 +186,7 @@ pub fn paint_gradient( }, lock_transparency, None, + None, ); } @@ -227,8 +249,16 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; + // Clicked on transparency: the flood fills empty pixels, and the empty part of the pixels + // along its anti-aliased edge (the soft rim a cleared selection leaves) is that same empty + // area, so it is filled in full rather than left as a semi-transparent ring (#11311). + let at_seed = usize::try_from(seed.1 - area.y0) + .ok() + .and_then(|y| y.checked_mul(area.width() as usize)) + .and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?)); + let empty_seed = at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); drop(img); - bucket_fill_region_inks(s, ®ion, opacity, selection, lock_transparency, src, inks, mode); + fill_region(s, ®ion, opacity, selection, lock_transparency, src, inks, mode, empty_seed); true } @@ -256,10 +286,31 @@ pub fn bucket_fill_region_inks( src: impl Fn(i32, i32) -> [f32; 4] + Sync, inks: Option<[f32; 4]>, mode: FillMode, +) { + fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); +} + +/// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region +/// touches takes the fill at the full opacity and selection coverage, while the region's +/// anti-aliasing still softens the colour over what is already there. Opaque pixels come out +/// exactly as without it. +#[allow(clippy::too_many_arguments)] +fn fill_region( + s: &mut Surface, + region: &crate::selection::Region, + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + src: impl Fn(i32, i32) -> [f32; 4] + Sync, + inks: Option<[f32; 4]>, + mode: FillMode, + fill_empty: bool, ) { // Composite only over the filled region's box. let b = region.bbox; - composite_area(s, b, mode, |x, y| region.at(x, y) * opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)), src, lock_transparency, inks); + let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); + let empty: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if fill_empty { Some(&strength) } else { None }; + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, empty); } #[cfg(test)] @@ -344,6 +395,51 @@ mod tests { assert_eq!(s.rgba(-4, 4), [0.0; 4], "outside the region"); } + /// #11311: flooding transparency with anti-aliasing fills the empty part of the region's edge + /// pixels at the fill's opacity, so the edge is no semi-transparent ring; opaque pixels the + /// anti-aliasing reaches blend exactly as before. + #[test] + fn bucket_on_transparency_fills_the_edge_pixels_in_full() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for (opaque, opacity) in [([1.0, 1.0, 1.0, 1.0], 1.0), ([1.0, 1.0, 1.0, 1.0], 0.5), ([1.0, 0.0, 0.0, 1.0], 1.0)] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 8, 1), &opaque); + // The same region filled without the rule: what the bucket used to do. + let mut before = s.clone(); + let img = crate::selection::rgba8_image(&before, a); + let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut before, ®ion, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)); + assert!(before.rgba(3, 0)[3] < opacity * 0.97, "{fmt:?}: the old edge was semi-transparent: {:?}", before.rgba(3, 0)); + + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + for x in 0..4 { + let p = s.rgba(x, 0); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3) && (p[3] - opacity).abs() < 3e-3, "{fmt:?} {opaque:?} at {x}: {p:?}"); + } + for x in 4..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} {opaque:?} at {x}: opaque pixels blend as before"); + } + assert!(s.rgba(4, 0)[3] > 0.999); + } + } + } + + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent + /// neighbour along the edge keeps its own transparency (it belongs to another area). + #[test] + fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() { + let a = Rect::new(0, 0, 8, 1); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + let edge = s.rgba(3, 0)[3]; + assert!(edge > 0.5 && edge < 0.6, "only the anti-aliased coverage lands: {edge}"); + assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region"); + } + /// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %). #[test] fn bucket_mode_blends_or_clears() { diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index ba30e9d719..835e450d83 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -328,3 +328,77 @@ fn bucket_and_gradient_reject_non_numeric_opacity_without_editing() { assert!((px(&s, 5, 5)[0] - 128.0 / 255.0).abs() < 0.01, "{cmd}: null opacity is 100%"); } } + +/// #11311: a white layer (the Background made a normal layer), a selection cleared to +/// transparency, Deselect, then the Paint Bucket clicked in the hole with white at 100 %. Returns +/// the session after the fill and the layer's pixels right after the clear. +fn clear_then_bucket(depth: u32, selection: Value, bucket_aa: bool) -> (Session, Vec<[f32; 4]>) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layerFromBackground", json!({})).unwrap(); + s.execute("select.rect", selection).unwrap(); + s.execute("edit.clear", json!({})).unwrap(); + let cleared = layer_rgba(&s); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("paint.bucket", json!({"x": 60, "y": 50, "color": "#ffffff", "antiAlias": bucket_aa})).unwrap(); + (s, cleared) +} + +/// The active layer's pixels over the canvas, row by row. +fn layer_rgba(s: &Session) -> Vec<[f32; 4]> { + let d = s.active().unwrap(); + let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap(); + let b = d.doc.bounds(); + (b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| surf.rgba(x, y)).collect() +} + +/// The first `n` pixels (as `x, y, rgba`) that aren't opaque white at 8 bits. +fn not_white(px: &[[f32; 4]], width: usize, n: usize) -> Vec<(usize, usize, [f32; 4])> { + let is_white = |p: &[f32; 4]| p.iter().all(|c| (c.clamp(0.0, 1.0) * 255.0).round() == 255.0); + px.iter().enumerate().filter(|(_, p)| !is_white(p)).take(n).map(|(i, p)| (i % width, i / width, *p)).collect() +} + +fn assert_all_white(s: &Session, what: &str) { + let doc = &s.active().unwrap().doc; + let width = doc.bounds().width() as usize; + let layer = layer_rgba(s); + assert_eq!(not_white(&layer, width, 8), vec![], "{what}: layer pixels left after the fill"); + let composite = photocraft_compose::render(doc, doc.bounds()).px.clone(); + assert_eq!(composite.len(), layer.len()); + assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill"); +} + +/// #11311: after clearing an anti-aliased selection and bucket-filling the hole white at 100 %, +/// every pixel of the layer and of the composite is opaque white. The clear itself is right: it +/// leaves a soft rim of white at partial alpha around a fully transparent hole. The bucket used to +/// leave that rim (and its own anti-aliased edge) semi-transparent: a grey ring over the checkerboard. +#[test] +fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { + for depth in [8, 16, 32] { + let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true}); + let (s, cleared) = clear_then_bucket(depth, ellipse, true); + // A transparent hole (its RGB zeroed) inside a rim of straight white at partial alpha, + // which the bucket's similarity test (RGB 255 away from the hole's 0) leaves out. + assert_eq!(cleared[50 * 120 + 60], [0.0; 4], "depth {depth}: the hole is empty"); + let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect(); + assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim"); + assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); + assert_all_white(&s, &format!("depth {depth}, anti-aliased ellipse")); + } +} + +/// Controls for #11311: a hard-edged selection leaves no soft rim, but the bucket's own +/// anti-aliasing used to leave the hole's edge pixels partly transparent too, so hard edges end +/// white as well; with neither anti-aliased (the case that was always right) it stays white. +#[test] +fn bucket_after_clearing_a_hard_selection_leaves_no_ring() { + let hard_ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": false}); + let rect = json!({"x": 30, "y": 20, "width": 60, "height": 60}); + for depth in [8, 16, 32] { + for (selection, bucket_aa) in [(hard_ellipse.clone(), true), (rect.clone(), true), (rect.clone(), false)] { + let (s, cleared) = clear_then_bucket(depth, selection.clone(), bucket_aa); + assert!(cleared.iter().all(|p| p[3] == 0.0 || p[3] == 1.0), "depth {depth} {selection}: a hard clear leaves no rim"); + assert_all_white(&s, &format!("depth {depth} {selection}, bucket antiAlias {bucket_aa}")); + } + } +} From 87e6bf6bfac1594476594194b09a19cefc8d60f8 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:06:16 -0600 Subject: [PATCH 02/14] fix(paint): write the picked CMYK inks at a transparent fill's made-opaque edge (#11311) --- crates/algo/src/paint.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 2070a59d42..d7a1139caf 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -126,11 +126,14 @@ fn composite_area( FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], }; from_rgba_into(&fmt, o, &mut enc); - // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it is. + // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it + // is — and pixels the fill made fully opaque out of transparency, whose colour is the + // fill alone even though their coverage is partial (the edge of a bucket fill on + // transparency, #11354 review). A pixel that held colour keeps its blended encoding. if let Some(i) = inks && fmt.mode == photocraft_color::ColorMode::Cmyk && mode == FillMode::Blend(BlendMode::Normal) - && k >= 1.0 + && (k >= 1.0 || (d[3] <= 0.0 && o[3] >= 1.0)) { enc[..4].copy_from_slice(&i); } @@ -426,6 +429,37 @@ mod tests { } } + /// #11354 review: on a CMYK target, the edge pixels a transparent-seed bucket makes + /// opaque take the picked inks like the fully covered interior — their colour is the + /// fill alone. A partially transparent destination the fill touches keeps the blended + /// colour it already had, so its inks stay the conversion of that blend. + #[test] + fn bucket_on_transparency_writes_the_picked_cmyk_inks_at_the_edge() { + let a = Rect::new(0, 0, 8, 1); + let inks = [1.0f32, 0.0, 0.0, 0.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(inks).map(|c| c.clamp(0.0, 1.0)); + let src = |_, _| [rgb[0], rgb[1], rgb[2], 1.0]; + let raw = |s: &Surface, x: i32| -> Vec { s.read_region(Rect::new(x, 0, x + 1, 1)).into_iter().take(4).collect() }; + let is_inks = |got: &[f32]| got.iter().zip(inks).all(|(a, b)| (a - b).abs() < 0.02); + + // Transparent run against opaque white: x=3 is the anti-aliased edge (coverage < 1). + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + assert!(is_inks(&raw(&s, 1)), "fully covered: {:?}", raw(&s, 1)); + assert!(is_inks(&raw(&s, 3)), "the made-opaque edge takes the picked inks: {:?}", raw(&s, 3)); + + // The edge pixel holds white at half alpha instead: the fill raises its alpha, + // but the colour is a blend, so the picked inks do not replace it. + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(Rect::new(3, 0, 4, 1), &[0.0, 0.0, 0.0, 0.0, 0.5]); + s.fill_rect(Rect::new(4, 0, 8, 1), &[0.0, 0.0, 0.0, 0.0, 1.0]); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, 1.0, None, false, src, Some(inks), FillMode::Blend(BlendMode::Normal))); + let edge = s.rgba(3, 0); + assert!(edge[3] > 0.5, "the fill raised the partial pixel's alpha: {edge:?}"); + assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); + } + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent /// neighbour along the edge keeps its own transparency (it belongs to another area). #[test] From 064dcd7fa6b154f997debebc5a6a2ffc7e8ce1ed Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:59:40 -0500 Subject: [PATCH 03/14] fix(engine): count markers keep their coordinates through Image Size, Canvas Size and Image Rotation (#11762) Count markers were mapped with the pixels by Image Size, Canvas Size and Image Rotation. In the reference application they keep their document coordinates, also where they end up off the canvas. These commands now put the count points back after mapping the rest of the geometry (keeping_count_points); notes, the ruler, paths, slices and guides still follow the image, and Crop (including its straighten turn), Perspective Crop, Trim, Reveal All and the artboard paths are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/canvas_geom.rs | 12 ++++ crates/engine/src/cmd.rs | 4 +- crates/engine/src/cmd/count_resize_tests.rs | 64 +++++++++++++++++++++ crates/engine/src/cmd/image_cmds.rs | 6 +- crates/engine/src/cmd/mode_cmds.rs | 12 +++- 5 files changed, 93 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/count_resize_tests.rs diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 93bc4654b9..33e1ad443a 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -287,6 +287,18 @@ pub(crate) fn transform_doc_marks(doc: &mut Document, a: &Affine) { } } +/// Runs `f` (Image Size, Canvas Size, Image Rotation) and puts the count points back where they +/// were: they keep their document coordinates, also where they end up off the canvas, as in the +/// reference application (#11762). Other marks follow the map as `f` applies it. +pub(crate) fn keeping_count_points(doc: &mut Document, f: impl FnOnce(&mut Document) -> R) -> R { + let saved: Vec> = doc.measurement.count_groups.iter().map(|g| g.points.clone()).collect(); + let r = f(doc); + for (g, points) in doc.measurement.count_groups.iter_mut().zip(saved) { + g.points = points; + } + r +} + /// Applies `a` to all non-pixel geometry of the document (layers and document marks). pub(crate) fn transform_geometry(doc: &mut Document, a: &Affine) { let dpi = doc.resolution_dpi; diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4c911e6be0..63741f7808 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -37,7 +37,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": POINT[0], "y": POINT[1]})).unwrap(); + s.execute("notes.add", json!({"x": 100, "y": 100})).unwrap(); + s +} + +fn count_point(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.measurement.count_groups[0].points[0] +} + +fn note(s: &Session) -> [f64; 2] { + s.active().unwrap().doc.notes[0].position +} + +#[test] +fn count_points_keep_their_coordinates() { + let steps: [(&str, Value); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200})), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})), + ("image.imageRotation.90cw", json!({})), + ("image.imageRotation.90ccw", json!({})), + ("image.imageRotation.180", json!({})), + ("image.imageRotation.flipCanvasHorizontal", json!({})), + ("image.imageRotation.flipCanvasVertical", json!({})), + ("image.rotation.arbitrary", json!({"angle": 30})), + ]; + for (cmd, p) in steps { + let mut s = doc(); + let before = note(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(count_point(&s), POINT, "{cmd}"); + assert_ne!(note(&s), before, "{cmd}: notes still follow the image"); + s.undo(); + assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); + } +} + +#[test] +fn all_three_in_a_row_leave_the_point_where_it_was() { + let mut s = doc(); + s.execute("image.imageSize", json!({"width": 300, "height": 200})).unwrap(); + s.execute("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})).unwrap(); + s.execute("image.imageRotation.90cw", json!({})).unwrap(); + assert_eq!(count_point(&s), POINT); +} + +#[test] +fn crop_still_moves_count_points() { + let mut s = doc(); + s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); + assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); +} diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index fa6a50e0a1..436935a5ec 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -293,7 +293,7 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; - resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles) + crate::canvas_geom::keeping_count_points(doc, |doc| resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). let size = s.active().ok_or(EngineError::NoDocument)?.doc.size; @@ -689,7 +689,7 @@ fn canvas_size(s: &mut Session, p: &Value) -> Result { let ext = extension_color(s, p); s.set_sampler_map(photocraft_geom::Affine::translate(f64::from(dx), f64::from(dy))); s.edit("Canvas Size", |doc, _| { - translate_doc(doc, "image.canvasSize", dx, dy)?; + crate::canvas_geom::keeping_count_points(doc, |doc| translate_doc(doc, "image.canvasSize", dx, dy))?; doc.size = Size::new(nw, nh); if nw > ow as u32 || nh > oh as u32 { drop_fill_caches(&mut doc.layers); @@ -1015,7 +1015,7 @@ fn rotated_crop(s: &mut Session, r: Rect, angle: f64, delete: bool, content_awar Ok(()) })?; } - crate::mode_cmds::rotate_arbitrary(s, &json!({"angle": angle, "direction": "ccw"}))?; + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": angle, "direction": "ccw"}), false)?; // Color Sampler points follow the crop's origin shift too (the rotation moved them above). s.set_sampler_map(crop_target.sampler_map(target)); let extension = s.tools.background; diff --git a/crates/engine/src/cmd/mode_cmds.rs b/crates/engine/src/cmd/mode_cmds.rs index ea6504f7a8..320d87552d 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -62,6 +62,12 @@ pub fn rotated_size(size: Size, deg: f64) -> Size { } pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { + rotate_arbitrary_with(s, p, true) +} + +/// [`rotate_arbitrary`]; `keep_counts` leaves the count points where they were (Image Rotation, +/// #11762). The Crop tool's straighten turn moves them with the image, as before. +pub(crate) fn rotate_arbitrary_with(s: &mut Session, p: &Value, keep_counts: bool) -> Result { const CMD: &str = "image.rotation.arbitrary"; // At full precision: an f32 angle can grow the canvas 1 px past what `rotated_size` gives callers. let angle = p.get("angle").and_then(Value::as_f64).unwrap_or(0.0); @@ -129,7 +135,11 @@ pub(crate) fn rotate_arbitrary(s: &mut Session, p: &Value) -> Result { // What Free Transform leaves alone: unlinked vector masks, gradient angles, artboards… crate::canvas_geom::transform_layer_geometry(l, &a, false, dpi); } - crate::canvas_geom::transform_doc_marks(doc, &a); + if keep_counts { + crate::canvas_geom::keeping_count_points(doc, |doc| crate::canvas_geom::transform_doc_marks(doc, &a)); + } else { + crate::canvas_geom::transform_doc_marks(doc, &a); + } for ch in doc.channels.iter_mut().chain(doc.quick_mask.as_mut()) { ch.surface = crate::transform_cmds::warp_gray(&ch.surface, &h, interp)?; } From 8abea6ca27231e0a47adf5d36e9aa36bfd88bf59 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:56:04 -0500 Subject: [PATCH 04/14] Ruler Straighten with crop turns count points with the image; the test checks each note position Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/analysis_cmds.rs | 3 +- crates/engine/src/cmd/count_resize_tests.rs | 36 ++++++++++++++------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index d9d7d1510c..ed6dba0254 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -728,7 +728,8 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height)); compound(s, "Straighten", |s| { if crop { - s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?; + // Count points turn with the image here, since the crop after it moves them too. + crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": rot, "direction": "cw"}), false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index 48b08db27e..32f3562aa4 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -26,22 +26,24 @@ fn note(s: &Session) -> [f64; 2] { #[test] fn count_points_keep_their_coordinates() { - let steps: [(&str, Value); 8] = [ - ("image.imageSize", json!({"width": 300, "height": 200})), - ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"})), - ("image.imageRotation.90cw", json!({})), - ("image.imageRotation.90ccw", json!({})), - ("image.imageRotation.180", json!({})), - ("image.imageRotation.flipCanvasHorizontal", json!({})), - ("image.imageRotation.flipCanvasVertical", json!({})), - ("image.rotation.arbitrary", json!({"angle": 30})), + // The note at [100, 100] on the 600×400 canvas, where each command moves it. + let steps: [(&str, Value, [f64; 2]); 8] = [ + ("image.imageSize", json!({"width": 300, "height": 200}), [50.0, 50.0]), + ("image.canvasSize", json!({"width": 400, "height": 300, "anchor": "center"}), [0.0, 50.0]), + ("image.imageRotation.90cw", json!({}), [300.0, 100.0]), + ("image.imageRotation.90ccw", json!({}), [100.0, 500.0]), + ("image.imageRotation.180", json!({}), [500.0, 300.0]), + ("image.imageRotation.flipCanvasHorizontal", json!({}), [500.0, 100.0]), + ("image.imageRotation.flipCanvasVertical", json!({}), [100.0, 300.0]), + ("image.rotation.arbitrary", json!({"angle": 30}), [236.794_919_243_112_3, 136.897_459_621_556_2]), ]; - for (cmd, p) in steps { + for (cmd, p, moved) in steps { let mut s = doc(); let before = note(&s); s.execute(cmd, p).unwrap(); assert_eq!(count_point(&s), POINT, "{cmd}"); - assert_ne!(note(&s), before, "{cmd}: notes still follow the image"); + let n = note(&s); + assert!((n[0] - moved[0]).abs() < 1e-6 && (n[1] - moved[1]).abs() < 1e-6, "{cmd}: note at {n:?}, expected {moved:?}"); s.undo(); assert_eq!((count_point(&s), note(&s)), (POINT, before), "{cmd}: undo"); } @@ -62,3 +64,15 @@ fn crop_still_moves_count_points() { s.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200})).unwrap(); assert_ne!(count_point(&s), POINT, "not measured: Crop keeps today's behaviour"); } + +#[test] +fn ruler_straighten_with_crop_moves_count_points_with_the_image() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); + let (c, n) = (count_point(&s), note(&s)); + assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); +} From d3fcccbe5e2fbc6afdbe93911e90b212e9ed216d Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:40:49 +0100 Subject: [PATCH 05/14] =?UTF-8?q?Actions:=20map=20Layer=20=E2=80=BA=20New?= =?UTF-8?q?=20=E2=80=BA=20Frame=20from=20Layers=20(#10723)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Make of class `framedGroupSection` with `From` = a layer by name loads as `layer.new.frameFromLayers` on that layer. The recorded descriptor, session ids included, saves back byte for byte while the step still frames the same layer with the same name; native steps write the measured keys without the session ids. frameFromLayers sized the frame from the selected layers even when given a `layer`, while the grouping it runs takes in only that layer; the frame now fits the given layer. --- crates/engine/src/cmd/atn_cmds.rs | 4 + crates/engine/src/cmd/atn_cmds/events.rs | 1 + .../src/cmd/atn_cmds/frame_section_tests.rs | 238 ++++++++++++++++++ .../src/cmd/atn_cmds/steps_frame_section.rs | 121 +++++++++ crates/engine/src/cmd/atn_cmds/steps_make.rs | 7 + crates/engine/src/cmd/atn_cmds/tests.rs | 1 + crates/engine/src/cmd/frame_cmds.rs | 5 +- docs/atn.md | 16 +- 8 files changed, 391 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/cmd/atn_cmds/frame_section_tests.rs create mode 100644 crates/engine/src/cmd/atn_cmds/steps_frame_section.rs diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 0e90e5d3dc..22e859ebd7 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -43,6 +43,7 @@ mod steps_direct_adjustments; mod steps_distort; mod steps_doc; mod steps_droplet; +mod steps_frame_section; mod steps_gallery; mod steps_gradient; mod steps_image; @@ -193,5 +194,8 @@ mod selection_tests; #[cfg(test)] mod render_tests; +#[cfg(test)] +mod frame_section_tests; + #[cfg(test)] mod recorded_tools_tests; diff --git a/crates/engine/src/cmd/atn_cmds/events.rs b/crates/engine/src/cmd/atn_cmds/events.rs index 2736c87b94..43d520df6e 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -855,6 +855,7 @@ pub(super) const EVENTS: &[Event] = &[ "image.calculations", "type.convertToShape", "type.createWorkPath", + super::steps_frame_section::COMMAND, "layer.new.layer", "layer.layerStyle.createLayer", "layer.new.group", diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs new file mode 100644 index 0000000000..396ba420a8 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -0,0 +1,238 @@ +//! #10723: Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection` +//! (`docs/atn.md`, "Recorded through the menus"). + +use super::*; +use photocraft_doc::{Layer, LayerId}; +use photocraft_geom::Rect; + +const FRAME: &str = "layer.new.frameFromLayers"; +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// `From`: the layer `name`, by name. +fn by_name(name: &str) -> D { + D::Reference(vec![ReferenceItem::Name { class: class("Lyr "), name: UnicodeString::new_nul(name) }]) +} + +/// The measured step, session ids included, built here independently of the converter. +fn recorded(from: D, name: &str) -> Descriptor { + Descriptor::new("null") + .with("null", D::Reference(vec![ReferenceItem::Class(class("framedGroupSection"))])) + .with("From", from) + .with("layerSectionStart", D::Integer(4)) + .with("layerSectionEnd", D::Integer(5)) + .with("Nm ", D::Text(UnicodeString::new_nul(name))) +} + +/// `d` without the keys `drop`. +fn without(mut d: Descriptor, drop: &[&str]) -> Descriptor { + d.items.retain(|(k, _)| !drop.iter().any(|key| k.is(key))); + d +} + +/// The step PhotoCraft writes: the measured keys without the session ids. +fn canonical(from: D, name: Option<&str>) -> Descriptor { + let d = without(recorded(from, name.unwrap_or("")), &["layerSectionStart", "layerSectionEnd"]); + if name.is_some() { d } else { without(d, &["Nm "]) } +} + +/// The target layer, the `From` of a step recorded in PhotoCraft without a layer of its own. +fn target_layer() -> D { + D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Trgt") }]) +} + +/// Load the Make steps holding `ds` as action "A" through `actions.load`. +fn load(ds: Vec) -> (Session, Value) { + let items = ds.into_iter().map(|d| AtnItem { event: AtnEvent::Code(*b"Mk "), dictionary: b"Make".to_vec(), descriptor: Some(d), ..Default::default() }); + let file = AtnFile { + name: UnicodeString::new_nul("Frames"), + actions: vec![AtnAction { name: UnicodeString::new_nul("A"), items: items.collect(), ..Default::default() }], + ..Default::default() + }; + let mut s = Session::new(); + let r = s.execute("actions.load", json!({"data": photocraft_paint::tile::b64_encode(&atn::write(&file).unwrap())})).unwrap(); + (s, r) +} + +/// The descriptor of the first step of action "A" as `actions.save` writes it. +fn saved(s: &mut Session) -> Option> { + let r = s.execute("actions.save", json!({"action": "A"})).unwrap(); + assert_eq!(r["skipped"], json!([]), "{r}"); + let mut items = atn::parse(&photocraft_paint::tile::b64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap().actions.remove(0).items; + assert_eq!(items[0].event, AtnEvent::Code(*b"Mk ")); + items.remove(0).descriptor.as_ref().map(Descriptor::to_bytes) +} + +/// The descriptor a native Frame from Layers step with `p` saves as, if it saves. +fn exported(p: &Value) -> Option { + export_item(FRAME, p, "S").and_then(|item| item.descriptor) +} + +/// A 100 × 80 document with "Photo" (pixels at (10, 15)–(40, 45)) under "Other" (pixels at +/// (60, 5)–(90, 25)), "Other" selected. +fn two_layers(s: &mut Session) -> (LayerId, LayerId) { + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + let mut add = |name: &str, r: Rect| { + s.edit(name, |doc, active| { + let fmt = doc.pixel_format(); + let mut l = Layer::raster(name, fmt); + l.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let id = doc.insert_above(None, l); + *active = Some(id); + Ok(id) + }) + .unwrap() + }; + let photo = add("Photo", Rect::new(10, 15, 40, 45)); + let other = add("Other", Rect::new(60, 5, 90, 25)); + s.execute("layer.select", json!({"layer": other.0, "mode": "replace"})).unwrap(); + (photo, other) +} + +/// The frame layers named `name`, as (group id, frame `[x, y, w, h]`). +fn frames(s: &Session, name: &str) -> Vec<(LayerId, [f64; 4])> { + let doc = &s.active().unwrap().doc; + doc.walk() + .into_iter() + .filter(|(_, _, l)| l.name == name) + .filter_map(|(_, _, l)| l.frame.as_ref().map(|f| (l.id, [f.transform.m[4], f.transform.m[5], f.transform.m[0], f.transform.m[3]]))) + .collect() +} + +/// Recorded steps load with the exact layer and name and save back byte for byte: the measured +/// form, another key order, no session ids, no name, and the target-layer form. +#[test] +fn recorded_steps_load_and_save_back_unchanged() { + let mut reordered = recorded(by_name("Photo"), "Frame 1"); + reordered.items.reverse(); + let cases = [ + (recorded(by_name("Photo"), "Frame 1"), json!({"layer": "Photo", "name": "Frame 1"})), + (reordered, json!({"layer": "Photo", "name": "Frame 1"})), + (without(recorded(by_name("Ébène"), "Cadre"), &["layerSectionStart", "layerSectionEnd"]), json!({"layer": "Ébène", "name": "Cadre"})), + (without(recorded(by_name("Photo"), ""), &["Nm "]), json!({"layer": "Photo"})), + (recorded(by_name("Photo"), ""), json!({"layer": "Photo", "name": ""})), + (canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + ]; + for (d, params) in cases { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"], json!([]), "{r}"); + let (id, p) = &s.actions.list[0].steps[0]; + let mut p = p.clone(); + p.as_object_mut().unwrap().remove(SOURCE); + assert_eq!((id.as_str(), &p), (FRAME, ¶ms)); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step frames the layer it names, not the selected one: the frame fits that layer's +/// pixels, the other layer stays where it was, and one Undo takes the frame back. +#[test] +fn a_loaded_step_frames_the_named_layer_and_undoes() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let (photo, other) = two_layers(&mut s); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); + s.execute("history.undo", json!({})).unwrap(); + assert!(frames(&s, "Frame 1").is_empty()); + let doc = &s.active().unwrap().doc; + assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other)); +} + +/// Without a layer of its own the command still frames the selected layers. +#[test] +fn without_a_layer_the_selected_layers_are_framed() { + let mut s = Session::new(); + let (photo, other) = two_layers(&mut s); + s.execute(FRAME, json!({"name": "Frame 1"})).unwrap(); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[60.0, 5.0, 30.0, 20.0]]); + let doc = &s.active().unwrap().doc; + assert!(doc.layer(other).is_none() && doc.layers.iter().any(|l| l.id == photo)); +} + +/// A step recorded in PhotoCraft writes the measured keys without the session ids: the layer by +/// name (the target layer without one) and `Nm ` for a name that isn't blank. It loads back to +/// the same settings. +#[test] +fn native_steps_save_the_measured_keys() { + for (p, d, back) in [ + (json!({"layer": "Photo", "name": "Frame 1"}), canonical(by_name("Photo"), Some("Frame 1")), json!({"layer": "Photo", "name": "Frame 1"})), + (json!({"layer": "Photo"}), canonical(by_name("Photo"), None), json!({"layer": "Photo"})), + (json!({"name": "Frame 1"}), canonical(target_layer(), Some("Frame 1")), json!({"name": "Frame 1"})), + (json!({"name": " ", "layer": null}), canonical(target_layer(), None), json!({})), + (json!({}), canonical(target_layer(), None), json!({})), + ] { + assert_eq!(exported(&p), Some(d.clone()), "{p}"); + let (s, _) = load(vec![d]); + assert_eq!(s.actions.list[0].steps[0], (FRAME.to_string(), back), "{p}"); + } +} + +/// A native step the event can't hold is refused: a layer by id or selector, a name that isn't +/// text, or the group options the command passes on (colour, mode, opacity), which the step +/// doesn't record. +#[test] +fn settings_the_event_cannot_hold_are_refused() { + for p in [ + json!({"layer": 3}), + json!({"layer": {"index": 2}}), + json!({"layer": {"background": true}}), + json!({"name": 4}), + json!({"name": "Frame 1", "color": "red"}), + json!({"mode": "multiply"}), + json!({"opacity": 50}), + json!({"name": "Frame 1", "width": 200}), + ] { + assert!(exported(&p).is_none(), "{p}"); + } +} + +/// Any other form keeps the reference step: no `From`, another `From`, a repeated or extra key, +/// values of another type, or another `null`. +#[test] +fn other_forms_keep_the_photoshop_step() { + let measured = recorded(by_name("Photo"), "Frame 1"); + let replaced = |key: &str, v: D| { + let mut d = measured.clone(); + d.items.iter_mut().filter(|(k, _)| k.is(key)).for_each(|slot| slot.1 = v.clone()); + d + }; + let forms = [ + without(measured.clone(), &["From"]), + replaced("From", D::Reference(vec![ReferenceItem::Index { class: class("Lyr "), index: 2 }])), + replaced("From", D::Reference(vec![ReferenceItem::Name { class: class("Chnl"), name: UnicodeString::new_nul("Photo") }])), + replaced("From", D::Reference(vec![ReferenceItem::Enumerated { class: class("Lyr "), type_id: Id::new("Ordn"), value: Id::new("Al ") }])), + replaced("From", D::Text(UnicodeString::new_nul("Photo"))), + replaced("Nm ", D::Integer(1)), + replaced("layerSectionEnd", D::Double(5.0)), + replaced("null", D::Reference(vec![ReferenceItem::Class(class("frame"))])), + measured.clone().with("Nm ", D::Text(UnicodeString::new_nul("Again"))), + measured.clone().with("From", by_name("Other")), + measured.clone().with("Wdth", D::UnitFloat { unit: PX, value: 200.0 }), + ]; + for d in forms { + let (mut s, r) = load(vec![d.clone()]); + assert_eq!(r["unsupported"].as_array().map(Vec::len), Some(1), "{d:?}"); + assert_eq!(s.actions.list[0].steps[0].0, PHOTOSHOP_STEP, "{d:?}"); + assert_eq!(saved(&mut s), Some(d.to_bytes())); + } +} + +/// A loaded step whose layer or name was changed saves the new settings, not the stale +/// recording; one whose recording is damaged still saves its settings. +#[test] +fn changed_or_damaged_steps_save_their_settings() { + let (s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + let mut p = s.actions.list[0].steps[0].1.clone(); + assert!(p.get(SOURCE).is_some(), "{p}"); + p["layer"] = json!("Other"); + assert_eq!(exported(&p), Some(canonical(by_name("Other"), Some("Frame 1")))); + p["layer"] = json!("Photo"); + p["name"] = json!(" "); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), None))); + p["name"] = json!("Frame 1"); + p[SOURCE] = json!("not base64!"); + assert_eq!(exported(&p), Some(canonical(by_name("Photo"), Some("Frame 1")))); +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs new file mode 100644 index 0000000000..e2340988e6 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/steps_frame_section.rs @@ -0,0 +1,121 @@ +//! Layer › New › Frame from Layers, recorded as a Make of class `framedGroupSection`, as +//! `docs/atn.md` ("Recorded through the menus") measures it (#10723): `From` = the layer **by +//! name**, `layerSectionStart`, `layerSectionEnd` (longs) and `Nm ` (text). The dialog's width +//! and height are not in the step. +//! +//! `layerSectionStart` and `layerSectionEnd` are ids of the recording session, so they are not +//! settings: a loaded step keeps them only inside its recorded descriptor. + +use super::descriptors::{class_ref, desc, jstr, name_ref, target_ref, text}; +use super::fields::{Mapped, step}; +use super::{D, Descriptor, ReferenceItem, Value, json}; + +/// The native command the step plays as. +pub(super) const COMMAND: &str = "layer.new.frameFromLayers"; +/// The recorded descriptor, kept when it differs from the one [`to`] would write (session ids, +/// key order), so a load and save keeps the step unchanged. +const SOURCE: &str = "_atnFrameSectionDescriptor"; + +/// The settings a step holds: the layer it frames (`None`: the selected layers) and the frame's +/// name (`None`: no `Nm `, so the frame takes the command's default name). +#[derive(Debug, PartialEq)] +struct Settings { + layer: Option, + name: Option, +} + +/// Text without the trailing NUL the format may carry. +fn plain(t: &super::UnicodeString) -> Option { + String::from_utf16(t.0.strip_suffix(&[0]).unwrap_or(&t.0)).ok() +} + +/// `From`: a layer by name, or the target layer (`Lyr ` `Ordn.Trgt`), the form a step recorded +/// in PhotoCraft without a layer of its own writes. +fn source_layer(v: &D) -> Option> { + let D::Reference(r) = v else { return None }; + match r.as_slice() { + [ReferenceItem::Name { class, name }] if class.class_id.is("Lyr ") => Some(Some(plain(name)?)), + [ReferenceItem::Enumerated { class, type_id, value }] if class.class_id.is("Lyr ") && type_id.is("Ordn") && value.is("Trgt") => Some(None), + _ => None, + } +} + +/// The measured form only: `null` = class `framedGroupSection`, `From`, optional session ids +/// (longs) and an optional `Nm `, each key at most once and nothing else. +fn recorded(d: &Descriptor) -> Option { + const KEYS: [&str; 5] = ["null", "From", "layerSectionStart", "layerSectionEnd", "Nm "]; + let once = |key: &str| d.items.iter().filter(|(k, _)| k.is(key)).count() <= 1; + if d.items.iter().any(|(k, _)| !KEYS.iter().any(|key| k.is(key))) || !KEYS.iter().all(|key| once(key)) { + return None; + } + let section = matches!(d.get("null")?, D::Reference(r) if matches!(r.as_slice(), [ReferenceItem::Class(c)] if c.class_id.is("framedGroupSection"))); + if !section || ["layerSectionStart", "layerSectionEnd"].iter().any(|key| d.get(key).is_some_and(|v| !matches!(v, D::Integer(_)))) { + return None; + } + let name = match d.get("Nm ") { + None => None, + Some(D::Text(t)) => Some(plain(t)?), + Some(_) => return None, + }; + Some(Settings { layer: source_layer(d.get("From")?)?, name }) +} + +/// The descriptor a step recorded in PhotoCraft saves as: the measured keys without the session +/// ids, `Nm ` only for a name of the step's own (not blank). +fn canonical(settings: &Settings) -> Descriptor { + let from = settings.layer.as_deref().map_or_else(|| target_ref("Lyr "), |layer| name_ref("Lyr ", layer)); + let d = desc("null").with("null", class_ref("framedGroupSection")).with("From", from); + match &settings.name { + Some(name) => d.with("Nm ", text(name)), + None => d, + } +} + +/// Map the measured form; any other stays a complete kept step. +pub(super) fn from(d: &Descriptor) -> Mapped { + let Some(settings) = recorded(d) else { return Mapped::Unsupported { harmless: false } }; + let mut p = json!({}); + if let Some(layer) = &settings.layer { + p["layer"] = layer.as_str().into(); + } + if let Some(name) = &settings.name { + p["name"] = name.as_str().into(); + } + if *d != canonical(&settings) { + p[SOURCE] = photocraft_paint::tile::b64_encode(&d.to_bytes()).into(); + } + step(COMMAND, p) +} + +/// A native step the event holds: the selected layers or a layer by name, and a name. A layer by +/// id (meaningless in another document) and the group options the command passes on to the +/// group it frames (colour, mode, opacity) refuse export: the step records none of them. +fn native(p: &Value) -> Option { + let m = p.as_object()?; + if m.keys().any(|key| !["layer", "name", SOURCE].contains(&key.as_str())) { + return None; + } + let layer = match m.get("layer") { + None | Some(Value::Null) => None, + Some(Value::String(layer)) => Some(layer.clone()), + Some(_) => return None, + }; + let name = match m.get("name") { + None | Some(Value::Null) => None, + // A blank name is no name to the command either. + Some(Value::String(n)) => Some(n.clone()).filter(|n| !n.trim().is_empty()), + Some(_) => return None, + }; + Some(Settings { layer, name }) +} + +/// Save the recorded descriptor while the step still frames the same layer with the same name, +/// otherwise the canonical form of the step's settings. +pub(super) fn to(p: &Value) -> Option { + let settings = native(p)?; + let source = jstr(p, SOURCE) + .and_then(photocraft_paint::tile::b64_decode) + .and_then(|bytes| Descriptor::from_bytes(&bytes).ok()) + .filter(|d| recorded(d).is_some_and(|r| r.layer == settings.layer && r.name.filter(|n| !n.trim().is_empty()) == settings.name)); + Some(source.unwrap_or_else(|| canonical(&settings))) +} diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c331d1c585..6a5eb6dea7 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -552,6 +552,10 @@ pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { return mapped; } + // Layer › New › Frame from Layers (#10723). + if get_ref(d, "null").and_then(ref_class).as_deref() == Some("framedGroupSection") { + return super::steps_frame_section::from(d); + } if d.items == type_shape_descriptor().items { return none("type.convertToShape"); } @@ -720,6 +724,9 @@ pub(super) fn make_to(id: &str, p: &Value) -> Option { if id == super::steps_layer_style::CREATE { return super::steps_layer_style::style_to(id, p); } + if id == super::steps_frame_section::COMMAND { + return super::steps_frame_section::to(p); + } if id == "type.convertToShape" { return p.as_object().filter(|p| p.is_empty()).map(|_| type_shape_descriptor()); } diff --git a/crates/engine/src/cmd/atn_cmds/tests.rs b/crates/engine/src/cmd/atn_cmds/tests.rs index ab152eddac..da45f9c2ff 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -691,6 +691,7 @@ fn every_mapped_command_exports_and_imports_back() { "rotationAdaptation":"none","scale":true,"mirror":false,"output":"new"}), ), ("edit.fade", json!({"opacity":50,"mode":"Multiply"})), + ("layer.new.frameFromLayers", json!({"layer": "Photo", "name": "Frame 1"})), ("layer.linkLayers", json!({})), ("layer.smartObjects.stackMode.range", json!({})), ("layer.smartObjects.stackMode.entropy", json!({})), diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index 8e2ea786b5..c88177cc97 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -135,8 +135,11 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { Ok(result) } fn frame_from_layers(s: &mut Session, p: &Value) -> Result { + // A `layer` of its own (a recorded step names its layer) is what the grouping below takes + // in, so the frame fits that layer, not whatever is selected. + let explicit = crate::commands::explicit_layer(s, p)?; let st = s.active().ok_or(EngineError::NoDocument)?; - let ids = st.selected_layers(); + let ids = explicit.map_or_else(|| st.selected_layers(), |id| vec![id]); let bounds = ids .iter() .filter_map(|id| st.doc.layer(*id)) diff --git a/docs/atn.md b/docs/atn.md index be7eca3787..33a476396f 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -147,7 +147,7 @@ row; the action still adds only one Undo entry. | `CtTL` | cutToLayer | Layer Via Cut | `layer.new.layerViaCut` | | `LnsF` | lensFlare | Lens Flare | `filter.render.lensFlare` | | `Lvls` | levels | Levels | `image.adjustments.levels`, `image.autoTone`, `image.autoContrast` | -| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | +| `Mk ` | make | Make | `image.calculations`, `layer.layerStyle.createLayer`, `layer.new.layer`, `layer.new.group`, `layer.groupLayers`, `layer.new.frameFromLayers` (Layer › New › Frame from Layers), `layer.duplicate`, `layer.new.layerViaCopy`, `layer.new.layerViaCut`, `layer.newFillLayer.solidColor`, `layer.newFillLayer.pattern`, `layer.newFillLayer.gradient`, `layer.newAdjustmentLayer.levels`, `layer.newAdjustmentLayer.curves`, `layer.newAdjustmentLayer.hueSaturation`, `layer.newAdjustmentLayer.brightnessContrast`, `layer.newAdjustmentLayer.threshold`, `layer.newAdjustmentLayer.posterize`, `layer.newAdjustmentLayer.invert`, `layer.newAdjustmentLayer.colorBalance`, `layer.newAdjustmentLayer.vibrance`, `layer.newAdjustmentLayer.exposure`, `layer.newAdjustmentLayer.photoFilter`, `layer.newAdjustmentLayer.blackWhite`, `layer.newAdjustmentLayer.channelMixer`, `layer.newAdjustmentLayer.selectiveColor`, `layer.newAdjustmentLayer.gradientMap`, `layer.layerMask.revealAll`, `layer.layerMask.hideAll`, `layer.layerMask.revealSelection`, `layer.layerMask.hideSelection`, `file.new`, `file.newFromClipboard`, `history.newSnapshot`, `type.convertToShape`, `type.createWorkPath` | | (string ID only) | animationFramesFromLayers | Make Frames from Layers | | | (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` | | `Mxm ` | maximum | Maximum | `filter.other.maximum` | @@ -272,6 +272,20 @@ options are refused on export. Playback uses the native command's preconditions and current state. Isolate Layers toggles the panel view; type defaults remain session settings; Record Measurements uses the current measurement configuration. +Layer › New › Frame from Layers is a Make with `null` = the class +`framedGroupSection`, `From` = the layer by name and `Nm ` = the frame's name. It +plays as `layer.new.frameFromLayers` on that layer, and the frame fits that +layer's bounds whatever is selected. The dialog's width and height are not in the +step. `layerSectionStart` and `layerSectionEnd` are ids of the recording session: +a loaded step saves back its recorded descriptor, session ids included, while it +still frames the same layer with the same name, and a step recorded in PhotoCraft +writes `null`, `From` and `Nm ` (only for a name that isn't blank) without them. A +native step without a layer of its own frames the selected layers and writes +`From` = the target layer, a form the recordings don't show. Another `From`, a +repeated or extra key, or a value of another type stays a kept step; a native step +with a layer by id, or with the group options the command passes on (colour, mode, +opacity), refuses export. + Link Layers plays as the toggle the reference application performs (played twice on the same layers it links, then unlinks them; see the measurements below). Unlink is explicit and idempotent: it keeps an already unlinked selection unlinked and clears singleton link groups. From c82594d1ebbc31a6f1cb82f25ecb55bcf5959f24 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:38:58 +0100 Subject: [PATCH 06/14] Frame from Layers: admit a step on the layer it names (#10723) The spec didn't declare `layer`, so admission checked the selection: with no layer selected a step naming an existing layer failed with "select a layer". --- .../engine/src/cmd/atn_cmds/frame_section_tests.rs | 12 ++++++++++++ crates/engine/src/cmd/frame_cmds.rs | 5 ++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs index 396ba420a8..dec64be796 100644 --- a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -141,6 +141,18 @@ fn a_loaded_step_frames_the_named_layer_and_undoes() { assert!(doc.layers.iter().any(|l| l.id == photo) && doc.layers.iter().any(|l| l.id == other)); } +/// A step that names its layer plays with no layer selected: the command is admitted on the +/// named layer, not the (empty) selection. +#[test] +fn a_loaded_step_plays_with_no_layer_selected() { + let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); + two_layers(&mut s); + s.execute("select.deselectLayers", json!({})).unwrap(); + let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); +} + /// Without a layer of its own the command still frames the selected layers. #[test] fn without_a_layer_the_selected_layers_are_framed() { diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index c88177cc97..e48f337246 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -362,7 +362,10 @@ pub fn specs() -> Vec { has_doc, new_frame, ), - CommandSpec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{name?:str}"#, has_layer, frame_from_layers) }, + CommandSpec { + menu: &["Layer", "New"], + ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{"layer":id?,"name":str?}"#, has_layer, frame_from_layers) + }, spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set), CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) }, spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert), From 3dc0a8dd1cecf071668c54173da0b03c9ca80d44 Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Mon, 9 Nov 2026 14:25:36 +0100 Subject: [PATCH 07/14] Frame from Layers: the no-selection test checks which layer was framed (#10723) --- crates/engine/src/cmd/atn_cmds/frame_section_tests.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs index dec64be796..873ace6627 100644 --- a/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -146,11 +146,15 @@ fn a_loaded_step_frames_the_named_layer_and_undoes() { #[test] fn a_loaded_step_plays_with_no_layer_selected() { let (mut s, _) = load(vec![recorded(by_name("Photo"), "Frame 1")]); - two_layers(&mut s); + let (photo, other) = two_layers(&mut s); s.execute("select.deselectLayers", json!({})).unwrap(); let played = s.execute("actions.play", json!({"action": "A"})).unwrap(); assert_eq!(played["ran"], 1, "{played}"); assert_eq!(frames(&s, "Frame 1").into_iter().map(|f| f.1).collect::>(), vec![[10.0, 15.0, 30.0, 30.0]]); + // The frame took in Photo, not Other. + let doc = &s.active().unwrap().doc; + assert!(doc.layer(photo).is_none(), "Photo went into the frame"); + assert!(doc.layers.iter().any(|l| l.id == other), "Other stays a top-level layer"); } /// Without a layer of its own the command still frames the selected layers. From c29a960956abb6283e7d93015746b3798586ce3a Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Tue, 10 Nov 2026 05:11:36 -0600 Subject: [PATCH 08/14] fix(paint): raise the rim around a transparent fill partly instead of to full opacity --- crates/algo/src/paint.rs | 91 +++++++++++++++++------ crates/engine/src/cmd/paint_cmds/tests.rs | 32 ++++++-- 2 files changed, 96 insertions(+), 27 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index d7a1139caf..5ad909d935 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,22 +63,37 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// `o`, the pixel `d` with `c` composited at coverage `k`, with what is left of `d`'s transparency -/// filled by `c` up to coverage `full` (≥ `k`) as well, behind the colour already there: the -/// transparent part of the pixel takes the fill at `full` while its colour keeps the softer `k`. -fn fill_transparency(o: [f32; 4], d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { - let add = ((full - k).max(0.0) * c[3].clamp(0.0, 1.0) * (1.0 - d[3]).max(0.0)).min((1.0 - o[3]).max(0.0)); - let a = o[3] + add; - if add.is_nan() || add <= 0.0 || a <= 0.0 { +/// The pixel `d` filled with `c` (mode `m`) by a bucket clicked on transparency. The colour `d` +/// holds blends with `c` at the region's coverage `k`, as on any fill. The transparent part of the +/// pixel (`1 − αd`) takes the fill at strength `full × (1 − αd)` instead of `k`: the emptier the +/// pixel, the more of its emptiness is filled. So the result's alpha is +/// `αd + (1 − αd)² × full × αc` whatever `k` is (#11354 review): +/// - empty pixels (the hole and the hole's anti-aliased edge) fill to `full`; +/// - the soft rim a Clear leaves rises only partly, so a faint rim stays (α 187 → 205, 56 → 211, +/// 3 → 252 at 8 bits; the reference application gives 204, 211, 253); +/// - opaque pixels come out bit-identical to a plain composite at `k`. +fn fill_transparency(m: BlendMode, d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { + let o = blend::composite(m, d, c, k); + let held = d[3].clamp(0.0, 1.0); + if held >= 1.0 || !full.is_finite() || !held.is_finite() { return o; } - let mix = |i: usize| (o[i] * o[3] + c[i] * add) / a; + let empty = 1.0 - held; + let add = full.clamp(0.0, 1.0) * c[3].clamp(0.0, 1.0) * empty * empty; + let a = held + add; + if a <= 0.0 { + return o; + } + // The colour `d` holds, blended at `k` as if it were all there; then the new part is `c`. + let soft = blend::composite(m, [d[0], d[1], d[2], 1.0], c, k); + let mix = |i: usize| (soft[i] * held + c[i] * add) / a; [mix(0), mix(1), mix(2), a] } /// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, -/// a covered pixel's transparency takes the fill at that coverage instead (see -/// [`fill_transparency`]); Lock Transparent Pixels and Clear ignore it. +/// a covered pixel's transparency takes the fill at a strength set by that value and by how empty +/// the pixel is, instead of by the coverage (see [`fill_transparency`]); Lock Transparent Pixels +/// and Clear ignore it. #[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, @@ -116,11 +131,10 @@ fn composite_area( let d = photocraft_raster::to_rgba(&fmt, px); let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => { - let c = color(x, y); - let o = blend::composite(m, d, c, k); - transparency.map_or(o, |full| fill_transparency(o, d, c, k, full(x, y))) - } + FillMode::Blend(m) => match transparency { + Some(full) => fill_transparency(m, d, color(x, y), k, full(x, y)), + None => blend::composite(m, d, color(x, y), k), + }, // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], @@ -252,9 +266,10 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; - // Clicked on transparency: the flood fills empty pixels, and the empty part of the pixels - // along its anti-aliased edge (the soft rim a cleared selection leaves) is that same empty - // area, so it is filled in full rather than left as a semi-transparent ring (#11311). + // Clicked on transparency: the flood fills empty pixels, and the empty pixels along its + // anti-aliased edge are that same empty area, so they fill in full rather than being left as + // a semi-transparent ring (#11311). The soft rim a cleared selection leaves rises only by how + // empty each pixel is, so a faint rim stays (#11354 review; see `fill_transparency`). let at_seed = usize::try_from(seed.1 - area.y0) .ok() .and_then(|y| y.checked_mul(area.width() as usize)) @@ -294,9 +309,10 @@ pub fn bucket_fill_region_inks( } /// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region -/// touches takes the fill at the full opacity and selection coverage, while the region's -/// anti-aliasing still softens the colour over what is already there. Opaque pixels come out -/// exactly as without it. +/// touches takes the fill at the opacity and selection coverage scaled by how transparent the +/// pixel is (empty pixels fill in full, a partly transparent rim rises partly), while the +/// region's anti-aliasing still softens the colour over what is already there. Opaque pixels come +/// out exactly as without it. #[allow(clippy::too_many_arguments)] fn fill_region( s: &mut Surface, @@ -460,6 +476,39 @@ mod tests { assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); } + /// #11354 review: the soft rim a Clear leaves rises only partly. The reference application + /// takes rim alphas 187, 56 and 3 to 204, 211 and 253; the rule here, `α + (1 − α)²`, gives + /// 205, 211 and 252, each within one level of it (fit in PR #11354's review round). The rim pixel + /// sits on the bucket's anti-aliased fringe; the hole beside it fills in full and the opaque + /// art behind it is untouched by the rule. + #[test] + fn bucket_on_transparency_raises_the_cleared_rim_partly() { + let a = Rect::new(0, 0, 8, 1); + let white = |_, _| [1.0, 1.0, 1.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (rim alpha after the Clear, the reference application's result, ours) + for (rim, reference, ours) in [(187, 204, 205), (56, 211, 211), (3, 253, 252)] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + let mut s = Surface::new(fmt); + // The cleared hole is [0, 0, 0, 0] (Clear zeroes its RGB), the rim straight white. + s.fill_rect(Rect::new(4, 0, 5, 1), &[1.0, 1.0, 1.0, rim as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, true, 1.0, None, false, white, None, FillMode::Blend(BlendMode::Normal))); + let p = s.rgba(4, 0); + assert_eq!(level(p[3]), ours, "{fmt:?}: rim {rim} -> {p:?}"); + assert!((ours - reference).abs() <= 1, "rim {rim}: ours {ours}, reference {reference}"); + assert!(p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "{fmt:?}: the rim stays white: {p:?}"); + for x in 0..4 { + assert_eq!(level(s.rgba(x, 0)[3]), 255, "{fmt:?} rim {rim}: the hole and its edge fill in full at {x}"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} rim {rim}: opaque art at {x}"); + } + } + } + } + /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent /// neighbour along the edge keeps its own transparency (it belongs to another area). #[test] diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index 835e450d83..8a1c81c90c 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -368,12 +368,15 @@ fn assert_all_white(s: &Session, what: &str) { assert_eq!(not_white(&composite, width, 8), vec![], "{what}: composite pixels left after the fill"); } -/// #11311: after clearing an anti-aliased selection and bucket-filling the hole white at 100 %, -/// every pixel of the layer and of the composite is opaque white. The clear itself is right: it -/// leaves a soft rim of white at partial alpha around a fully transparent hole. The bucket used to -/// leave that rim (and its own anti-aliased edge) semi-transparent: a grey ring over the checkerboard. +/// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole +/// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched. +/// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the +/// reference application: a pixel the fill reaches at alpha `α` ends at `α + (1 − α)²`, so a faint +/// rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); +/// the first round filled the rim to 255 too, which the reference does not do. #[test] -fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { +fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() { + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; for depth in [8, 16, 32] { let ellipse = json!({"x": 20, "y": 10, "width": 80, "height": 80, "ellipse": true, "antiAlias": true}); let (s, cleared) = clear_then_bucket(depth, ellipse, true); @@ -383,7 +386,24 @@ fn bucket_after_clearing_an_antialiased_selection_leaves_no_ring() { let rim: Vec<&[f32; 4]> = cleared.iter().filter(|p| p[3] > 0.0 && p[3] < 1.0).collect(); assert!(!rim.is_empty(), "depth {depth}: an anti-aliased clear leaves a soft rim"); assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); - assert_all_white(&s, &format!("depth {depth}, anti-aliased ellipse")); + + let after = layer_rgba(&s); + let mut raised = 0; + for (i, (was, now)) in cleared.iter().zip(&after).enumerate() { + let at = (i % 120, i / 120); + if was[3] <= 0.0 || was[3] >= 1.0 { + assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}"); + } else if now[3] > was[3] { + raised += 1; + let want = was[3] + (1.0 - was[3]).powi(2); + assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}"); + } else { + assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel the fill does not reach stays"); + } + assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}"); + } + assert!(raised > 0, "depth {depth}: the fill reaches the rim"); + assert!(after.iter().any(|p| level(p[3]) < 255), "depth {depth}: a faint rim stays, as in the reference"); } } From 612afbff218004eb01c8e28f2079e486ab55c5a8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:45:21 +0100 Subject: [PATCH 09/14] #11871: Ruler Straighten with crop asks an untrusted session's gate for its nested Image Rotation, now called directly Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/analysis_cmds.rs | 8 +++++++- crates/engine/src/cmd/count_resize_tests.rs | 12 ++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index 4b6f0f8317..41585c3360 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -796,7 +796,13 @@ fn straighten(s: &mut Session, p: &Value) -> Result { compound(s, "Straighten", |s| { if crop { // Count points turn with the image here, since the crop after it moves them too. - crate::mode_cmds::rotate_arbitrary_with(s, &json!({"angle": rot, "direction": "cw"}), false)?; + // Called directly rather than through `execute`, so an untrusted session's gate is + // asked here, as dispatch would have asked it for the nested rotation. + let rotation = json!({"angle": rot, "direction": "cw"}); + if let Some(gate) = s.authorize { + gate("image.rotation.arbitrary", &rotation)?; + } + crate::mode_cmds::rotate_arbitrary_with(s, &rotation, false)?; let nd = doc(s)?; let (cw, ch) = inscribed(w0, h0, rot.to_radians()); let (nw, nh) = (f64::from(nd.size.width), f64::from(nd.size.height)); diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index 32f3562aa4..ccc4adad09 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -76,3 +76,15 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { let (c, n) = (count_point(&s), note(&s)); assert!((c[0] - n[0]).abs() < 1e-6 && (c[1] - n[1]).abs() < 1e-6, "count {c:?} vs note {n:?}"); } + +#[test] +fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); + let size = s.active().unwrap().doc.size; + s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) }); + assert!(s.execute("image.analysis.straightenLayer", json!({"crop": true})).is_err(), "the nested rotation is denied"); + s.authorize = None; + assert_eq!(s.active().unwrap().doc.size, size, "nothing turned"); +} From 40a8891077069d794efddc43b765ec42ffda3870 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 15:22:48 +0100 Subject: [PATCH 10/14] #11871: the Straighten tests run on a pixel layer, since main turns Straighten Layer off for the Background (#12033) Co-Authored-By: DuBearte Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/count_resize_tests.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs index ccc4adad09..7648ed0051 100644 --- a/crates/engine/src/cmd/count_resize_tests.rs +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -71,6 +71,8 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); s.execute("count.add", json!({"x": 250, "y": 150})).unwrap(); s.execute("notes.add", json!({"x": 250, "y": 150})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); s.execute("image.analysis.straightenLayer", json!({"crop": true})).unwrap(); let (c, n) = (count_point(&s), note(&s)); @@ -81,6 +83,8 @@ fn ruler_straighten_with_crop_moves_count_points_with_the_image() { fn ruler_straighten_with_crop_asks_the_gate_for_its_rotation() { let mut s = Session::new(); s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + // Straighten Layer is off for the Background (#12033). + s.execute("layer.new.layer", json!({})).unwrap(); s.execute("image.analysis.rulerTool", json!({"start": [0, 0], "end": [100, 10]})).unwrap(); let size = s.active().unwrap().doc.size; s.authorize = Some(|id, _| if id == "image.rotation.arbitrary" { Err(crate::EngineError::Other("denied".into())) } else { Ok(()) }); From 3a23cf3e6b10283637e927e4c6923eb3804d3a56 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 20:28:37 +0100 Subject: [PATCH 11/14] fix(paint): raise only the ring next to a transparent flood, at coverage 1 - alpha (#11354) Since main's wand fringe gives a transparent seed no fringe coverage (#11776), the PR's rim rule never ran after the merge. The rim now has its own reach: with Anti-alias on, each pixel 8-adjacent to the flood takes a plain composite of the fill at coverage (1 - alpha) x opacity x selection. That gives the measured alpha alpha + (1 - alpha)^2 for a white rim, and also the reference colours for a black edge filled green (#12528: alpha 40 -> (0,248,0,221), 112 -> (0,190,0,192), 197 -> (0,70,0,210), 253 -> (0,2,0,253)), which the earlier colour mix missed. Pixels further out keep their alpha, and Anti-alias off leaves the ring alone, both as measured. The flood itself is fully covered on main, so the CMYK inks rule is back to "fully covered". Co-Authored-By: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/algo/src/paint.rs | 184 ++++++++++++++-------- crates/engine/src/cmd/paint_cmds/tests.rs | 14 +- 2 files changed, 131 insertions(+), 67 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 2ba5ddb736..5d40e81d93 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,37 +63,10 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// The pixel `d` filled with `c` (mode `m`) by a bucket clicked on transparency. The colour `d` -/// holds blends with `c` at the region's coverage `k`, as on any fill. The transparent part of the -/// pixel (`1 − αd`) takes the fill at strength `full × (1 − αd)` instead of `k`: the emptier the -/// pixel, the more of its emptiness is filled. So the result's alpha is -/// `αd + (1 − αd)² × full × αc` whatever `k` is (#11354 review): -/// - empty pixels (the hole and the hole's anti-aliased edge) fill to `full`; -/// - the soft rim a Clear leaves rises only partly, so a faint rim stays (α 187 → 205, 56 → 211, -/// 3 → 252 at 8 bits; the reference application gives 204, 211, 253); -/// - opaque pixels come out bit-identical to a plain composite at `k`. -fn fill_transparency(m: BlendMode, d: [f32; 4], c: [f32; 4], k: f32, full: f32) -> [f32; 4] { - let o = blend::composite(m, d, c, k); - let held = d[3].clamp(0.0, 1.0); - if held >= 1.0 || !full.is_finite() || !held.is_finite() { - return o; - } - let empty = 1.0 - held; - let add = full.clamp(0.0, 1.0) * c[3].clamp(0.0, 1.0) * empty * empty; - let a = held + add; - if a <= 0.0 { - return o; - } - // The colour `d` holds, blended at `k` as if it were all there; then the new part is `c`. - let soft = blend::composite(m, [d[0], d[1], d[2], 1.0], c, k); - let mix = |i: usize| (soft[i] * held + c[i] * add) / a; - [mix(0), mix(1), mix(2), a] -} - -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. With `transparency`, -/// a covered pixel's transparency takes the fill at a strength set by that value and by how empty -/// the pixel is, instead of by the coverage (see [`fill_transparency`]); Lock Transparent Pixels -/// and Clear ignore it. +/// Composites `color(i)` over `area` of the surface with per-pixel coverage. Where the coverage is +/// zero, `rim(x, y)` (when given) is the strength of a bucket's transparent-seed fringe there: the +/// pixel takes the fill at coverage `rim × (1 − α)`, its own transparency (#11354 review; see +/// [`bucket_fill_inks`]). Lock Transparent Pixels and Clear ignore it. #[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, @@ -103,7 +76,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, - transparency: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, + rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. @@ -118,8 +91,12 @@ fn composite_area( let mut enc = [0.0f32; 8]; for y in r.y0..r.y1 { for x in r.x0..r.x1 { - let k = coverage(x, y); - if k <= 0.0 { + let mut k = coverage(x, y); + let on_rim = match rim { + Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_)) => rim(x, y), + _ => 0.0, + }; + if k <= 0.0 && on_rim <= 0.0 { continue; } if !any { @@ -129,25 +106,26 @@ fn composite_area( let i = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n; let px = &mut region[i..i + n]; let d = photocraft_raster::to_rgba(&fmt, px); + if k <= 0.0 { + // A rim pixel: only its transparency takes the fill, so opaque art stays as it is. + k = on_rim * (1.0 - d[3].clamp(0.0, 1.0)); + if k.is_nan() || k <= 0.0 { + continue; + } + } let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), - FillMode::Blend(m) => match transparency { - Some(full) => fill_transparency(m, d, color(x, y), k, full(x, y)), - None => blend::composite(m, d, color(x, y), k), - }, + FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], }; from_rgba_into(&fmt, o, &mut enc); - // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it - // is — and pixels the fill made fully opaque out of transparency, whose colour is the - // fill alone even though their coverage is partial (the edge of a bucket fill on - // transparency, #11354 review). A pixel that held colour keeps its blended encoding. + // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it is. if let Some(i) = inks && fmt.mode == photocraft_color::ColorMode::Cmyk && mode == FillMode::Blend(BlendMode::Normal) - && (k >= 1.0 || (d[3] <= 0.0 && o[3] >= 1.0)) + && k >= 1.0 { enc[..4].copy_from_slice(&i); } @@ -267,15 +245,18 @@ pub fn bucket_fill_inks( } let img = crate::selection::rgba8_image(s, area); let Some(region) = crate::selection::wand_region(&img, area, seed, tolerance, contiguous, anti_alias) else { return false }; - // Clicked on transparency: the flood fills empty pixels, and the empty pixels along its - // anti-aliased edge are that same empty area, so they fill in full rather than being left as - // a semi-transparent ring (#11311). The soft rim a cleared selection leaves rises only by how - // empty each pixel is, so a faint rim stays (#11354 review; see `fill_transparency`). + // Clicked on transparency with Anti-alias on: the wand's fringe gives the partly transparent + // pixels around the flood no coverage (their alpha is measured against the seed's 0), but the + // reference application fills each pixel 8-adjacent to the flood at coverage `1 − α`, so the + // soft rim a cleared selection leaves rises partly (α 187 → 205, 56 → 211, 3 → 252; the + // reference gives 204, 211, 253) and a black edge pixel of alpha 40 filled green becomes + // (0, 248, 0, 221) (#11311, #12528, #11354 review). Pixels further out stay as they are; with + // Anti-alias off nothing outside the flood changes. let at_seed = usize::try_from(seed.1 - area.y0) .ok() .and_then(|y| y.checked_mul(area.width() as usize)) .and_then(|row| row.checked_add(usize::try_from(seed.0 - area.x0).ok()?)); - let empty_seed = at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); + let empty_seed = anti_alias && at_seed.and_then(|i| img.get(i)).is_some_and(|p| p[3] == 0); drop(img); fill_region(s, ®ion, opacity, selection, lock_transparency, src, inks, mode, empty_seed); true @@ -309,11 +290,9 @@ pub fn bucket_fill_region_inks( fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); } -/// [`bucket_fill_region_inks`]; with `fill_empty`, the transparent part of every pixel the region -/// touches takes the fill at the opacity and selection coverage scaled by how transparent the -/// pixel is (empty pixels fill in full, a partly transparent rim rises partly), while the -/// region's anti-aliasing still softens the colour over what is already there. Opaque pixels come -/// out exactly as without it. +/// [`bucket_fill_region_inks`]; with `rim`, the pixels 8-adjacent to the region's fully covered +/// pixels that the region itself leaves uncovered take the fill at coverage `1 − α` (see +/// [`composite_area`]). Fully covered pixels and pixels further out are filled as without it. #[allow(clippy::too_many_arguments)] fn fill_region( s: &mut Surface, @@ -324,13 +303,35 @@ fn fill_region( src: impl Fn(i32, i32) -> [f32; 4] + Sync, inks: Option<[f32; 4]>, mode: FillMode, - fill_empty: bool, + rim: bool, ) { - // Composite only over the filled region's box. + // Composite only over the filled region's box (with Anti-alias on it already holds the + // one-pixel ring around the flood). let b = region.bbox; let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); - let empty: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if fill_empty { Some(&strength) } else { None }; - composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, empty); + let ring = if rim { rim_ring(region) } else { Vec::new() }; + let on_ring = |x: i32, y: i32| { + let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); + let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i)); + if hit == Some(&true) { strength(x, y) } else { 0.0 } + }; + let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if rim { Some(&on_ring) } else { None }; + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); +} + +/// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its +/// fully covered pixels, diagonals included. +fn rim_ring(region: &crate::selection::Region) -> Vec { + let (w, h) = (region.bbox.width() as usize, region.bbox.height() as usize); + let full = |x: usize, y: usize| y.checked_mul(w).and_then(|r| r.checked_add(x)).and_then(|i| region.mask.get(i)) == Some(&255); + let n = w.saturating_mul(h).min(region.mask.len()); + (0..n) + .map(|i| { + let (x, y) = (i % w, i / w); + region.mask.get(i) == Some(&0) + && (y.saturating_sub(1)..=(y + 1).min(h - 1)).any(|ny| (x.saturating_sub(1)..=(x + 1).min(w - 1)).any(|nx| (nx, ny) != (x, y) && full(nx, ny))) + }) + .collect() } #[cfg(test)] @@ -435,7 +436,6 @@ mod tests { let img = crate::selection::rgba8_image(&before, a); let region = crate::selection::wand_region(&img, a, (1, 0), 0.0, true, true).unwrap(); bucket_fill_region_inks(&mut before, ®ion, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal)); - assert!(before.rgba(3, 0)[3] < opacity * 0.97, "{fmt:?}: the old edge was semi-transparent: {:?}", before.rgba(3, 0)); assert!(bucket_fill_inks(&mut s, a, (1, 0), 0.0, true, true, opacity, None, false, white, None, FillMode::Blend(BlendMode::Normal))); for x in 0..4 { @@ -514,20 +514,80 @@ mod tests { } } - /// The rule is for a click on transparency only: from an opaque seed, a semi-transparent - /// neighbour along the edge keeps its own transparency (it belongs to another area). + /// The rule is for a click on transparency only: from an opaque seed the fill is exactly the + /// wand region's own fill, fringe included. #[test] fn bucket_on_opaque_pixels_keeps_neighbouring_transparency() { let a = Rect::new(0, 0, 8, 1); let mut s = Surface::new(PixelFormat::RGBA8); s.fill_rect(Rect::new(0, 0, 4, 1), &[1.0, 1.0, 1.0, 0.5]); s.fill_rect(Rect::new(4, 0, 8, 1), &[1.0, 1.0, 1.0, 1.0]); + let mut plain = s.clone(); + let img = crate::selection::rgba8_image(&plain, a); + let region = crate::selection::wand_region(&img, a, (6, 0), 0.0, true, true).unwrap(); + bucket_fill_region_inks(&mut plain, ®ion, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal)); assert!(bucket_fill_inks(&mut s, a, (6, 0), 0.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); - let edge = s.rgba(3, 0)[3]; - assert!(edge > 0.5 && edge < 0.6, "only the anti-aliased coverage lands: {edge}"); + for x in 0..8 { + assert_eq!(s.rgba(x, 0), plain.rgba(x, 0), "at {x}"); + } assert!((s.rgba(1, 0)[3] - 0.5).abs() < 0.01, "outside the region"); } + /// #12528 (reference application, transparent seed, Tolerance 32, Anti-alias on): a black + /// edge pixel bordering the filled area takes the green fill at coverage `1 − α`, so its + /// colour as well as its alpha follow the reference within two levels; with Anti-alias off it + /// stays as it was. + #[test] + fn bucket_on_transparency_blends_into_the_edge_at_its_transparency() { + let a = Rect::new(0, 0, 8, 1); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32; + // (edge alpha, the reference application's result) + for (alpha, reference) in [(40, [0, 248, 0, 221]), (112, [0, 190, 0, 192]), (197, [0, 70, 0, 210]), (253, [0, 2, 0, 253])] { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] { + for anti_alias in [true, false] { + let mut s = Surface::new(fmt); + s.fill_rect(Rect::new(4, 0, 5, 1), &[0.0, 0.0, 0.0, alpha as f32 / 255.0]); + s.fill_rect(Rect::new(5, 0, 8, 1), &[0.0, 0.0, 0.0, 1.0]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 32.0, true, anti_alias, 1.0, None, false, green, None, FillMode::Blend(BlendMode::Normal))); + let got = s.rgba(4, 0).map(level); + if anti_alias { + assert!(got.iter().zip(reference).all(|(g, r)| (g - r).abs() <= 2), "{fmt:?} alpha {alpha}: {got:?}, reference {reference:?}"); + } else { + assert_eq!(s.rgba(4, 0), before.rgba(4, 0), "{fmt:?} alpha {alpha}: Anti-alias off leaves the edge"); + } + for x in 5..8 { + assert_eq!(s.rgba(x, 0), before.rgba(x, 0), "{fmt:?} alpha {alpha}: opaque art at {x}"); + } + } + } + } + } + + /// #11354 review (measured in the reference application with a 4 px feathered rim): only the + /// one-pixel ring 8-adjacent to the flood rises, diagonals included; pixels further out keep + /// their alpha exactly. + #[test] + fn bucket_on_transparency_raises_only_the_ring_next_to_the_flood() { + let a = Rect::new(0, 0, 7, 7); + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(a, &[1.0, 1.0, 1.0, 100.0 / 255.0]); + s.fill_rect(Rect::new(3, 3, 4, 4), &[0.0; 4]); + let before = s.clone(); + assert!(bucket_fill_inks(&mut s, a, (3, 3), 32.0, true, true, 1.0, None, false, |_, _| [1.0; 4], None, FillMode::Blend(BlendMode::Normal))); + for y in 0..7 { + for x in 0..7 { + let (p, was) = (s.rgba(x, y), before.rgba(x, y)); + match ((x - 3).abs(), (y - 3).abs()) { + (0, 0) => assert!(p[3] > 0.999, "the flood at ({x},{y}): {p:?}"), + (dx, dy) if dx <= 1 && dy <= 1 => assert!(p[3] > was[3] + 0.1, "the ring at ({x},{y}) rises: {p:?}"), + _ => assert_eq!(p, was, "beyond the ring at ({x},{y})"), + } + } + } + } + /// The Paint Bucket's Mode: Multiply darkens what's there, Clear erases it (half at 50 %). #[test] fn bucket_mode_blends_or_clears() { diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index e915eceef9..7043373580 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -372,8 +372,8 @@ fn assert_all_white(s: &Session, what: &str) { /// #11311 / #11354 review: after clearing an anti-aliased selection and bucket-filling the hole /// white at 100 %, the hole and the hole's edge are opaque white and the opaque art is untouched. /// The soft rim the Clear left (straight white at partial alpha) rises only partly, as in the -/// reference application: a pixel the fill reaches at alpha `α` ends at `α + (1 − α)²`, so a faint -/// rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); +/// reference application: a pixel of the one-pixel ring 8-adjacent to the flood, at alpha `α`, +/// ends at `α + (1 − α)²`, and pixels further out keep their alpha, so a faint rim stays. Before the first round the hole's own edge stayed semi-transparent (a grey ring); /// the first round filled the rim to 255 too, which the reference does not do. #[test] fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_rim_partly() { @@ -389,17 +389,21 @@ fn bucket_after_clearing_an_antialiased_selection_fills_the_hole_and_raises_the_ assert!(rim.iter().all(|p| p[..3].iter().all(|c| (c - 1.0).abs() < 1e-3)), "depth {depth}: the rim keeps its white"); let after = layer_rgba(&s); + // The flood is every pixel the 8-bit wand sees as empty; the ring is the pixels 8-adjacent to it. + let empty = |x: i64, y: i64| (0..120).contains(&x) && (0..100).contains(&y) && level(cleared[(y * 120 + x) as usize][3]) == 0; let mut raised = 0; for (i, (was, now)) in cleared.iter().zip(&after).enumerate() { let at = (i % 120, i / 120); - if was[3] <= 0.0 || was[3] >= 1.0 { + let (x, y) = (at.0 as i64, at.1 as i64); + let next_to_flood = (-1..=1).any(|dy| (-1..=1).any(|dx| (dx, dy) != (0, 0) && empty(x + dx, y + dy))); + if level(was[3]) == 0 || was[3] >= 1.0 { assert_eq!(level(now[3]), 255, "depth {depth} at {at:?}: hole, hole edge and opaque art end opaque: {now:?}"); - } else if now[3] > was[3] { + } else if next_to_flood { raised += 1; let want = was[3] + (1.0 - was[3]).powi(2); assert!((now[3] - want).abs() < 1.5 / 255.0, "depth {depth} at {at:?}: rim {was:?} -> {now:?}, want alpha {want}"); } else { - assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel the fill does not reach stays"); + assert_eq!(now, was, "depth {depth} at {at:?}: a rim pixel beyond the ring next to the flood stays"); } assert!(now[..3].iter().all(|c| (c - 1.0).abs() < 1e-3), "depth {depth} at {at:?}: white: {now:?}"); } From bf550d8fcb0f33a57d800974f7a37cd3eb5a2c84 Mon Sep 17 00:00:00 2001 From: Josias Eli Rodriguez <339499413+chamber074@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:29:47 -0600 Subject: [PATCH 12/14] perf(paint): only build the rim ring when an unlocked Blend fill can read it (#11354) --- crates/algo/src/paint.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 5d40e81d93..0a5b113c5c 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -309,13 +309,17 @@ fn fill_region( // one-pixel ring around the flood). let b = region.bbox; let strength = |x: i32, y: i32| opacity * selection.map_or(1.0, |m| m.sample_channel(x, y, 0)); - let ring = if rim { rim_ring(region) } else { Vec::new() }; + // The ring is only ever read for an unlocked Blend fill (see composite_area), and it is + // empty when the region covers every pixel, so do not build it in those cases: on a large + // canvas it is a bool per pixel plus a full scan of the mask. + let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_)) && region.mask.contains(&0); + let ring = if use_rim { rim_ring(region) } else { Vec::new() }; let on_ring = |x: i32, y: i32| { let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); let hit = at.and_then(|(yy, xx)| yy.checked_mul(b.width() as usize)?.checked_add(xx)).and_then(|i| ring.get(i)); if hit == Some(&true) { strength(x, y) } else { 0.0 } }; - let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if rim { Some(&on_ring) } else { None }; + let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None }; composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, lock_transparency, inks, rim); } From 667a16dd475fbaccdbc17163da63a398070d27dc Mon Sep 17 00:00:00 2001 From: ljkx <177671075+ljkx@users.noreply.github.com> Date: Thu, 12 Nov 2026 20:22:20 +0100 Subject: [PATCH 13/14] Actions: keep make_from under the cognitive-complexity limit The Frame from Layers branch pushed make_from to 31/30 once main's Artboard mapping was merged in. Move the Make events another module maps (type path, artboard, layer style, frame) into delegated_make_from, tried in the same order as before. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/atn_cmds/steps_make.rs | 30 ++++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/atn_cmds/steps_make.rs b/crates/engine/src/cmd/atn_cmds/steps_make.rs index c3ea88ab58..0e16f09c8f 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -540,26 +540,32 @@ fn type_shape_descriptor() -> Descriptor { desc("null").with("null", class_ref("contentLayer")).with("Usng", target_ref("textLayer")) } +/// Make events another module maps: a type path, an artboard, a layer style or a frame, +/// tried in that order. +fn delegated_make_from(d: &Descriptor) -> Option { + let class = get_ref(d, "null").and_then(ref_class); + match class.as_deref() { + Some("Path") => return Some(super::steps_type_path::from(d)), + // Layer › New › Artboard and Artboard from Layers (#10723). + Some("artboardSection") => return Some(super::steps_artboard_section::from(d)), + _ => {} + } + if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + return Some(mapped); + } + // Layer › New › Frame from Layers (#10723). + (class.as_deref() == Some("framedGroupSection")).then(|| super::steps_frame_section::from(d)) +} + /// Import Make events only when their geometry and options can be represented faithfully, /// including the exact target-text-to-content-layer references. pub(super) fn make_from(d: &Descriptor) -> Mapped { if let Some(mapped) = super::steps_calculations::from_descriptor(d) { return mapped; } - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("Path") { - return super::steps_type_path::from(d); - } - // Layer › New › Artboard and Artboard from Layers (#10723). - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("artboardSection") { - return super::steps_artboard_section::from(d); - } - if let Some(mapped) = super::steps_layer_style::create_from_descriptor(d) { + if let Some(mapped) = delegated_make_from(d) { return mapped; } - // Layer › New › Frame from Layers (#10723). - if get_ref(d, "null").and_then(ref_class).as_deref() == Some("framedGroupSection") { - return super::steps_frame_section::from(d); - } if d.items == type_shape_descriptor().items { return none("type.convertToShape"); } From 8631a921785429670f322bf67dacf9fd5a066799 Mon Sep 17 00:00:00 2001 From: MarekSpodBiedry <73122968+MarekSpodBiedry@users.noreply.github.com> Date: Fri, 13 Nov 2026 01:16:51 +0100 Subject: [PATCH 14/14] Rasterize: undo the layers already converted when a later step fails (#4974) (#5073) * Rasterize: undo the layers already converted when a later step fails (#4974) * Rasterize: roll back through the shared compound helper when a later layer fails (#4974) * Test that a failed Rasterize keeps a clean document clean (#4974) * Rasterize: undo the layers already converted when a later step fails, and refuse before a step starts when there is nothing to do (#4974) * Format the rasterize rollback tests * Rasterize: cover the All Layers and Layer Style refusals through the real commands * Rasterize: name the history step after the variant, and test the rollback through the real commands (#4974) --------- Co-authored-by: skylar --- crates/engine/src/cmd/extra_cmds.rs | 94 +++++++++--- crates/engine/src/cmd/extra_cmds/tests.rs | 52 +++++++ crates/engine/src/cmd/rasterize_style_cmds.rs | 31 ++-- .../src/cmd/rasterize_style_cmds/tests.rs | 55 +++++++ .../tests/it/rasterize_selected_layers.rs | 140 +++++++++++++++++- 5 files changed, 339 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/extra_cmds.rs b/crates/engine/src/cmd/extra_cmds.rs index 96ac6d88c3..4d8e110689 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -727,11 +727,20 @@ pub(crate) fn kind_of(s: &Session, id: LayerId) -> Option<&'static str> { }) } +fn has_vector_mask(s: &Session, id: LayerId, only: Option<&str>) -> bool { + only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()) +} + +/// Whether `rasterize_one` has something to do for this layer. +fn has_rasterize_work(s: &Session, id: LayerId, only: Option<&str>) -> bool { + kind_of(s, id).is_some_and(|k| only.is_none_or(|o| o == k)) || has_vector_mask(s, id, only) +} + /// Rasterize one layer; `only` restricts it to one kind. Without `only` (Rasterize › Layer / All /// Layers: "all vector data") a vector mask becomes a pixel mask too; layer effects stay live, as /// in Photoshop (Rasterize › Layer Style bakes them). Returns false when there was nothing to do. pub(crate) fn rasterize_one(s: &mut Session, id: LayerId, only: Option<&str>, key: &str) -> Result { - let vector_mask = only.is_none() && s.active().and_then(|d| d.doc.layer(id)).is_some_and(|l| l.vector_mask.is_some()); + let vector_mask = has_vector_mask(s, id, only); let content = rasterize_content(s, id, only, key)?; if vector_mask { s.execute("layer.rasterize.vectorMask", json!({"layer": id.0, "coalesce": key}))?; @@ -800,36 +809,75 @@ fn rasterize_content(s: &mut Session, id: LayerId, only: Option<&str>, key: &str /// rasterize"), every selected layer the command applies to, in one history step. pub(crate) fn rasterize(s: &mut Session, p: &Value, only: Option<&'static str>) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; - let many = ids.len() > 1; - let key = step_key(s, "rasterize"); - let mut done = Vec::new(); - for id in ids { - if rasterize_one(s, id, only, &key)? { - done.push(id.0); - } + rasterize_layers(s, ids, only, rasterize_one) +} + +/// The history label of a Rasterize step: the kind it was limited to, or plain "Rasterize". +fn rasterize_label(only: Option<&str>) -> &'static str { + match only { + Some("type") => "Rasterize Type", + Some("shape") => "Rasterize Shape", + Some("fill") => "Rasterize Fill Content", + Some("smart") => "Rasterize Smart Object", + _ => "Rasterize", } - let Some(&first) = done.first() else { - return Err(EngineError::Other(match (only, many) { - (Some(k), false) => format!("the layer is not a {k} layer"), - (Some(k), true) => format!("none of the selected layers is a {k} layer"), - (None, false) => "the layer has nothing to rasterize".into(), - (None, true) => "none of the selected layers has anything to rasterize".into(), - })); - }; +} + +fn nothing_to_rasterize(only: Option<&str>, many: bool) -> EngineError { + EngineError::Other(match (only, many) { + (Some(k), false) => format!("the layer is not a {k} layer"), + (Some(k), true) => format!("none of the selected layers is a {k} layer"), + (None, false) => "the layer has nothing to rasterize".into(), + (None, true) => "none of the selected layers has anything to rasterize".into(), + }) +} + +/// Convert `ids` with `convert` as one history step; a layer that fails takes back the ones +/// converted before it (#4974). +fn rasterize_layers( + s: &mut Session, + ids: Vec, + only: Option<&str>, + convert: impl Fn(&mut Session, LayerId, Option<&str>, &str) -> Result, +) -> Result { + let many = ids.len() > 1; + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| has_rasterize_work(s, id, only)) { + return Err(nothing_to_rasterize(only, many)); + } + let key = step_key(s, "rasterize"); + let (first, done) = crate::analysis_cmds::compound(s, rasterize_label(only), |s| { + let mut done = Vec::new(); + for id in ids { + if convert(s, id, only, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing_to_rasterize(only, many)) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } pub(crate) fn rasterize_all(s: &mut Session) -> Result { let ids: Vec = s.active().map(|d| d.doc.walk().into_iter().map(|(_, _, l)| l.id).collect()).unwrap_or_default(); - let key = step_key(s, "rasterizeAll"); - let mut n = 0; - for id in ids { - // Every sub-step shares one history entry via the coalescing key. - if rasterize_one(s, id, None, &key)? { - n += 1; - } + let ids: Vec = ids.into_iter().filter(|&id| has_rasterize_work(s, id, None)).collect(); + if ids.is_empty() { + return Ok(json!({"rasterized": 0})); } + let key = step_key(s, "rasterizeAll"); + let n = crate::analysis_cmds::compound(s, "Rasterize All Layers", |s| { + let mut n = 0; + for id in ids { + // Every sub-step shares one history entry via the coalescing key. + if rasterize_one(s, id, None, &key)? { + n += 1; + } + } + Ok(n) + })?; Ok(json!({"rasterized": n})) } diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 647a585a23..d85e7c9585 100644 --- a/crates/engine/src/cmd/extra_cmds/tests.rs +++ b/crates/engine/src/cmd/extra_cmds/tests.rs @@ -94,6 +94,10 @@ fn active(s: &Session) -> &Layer { d.doc.layer(d.active_layer.unwrap()).unwrap() } +fn layer_of(s: &Session, id: u64) -> &Layer { + doc(s).layer(LayerId(id)).unwrap() +} + fn pixel(s: &Session, x: i32, y: i32) -> Vec { active(s).surface().unwrap().pixel(x, y) } @@ -1165,6 +1169,54 @@ fn rasterize_fill_and_all_in_one_step() { assert!(doc(&s).walk().iter().all(|(_, _, l)| !matches!(l.content, LayerContent::Fill(_)))); } +/// #4974: Rasterize converts its layers as one step, so a layer that fails after another was +/// converted leaves the document, history, journal and dirty state as they were. +#[test] +fn a_later_layer_failing_takes_back_the_rasterized_ones() { + let mut s = session(8); + let a = s.execute("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap()["layer"].as_u64().unwrap(); + let b = s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + + let ids = vec![LayerId(a), LayerId(b)]; + let r = rasterize_layers(&mut s, ids.clone(), None, |s, id, only, key| { + if id.0 == b { Err(EngineError::Other("second layer failed".into())) } else { rasterize_one(s, id, only, key) } + }); + assert!(r.is_err()); + assert!(matches!(layer_of(&s, a).content, LayerContent::Fill(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Fill(_))); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); + + // Without the failure both are converted in a single step. + rasterize_layers(&mut s, ids, None, rasterize_one).unwrap(); + assert!(matches!(layer_of(&s, a).content, LayerContent::Raster(_))); + assert!(matches!(layer_of(&s, b).content, LayerContent::Raster(_))); + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); +} + +/// A refused Rasterize starts no step: the revision and the saved state do not move. +#[test] +fn rasterize_with_nothing_to_convert_changes_nothing() { + let mut s = session(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + assert!(s.execute("layer.rasterize.layer", json!({})).is_err()); + assert!(s.execute("layer.rasterize.type", json!({})).is_err()); + assert_eq!(s.execute("layer.rasterize.allLayers", json!({})).unwrap()["rasterized"], 0); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + #[test] fn rasterize_smart_object_layer() { let mut s = session(8); diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 55a637d5cb..5c8210852b 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds.rs @@ -106,17 +106,30 @@ fn bake_one(s: &mut Session, id: LayerId, key: &str) -> Result { /// one history step. fn rasterize_layer_style(s: &mut Session, p: &Value) -> Result { let ids = crate::layer_multi_cmds::targets(s, p)?; + bake_layers(s, ids, bake_one) +} + +/// Bake `ids` with `bake` as one history step; a layer that fails takes back the ones baked before +/// it (#4974). +fn bake_layers(s: &mut Session, ids: Vec, bake: impl Fn(&mut Session, LayerId, &str) -> Result) -> Result { let many = ids.len() > 1; - let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); - let mut done = Vec::new(); - for id in ids { - if bake_one(s, id, &key)? { - done.push(id.0); - } + let nothing = || EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into()); + // Refused before a step starts: a failed `compound` still moves the revision, and a command + // that changes nothing must leave it alone. + if !ids.iter().any(|&id| s.active().and_then(|d| d.doc.layer(id)).is_some_and(can_bake)) { + return Err(nothing()); } - let Some(&first) = done.first() else { - return Err(EngineError::Other(if many { "none of the selected layers has layer effects" } else { "the layer has no layer effects" }.into())); - }; + let key = crate::extra_cmds::step_key(s, "rasterizeLayerStyle"); + let (first, done) = crate::analysis_cmds::compound(s, "Rasterize Layer Style", |s| { + let mut done = Vec::new(); + for id in ids { + if bake(s, id, &key)? { + done.push(id.0); + } + } + let Some(&first) = done.first() else { return Err(nothing()) }; + Ok((first, done)) + })?; let active = s.active().and_then(|d| d.active_layer).map(|id| id.0).filter(|id| done.contains(id)); Ok(json!({"layer": active.unwrap_or(first), "layers": done})) } diff --git a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs index b4391cb6f2..285ef60d97 100644 --- a/crates/engine/src/cmd/rasterize_style_cmds/tests.rs +++ b/crates/engine/src/cmd/rasterize_style_cmds/tests.rs @@ -162,3 +162,58 @@ fn disabled_and_bad_params_fail_gracefully() { s.execute("layer.layerStyle.stroke", json!({"layer": g})).unwrap(); assert!(s.execute(ID, json!({"layer": g})).is_err(), "group styles are not baked"); } + +/// #4974: a layer that fails to bake takes back the ones baked before it. +#[test] +fn a_later_layer_failing_takes_back_the_baked_ones() { + let (mut s, id) = scene(8); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + let journal = s.journal.len(); + let calls = std::cell::Cell::new(0); + let r = bake_layers(&mut s, vec![LayerId(id), LayerId(id)], |s, id, key| { + calls.set(calls.get() + 1); + if calls.get() == 1 { bake_one(s, id, key) } else { Err(EngineError::Other("second layer failed".into())) } + }); + assert!(r.is_err()); + assert_eq!(calls.get(), 2); + assert_eq!(layer(&s, id).effects.items.len(), 5); + assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &before)); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().history.can_redo()); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} + +/// A layer with no effects is refused before a step starts: the revision does not move. +#[test] +fn a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + let plain = s.execute("layer.new.layer", json!({"name": "plain"})).unwrap()["layer"].as_u64().unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps) = (s.active().unwrap().revision, s.active().unwrap().history.past_len()); + let err = bake_layers(&mut s, vec![LayerId(plain)], bake_one).unwrap_err().to_string(); + assert!(err.contains("no layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert!(!s.active().unwrap().is_dirty()); +} + +/// Through the command itself: a layer without effects is refused and nothing moves. +#[test] +fn rasterize_layer_style_on_a_layer_without_effects_changes_nothing() { + let (mut s, _) = scene(8); + s.execute("layer.new.layer", json!({"name": "plain"})).unwrap(); + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let (revision, steps, journal) = (s.active().unwrap().revision, s.active().unwrap().history.past_len(), s.journal.len()); + let err = s.execute(ID, json!({})).unwrap_err().to_string(); + assert!(err.contains("no selected layer has layer effects"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().history.past_len(), steps); + assert_eq!(s.journal.len(), journal); + assert!(!s.active().unwrap().is_dirty()); +} diff --git a/crates/engine/tests/it/rasterize_selected_layers.rs b/crates/engine/tests/it/rasterize_selected_layers.rs index a738b51681..265af58894 100644 --- a/crates/engine/tests/it/rasterize_selected_layers.rs +++ b/crates/engine/tests/it/rasterize_selected_layers.rs @@ -3,7 +3,7 @@ //! only on the one that was clicked. An explicit `layer` param still targets exactly that layer. use photocraft_doc::{LayerContent, LayerId}; -use photocraft_engine::Session; +use photocraft_engine::{EngineError, Session}; use serde_json::{Value, json}; fn kind(s: &Session, id: LayerId) -> &'static str { @@ -143,3 +143,141 @@ fn bad_targets_fail_gracefully() { assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer"); } } + +fn deny(denied: &'static str, id: &str) -> photocraft_engine::Result<()> { + if id == denied { Err(EngineError::Other("denied".into())) } else { Ok(()) } +} + +fn deny_shape_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.shape", id) +} + +fn deny_vector_mask_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("layer.rasterize.vectorMask", id) +} + +fn deny_type_rasterize(id: &str, _: &Value) -> photocraft_engine::Result<()> { + deny("type.rasterize", id) +} + +/// Everything a refused Rasterize has to leave as it was (#4974). +struct Snapshot { + doc: std::sync::Arc, + steps: usize, + journal: usize, + selection: Vec, +} + +impl Snapshot { + fn of(s: &mut Session) -> Snapshot { + // A clean document, and a redo entry that a step recorded by mistake would drop. + let st = s.active_mut().unwrap(); + st.saved_revision = st.revision; + let st = s.active().unwrap(); + assert!(st.history.can_redo(), "the test needs a redo entry"); + Snapshot { doc: st.doc.clone(), steps: st.history.past_len(), journal: s.journal.len(), selection: st.selected_layers() } + } + + fn assert_restored(&self, s: &Session) { + let st = s.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&st.doc, &self.doc), "the document is the one from before"); + assert_eq!(st.history.past_len(), self.steps); + assert!(st.history.can_redo(), "the redo entry survives"); + assert_eq!(s.journal.len(), self.journal); + assert!(!st.is_dirty()); + assert_eq!(st.selected_layers(), self.selection); + } +} + +impl Scene { + /// Leave a redo entry behind: a layer that was made, then undone. + fn make_redo_entry(&mut self) { + self.s.execute("layer.new.layer", json!({})).unwrap(); + assert!(self.s.undo()); + assert!(self.s.active().unwrap().history.can_redo()); + } +} + +#[test] +fn rasterize_layer_takes_back_a_converted_layer_when_a_later_one_is_refused() { + let mut sc = scene(); + // The type layer is lower, so it is converted first; the shape layer's step is then denied. + sc.select(&[sc.text, sc.shape]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_shape_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["type", "shape"]); + before.assert_restored(&sc.s); + // Allowed again, the same command converts both in one step. + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layer", json!({})).unwrap(); + assert_eq!(kinds(&sc.s, &[sc.text, sc.shape]), ["raster", "raster"]); + assert_eq!(sc.s.active().unwrap().history.past_len(), before.steps + 1); +} + +#[test] +fn rasterize_layer_takes_back_the_content_when_its_vector_mask_step_is_refused() { + let mut sc = scene(); + let square = json!({"subpaths": [{"closed": true, "knots": [[4, 4], [40, 4], [40, 30], [4, 30]]}]}); + sc.s.execute("layer.vectorMask.add", json!({"layer": sc.text.0, "path": square})).unwrap(); + sc.select(&[sc.text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + // The type content converts, then the mask step is denied. + sc.s.authorize = Some(deny_vector_mask_rasterize); + assert!(sc.s.execute("layer.rasterize.layer", json!({})).is_err()); + assert_eq!(kind(&sc.s, sc.text), "type"); + assert!(sc.s.active().unwrap().doc.layer(sc.text).unwrap().vector_mask.is_some()); + before.assert_restored(&sc.s); +} + +#[test] +fn rasterize_layer_style_takes_back_a_baked_layer_when_a_later_one_is_refused() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let pixels = id_of(s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap()); + s.execute("paint.stroke", json!({"points": [[20, 20]], "size": 12})).unwrap(); + let shadow = json!({"blend": "normal", "distance": 4, "size": 2, "color": "#102040"}); + s.execute("layer.layerStyle.dropShadow", shadow.clone()).unwrap(); + let text = id_of(s.execute("type.create", json!({"text": "Hi", "size": 24, "x": 4, "y": 30})).unwrap()); + s.execute("layer.layerStyle.dropShadow", shadow).unwrap(); + let mut sc = Scene { s, text, shape: pixels, smart: pixels, fill: pixels, bystander: pixels }; + // The pixel layer is lower, so it is baked first; the type layer's content step is then denied. + sc.select(&[pixels, text]); + sc.make_redo_entry(); + let before = Snapshot::of(&mut sc.s); + sc.s.authorize = Some(deny_type_rasterize); + assert!(sc.s.execute("layer.rasterize.layerStyle", json!({})).is_err()); + let st = sc.s.active().unwrap(); + assert!(!st.doc.layer(pixels).unwrap().effects.items.is_empty(), "the baked layer has its effects back"); + assert_eq!(kind(&sc.s, text), "type"); + before.assert_restored(&sc.s); + sc.s.authorize = None; + sc.s.execute("layer.rasterize.layerStyle", json!({})).unwrap(); + assert!(sc.s.active().unwrap().doc.layer(pixels).unwrap().effects.items.is_empty()); + assert_eq!(kind(&sc.s, text), "raster"); +} + +#[test] +fn each_rasterize_command_names_its_history_step() { + let cases = [ + ("layer.rasterize.layer", "text", "Rasterize"), + ("layer.rasterize.type", "text", "Rasterize Type"), + ("layer.rasterize.shape", "shape", "Rasterize Shape"), + ("layer.rasterize.fillContent", "fill", "Rasterize Fill Content"), + ("layer.rasterize.smartObject", "smart", "Rasterize Smart Object"), + ]; + for (cmd, which, label) in cases { + let mut sc = scene(); + let id = match which { + "text" => sc.text, + "shape" => sc.shape, + "fill" => sc.fill, + _ => sc.smart, + }; + sc.select(&[id]); + sc.s.execute(cmd, json!({})).unwrap(); + assert_eq!(sc.s.active().unwrap().history.undo_label(), Some(label), "{cmd}"); + } +}