diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index a7f57c337d..0a5b113c5c 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -63,7 +63,11 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { } } -/// Composites `color(i)` over `area` of the surface with per-pixel coverage. +/// 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, area: Rect, @@ -72,6 +76,7 @@ fn composite_area( color: impl Fn(i32, i32) -> [f32; 4] + Sync, lock_transparency: bool, inks: Option<[f32; 4]>, + 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. @@ -86,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 { @@ -97,6 +106,13 @@ 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) => blend::composite(m, d, color(x, y), k), @@ -166,6 +182,7 @@ pub fn paint_gradient( }, lock_transparency, None, + None, ); } @@ -228,8 +245,20 @@ 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 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 = anti_alias && 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 } @@ -258,9 +287,55 @@ pub fn bucket_fill_region_inks( inks: Option<[f32; 4]>, mode: FillMode, ) { - // Composite only over the filled region's box. + fill_region(s, region, opacity, selection, lock_transparency, src, inks, mode, false); +} + +/// [`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, + 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, + rim: bool, +) { + // 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; - 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)); + // 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 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); +} + +/// 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)] @@ -349,6 +424,174 @@ 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!(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); + } + } + } + + /// #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)); + } + + /// #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 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))); + 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/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 795ba9d1bb..c3e3254ac2 100644 --- a/crates/engine/src/canvas_geom.rs +++ b/crates/engine/src/canvas_geom.rs @@ -305,6 +305,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 a17fdec405..ed45d55021 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 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. + // 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/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index ab719ce18c..4b50abfcf5 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -45,6 +45,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; @@ -205,6 +206,9 @@ 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 bbe17feb8e..97292737a4 100644 --- a/crates/engine/src/cmd/atn_cmds/events.rs +++ b/crates/engine/src/cmd/atn_cmds/events.rs @@ -856,6 +856,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..873ace6627 --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/frame_section_tests.rs @@ -0,0 +1,254 @@ +//! #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)); +} + +/// 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")]); + 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. +#[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 4b0c53a0a0..0e16f09c8f 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_make.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_make.rs @@ -540,20 +540,30 @@ 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; } if d.items == type_shape_descriptor().items { @@ -727,6 +737,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 2319762534..cbbb23f6cc 100644 --- a/crates/engine/src/cmd/atn_cmds/tests.rs +++ b/crates/engine/src/cmd/atn_cmds/tests.rs @@ -706,6 +706,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.new.artboard", json!({"rect": [10, 20, 100, 50], "name": "Hero"})), ("layer.new.artboardFromLayers", json!({"name": "Cards"})), diff --git a/crates/engine/src/cmd/count_resize_tests.rs b/crates/engine/src/cmd/count_resize_tests.rs new file mode 100644 index 0000000000..7648ed0051 --- /dev/null +++ b/crates/engine/src/cmd/count_resize_tests.rs @@ -0,0 +1,94 @@ +//! #11762: count points keep their document coordinates through Image Size, Canvas Size and Image +//! Rotation (right angles, flips and arbitrary), also off the new canvas; other marks still follow +//! the image, and Crop keeps today's behaviour. + +use serde_json::{Value, json}; + +use crate::Session; + +const POINT: [f64; 2] = [99.3, 99.7]; + +fn doc() -> 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() { + // 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, moved) in steps { + let mut s = doc(); + let before = note(&s); + s.execute(cmd, p).unwrap(); + assert_eq!(count_point(&s), POINT, "{cmd}"); + 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"); + } +} + +#[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"); +} + +#[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(); + // 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)); + 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(); + // 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(()) }); + 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"); +} diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index efd8d60df3..4887228dfc 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -7,6 +7,10 @@ //! layers with locked transparency; the Background Eraser erases them to transparency and leaves //! the lock on. Both respect the selection, work in the layer's own colour model and depth, and are //! one undo step per click / stroke. +//! +//! The Magic Eraser refuses Indexed Color and Bitmap documents with the reference's alerts +//! ([`MAGIC_ERASER_INDEXED_ERROR`] and [`MAGIC_ERASER_BITMAP_ERROR`], #12032), before it samples +//! anything, so a refused click leaves the document exactly as it was. use photocraft_algo::selection as sel; use photocraft_color::{ColorMode, SampleType}; @@ -79,6 +83,28 @@ fn damage(s: &mut Session, dmg: Rect, erased: bool) -> Value { json!({ "erased": erased, "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }) } +/// The reference's alert for a Magic Eraser click in an Indexed Color document (#12032), measured: +/// one alert with an OK button. The UI shows this text through `tl!` (English is the catalog +/// source); the command returns it as its error. +pub const MAGIC_ERASER_INDEXED_ERROR: &str = + "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// The same alert for a Bitmap document (#12032), which points at Grayscale instead. +pub const MAGIC_ERASER_BITMAP_ERROR: &str = + "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The alert `doc` gets instead of a Magic Eraser click, or `None` when the click may erase +/// (#12032). Indexed Color and Bitmap are the two measured refusals, at every bit depth; Duotone +/// and Multichannel are not measured and keep erasing, as do RGB, Grayscale, CMYK and Lab. +/// The text is exactly what `paint.magicEraser` answers with, so the tool can refuse the press with +/// what the command would refuse. +pub fn magic_eraser_refusal(doc: &Document) -> Option<&'static str> { + match doc.mode { + ColorMode::Indexed => Some(MAGIC_ERASER_INDEXED_ERROR), + ColorMode::Bitmap => Some(MAGIC_ERASER_BITMAP_ERROR), + _ => None, + } +} + /// `paint.magicEraser`: erase the wand region around `(x, y)`. fn magic_eraser(s: &mut Session, p: &Value) -> Result { const CMD: &str = "paint.magicEraser"; @@ -89,6 +115,13 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result { let tolerance = number(p, CMD, "tolerance", 32.0, 0.0..=255.0)? as f32; let opacity = number(p, CMD, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0; let (anti_alias, contiguous, sample_all) = (flag(p, "antiAlias", true), flag(p, "contiguous", true), flag(p, "sampleAllLayers", false)); + // #12032: an Indexed Color or a Bitmap document gets the reference's alert before anything is + // sampled or edited, so the click changes nothing: no pixels, no selection, no History step, + // and the Background stays a Background. The tool refuses the press with this same text + // (`eraser_ui::click`), which is why the check belongs to the command. + if let Some(msg) = s.active().and_then(|st| magic_eraser_refusal(&st.doc)) { + return Err(EngineError::Other(msg.into())); + } let id = active_pixel_layer(s, p, CMD)?; { let d = s.active().ok_or(EngineError::NoDocument)?; @@ -280,7 +313,7 @@ pub fn specs() -> Vec { label: "Magic Eraser", menu: &[], shortcut: None, - params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100}"##, + params: r##"{"x":px,"y":px,"tolerance":0..255=32,"antiAlias":bool=true,"contiguous":bool=true,"sampleAllLayers":bool=false,"opacity":1..100=100} (one undo step; a click off the canvas erases nothing and records no step; refused with the tool's alert and nothing changes: an Indexed Color document answers "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).", a Bitmap document "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; Duotone and Multichannel erase as before)"##, enabled: has_pixel_layer, run: magic_eraser, journal: true, @@ -298,6 +331,8 @@ pub fn specs() -> Vec { ] } +#[cfg(test)] +mod magic_eraser_mode_refusal_tests; #[cfg(test)] mod magic_eraser_tolerance_tests; #[cfg(test)] diff --git a/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs new file mode 100644 index 0000000000..b56d839310 --- /dev/null +++ b/crates/engine/src/cmd/eraser_cmds/magic_eraser_mode_refusal_tests.rs @@ -0,0 +1,104 @@ +//! #12032: the Magic Eraser refuses Indexed Color and Bitmap documents with the reference's +//! alerts, and refuses them *before* it samples or edits anything: no History step, the Background +//! stays a Background, the pixels and the selection stay as they were. Duotone and Multichannel +//! are not measured, so they keep today's behaviour; the modes and depths the issue lists as +//! working (RGB, Grayscale, CMYK and Lab at 8 bits, RGB at 16 and 32 bits) still erase. + +use super::*; +use photocraft_doc::{Color, SampleType, Size}; + +/// The reference's alert for an Indexed Color document, measured (#12032); the alert has one OK +/// button. Spelled out here rather than taken from the command, so the test fails if the text the +/// app shows ever drifts from what was measured. +const INDEXED: &str = "Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +/// Its alert for a Bitmap document, measured (#12032). +const BITMAP: &str = "Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// A 64x48 document in `mode` at `depth`: a white Background - one flat colour, so a Magic Eraser +/// click on it would wipe the canvas out - with a live selection. Both must survive a refusal. +fn session(mode: photocraft_color::ColorMode, depth: SampleType) -> Session { + let d = Document::with_background("palette", Size::new(64, 48), mode, depth, Color::WHITE); + let mut s = Session::new(); + s.add_document(d, None); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 20, "height": 20, "antiAlias": false})).unwrap(); + s +} + +/// What a refused click must leave exactly as it was: the document itself, the History depth, one +/// pixel, and the selection. +fn snapshot(s: &Session) -> (std::sync::Arc, usize, Vec, Option) { + let st = s.active().unwrap(); + let pixels = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(2, 2).to_vec(); + (st.doc.clone(), st.history.past_len(), pixels, st.doc.selection.clone()) +} + +/// The text `paint.magicEraser` answers this click with, panicking with `case` in its message when +/// it erases or answers something else. +fn alert(s: &mut Session, case: &str, want: &str, p: Value) -> String { + match s.execute("paint.magicEraser", p.clone()) { + Err(e) if e.to_string() == want => e.to_string(), + Err(e) => panic!("{case}: refused with the wrong text: {e}"), + Ok(r) => panic!("{case}: the click erased instead of being refused: {r}"), + } +} + +#[test] +fn magic_eraser_refuses_indexed_and_bitmap_with_the_reference_alerts() { + for (case, mode, want) in [("Indexed", photocraft_color::ColorMode::Indexed, INDEXED), ("Bitmap", photocraft_color::ColorMode::Bitmap, BITMAP)] { + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + // The refusal is the same whatever else the click asks for: sampling every layer or + // only this one, the whole canvas or one colour, inside the selection or not. + for p in [ + json!({"x": 2, "y": 2, "antiAlias": false}), + json!({"x": 12, "y": 12, "antiAlias": false}), + json!({"x": 2, "y": 2, "antiAlias": false, "sampleAllLayers": true}), + json!({"x": 2, "y": 2, "antiAlias": false, "contiguous": false, "tolerance": 255, "opacity": 1}), + ] { + let name = format!("{case} {depth:?} {p}"); + let mut s = session(mode, depth); + let (doc, steps, pixels, selection) = snapshot(&s); + let id = s.active().unwrap().active_layer.unwrap(); + assert_eq!(alert(&mut s, &name, want, p), want.to_string()); + let st = s.active().unwrap(); + // Nothing at all happened: not a History step, not a pixel, not the selection, and + // the Background is still a Background rather than the "Layer 0" the erase makes. + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{name}: the document is untouched"); + assert_eq!(st.history.past_len(), steps, "{name}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{name}: the layer name"); + assert!(st.doc.is_background(id), "{name}: still a Background"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2).to_vec(), pixels, "{name}: pixels unchanged"); + assert_eq!(st.doc.selection, selection, "{name}: the selection is unchanged"); + } + } + } +} + +#[test] +fn magic_eraser_still_erases_the_measured_modes_and_depths() { + for (mode, depth) in [("rgb", 8), ("gray", 8), ("cmyk", 8), ("lab", 8), ("rgb", 16), ("rgb", 32)] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "mode": mode, "depth": depth})).unwrap(); + let h = s.active().unwrap().history.past_len(); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})).unwrap(); + assert_eq!(r["erased"], true, "{mode} {depth}: still erases"); + assert_eq!(s.active().unwrap().history.past_len(), h + 1, "{mode} {depth}: one undo step"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{mode} {depth}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{mode} {depth}: erased to transparency"); + } +} + +/// Duotone and Multichannel are *not measured* (#12032), so they keep today's behaviour: the click +/// erases, and neither of the two alerts appears. +#[test] +fn duotone_and_multichannel_keep_todays_behaviour() { + for (case, mode) in [("Duotone", photocraft_color::ColorMode::Duotone), ("Multichannel", photocraft_color::ColorMode::Multichannel)] { + let mut s = session(mode, SampleType::U8); + let id = s.active().unwrap().active_layer.unwrap(); + let r = s.execute("paint.magicEraser", json!({"x": 2, "y": 2, "antiAlias": false})); + assert!(r.is_ok(), "{case}: keeps today's behaviour, answers {r:?}"); + assert_eq!(r.unwrap()["erased"], true, "{case}"); + assert_eq!(s.active().unwrap().doc.layer(id).unwrap().name, "Layer 0", "{case}"); + } +} 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/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index 8e2ea786b5..e48f337246 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)) @@ -359,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), diff --git a/crates/engine/src/cmd/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 9eff784a42..898c71c981 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -318,7 +318,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; @@ -714,7 +714,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); @@ -1049,7 +1049,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 218718ebd0..dcaf8a8f18 100644 --- a/crates/engine/src/cmd/mode_cmds.rs +++ b/crates/engine/src/cmd/mode_cmds.rs @@ -63,6 +63,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); @@ -132,7 +138,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)?; } diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index bbcc8f7012..7043373580 100644 --- a/crates/engine/src/cmd/paint_cmds/tests.rs +++ b/crates/engine/src/cmd/paint_cmds/tests.rs @@ -329,3 +329,101 @@ 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 / #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 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() { + 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); + // 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"); + + 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); + 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 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 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:?}"); + } + 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"); + } +} + +/// 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}")); + } + } +} 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}"); + } +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index d600445e75..bfad6a57b8 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -518,8 +518,9 @@ pub const NO_SELECTION_MENU: &[Row] = &[ ]; /// Photoshop's generic layer menu, in its order for a pixel layer without a selection: the Count -/// tool's canvas menu on a marker or off one (#11772), and the Red Eye tool's without a selection. Each row is enabled as the Layers panel -/// menu enables it for the active layer (`menus::is_enabled`) and runs like the menu item. +/// tool's canvas menu on a marker or off one (#11772), and the Red Eye and Object Selection +/// (#12866) tools' without a selection. Each row is enabled as the Layers panel menu enables it +/// for the active layer (`menus::is_enabled`) and runs like the menu item. pub const COUNT_MENU: &[Row] = &[ Some(("Blending Options…", "layer.layerStyle.blendingOptions")), None, @@ -543,8 +544,9 @@ pub const COUNT_MENU: &[Row] = &[ /// Right-click with the Content-Aware Move tool inside an active selection (#12194). pub const CAM_INSIDE_SELECTION_MENU: &[Row] = &[Some(("Color Range…", "select.colorRange")), Some(("Load Selection…", "select.loadSelection"))]; -/// The selection menu as measured in the reference application with the Red Eye tool (#12577): -/// no Distort or Perspective, and Delete and Fill Selection after the fills. +/// The selection menu as measured in the reference application with the Red Eye tool (#12577) and +/// the Object Selection tool (#12866): no Distort or Perspective, and Delete and Fill Selection +/// after the fills. pub const MEASURED_SELECTION_MENU: &[Row] = selection_menu![ None, Some(("Fill…", "edit.fill")), @@ -851,7 +853,7 @@ pub fn rows(menu: &CanvasToolMenu) -> &'static [Row] { SAMPLER_MENU } else if menu.tool == Tool::Count { COUNT_MENU - } else if menu.tool == Tool::RedEye { + } else if matches!(menu.tool, Tool::RedEye | Tool::ObjectSelection) { if menu.has_selection { MEASURED_SELECTION_MENU } else { COUNT_MENU } } else if menu.tool == Tool::Eyedropper { EYEDROPPER_MENU @@ -1838,3 +1840,6 @@ mod delete_anchor_menu_tests; #[cfg(test)] mod convert_point_menu_tests; + +#[cfg(test)] +mod object_selection_menu_tests; diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs new file mode 100644 index 0000000000..a1f722a626 --- /dev/null +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/object_selection_menu_tests.rs @@ -0,0 +1,192 @@ +//! #12866: the Object Selection tool's canvas menu lists the reference application's rows: with a +//! selection, no Distort or Perspective and Delete and Fill Selection after the fills; with none, +//! the layer menu, its rows greyed as measured over the Background, a type and a shape layer. The +//! marquees', lassos' and Magic Wand's menus are unchanged. + +use egui::{Context, Modifiers}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; + +use super::tests::{app, harness, labels, right_click}; +use super::{COUNT_MENU, NO_SELECTION_MENU, SELECTION_MENU, available, open, rows}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A pixel layer filled red, active, with `select` run first when given. +fn pixel_layer(select: &[(&str, Value)]) -> PhotocraftApp { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + for (id, params) in select { + app.run(id, params.clone()).unwrap(); + } + app.ui.tool = Tool::ObjectSelection; + app +} + +/// Right-click the middle of the canvas: the open menu's entries as `ui.inspect` lists them. +fn right_click_entries(h: &mut Harness<'static, PhotocraftApp>) -> Vec { + let center = h.state().last_canvas_rect.center(); + right_click(h, center, Modifiers::NONE); + let inspected = crate::control::inspect(h.state(), &h.ctx); + assert_eq!(inspected["canvasToolMenu"]["tool"], json!("ObjectSelection")); + inspected["canvasToolMenu"]["entries"].as_array().cloned().unwrap_or_default() +} + +/// The entries' labels, a separator as `None`. +fn shown(entries: &[Value]) -> Vec> { + entries.iter().map(|e| if e["separator"] == json!(true) { None } else { e["label"].as_str().map(String::from) }).collect() +} + +/// The issue's notation: rows joined by " · ", separators written " ― ". +fn menu(spec: &str) -> Vec> { + spec.split(" ― ") + .enumerate() + .flat_map(|(i, group)| (i > 0).then_some(None).into_iter().chain(group.split(" · ").map(|label| Some(label.to_owned())))) + .collect() +} + +#[test] +fn with_a_selection_the_menu_lists_the_reference_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Deselect · Select Inverse · Feather… · Select and Mask… ― Save Selection… · Make Work Path… ― Layer Via Copy · Layer Via Cut · \ + New Layer… ― Free Transform · Transform Selection ― Fill… · Stroke… · Content-Aware Fill… · Delete and Fill Selection ― \ + Last Filter ― Fade…" + ) + ); + // A row the menu had before runs its command, as before. + let before = h.state().session.journal.len(); + h.get_by_label("Select Inverse").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.journal[before..].iter().any(|(id, _)| id == "select.inverse")); +} + +#[test] +fn with_no_selection_the_menu_lists_the_layer_rows() { + let mut h = harness(pixel_layer(&[("select.rect", json!({"x": 4, "y": 4, "width": 24, "height": 24})), ("select.deselect", json!({}))])); + let entries = right_click_entries(&mut h); + assert_eq!( + shown(&entries), + menu( + "Blending Options… ― Duplicate Layer… · Delete Layer · Group from Layers… ― Convert to Smart Object · Convert to Layers ― \ + Rasterize Layer · Rasterize Layer Style ― Free Transform ― Color Range… · Load Selection… · Reselect" + ) + ); + // Over a plain pixel layer these have nothing to act on and grey out. + for label in ["Convert to Layers", "Rasterize Layer", "Rasterize Layer Style"] { + let entry = entries.iter().find(|e| e["label"] == json!(label)); + assert_eq!(entry.map(|e| &e["enabled"]), Some(&json!(false)), "{label} is greyed out"); + } + h.get_by_label("Reselect").click(); + h.run_steps(2); + assert!(h.state().ui.canvas_tool_menu.is_none()); + assert!(h.state().session.active().unwrap().doc.selection.is_some(), "Reselect brings the selection back"); + assert_eq!(h.state().session.journal.last().map(|(id, _)| id.as_str()), Some("select.reselect")); +} + +/// The rows greyed without a selection, as measured over each layer kind (#12866). Load +/// Selection… and Reselect follow the document, not the layer, and are left out. +const GREYED: [(&str, &[&str]); 3] = [ + ("Background", &["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]), + ("Type", &["Convert to Layers", "Rasterize Layer Style"]), + ("Shape", &["Convert to Layers", "Rasterize Layer Style"]), +]; + +#[test] +fn background_type_and_shape_layers_get_the_layer_menu_greyed_as_measured() { + for (kind, greyed) in GREYED { + let mut app = app(); + // The Background stays active under a second layer, so Delete Layer has one to keep. + let background = app.session.active().and_then(|st| st.active_layer).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + match kind { + "Background" => app.session.set_active_layer(Some(background)), + "Type" => { + app.run("type.create", json!({"x": 4, "y": 20, "text": "A", "size": 12})).unwrap(); + } + _ => { + app.run("shape.create", json!({"kind": "rect", "rect": [4, 4, 20, 20], "fill": "#ff0000"})).unwrap(); + } + } + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + assert_eq!(if st.doc.is_background(layer.id) { "Background" } else { layer.content.kind_name() }, kind); + app.ui.tool = Tool::ObjectSelection; + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0]), "{kind}"); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert_eq!(labels(rows(&menu)), labels(COUNT_MENU), "{kind}"); + let wrong: Vec<_> = rows(&menu) + .iter() + .flatten() + .filter(|(label, id)| !matches!(*label, "Load Selection…" | "Reselect") && available(&app, &menu, id) == greyed.contains(label)) + .map(|(label, _)| *label) + .collect(); + assert!(wrong.is_empty(), "{kind}: enabled or greyed unlike the reference: {wrong:?}"); + } +} + +/// The reference application greys Group from Layers… whenever the Background is selected, also +/// beside a pixel layer that is the active one. +#[test] +fn group_from_layers_is_greyed_with_the_background_among_the_selected_layers() { + let mut app = pixel_layer(&[]); + let st = app.session.active().unwrap(); + let pixel = st.active_layer.unwrap(); + let background = st.doc.layers.iter().map(|l| l.id).find(|id| st.doc.is_background(*id)).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(available(&app, &menu, "layer.new.groupFromLayers"), "a pixel layer alone can be grouped"); + app.run("layer.select", json!({"layer": background.0, "mode": "add"})).unwrap(); + app.session.set_active_layer(Some(pixel)); + assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + assert!(!available(&app, &menu, "layer.new.groupFromLayers"), "the Background is selected too"); +} + +#[test] +fn every_object_selection_row_runs_a_known_command() { + let mut app = pixel_layer(&[]); + let items = crate::menus::menu_items(&app); + // Selected first, then deselected. + for id in ["select.all", "select.deselect"] { + app.run(id, json!({})).unwrap(); + assert!(open(&mut app, &Context::default(), Tool::ObjectSelection, [10.0, 10.0])); + let menu = app.ui.canvas_tool_menu.clone().unwrap(); + for (label, id) in rows(&menu).iter().flatten() { + assert!(items.iter().any(|i| i.id == *id) || photocraft_engine::commands::find(id).is_some(), "{label}: unknown command {id}"); + } + } +} + +#[test] +fn the_other_selection_tools_keep_their_menus() { + let tools = [ + Tool::RectMarquee, + Tool::EllipseMarquee, + Tool::SingleRowMarquee, + Tool::SingleColumnMarquee, + Tool::Lasso, + Tool::PolygonLasso, + Tool::MagneticLasso, + Tool::MagicWand, + ]; + for tool in tools { + for (selection, menu) in [(true, SELECTION_MENU), (false, NO_SELECTION_MENU)] { + let mut app = app(); + if selection { + app.run("select.all", json!({})).unwrap(); + } + app.ui.tool = tool; + assert!(open(&mut app, &Context::default(), tool, [10.0, 10.0]), "{tool:?}"); + let open_rows = rows(app.ui.canvas_tool_menu.as_ref().unwrap()); + assert_eq!(labels(open_rows), labels(menu), "{tool:?}, selection {selection}"); + } + } +} diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs index 6a3c5075c5..debcd8aee4 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu/tests.rs @@ -387,7 +387,7 @@ fn transform_menu_follows_photoshop_order() { } } -fn labels(rows: &[Row]) -> Vec> { +pub(super) fn labels(rows: &[Row]) -> Vec> { rows.iter().map(|row| row.map(|(label, _)| label)).collect() } diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index 27e20888dd..b85c146e23 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -41,10 +41,10 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // in Normal mode: each tool's Mode starts at Normal, so a Multiply Brush doesn't make the // first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have). // The Art History Brush also starts at full opacity (#10263): its Opacity is its own. - // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools and the Clone - // Stamp start with their own measured tips instead, as the whole brush Reset Tool gives - // them (#11911, #12099, #12671, #12684, #13029, #12601). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp) => { + // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone + // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush + // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). + None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { fresh_brush(tool, ¤t) } None => { @@ -90,13 +90,15 @@ const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); /// The Remove tool's size after Reset Tool (#12548): 19 px. Its hardness and spacing are not /// measured, so they stay the default brush's. const REMOVE_TOOL_SIZE: f32 = 19.0; +/// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. +const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is /// [`BRUSH_TOOL_TIP`], the Background Eraser's [`BACKGROUND_ERASER_TIP`], the Healing Brush's /// [`HEALING_BRUSH_TIP`], the Burn, Dodge and Sponge tools' [`TONING_TOOL_TIP`], the Clone Stamp's -/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`]; the other -/// tools keep the default tip. +/// [`CLONE_STAMP_TIP`] with no smoothing, the Remove tool's size [`REMOVE_TOOL_SIZE`], the Smudge +/// tool's [`SMUDGE_TOOL_TIP`]; the other tools keep the default tip. pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings { let mut brush = BrushSettings { smoothing: first_smoothing(), ..BrushSettings::default() }; match tool { @@ -104,6 +106,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings Tool::BackgroundEraser => (brush.size, brush.hardness, brush.spacing) = BACKGROUND_ERASER_TIP, Tool::Healing => (brush.size, brush.hardness, brush.spacing) = HEALING_BRUSH_TIP, Tool::Burn | Tool::Dodge | Tool::Sponge => (brush.size, brush.hardness, brush.spacing) = TONING_TOOL_TIP, + Tool::Smudge => (brush.size, brush.hardness, brush.spacing) = SMUDGE_TOOL_TIP, Tool::CloneStamp => { (brush.size, brush.hardness, brush.spacing) = CLONE_STAMP_TIP; brush.smoothing.amount = 0.0; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5fbd4f4378..b46f0503b8 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1103,6 +1103,8 @@ mod background_eraser_digit_keys_tests; #[cfg(test)] mod clone_stamp_reset_tip_tests; #[cfg(test)] +mod smudge_default_tip_tests; +#[cfg(test)] mod sponge_default_tip_tests; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 3da894ccf7..dfe898d298 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -27,6 +27,8 @@ fn background_blocks(id: &str, has_selection: bool) -> bool { "layer.createClippingMask" | "layer.releaseClippingMask" | "layer.mergeDown" + // The Background can't go into a group (#12866, measured on the canvas menu). + | "layer.new.groupFromLayers" | "layer.lockLayers" | "layer.maskAllObjects" | "edit.puppetWarp" @@ -104,6 +106,11 @@ fn selection_targets(id: &str) -> Option { /// runs on all of them is greyed only when none of them can take it (the active layer alone must /// not decide). Everything else, and a single selected layer, is judged by the active layer. pub fn disabled_for_selection(doc: &Document, selected: &[LayerId], active: Option<&Layer>, id: &str) -> bool { + // The reference application refuses Group from Layers whenever the Background is among the + // selected layers, not only when it is the active one. + if id == "layer.new.groupFromLayers" && selected.iter().filter_map(|l| doc.layer(*l)).any(|l| crate::doc_props_ui::is_background(doc, l)) { + return true; + } let Some(rule) = selection_targets(id).filter(|_| selected.len() > 1) else { return disabled_for(doc, active, id) }; let layers = selected.iter().filter_map(|l| doc.layer(*l)); let can = |l: &Layer| !disabled_for(doc, Some(l), id) && (!matches!(rule, Targets::WithoutMask) || l.mask.is_none()); @@ -186,7 +193,7 @@ pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { return true; } // Only these commands depend on the selection; skip walking the layers for the rest. - if selection_targets(id).is_some() { + if selection_targets(id).is_some() || id == "layer.new.groupFromLayers" { return disabled_for_selection(&st.doc, &st.selected_layers(), active, id); } disabled_for(&st.doc, active, id) diff --git a/crates/ui-egui/src/red_eye_context_menu_tests.rs b/crates/ui-egui/src/red_eye_context_menu_tests.rs index a7a5a20933..277eac2107 100644 --- a/crates/ui-egui/src/red_eye_context_menu_tests.rs +++ b/crates/ui-egui/src/red_eye_context_menu_tests.rs @@ -63,9 +63,10 @@ const NO_SELECTION: [&str; 17] = [ "Reselect", ]; -/// The reference also greys Group from Layers… and Load Selection…, but their menu-bar twins are -/// live here (as in the Count tool's menu), and the rows follow the twins. -const NO_SELECTION_GREY: [&str; 5] = ["Blending Options…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]; +/// The reference also greys Load Selection…, but its menu-bar twin is live here (as in the Count +/// tool's menu), and the row follows the twin. +const NO_SELECTION_GREY: [&str; 6] = + ["Blending Options…", "Group from Layers…", "Convert to Layers", "Rasterize Layer", "Rasterize Layer Style", "Free Transform"]; const IN_SELECTION: [&str; 23] = [ "Deselect", diff --git a/crates/ui-egui/src/smudge_default_tip_tests.rs b/crates/ui-egui/src/smudge_default_tip_tests.rs new file mode 100644 index 0000000000..3086f52467 --- /dev/null +++ b/crates/ui-egui/src/smudge_default_tip_tests.rs @@ -0,0 +1,84 @@ +//! #12964: the Smudge tool starts, and comes back after Reset Tool, with the reference +//! application's tip: a 13 px soft round (hardness 0 %, angle 0°, roundness 100 %) at 25 % +//! spacing. Other tools' starting tips are unchanged. + +use serde_json::json; + +use crate::PhotocraftApp; +use crate::burn_default_tip_tests::{app, invoke, pick}; +use crate::state::Tool; + +/// Size, hardness, spacing, angle and roundness of the live brush, as `brush.get` reports them. +fn tip(app: &mut PhotocraftApp) -> [f64; 5] { + let b = app.run("brush.get", json!({})).unwrap(); + ["size", "hardness", "spacing", "angle", "roundness"].map(|k| (b[k].as_f64().unwrap() * 1e4).round() / 1e4) +} + +/// A tip that is no tool's starting tip, so a reset has something to undo. +fn scramble(app: &mut PhotocraftApp) { + let b = &mut app.session.tools.brush; + (b.size, b.hardness, b.spacing, b.angle, b.roundness) = (57.0, 0.4, 0.6, 30.0, 0.5); +} + +const SMUDGE_TIP: [f64; 5] = [13.0, 0.0, 0.25, 0.0, 1.0]; +const DEFAULT_TIP: [f64; 5] = [20.0, 1.0, 0.1, 0.0, 1.0]; + +#[test] +fn reset_tool_gives_the_smudge_tool_a_13_px_soft_tip() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.reset", json!({})); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // The options-bar brush chip reads the live brush's rounded size. + assert_eq!(app.session.tools.brush.size.round(), 13.0); +} + +#[test] +fn a_first_use_starts_with_the_tip() { + // No stored tool brushes, as on a fresh install: the Smudge tool's first pick, after another + // tool's tip. + let mut app = app(); + pick(&mut app, Tool::Pencil); + scramble(&mut app); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP); + // Its own tip is then kept across tool switches. + app.session.tools.brush.size = 42.0; + pick(&mut app, Tool::Pencil); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app)[0], 42.0); +} + +#[test] +fn reset_all_tools_gives_it_the_tip_active_or_picked_later() { + let mut app = app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + assert_eq!(tip(&mut app), SMUDGE_TIP, "active"); + let mut app = self::app(); + pick(&mut app, Tool::Smudge); + scramble(&mut app); + pick(&mut app, Tool::Pencil); + invoke(&mut app, "tool.resetAll", json!({"confirmed": true})); + pick(&mut app, Tool::Smudge); + assert_eq!(tip(&mut app), SMUDGE_TIP, "picked after the reset"); +} + +#[test] +fn blur_and_sharpen_keep_their_tips() { + for tool in [Tool::Blur, Tool::Sharpen] { + let mut a = app(); + pick(&mut a, tool); + scramble(&mut a); + invoke(&mut a, "tool.reset", json!({})); + assert_eq!(tip(&mut a), DEFAULT_TIP, "{tool:?}"); + // A first use still takes the current tip, as before. + let mut a = app(); + pick(&mut a, Tool::Pencil); + scramble(&mut a); + pick(&mut a, tool); + assert_eq!(tip(&mut a)[0], 57.0, "{tool:?}, first use"); + } +} diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ee9461f6fd..d569f73f11 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -545,8 +545,10 @@ fn a_shift_click_dodge_line_commits_its_live_pixels_unsmoothed() { fn pressure_sized_smudge_release_matches_replay_and_undo_redo() { use crate::stylus::PenSample; + // The spacing is set too: the Smudge tool starts with its own tip (#12964), the replay's + // fresh session with the default brush. let setup = |run: &mut dyn FnMut(&str, Value)| { - run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"pressureSize":true,"smoothing":{"amount":0.4}}})); + run("tools.setBrush", json!({"brush": {"size":40,"hardness":0.7,"spacing":0.1,"pressureSize":true,"smoothing":{"amount":0.4}}})); run("paint.stroke", json!({"points":[[10,20],[190,80]],"size":30,"color":"#2060c0"})); }; let mut h = harness(); diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 9d4bf194af..3a88440a52 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -1,10 +1,14 @@ //! UI for the Eraser group's colour-aware tools: Magic Eraser (click → `paint.magicEraser`) and //! Background Eraser (stroke → `paint.backgroundEraser`), with their options bars. +//! +//! A Magic Eraser press in an Indexed Color or Bitmap document shows the reference's alert (message +//! + OK) and runs nothing: the document keeps its pixels and its History (#12032). +use photocraft_engine::eraser_cmds::{MAGIC_ERASER_BITMAP_ERROR, MAGIC_ERASER_INDEXED_ERROR}; use serde_json::{Value, json}; use crate::PhotocraftApp; -use crate::state::Tool; +use crate::state::{DialogKind, Tool}; use crate::theme::Tokens; use crate::{icons, widgets}; @@ -15,11 +19,50 @@ fn report(app: &mut PhotocraftApp, r: Result) { } } +/// The alert this document gets instead of a Magic Eraser click (#12032): `Some(text)` means the +/// click is refused. The check is the engine's, so the press and `paint.magicEraser` can never +/// disagree about what is erased. +fn document_alert(app: &PhotocraftApp) -> Option<&'static str> { + app.session.active().and_then(|st| photocraft_engine::eraser_cmds::magic_eraser_refusal(&st.doc)) +} + +/// A `paint.magicEraser` error as the alert it was meant to be (#12032), so a click that reaches +/// the command shows the same dialog the press shows rather than only the status bar. +fn error_alert(error: &str) -> Option<&'static str> { + [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR].into_iter().find(|text| *text == error) +} + +/// Opens the alert: the message and one OK button, as a refused Move press does +/// (`move_lock::prompt`). +fn refuse(app: &mut PhotocraftApp, message: &str) { + app.ui.open_dialog(DialogKind::Error, json!({"message": alert_text(message)}).as_object().cloned().unwrap_or_default()); +} + +/// The alert in the UI language. Literal keys, so the translation report lists both alerts for the +/// translators; `alert_keys_match_the_engine_texts` keeps them equal to the engine's texts. +fn alert_text(message: &str) -> &str { + match message { + MAGIC_ERASER_INDEXED_ERROR => { + tl!("Could not use the magic eraser because it does not work with Indexed Color images (convert image to RGB Color mode to edit).") + } + MAGIC_ERASER_BITMAP_ERROR => { + tl!("Could not use the magic eraser because it does not work with Bitmap images (convert image to Grayscale mode to edit).") + } + other => tl!(other), + } +} + /// Magic Eraser click at document `(x, y)`. Returns false for other tools. pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { if tool != Tool::MagicEraser { return false; } + // An Indexed Color or Bitmap document (#12032): the reference answers the click with its alert + // and erases nothing, so the command is never reached - and the document keeps its History. + if let Some(message) = document_alert(app) { + refuse(app, message); + return true; + } let o = &app.ui.tool_options; let p = json!({ "x": x.floor(), @@ -31,6 +74,11 @@ pub fn click(app: &mut PhotocraftApp, tool: Tool, x: f64, y: f64) -> bool { "opacity": o.magic_eraser_opacity, }); let r = app.run("paint.magicEraser", p); + if let Err(e) = &r + && let Some(message) = error_alert(e) + { + refuse(app, message); + } report(app, r); true } @@ -327,3 +375,89 @@ pub(crate) fn open_range_alert(app: &mut PhotocraftApp) { app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); } } + +#[cfg(test)] +mod tests { + use super::*; + use photocraft_doc::{Color, ColorMode, Document, SampleType, Size}; + + /// #12032: the literal translation keys are the engine's alert texts, so an English UI shows + /// exactly what `paint.magicEraser` answers and the catalogs translate the right string. + #[test] + fn alert_keys_match_the_engine_texts() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + for text in [MAGIC_ERASER_INDEXED_ERROR, MAGIC_ERASER_BITMAP_ERROR] { + assert_eq!(alert_text(text), text); + } + }); + } + + /// The message of every open error dialog, in the order they were opened. + fn alerts(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(|m| m.as_str())).collect() + } + + /// The app with a white 64x48 document in `mode` open and the Magic Eraser picked: a click on + /// it would wipe the flat canvas out. + fn app_in(mode: ColorMode) -> PhotocraftApp { + let mut s = photocraft_engine::Session::new(); + s.add_document(Document::with_background("p", Size::new(64, 48), mode, SampleType::U8, Color::WHITE), None); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + app.ui.tool = Tool::MagicEraser; + app + } + + /// #12032: the press in an Indexed Color or a Bitmap document shows the reference's alert - the + /// measured text and an OK button - and runs nothing: no History step, no erase, the Background + /// stays a Background, and the alert rather than the status bar carries the message. + #[test] + fn a_press_in_an_indexed_or_bitmap_document_shows_the_alert_and_erases_nothing() { + for (case, mode, want) in [("Indexed", ColorMode::Indexed, MAGIC_ERASER_INDEXED_ERROR), ("Bitmap", ColorMode::Bitmap, MAGIC_ERASER_BITMAP_ERROR)] { + let mut app = app_in(mode); + let st = app.session.active().unwrap(); + let (doc, steps) = (st.doc.clone(), st.history.past_len()); + let id = st.active_layer.unwrap(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}: the Magic Eraser takes the click"); + assert_eq!(alerts(&app), [want], "{case}: one alert with the reference's text"); + let st = app.session.active().unwrap(); + assert!(std::sync::Arc::ptr_eq(&doc, &st.doc), "{case}: the command never ran"); + assert_eq!(st.history.past_len(), steps, "{case}: no History step"); + assert_eq!(st.doc.layer(id).unwrap().name, "Background", "{case}: still a Background"); + assert!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3] > 0.0, "{case}: nothing erased"); + assert!(!app.ui.status_error, "{case}: the alert is the answer, not the status bar"); + // OK closes it (`DialogKind::Error` asks for nothing else), and the next press answers + // the same way: the document is no more erasable than it was. + let open: Vec = app.ui.dialogs.iter().map(|d| d.id).collect(); + for dialog in open { + app.ui.close_dialog(dialog); + } + click(&mut app, Tool::MagicEraser, 10.0, 10.0); + assert_eq!(alerts(&app), [want], "{case}: the next press is refused too"); + assert_eq!(app.session.active().unwrap().history.past_len(), steps, "{case}: still no History step"); + } + } + + /// #12032: the new press check leaves every document the tool can edit exactly as it was: the + /// click erases, no alert opens. + #[test] + fn a_press_in_an_editable_document_still_erases() { + for (case, mode) in [ + ("RGB", ColorMode::Rgb), + ("Grayscale", ColorMode::Grayscale), + ("CMYK", ColorMode::Cmyk), + ("Lab", ColorMode::Lab), + ("Duotone", ColorMode::Duotone), + ("Multichannel", ColorMode::Multichannel), + ] { + let mut app = app_in(mode); + let steps = app.session.active().unwrap().history.past_len(); + assert!(click(&mut app, Tool::MagicEraser, 2.0, 2.0), "{case}"); + assert!(app.ui.dialogs.iter().all(|d| d.kind != DialogKind::Error), "{case}: no alert"); + let st = app.session.active().unwrap(); + let id = st.active_layer.unwrap(); + assert_eq!(st.doc.layer(id).unwrap().name, "Layer 0", "{case}: the Background became a layer"); + assert_eq!(st.doc.layer(id).unwrap().surface().unwrap().rgba(2, 2)[3], 0.0, "{case}: erased to transparency"); + assert_eq!(st.history.past_len(), steps + 1, "{case}: one undo step"); + } + } +} diff --git a/docs/atn.md b/docs/atn.md index 35281b49f0..85a0c1eb21 100644 --- a/docs/atn.md +++ b/docs/atn.md @@ -147,6 +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.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` | | `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`, `layer.new.artboard` (Layer › New › Artboard), `layer.new.artboardFromLayers` (Layer › New › Artboard from Layers) | | (string ID only) | animationFramesFromLayers | Make Frames from Layers | | | (string ID only) | matchColor | Match Color | `image.adjustments.matchColor` | @@ -273,6 +274,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.