diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1282fc662c9..cf927388b63 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -174,8 +174,8 @@ jobs: # Windows tests run as two legs in parallel: the unit tests and the integration tests. As one job # they took ~28 min on the Windows runner; the legs take ~13 and ~15. Splitting the integration # tests over a third runner (nextest --partition) saved ~2 min of wall time but cost ~7 - # runner-minutes and one more Windows slot per PR. They stay outside the shared gate for sccache, - # which needs its own action step. + # runner-minutes and one more Windows slot per PR. Moving these legs into the shared gate is + # tracked by storytold/craft-common-actions#212. windows: needs: platforms if: needs.platforms.outputs.windows == 'true' @@ -187,6 +187,10 @@ jobs: matrix: part: [unit, integration] env: + # Released sccache expands Cargo's response files and exceeds Windows' rustc spawn limit + # (#13543). Let Cargo handle long commands until a release includes mozilla/sccache#3026. + # The dependency rust-cache below stays enabled; only compiler caching is disabled. + RUSTC_WRAPPER: "" # No debuginfo on Windows: writing PDBs for ~200 test binaries cost 2.2 of ~21 build minutes. # A panic still names its file and line; only backtrace frames lose theirs (Linux keeps # line-tables-only, so a backtrace with lines is one OS away). @@ -236,24 +240,6 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' && matrix.part == 'integration' }} cache-on-failure: true - # sccache caches the workspace crates' compiled libraries, which rust-cache leaves out: - # warm, each Windows leg built 4.5 min faster. Like rust-cache, only main writes (PRs read - # main's entries); a full set is ~90 MB, so it barely touches the 10 GB budget (#2688). - # Test executables can't be cached, so a PR still links its tests. - - name: Install sccache - uses: step-security/sccache-action@ae2d64c53dbae979f387673f0aae7ebb52087f6b # v0.0.11 - with: - version: v0.18.0 - - - name: Use sccache - env: - MAIN: ${{ github.ref == 'refs/heads/main' }} - run: | - echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV" - echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV" - if [ "$MAIN" != true ]; then echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"; fi - shell: bash - - name: Clippy if: matrix.part == 'integration' run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings diff --git a/apps/photocraft/src/external_svg.rs b/apps/photocraft/src/external_svg.rs index 1d4f5525734..c34dd88bd03 100644 --- a/apps/photocraft/src/external_svg.rs +++ b/apps/photocraft/src/external_svg.rs @@ -627,17 +627,14 @@ mod native { /// True for a symlink, or on Windows any reparse point, whose target could be swapped. /// Expects `symlink_metadata`, which describes the link itself rather than its target. fn is_redirect(metadata: &Metadata) -> bool { - if metadata.file_type().is_symlink() { - return true; - } #[cfg(windows)] { use std::os::windows::fs::MetadataExt; - metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT + metadata.file_type().is_symlink() || metadata.file_attributes() & 0x0000_0400 != 0 // FILE_ATTRIBUTE_REPARSE_POINT } #[cfg(not(windows))] { - false + metadata.file_type().is_symlink() } } diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index a7f57c337d5..0a5b113c5cf 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/algo/src/photo_util.rs b/crates/algo/src/photo_util.rs index 96c6f7b434c..8f1e436d533 100644 --- a/crates/algo/src/photo_util.rs +++ b/crates/algo/src/photo_util.rs @@ -167,8 +167,8 @@ impl BandChol { let n = a.diag.len(); let mut p = 0; for i in 0..n { - for k in a.rows[i]..a.rows[i + 1] { - p = p.max(i.abs_diff(a.cols[k])); + for &j in &a.cols[a.rows[i]..a.rows[i + 1]] { + p = p.max(i.abs_diff(j)); } } if n.saturating_mul(p + 1) > 40_000_000 { diff --git a/crates/algo/src/transform.rs b/crates/algo/src/transform.rs index 5a46b472e9e..5dabbd2a0cc 100644 --- a/crates/algo/src/transform.rs +++ b/crates/algo/src/transform.rs @@ -210,6 +210,15 @@ pub fn convex_quad(q: &[[f64; 2]; 4]) -> bool { area2.is_finite() && area2 >= 2.0 } +/// Is `q` (TL, TR, BR, BL) a usable Perspective Crop quad in either winding: a [`convex_quad`], +/// or one wound counter-clockwise on screen (a box flipped on one axis, which crops mirrored, +/// #12489) with the same corner angle and area limits? Self-crossing, degenerate and non-finite +/// quads are not. The Perspective Warp steps keep the clockwise-only [`convex_quad`]. +pub fn convex_quad_any_winding(q: &[[f64; 2]; 4]) -> bool { + let [tl, tr, br, bl] = *q; + convex_quad(q) || convex_quad(&[tl, bl, br, tr]) +} + /// The output size a Perspective Crop of `q` (TL, TR, BR, BL) takes when none is given: the mean /// length of the top and bottom edges by the mean length of the left and right edges. pub fn quad_size(q: &[[f64; 2]; 4]) -> (f64, f64) { @@ -287,9 +296,10 @@ fn perspective_estimate(q: &[[f64; 2]; 4], [cx, cy]: [f64; 2]) -> Option<(f64, f /// The homography taking the quad `q` (TL, TR, BR, BL) onto the rectangle (0, 0)–(`w`, `h`), corner /// to corner: the inverse of the unit-square-to-quad map (Heckbert, "Fundamentals of Texture /// Mapping and Image Warping", 1989, §2.2.3) scaled to the rectangle. `None` when `q` isn't a -/// [`convex_quad`] or the size isn't positive. +/// [`convex_quad_any_winding`] or the size isn't positive. A quad wound counter-clockwise maps +/// mirrored, each corner onto its own rectangle corner. pub fn quad_to_rect(q: &[[f64; 2]; 4], w: f64, h: f64) -> Option { - if !(convex_quad(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + if !(convex_quad_any_winding(q) && w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { return None; } Homography::rect_to_quad([0.0, 0.0, w, h], *q)?.inverse() diff --git a/crates/algo/src/transform/tests.rs b/crates/algo/src/transform/tests.rs index b70bc74c3d4..af6e81b615e 100644 --- a/crates/algo/src/transform/tests.rs +++ b/crates/algo/src/transform/tests.rs @@ -61,7 +61,7 @@ fn the_interruptible_warp_reports_progress_and_stops_when_cancelled() { } /// Perspective Crop's map lands each quad corner exactly on its rectangle corner; degenerate, -/// self-crossing, counter-clockwise and non-finite quads have none. +/// self-crossing and non-finite quads have none. #[test] fn quad_to_rect_maps_corners_and_refuses_bad_quads() { let q = [[30.0, 12.0], [140.0, 25.0], [128.0, 110.0], [14.0, 95.0]]; @@ -75,7 +75,7 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { for bad in [ [[0.0, 0.0], [50.0, 0.0], [100.0, 0.0], [0.0, 50.0]], [[0.0, 0.0], [50.0, 50.0], [50.0, 0.0], [0.0, 50.0]], - [[0.0, 0.0], [0.0, 50.0], [50.0, 50.0], [50.0, 0.0]], + [[0.0, 0.0], [50.0, 50.0], [0.0, 50.0], [50.0, 0.0]], [[0.0, 0.0], [f64::NAN, 0.0], [50.0, 50.0], [0.0, 50.0]], [[0.0, 0.0]; 4], ] { @@ -84,6 +84,30 @@ fn quad_to_rect_maps_corners_and_refuses_bad_quads() { assert!(quad_to_rect(&q, 0.0, 10.0).is_none()); } +/// #12489: a quad wound counter-clockwise (a box flipped on one axis) maps mirrored, each corner +/// onto its own rectangle corner. Perspective Warp's clockwise-only check still refuses it. +#[test] +fn quad_to_rect_maps_a_counter_clockwise_quad_mirrored() { + let q = [[140.0, 25.0], [30.0, 12.0], [14.0, 95.0], [128.0, 110.0]]; + assert!(!convex_quad(&q) && convex_quad_any_winding(&q)); + let h = quad_to_rect(&q, 100.0, 80.0).unwrap(); + for (c, want) in q.iter().zip([[0.0, 0.0], [100.0, 0.0], [100.0, 80.0], [0.0, 80.0]]) { + let (x, y) = h.apply(c[0], c[1]); + assert!((x - want[0]).abs() < 1e-9 && (y - want[1]).abs() < 1e-9, "{c:?} -> ({x}, {y})"); + } + // Self-crossing in either winding, three corners on a line, and a sliver stay refused. + for bad in [ + [[0.0, 0.0], [50.0, 0.0], [0.0, 50.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [50.0, 50.0], [0.0, 50.0]], + [[50.0, 0.0], [25.0, 0.0], [0.0, 0.0], [50.0, 50.0]], + [[50.0, 0.0], [0.0, 0.0], [0.0, 0.01], [50.0, 0.01]], + [[50.0, 0.0], [0.0, f64::INFINITY], [0.0, 50.0], [50.0, 50.0]], + ] { + assert!(!convex_quad_any_winding(&bad), "{bad:?}"); + assert!(quad_to_rect(&bad, 10.0, 10.0).is_none(), "{bad:?}"); + } +} + fn rgba() -> Surface { Surface::new(PixelFormat::RGBA8) } diff --git a/crates/cms/src/gamut.rs b/crates/cms/src/gamut.rs index 8b1abe1dd38..94818dddb88 100644 --- a/crates/cms/src/gamut.rs +++ b/crates/cms/src/gamut.rs @@ -2,13 +2,18 @@ use crate::clut::Clut; use crate::pipeline::{Pipeline, Stage}; -use crate::profile::Profile; +use crate::profile::{ColorSpace, Profile}; use crate::transform::link_stages; use crate::{CmsError, Intent}; /// Default ΔE76 threshold above which a colour counts as out of gamut. pub const DEFAULT_THRESHOLD: f32 = 4.0; +#[cfg(not(target_arch = "wasm32"))] +const PAR_MIN_PIXELS: usize = 16 * 1024; +#[cfg(not(target_arch = "wasm32"))] +const PAR_CHUNK_PIXELS: usize = 16 * 1024; + /// Precomputed out-of-gamut test for colours of `src` against `proof`. /// /// A colour is out of gamut when sending it to the proof device (relative colorimetric, @@ -17,6 +22,7 @@ pub const DEFAULT_THRESHOLD: f32 = 4.0; #[derive(Debug)] pub struct GamutCheck { inputs: usize, + source_space: ColorSpace, grid: Option, exact: (Pipeline, Pipeline), pub threshold: f32, @@ -44,7 +50,7 @@ impl GamutCheck { 4 => Some(Clut::sample(vec![17; 4], 1, de)), _ => None, }; - Ok(GamutCheck { inputs: n, grid, exact: (direct, via), threshold }) + Ok(GamutCheck { inputs: n, source_space: src.color_space, grid, exact: (direct, via), threshold }) } pub fn inputs(&self) -> usize { @@ -75,4 +81,83 @@ impl GamutCheck { pub fn out_of_gamut(&self, px: &[f32]) -> bool { self.delta_e(px) > self.threshold } + + /// Out-of-gamut mask for RGBA pixels: `255` where the pixel has alpha > 0 and its RGB + /// channels are out of gamut, `0` elsewhere. Returns the number of flagged pixels. Only + /// `min(px.len(), mask.len())` pixels are processed. Runs on the rayon pool (not on wasm); + /// the result is identical to calling [`Self::out_of_gamut`] per pixel. + /// + /// # Errors + /// [`CmsError::Invalid`] when the check was not built from an RGB source profile: an RGBA + /// pixel carries only RGB colour channels, so it cannot be tested against a CMYK, gray or + /// Lab source. Nothing is written to `mask` in that case. + pub fn mask_rgba(&self, px: &[[f32; 4]], mask: &mut [u8]) -> Result { + if self.source_space != ColorSpace::Rgb || self.inputs != 3 { + return Err(CmsError::Invalid(format!("gamut mask needs an RGB source profile, got {:?} with {} channels", self.source_space, self.inputs))); + } + let n = px.len().min(mask.len()); + let (px, mask) = (&px[..n], &mut mask[..n]); + let run = |p: &[[f32; 4]], m: &mut [u8]| { + let mut count = 0; + for (p, m) in p.iter().zip(m.iter_mut()) { + let hit = p[3] > 0.0 && self.out_of_gamut(&p[..3]); + *m = if hit { 255 } else { 0 }; + count += usize::from(hit); + } + count + }; + #[cfg(not(target_arch = "wasm32"))] + if n >= PAR_MIN_PIXELS { + use rayon::prelude::*; + return Ok(px.par_chunks(PAR_CHUNK_PIXELS).zip(mask.par_chunks_mut(PAR_CHUNK_PIXELS)).map(|(p, m)| run(p, m)).sum()); + } + Ok(run(px, mask)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Builtin; + + fn image(n: usize) -> Vec<[f32; 4]> { + let mut s = 0x9E37_79B9u32; + let mut rnd = move || { + s ^= s << 13; + s ^= s >> 17; + s ^= s << 5; + (s >> 8) as f32 / (1u32 << 24) as f32 + }; + // Includes out-of-range values and zero alpha. + (0..n).map(|i| [rnd() * 1.2 - 0.1, rnd(), rnd(), if i % 7 == 0 { 0.0 } else { rnd() }]).collect() + } + + #[test] + fn mask_rgba_matches_per_pixel_check() { + let src = Builtin::Srgb.profile(); + // Sizes straddle the parallel threshold and the chunk size, odd ones included. + for (proof, threshold) in [(Builtin::CoatedCmyk, 4.0), (Builtin::CoatedCmyk, 1.5), (Builtin::GrayGamma22, 4.0), (Builtin::DisplayP3, 0.5)] { + let check = GamutCheck::new(src, proof.profile(), threshold).unwrap(); + for n in [0, 1, 1023, 16 * 1024 - 1, 16 * 1024, 16 * 1024 + 1, 50_001] { + let px = image(n); + let want: Vec = px.iter().map(|p| if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { 255 } else { 0 }).collect(); + let mut got = vec![7u8; n]; + let count = check.mask_rgba(&px, &mut got).unwrap(); + assert_eq!(got, want, "{proof:?} threshold {threshold} n {n}"); + assert_eq!(count, want.iter().filter(|&&m| m == 255).count()); + } + } + } + + #[test] + fn mask_rgba_rejects_non_rgb_source() { + // A CMYK (4-channel), gray (1-channel) and Lab (3-channel, not RGB) source cannot be tested from RGBA pixels. + for src in [Builtin::CoatedCmyk, Builtin::GrayGamma22, Builtin::LabD50] { + let check = GamutCheck::new(src.profile(), Builtin::Srgb.profile(), 4.0).unwrap(); + let px = image(64); + let mut mask = vec![9u8; 64]; + assert!(matches!(check.mask_rgba(&px, &mut mask), Err(CmsError::Invalid(_))), "{src:?}"); + assert!(mask.iter().all(|&m| m == 9), "mask must stay untouched"); + } + } } diff --git a/crates/cms/src/synth.rs b/crates/cms/src/synth.rs index 390e509dce3..c86bedc9bd9 100644 --- a/crates/cms/src/synth.rs +++ b/crates/cms/src/synth.rs @@ -119,7 +119,7 @@ impl CmykModel { (v + 4.0 * self.tvi[i] * v * (1.0 - v)).clamp(0.0, 1.0) }); let mut s = [0.0; 3]; - for m in 0..16 { + for (m, prim) in self.prim_n.iter().enumerate() { let mut w = 1.0; for (i, ai) in a.iter().enumerate() { w *= if m & (1 << i) != 0 { *ai } else { 1.0 - ai }; @@ -127,7 +127,7 @@ impl CmykModel { if w == 0.0 { continue; } - for (acc, p) in s.iter_mut().zip(&self.prim_n[m]) { + for (acc, p) in s.iter_mut().zip(prim) { *acc += w * p; } } diff --git a/crates/engine/src/canvas_geom.rs b/crates/engine/src/canvas_geom.rs index 795ba9d1bbc..c3e3254ac2f 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 a17fdec405d..3bc3de49e50 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -27,6 +27,11 @@ pub struct CommandSpec { pub journal: bool, } +/// Image › Adjustments › Desaturate: Hue/Saturation with saturation at -100. +pub(crate) fn desaturate_adjustment() -> Adjustment { + Adjustment::HueSaturation { hue: 0.0, saturation: -100.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() } +} + /// Image › Image Rotation by a right angle or a flip (pixels, vectors, guides, … all move). fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result { if let Some(d) = s.active() { @@ -37,7 +42,7 @@ fn turn(s: &mut Session, label: &str, t: crate::canvas_geom::Turn) -> Result Vec { ["Image", "Adjustments"], Some("Cmd+Shift+U"), r##"{"target":"pixels"|"mask"|{"color":i}|{"colors":[i,…]}?=Channels panel target,"layer":id|name?=active}"##, - has_pixel_layer, + crate::adjust_cmds::has_adjustable, |s, p| { - destructive_adjust( - s, - "Desaturate", - Adjustment::HueSaturation { - hue: 0.0, - saturation: -100.0, - lightness: 0.0, - colorize: false, - ranges: photocraft_doc::adjust::HueRange::defaults(), - }, - p, - ) + if crate::adjust_cmds::adjust_as_smart_filter(s, "desaturate", "Desaturate", p)? { + return Ok(Value::Null); + } + destructive_adjust(s, "Desaturate", desaturate_adjustment(), p) } ), // Paint diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index ec8a7f753a3..c63edf36086 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -335,20 +335,25 @@ pub(crate) fn has_adjustable(s: &Session) -> std::result::Result<(), String> { } } +/// The smart object an adjustment's pixels would go to: the layer the params resolve to (the +/// active one by default), when the command edits its pixels and that layer is a smart object. +/// `None` for a mask or channel target, or a layer that is not a smart object. +pub(crate) fn smart_pixel_target(s: &Session, p: &Value) -> Result> { + if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { + return Ok(None); + } + let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(None) }; + let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); + Ok(smart.then_some(id)) +} + /// Image › Adjustments on a smart object record `image.adjustments.` as a smart filter /// (Photoshop): the adjustment re-runs from the source whenever the object re-renders, through /// [`adjust_as_filter`]. `Ok(true)` when it was recorded (one history step, the selection becomes /// the filter mask); `Ok(false)` when the command should edit pixels instead (a mask or channel /// target, or the active layer is not a smart object). pub(crate) fn adjust_as_smart_filter(s: &mut Session, kind: &str, label: &str, p: &Value) -> Result { - if crate::commands::is_mask_target(p) || crate::channel_cmds::is_channel_target(p) || crate::color_channels::target(s, p)?.is_some() { - return Ok(false); - } - let Ok(id) = crate::commands::layer_param(s, p) else { return Ok(false) }; - let smart = s.active().is_some_and(|d| matches!(d.doc.layer(id).map(|l| &l.content), Some(LayerContent::Smart(_)))); - if !smart { - return Ok(false); - } + let Some(id) = smart_pixel_target(s, p)? else { return Ok(false) }; // A pixel or full lock refuses the smart filter, as for `filter.*` on a smart object. crate::commands::check_pixels_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?; // The recorded params are the command's own, minus the engine's private `__kind` key. @@ -376,7 +381,7 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { /// Image › Adjustments run as a smart filter (`image.adjustments.` recorded on a smart /// object): the adjustment applied to a copy of `surf`. `None` for kinds or params it can't run. -pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Result> { +pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface, histogram_mask: Option<&photocraft_doc::LayerMask>) -> Result> { // A Color Lookup filter re-reads its LUT `file`, a path stored in the document: followed only // as `doc_path` allows, else the filter can't run (like a missing file). let resolved; @@ -391,7 +396,24 @@ pub(crate) fn adjust_as_filter(kind: &str, p: &Value, surf: &Surface) -> Result< None => p, }; let mut out = surf.clone(); - if kind == "shadowsHighlights" { + if kind == "replaceColor" { + let Ok((c, fuzz, h, sat, l)) = replace_color_params("image.adjustments.replaceColor", p, [0.0, 0.0, 0.0, 1.0]) else { return Ok(None) }; + process_surface(&mut out, None, &mut |px, _| { + tone::replace_color(px, [c[0], c[1], c[2]], fuzz, h, sat, l); + })?; + } else if kind == "desaturate" { + let mode = surf.format().mode; + if crate::pixels::adjust_surface(&mut out, &crate::commands::desaturate_adjustment(), None, mode).is_err() { + return Ok(None); + } + } else if kind == "equalize" { + process_surface(&mut out, None, &mut |px, area| { + let width = area.width() as usize; + let cover = + (0..px.len()).map(|i| histogram_mask.map_or(1.0, |m| m.value(area.x0 + (i % width) as i32, area.y0 + (i / width) as i32))).collect::>(); + crate::extra_cmds::equalize_pixels(px, &cover); + })?; + } else if kind == "shadowsHighlights" { let sh = shadows_highlights_params(p); process_surface(&mut out, None, &mut |px, r| tone::shadows_highlights(px, r.width() as usize, r.height() as usize, &sh))?; } else { @@ -429,15 +451,56 @@ fn shadows_highlights_params(p: &Value) -> ShadowsHighlights { } } -/// Recorded Lab bounds use native profile matching; ordinary RGB samples keep their existing path. +fn replace_color_params(cmd: &str, p: &Value, default_color: [f32; 4]) -> Result<([f32; 4], f32, f32, f32, f32)> { + match given(p, "color") { + None => {} + Some(Value::String(s)) if crate::commands::parse_hex(s).is_some() => {} + Some(Value::Array(a)) if (3..=4).contains(&a.len()) && a.iter().all(Value::is_number) => {} + Some(_) => return Err(bad(cmd, "`color` must be a hex colour or an array of 3 or 4 finite numbers")), + } + let c = crate::commands::color_param(cmd, p, "color", default_color)?; + let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); + let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); + Ok((c, fuzz, h, sat, l)) +} + fn replace_color(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "image.adjustments.replaceColor"; + let localized_requested = p.get("localized").and_then(Value::as_bool).unwrap_or(false); + // Only the smart object's own pixels are restricted: a mask, alpha channel or Quick Mask over + // it edits as for any layer. + let on_smart = smart_pixel_target(s, p)?.is_some(); + // Recorded Lab bounds use native profile matching and edit pixels in place; ordinary RGB + // samples keep their existing path. A smart object has no pixels to edit that way. + if on_smart && (p.get("labMinimum").is_some() || p.get("labMaximum").is_some()) { + return Err(bad(CMD, "Lab bounds require a pixel layer, not a smart object")); + } if let Some(result) = replace_color_range::apply(s, p)? { return Ok(result); } - const CMD: &str = "image.adjustments.replaceColor"; - let c = crate::commands::color_param(CMD, p, "color", s.tools.foreground)?; - let fuzz = num(p, "fuzziness", 40.0).clamp(0.0, 200.0); - let (h, sat, l) = (num(p, "hue", 0.0).clamp(-180.0, 180.0), num(p, "saturation", 0.0).clamp(-100.0, 100.0), num(p, "lightness", 0.0).clamp(-100.0, 100.0)); + if localized_requested && on_smart { + return Err(bad(CMD, "Localized Color Clusters are not available as a smart filter yet")); + } + // Several samples (Add/Subtract from Sample) edit pixels through Color Range's matcher; the + // smart filter replays one colour only, so recording it would silently drop the extra samples. + if on_smart { + let multi = p.get("points").and_then(Value::as_array).is_some_and(|a| a.len() > 1); + let subtracted = p.get("subtractPoints").and_then(Value::as_array).is_some_and(|a| !a.is_empty()); + if multi || subtracted { + return Err(bad(CMD, "Add/Subtract from Sample are not available as a smart filter yet")); + } + } + let (c, fuzz, h, sat, l) = replace_color_params(CMD, p, s.tools.foreground)?; + if !localized_requested { + // Resolve and validate before recording, including the null foreground fallback. + let mut q = Value::Object(p.as_object().cloned().unwrap_or_default()); + if let Value::Object(m) = &mut q { + m.insert("color".into(), json!(c)); + } + if adjust_as_smart_filter(s, "replaceColor", "Replace Color", &q)? { + return Ok(Value::Null); + } + } // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range // (a percentage of the canvas's longer side) of where it was picked. let points = sample_points(p).map_err(|m| bad(CMD, m))?; @@ -622,7 +685,7 @@ pub fn specs() -> Vec { "Replace Color…", ["Image", "Adjustments"], r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"subtractPoints":[[x,y],…]?,"order":["+"|"-",…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/subtractPoints/order/localized/range; composite pixel-layer target only. Otherwise color ("#rrggbb") defaults to the foreground; localized points use range % of the longer side; several "points" (Add to Sample) or any "subtractPoints" (Subtract from Sample) match as select.colorRange does for the same samples, "order" the click order.)"##, - has_pixels, + has_adjustable, replace_color ), spec!( diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 0efa30e1492..62bbad6c099 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -578,7 +578,7 @@ fn locked_smart_objects_refuse_adjustment_smart_filters() { } /// A wrong-typed value errors before anything is recorded (never a panic), and the adjustments -/// that can't re-render from a source (Replace Color, Match Color) stay off a smart object. +/// that can't re-render from a source (Match Color) stays off a smart object. #[test] fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { let mut s = smart_session(); @@ -588,10 +588,63 @@ fn a_bad_adjustment_param_on_a_smart_object_is_an_error() { assert_eq!(smart_filters_of(&s).len(), filters, "nothing recorded"); assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); assert_eq!(flatten(&s), flat, "pixels untouched"); - assert!(!s.is_enabled("image.adjustments.replaceColor"), "only adjustments that re-render become smart filters"); assert!(!s.is_enabled("image.adjustments.matchColor"), "only adjustments that re-render become smart filters"); } +/// Add/Subtract from Sample edit through Color Range's matcher, which the one-colour smart filter +/// cannot replay: refused on a smart object instead of recording a filter that drops the samples. +#[test] +fn multi_sample_replace_color_is_refused_on_a_smart_object() { + let mut s = smart_session(); + let (filters, steps) = (smart_filters_of(&s).len(), s.active().unwrap().history.past_len()); + for p in [json!({"points": [[1, 1], [2, 2]]}), json!({"subtractPoints": [[1, 1]]})] { + let e = s.execute("image.adjustments.replaceColor", p).unwrap_err(); + assert!(e.to_string().contains("smart filter"), "{e}"); + } + assert_eq!(smart_filters_of(&s).len(), filters, "nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "no history step"); +} + +/// Localized Replace Color is refused only for the smart object's own pixels: an alpha channel, +/// or an explicit `layer` that is not a smart object, edits as usual while a smart object is active. +#[test] +fn localized_replace_color_is_refused_only_for_the_smart_objects_pixels() { + let mut s = smart_session(); + let (filters, steps) = (smart_filters_of(&s).len(), s.active().unwrap().history.past_len()); + let own = json!({"localized": true, "points": [[3, 3]]}); + let e = s.execute("image.adjustments.replaceColor", own).unwrap_err(); + assert!(e.to_string().contains("smart filter"), "{e}"); + assert_eq!(smart_filters_of(&s).len(), filters); + s.execute("channel.new", json!({"name": "Alpha", "fill": "white"})).unwrap(); + let channel = json!({"localized": true, "points": [[3, 3]], "target": {"channel": 0}}); + s.execute("image.adjustments.replaceColor", channel).expect("a channel under a smart object is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters, "no smart filter for a channel edit"); + assert!(s.active().unwrap().history.past_len() > steps); + // The smart object is active, but the command names the Background. + let background = doc(&s).layers.iter().find(|l| !matches!(l.content, LayerContent::Smart(_))).unwrap().id; + let other = json!({"localized": true, "points": [[3, 3]], "layer": background.0}); + s.execute("image.adjustments.replaceColor", other).expect("an explicit pixel layer is not refused"); + assert_eq!(smart_filters_of(&s).len(), filters); +} + +/// Equalize Entire Image Based On Selected Area needs the selection for the histogram only, which +/// a smart filter's output mask cannot express: refused rather than recorded as "selected area only". +#[test] +fn equalize_entire_image_is_refused_on_a_smart_object_with_a_selection() { + let mut s = smart_session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 24, "height": 32})).unwrap(); + let steps = s.active().unwrap().history.past_len(); + let e = s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap_err(); + assert!(e.to_string().contains("smart object"), "{e}"); + assert!(smart_filters_of(&s).is_empty(), "nothing recorded"); + assert_eq!(s.active().unwrap().history.past_len(), steps); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": true})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 1, "the selected area itself still records a filter"); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.adjustments.equalize", json!({"selectedAreaOnly": false})).unwrap(); + assert_eq!(smart_filters_of(&s).len(), 2, "without a selection it is plain Equalize"); +} + /// #780: a targeted mask enables Invert (and filters) on layers without pixels, such as an /// adjustment layer; viewing the mask (⌥-click) targets it too. #[test] @@ -625,6 +678,67 @@ fn a_targeted_mask_enables_editing_it_on_any_layer() { assert_eq!(rgba(&s, 23, 3), pixels); } +/// Desaturate, Equalize and Replace Color on a smart object record a smart filter that renders +/// what the destructive command bakes into the same pixels (they used to be refused). +#[test] +fn desaturate_equalize_and_replace_color_record_smart_filters() { + let replace = json!({"color": "#ff0000", "fuzziness": 120, "hue": 90}); + for (id, params) in [("image.adjustments.desaturate", json!({})), ("image.adjustments.equalize", json!({})), ("image.adjustments.replaceColor", replace)] { + let mut plain = session(8, "rgb"); + let original = flatten(&plain); + plain.execute(id, params.clone()).unwrap(); + let baked = flatten(&plain); + assert!(max_diff(&original, &baked) > 0.02, "{id}: the control changes the pixels"); + + let mut s = smart_session(); + assert!(s.is_enabled(id), "{id} runs on a smart object"); + s.execute(id, params).unwrap(); + let sf = smart_filters_of(&s); + assert_eq!(sf.len(), 1, "{id}"); + assert_eq!(sf[0].command, id); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "{id}: the smart filter renders the destructive result"); + s.undo(); + assert!(smart_filters_of(&s).is_empty(), "{id}: undo removes the filter"); + } +} + +/// Replace Color without `color` samples the foreground: the smart filter records that colour, so +/// changing the foreground afterwards and re-rendering the filter leaves its result unchanged. +#[test] +fn replace_color_smart_filter_keeps_the_foreground_it_was_run_with() { + let picked = [0.27, 0.6, 0.52, 1.0]; + let params = json!({"fuzziness": 60, "hue": 90}); + let mut plain = session(8, "rgb"); + plain.tools.foreground = picked; + plain.execute("image.adjustments.replaceColor", params.clone()).unwrap(); + let baked = flatten(&plain); + + let mut s = smart_session(); + let original = flatten(&s); + s.tools.foreground = picked; + s.execute("image.adjustments.replaceColor", params).unwrap(); + assert!(smart_filters_of(&s)[0].params.get("color").is_some(), "the foreground colour is recorded"); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "the filter replaces the foreground colour"); + assert!(max_diff(&original, &baked) > 0.02, "the control changes the pixels"); + // A new foreground, then a re-render (hide and show the filter): the result stays put. + s.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + s.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap(); + s.execute("layer.smartFilter.setVisible", json!({"index": 0})).unwrap(); + assert!(smart_filters_of(&s)[0].visible); + assert_eq!(max_diff(&flatten(&s), &baked), 0.0, "changing the foreground leaves the filter unchanged"); +} + +/// Lab bounds edit pixels in place; a smart object keeps its pixels, so they are refused there. +#[test] +fn replace_color_lab_bounds_are_refused_on_a_smart_object() { + let mut s = smart_session(); + let before = flatten(&s); + let r = s.execute("image.adjustments.replaceColor", json!({"labMinimum": [0, -128, -128], "labMaximum": [100, 127, 127], "hue": 90})); + assert!(r.is_err(), "Lab bounds on a smart object must be refused"); + assert!(smart_filters_of(&s).is_empty()); + assert_eq!(max_diff(&flatten(&s), &before), 0.0); +} + /// #5335: Curves (⌘M) edits the targeted layer mask, saved channel or Quick Mask at every depth. #[test] fn curves_apply_to_non_colour_targets_at_every_depth() { @@ -1043,6 +1157,49 @@ fn invert_turns_the_black_of_quick_mask_and_alpha_channels_white() { } } +#[test] +fn equalize_smart_filter_uses_selected_pixels_for_its_histogram() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + for s in [&mut plain, &mut smart] { + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 12, "height": 32})).unwrap(); + s.execute("image.adjustments.equalize", json!({})).unwrap(); + } + assert!(max_diff(&flatten(&plain), &flatten(&smart)) < 2.0 / 255.0, "depth={depth}"); + // Disabling the filter mask changes the histogram too: no stale cached stage. + let mut full = session(depth, "rgb"); + full.execute("image.adjustments.equalize", json!({})).unwrap(); + smart.execute("select.deselect", json!({})).unwrap(); + smart.execute("layer.smartFilter.disableFilterMask", json!({"enabled": false})).unwrap(); + assert!(max_diff(&flatten(&full), &flatten(&smart)) < 2.0 / 255.0, "disabled mask, depth={depth}"); + } +} + +#[test] +fn replace_color_null_records_foreground_and_bad_color_does_not_edit() { + for depth in DEPTHS { + let mut plain = session(depth, "rgb"); + let mut smart = session(depth, "rgb"); + smart.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let params = json!({"color": null, "fuzziness": 200, "hue": 90}); + for s in [&mut plain, &mut smart] { + s.tools.foreground = [0.27, 0.6, 0.52, 1.0]; + s.execute("image.adjustments.replaceColor", params.clone()).unwrap(); + } + assert_eq!(max_diff(&flatten(&plain), &flatten(&smart)), 0.0); + assert_eq!(smart_filters_of(&smart)[0].params["color"], json!([0.27_f32, 0.6_f32, 0.52_f32, 1.0_f32])); + let before = smart.active().unwrap().doc.clone(); + let steps = smart.active().unwrap().history.past_len(); + for color in [json!(3), json!("wrong"), json!([1, 2]), json!([1e300, 0, 0]), json!(["red", 0, 0])] { + assert!(smart.execute("image.adjustments.replaceColor", json!({"color": color})).is_err()); + assert!(std::sync::Arc::ptr_eq(&smart.active().unwrap().doc, &before)); + assert_eq!(smart.active().unwrap().history.past_len(), steps); + } + } +} + /// #6558: a LUT folder lists its LUT files by name, case-insensitively, and nothing else. #[test] fn folder_luts_lists_lut_files_by_name() { diff --git a/crates/engine/src/cmd/analysis_cmds.rs b/crates/engine/src/cmd/analysis_cmds.rs index b933549b75a..451cdeaf675 100644 --- a/crates/engine/src/cmd/analysis_cmds.rs +++ b/crates/engine/src/cmd/analysis_cmds.rs @@ -795,7 +795,14 @@ fn straighten(s: &mut Session, p: &Value) -> Result { let (w0, h0) = (f64::from(d.size.width), f64::from(d.size.height)); compound(s, "Straighten", |s| { if crop { - s.execute("image.rotation.arbitrary", json!({"angle": rot, "direction": "cw"}))?; + // Count points turn with the image here, since the crop after it moves them too. + // 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 ab719ce18c7..4b50abfcf56 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 bbe17feb8e4..97292737a4c 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 00000000000..873ace66273 --- /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 00000000000..e2340988e69 --- /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 4b0c53a0a01..0e16f09c8f8 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 23197625345..cbbb23f6ccf 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/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 0a410926799..82abc3d4364 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -12,7 +12,7 @@ use photocraft_paint::mixer::{MixerSettings, MixerState}; use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{ - BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke, + BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke_clipped, }; use photocraft_raster::Surface; use serde_json::{Value, json}; @@ -90,6 +90,12 @@ pub(crate) fn check_coords(pts: &[StrokePoint], cmd: &str) -> Result<()> { Ok(()) } +/// Where a stroke can change pixels: the canvas plus any pixels the layer already holds past its +/// edge (a moved layer keeps them, #5067). Dabs that reach neither are not rasterized. +fn paintable_area(canvas: Rect, surf: &Surface) -> Rect { + canvas.union(&surf.tile_bounds()) +} + /// Deep-merge `patch` into `base` (objects merge key by key; anything else replaces). fn merge(base: &mut Value, patch: &Value) { match (base, patch) { @@ -291,7 +297,9 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS } let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; + let clip = paintable_area(canvas, surf); let mut brush = brush; erase_locked(&mut brush, lock, bg); if auto_erase { @@ -307,23 +315,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS .iter() .filter(|p| crate::symmetry_cmds::SymmetryAxis::has_distinct_mirror(&pts, p)) .map(|p| { - let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); renderer.push(p); renderer.finish(); renderer }) .collect(); if copies.is_empty() { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) } else { let pre = surf.clone(); - let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let mut original = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); original.push(&pts); original.finish(); original.composite_union_many(&copies, &pre, surf, sel.as_ref(), lock) } } else { - render_stroke(surf, &brush, &pts, sel.as_ref(), lock, zoom) + render_stroke_clipped(surf, &brush, &pts, sel.as_ref(), lock, zoom, Some(clip)) }; if let (Some(table), Some(pre)) = (&table, &unpainted) { crate::mode_cmds::keep_in_color_table(table, pre, surf, damage); @@ -341,12 +349,23 @@ fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushS /// Pencil Auto Erase: a stroke that starts on a pixel of the foreground colour paints the /// background colour instead (Photoshop). The match is exact (#11966): the foreground as the /// layer would store it (its mode and depth) against the pixel, its alpha aside, so one level -/// off paints the foreground. +/// off paints the foreground. In a CMYK layer a foreground picked as CMYK is probed as the inks +/// the stroke paints (#13060), not as its RGB stand-in converted back. fn apply_auto_erase(brush: &mut BrushSettings, surf: &Surface, start: Option<&StrokePoint>, fg: [f32; 4], bg: [f32; 4]) { let Some(p0) = start else { return }; let c = surf.rgba(p0.x.floor() as i32, p0.y.floor() as i32); - let mut probe = Surface::new(surf.format()); - probe.write_pixel(0, 0, &photocraft_raster::from_rgba(&surf.format(), [fg[0], fg[1], fg[2], 1.0])); + let format = surf.format(); + let mut px = photocraft_raster::from_rgba(&format, [fg[0], fg[1], fg[2], 1.0]); + // The renderer's condition for painting the picked inks (`StrokeRenderer::composite`), keyed + // on the foreground being probed. + if let (photocraft_color::ColorMode::Cmyk, Some((rgb, inks))) = (format.mode, brush.color_cmyk) + && rgb == [fg[0], fg[1], fg[2]] + && let Some(channels) = px.get_mut(..4) + { + channels.copy_from_slice(&inks); + } + let mut probe = Surface::new(format); + probe.write_pixel(0, 0, &px); let stored = probe.rgba(0, 0); // Far below one 8-bit level: only the float noise of the conversion. if c[3] > 0.0 && (0..3).all(|i| (c[i] - stored[i]).abs() < 1e-5) { @@ -626,16 +645,19 @@ impl LiveStroke { let mut doc = (*st.doc).clone(); let sel = doc.selection.clone(); let table = crate::mode_cmds::paint_color_table(&doc, p); + let canvas = doc.bounds(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, layer, p)?; + let clip = paintable_area(canvas, surf); let bg = crate::color_cmds::swatch_in_doc(s, s.tools.background); erase_locked(&mut brush, lock, bg); if pencil && flag(p, "autoErase", false) { let fg = table.as_ref().map_or(fg, |t| crate::mode_cmds::table_color(t, fg)); apply_auto_erase(&mut brush, surf, pts.first(), fg, s.tools.background); } - let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom); + let renderer = StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip); let symmetry = s.active().and_then(|st| st.symmetry.clone()); - let mirrors: Vec<_> = (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom)).collect(); + let mirrors: Vec<_> = + (0..symmetry.as_ref().map_or(0, |s| s.mirror_count())).map(|_| StrokeRenderer::new(&brush, Some(surf.format()), zoom).with_clip(clip)).collect(); let mirror_distinct = vec![false; mirrors.len()]; let pre = surf.clone(); let mut live = Self { diff --git a/crates/engine/src/cmd/brush_cmds/tests.rs b/crates/engine/src/cmd/brush_cmds/tests.rs index 7a424e2f03b..3de48710318 100644 --- a/crates/engine/src/cmd/brush_cmds/tests.rs +++ b/crates/engine/src/cmd/brush_cmds/tests.rs @@ -32,6 +32,23 @@ fn stroke_backwards_compatible() { assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01); } +#[test] +fn a_stroke_from_far_off_the_canvas_paints_only_what_reaches_it() { + // Dabs that cannot reach the canvas are not rasterized (their coverage is never read). + let mut s = session(80, 80); + let r = s + .execute( + "paint.stroke", + json!({"points": [[-100_000, 20], [70, 20], [70, 60]], "size": 6, "color": "#0000ff", "brush": {"hardness": 0.5, "smoothing": {"amount": 0.0}}}), + ) + .unwrap(); + assert!(rgba(&s, 40, 20)[3] > 0.9, "the part on the canvas is painted: {:?} {r}", rgba(&s, 40, 20)); + assert!(rgba(&s, 70, 50)[3] > 0.9); + assert_eq!(rgba(&s, 40, 40)[3], 0.0); + let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); + assert!(d[0] > -100, "the damage does not span the off-canvas path: {r}"); +} + #[test] fn fill_fills_the_enclosed_region_not_the_outline() { // #3659: a closed gesture with `fill` paints the interior, not a ring. @@ -212,6 +229,35 @@ fn pencil_is_aliased_and_auto_erases() { assert_eq!(rgba(&s, 40, 26), [0.0, 0.0, 0.0, 1.0]); } +/// #13060: in a CMYK document a foreground picked as CMYK inks (a rich black, which its sRGB +/// stand-in does not convert back to) is painted as those inks, and Pencil Auto Erase recognises +/// them: a stroke that starts on it paints the background colour, live and committed. +#[test] +fn pencil_auto_erase_probes_a_cmyk_pick_with_the_picked_inks() { + let rich_black = [0.6f32, 0.4, 0.4, 1.0]; + let rgb = photocraft_color::convert::cmyk_to_rgb(rich_black).map(|c| c.clamp(0.0, 1.0)); + let mut s = session(40, 20); + s.execute("image.mode.cmyk", json!({})).unwrap(); + s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": rich_black, "background": "#ffffff"})).unwrap(); + s.execute("paint.pencil", json!({"points": [[5, 10], [35, 10]], "size": 5})).unwrap(); + let pixel = |s: &Session, x: i32, y: i32| -> Vec { surface(s).read_region(Rect::new(x, y, x + 1, y + 1)).into_iter().take(4).collect() }; + let painted = pixel(&s, 20, 10); + assert!(painted.iter().zip(rich_black).all(|(a, b)| (a - b).abs() < 0.01), "the stroke paints the picked inks: {painted:?}"); + let white = [1.0f32, 1.0, 1.0, 1.0]; + + // Live: the stroke that starts on the rich black paints the background. + let p = json!({"points": [[12, 10]], "autoErase": true, "smoothing": 0.0}); + let mut live = LiveStroke::begin_with(&s, "paint.pencil", &p).unwrap(); + live.push(&[StrokePoint::new(12.0, 18.0, 1.0)]).unwrap(); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(12, 17); + assert!(shown.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "live: {shown:?}"); + + // Committed: the same. + s.execute("paint.pencil", json!({"points": [[20, 10], [20, 18]], "size": 3, "autoErase": true})).unwrap(); + let erased = rgba(&s, 20, 17); + assert!(erased.iter().zip(white).all(|(a, b)| (a - b).abs() < 1e-3), "committed: {erased:?}"); +} + #[test] fn mixer_brush_reservoir_and_cleaning() { let mut s = session(200, 30); @@ -1157,12 +1203,15 @@ fn out_of_range_scatter_is_rejected_and_the_maximum_still_paints() { assert!(s.execute("tools.setBrush", json!({ "brush": scatter(1e38) })).is_err()); assert!(s.execute("paint.stroke", stroke.clone()).is_ok()); // The maximum (1000 %) is accepted and paints a finite, well-formed dab. - for patch in [scatter(10.0), dual(10.0)] { + for (patch, primary_on_canvas) in [(scatter(10.0), false), (dual(10.0), true)] { let mut s = new(); s.execute("tools.setBrush", json!({ "brush": patch })).unwrap(); let r = s.execute("paint.stroke", stroke.clone()).unwrap(); let d: Vec = r["damage"].as_array().unwrap().iter().map(|v| v.as_i64().unwrap()).collect(); - assert!(d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0, "{r}"); + // A dab scattered clear of the canvas is not rasterized, so its damage is empty. The dual + // brush scatters only its own tip: the primary dab stays on the canvas and always paints. + let off_canvas = !primary_on_canvas && d[2] == 0 && d[3] == 0; + assert!(off_canvas || (d[0].abs() < 1000 && d[1].abs() < 1000 && d[2] > 0 && d[3] > 0), "{r}"); } // Control: 200 % scatter paints where it did before the cap (the soft default tip reaches a // little past its radius). diff --git a/crates/engine/src/cmd/color_cmds.rs b/crates/engine/src/cmd/color_cmds.rs index e0bf17a271e..de14c9f420d 100644 --- a/crates/engine/src/cmd/color_cmds.rs +++ b/crates/engine/src/cmd/color_cmds.rs @@ -988,19 +988,8 @@ pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result Result<(Vec, usize)> { let check = GamutCheck::new(&composite_profile(doc), &setup.profile, threshold).map_err(cms_err)?; let buf = photocraft_compose::flatten(doc); - let mut count = 0; - let mask = buf - .px - .iter() - .map(|p| { - if p[3] > 0.0 && check.out_of_gamut(&p[..3]) { - count += 1; - 255 - } else { - 0 - } - }) - .collect(); + let mut mask = vec![0u8; buf.px.len()]; + let count = check.mask_rgba(&buf.px, &mut mask).map_err(cms_err)?; Ok((mask, count)) } 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 00000000000..7648ed00514 --- /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 efd8d60df35..4887228dfc5 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 00000000000..b56d839310b --- /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 96ac6d88c36..30bedcec9f0 100644 --- a/crates/engine/src/cmd/extra_cmds.rs +++ b/crates/engine/src/cmd/extra_cmds.rs @@ -242,7 +242,23 @@ fn equalize(s: &mut Session, p: &Value) -> Result { Some(Value::Bool(only)) => !only, Some(_) => return Err(EngineError::BadParams { cmd: "image.adjustments.equalize".into(), msg: "selectedAreaOnly must be true or false".into() }), }; - map_pixels_in(s, "Equalize", p, whole, |_, px, cover| { + // A smart filter's selection is its output mask, so it cannot also stand for "histogram from + // the selection, applied to everything": refuse instead of quietly leaving the rest unchanged. + if whole && s.active().is_some_and(|d| d.doc.selection.is_some()) && crate::adjust_cmds::smart_pixel_target(s, p)?.is_some() { + return Err(EngineError::BadParams { + cmd: "image.adjustments.equalize".into(), + msg: "Equalize Entire Image Based On Selected Area is not available on a smart object yet".into(), + }); + } + if crate::adjust_cmds::adjust_as_smart_filter(s, "equalize", "Equalize", p)? { + return Ok(Value::Null); + } + map_pixels_in(s, "Equalize", p, whole, |_, px, cover| equalize_pixels(px, cover)) +} + +/// [`equalize`] on straight RGBA pixels with a coverage weight each (also run as a smart filter). +pub(crate) fn equalize_pixels(px: &mut [[f32; 4]], cover: &[f32]) { + { let mut hist = [0f64; 256]; for (p, &k) in px.iter().zip(cover) { if k > 0.0 && p[3] > 0.0 { @@ -269,7 +285,7 @@ fn equalize(s: &mut Session, p: &Value) -> Result { *v = map(*v); } } - }) + } } // ---------- transform presets ---------- @@ -727,11 +743,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 +825,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})) } @@ -906,7 +970,7 @@ pub fn specs() -> Vec { &["Image", "Adjustments"], None, r#"{"selectedAreaOnly":bool=true (with a selection, false equalizes the layer within the canvas by the selection's histogram)}"#, - has_pixels, + crate::adjust_cmds::has_adjustable, equalize ), spec!("image.revealAll", "Reveal All", &["Image"], None, "{}", has_doc, |s, _| { diff --git a/crates/engine/src/cmd/extra_cmds/tests.rs b/crates/engine/src/cmd/extra_cmds/tests.rs index 647a585a23f..d85e7c95850 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 8e2ea786b50..e48f3372461 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 9eff784a429..898c71c9812 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 218718ebd0c..dcaf8a8f185 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/multichannel_cmds/tests.rs b/crates/engine/src/cmd/multichannel_cmds/tests.rs index fc3cfd1cd63..99ad72d6733 100644 --- a/crates/engine/src/cmd/multichannel_cmds/tests.rs +++ b/crates/engine/src/cmd/multichannel_cmds/tests.rs @@ -110,8 +110,8 @@ fn flattens_layers_and_keeps_alpha_channels() { assert_eq!(d.channels.len(), 4); assert!(d.channels[3].spot.is_none(), "the saved selection stays an alpha channel"); // The black fill on the upper layer is solid ink in all three plates. - for k in 0..3 { - assert!(d.channels[k].surface.pixel(1, 1)[0] > 0.99); + for c in &d.channels[..3] { + assert!(c.surface.pixel(1, 1)[0] > 0.99); } // Back to RGB: the alpha channel survives, the inks become colour channels. s.execute("image.mode.rgb", json!({})).unwrap(); diff --git a/crates/engine/src/cmd/paint_cmds/tests.rs b/crates/engine/src/cmd/paint_cmds/tests.rs index bbcc8f7012d..70433735809 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/perspective_crop_cmds.rs b/crates/engine/src/cmd/perspective_crop_cmds.rs index d5d4db24f57..161fa35e704 100644 --- a/crates/engine/src/cmd/perspective_crop_cmds.rs +++ b/crates/engine/src/cmd/perspective_crop_cmds.rs @@ -12,7 +12,7 @@ //! editable equivalent for them. Vector masks, paths, notes, slices and guides follow the affine //! map closest to the homography (exact when the quad is a parallelogram). -use photocraft_algo::transform::{Homography, Interp, convex_quad, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; +use photocraft_algo::transform::{Homography, Interp, convex_quad_any_winding, quad_free_size, quad_size, quad_to_rect, warp_surface_clipped}; use photocraft_color::PixelFormat; use photocraft_doc::{Document, Layer, LayerContent, LayerId, Size}; use photocraft_geom::{Affine, Rect}; @@ -39,7 +39,8 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } -/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad clockwise on screen. +/// `corners`: four `[x, y]` points, TL, TR, BR, BL, forming a convex quad. Wound counter-clockwise +/// on screen (a box flipped on one axis) it crops mirrored, each corner as it lies (#12489). fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { let shape = || bad("`corners` must be four [x, y] points: top-left, top-right, bottom-right, bottom-left"); let list = p.get("corners").and_then(Value::as_array).filter(|a| a.len() == 4).ok_or_else(shape)?; @@ -52,9 +53,9 @@ fn corners(p: &Value) -> Result<[[f64; 2]; 4]> { } *slot = [x, y]; } - if !convex_quad(&q) { + if !convex_quad_any_winding(&q) { return Err(bad( - "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (clockwise on screen)", + "the corners must form a convex quadrilateral at least 1 px in area, in order top-left, top-right, bottom-right, bottom-left (counter-clockwise on screen crops mirrored)", )); } Ok(q) @@ -387,7 +388,7 @@ mod tests { json!({"corners": [[0, 0], [10, 0], [10, 10]]}), json!({"corners": [[0, 0], [50, 0], [100, 0], [0, 50]]}), json!({"corners": [[0, 0], [50, 50], [50, 0], [0, 50]]}), - json!({"corners": [[0, 0], [0, 50], [50, 50], [50, 0]]}), + json!({"corners": [[50, 0], [0, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], [0.5, 0], [0.5, 0.5], [0, 0.5]]}), json!({"corners": [[0, 0], [1e300, 0], [50, 50], [0, 50]]}), json!({"corners": [[0, 0], ["a", 0], [50, 50], [0, 50]]}), diff --git a/crates/engine/src/cmd/rasterize_style_cmds.rs b/crates/engine/src/cmd/rasterize_style_cmds.rs index 55a637d5cbc..5c8210852b7 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 b4391cb6f22..285ef60d97f 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/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs new file mode 100644 index 00000000000..16e430f6508 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/blur_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12656: the Blur tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the blur tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the blur tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.blur", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.blur", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.blur", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.blur", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs new file mode 100644 index 00000000000..d278633555e --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/burn_refuses_indexed_tests.rs @@ -0,0 +1,48 @@ +//! #12673: the Burn tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the burn tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the burn tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "range": "midtones", "exposure": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.burn", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.burn", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.burn", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.burn", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 082fa9a28e2..2a89e5527e5 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -280,13 +280,18 @@ impl DabTool { } } -/// The reference application refuses a Dodge or Sharpen stroke in Indexed Color and Bitmap -/// documents, with its alert's words (#12686, #12953); other modes (Multichannel and Duotone were -/// not measured) paint as before. The live stroke checks this too, so it previews nothing there. +/// The reference application refuses a Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke in +/// Indexed Color and Bitmap documents, with its alert's words (#12686, #12673, #13033, #12656, +/// #12953, #12967); other modes (Multichannel and Duotone were not measured) paint as before. The +/// live stroke checks this too, so it previews nothing there. fn mode_refusal(s: &Session, cmd: &str) -> Result<()> { let tool = match cmd { "paint.dodge" => "dodge tool", + "paint.burn" => "burn tool", + "paint.sponge" => "sponge tool", + "paint.blur" => "blur tool", "paint.sharpen" => "sharpen tool", + "paint.smudge" => "smudge tool", _ => return Ok(()), }; let why = match s.active().map(|st| st.doc.mode) { @@ -717,6 +722,22 @@ mod dodge_refuses_indexed_tests; #[path = "sharpen_refuses_indexed_tests.rs"] mod sharpen_refuses_indexed_tests; +#[cfg(test)] +#[path = "burn_refuses_indexed_tests.rs"] +mod burn_refuses_indexed_tests; + +#[cfg(test)] +#[path = "sponge_refuses_indexed_tests.rs"] +mod sponge_refuses_indexed_tests; + +#[cfg(test)] +#[path = "blur_refuses_indexed_tests.rs"] +mod blur_refuses_indexed_tests; + +#[cfg(test)] +#[path = "smudge_refuses_indexed_tests.rs"] +mod smudge_refuses_indexed_tests; + #[cfg(test)] #[path = "smudge_mode_tests.rs"] mod smudge_mode_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs new file mode 100644 index 00000000000..4a621b27c3f --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/smudge_refuses_indexed_tests.rs @@ -0,0 +1,57 @@ +//! #12967: the Smudge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the smudge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the smudge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +/// The grey document with its left half black: an edge for the stroke to work on. +fn edged(mode: ColorMode, depth: SampleType) -> Session { + let mut s = session(mode, depth); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 64})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "strength": 100}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = edged(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.smudge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.smudge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = edged(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.smudge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + let before = pixels(&s); + s.execute("paint.smudge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_ne!(pixels(&s), before, "{mode:?}/{depth:?}: the stroke changed pixels"); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs new file mode 100644 index 00000000000..61dd03901c3 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/sponge_refuses_indexed_tests.rs @@ -0,0 +1,49 @@ +//! #13033: the Sponge tool refuses Indexed Color and Bitmap documents with the reference +//! application's messages, changing nothing and adding no history; the live stroke is refused the +//! same way. RGB, Grayscale, CMYK and Lab at every depth, Multichannel and Duotone keep working. + +use photocraft_color::{ColorMode, SampleType}; +use serde_json::json; + +use super::dodge_refuses_indexed_tests::{pixels, session, steps}; +use super::*; + +const INDEXED: &str = "Could not use the sponge tool because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; +const BITMAP: &str = "Could not use the sponge tool because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; + +fn stroke() -> Value { + json!({"points": [[20, 32], [44, 32]], "size": 20, "hardness": 100, "mode": "desaturate"}) +} + +#[test] +fn indexed_and_bitmap_documents_refuse_with_the_reference_words() { + // Per mode: the command's error, the live stroke's error, pixels kept, history kept. + let got = [ColorMode::Indexed, ColorMode::Bitmap].map(|mode| { + let mut s = session(mode, SampleType::U8); + let (before, n) = (pixels(&s), steps(&s)); + let err = s.execute("paint.sponge", stroke()).err().map(|e| e.to_string()); + let live = LiveDab::begin(&s, "paint.sponge", &stroke()).err().map(|e| e.to_string()); + (err, live, pixels(&s) == before, steps(&s) == n) + }); + let want = [INDEXED, BITMAP].map(|m| (Some(m.to_string()), Some(m.to_string()), true, true)); + assert_eq!(got, want); +} + +/// Every other mode and depth keeps working: one History step and a live stroke. +/// +/// The grey document has no saturation to take away, so this checks that the stroke runs and +/// records its History step, not that pixels change. +#[test] +fn other_modes_keep_working_at_every_depth() { + let depths = [SampleType::U8, SampleType::U16, SampleType::F32]; + let measured = [ColorMode::Rgb, ColorMode::Grayscale, ColorMode::Cmyk, ColorMode::Lab].into_iter().flat_map(|m| depths.map(|d| (m, d))); + // Not measured in the reference: they keep today's behaviour. + let unmeasured = [(ColorMode::Multichannel, SampleType::U8), (ColorMode::Duotone, SampleType::U8)]; + for (mode, depth) in measured.chain(unmeasured) { + let mut s = session(mode, depth); + let n = steps(&s); + assert!(LiveDab::begin(&s, "paint.sponge", &stroke()).is_ok(), "{mode:?}/{depth:?}: live"); + s.execute("paint.sponge", stroke()).unwrap_or_else(|e| panic!("{mode:?}/{depth:?}: {e}")); + assert_eq!(steps(&s), n + 1, "{mode:?}/{depth:?}: one history step"); + } +} diff --git a/crates/engine/src/cmd/smart_cmds/rendering.rs b/crates/engine/src/cmd/smart_cmds/rendering.rs index e922e125ef4..5102e728f87 100644 --- a/crates/engine/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine/src/cmd/smart_cmds/rendering.rs @@ -156,8 +156,16 @@ fn renders_in_object(f: &SmartFilter) -> bool { /// requesting session's authority denies the filter's params: callers surface the error instead of /// rendering (and caching) unfiltered pixels. fn apply_smart_filter(f: &SmartFilter, sm: &SmartObject, cur: &Surface, canvas: Rect, extent: Rect, ctx: &JobCtx) -> Result { + // Equalize bypasses `apply_filter_to_surface_in` (the gate there), so check the command first. + crate::jobs::authorize_render_command(&f.command, &f.params)?; let params = crate::distort_cmds::placed_puppet_params(&f.command, &f.params, sm); - let out = match crate::filters::apply_filter_to_surface_in(&f.command, ¶ms, cur, canvas, None, extent, ctx)? { + let rendered = if f.command == "image.adjustments.equalize" { + ctx.check()?; + crate::adjust_cmds::adjust_as_filter("equalize", ¶ms, cur, sm.filter_mask.as_ref())? + } else { + crate::filters::apply_filter_to_surface_in(&f.command, ¶ms, cur, canvas, None, extent, ctx)? + }; + let out = match rendered { // Unknown ids (e.g. Photoshop filters we don't implement) leave the pixels alone. Some(out) => out, None => cur.clone(), @@ -347,7 +355,7 @@ pub(super) fn render_in(doc: &Document, sm: &SmartObject, ctx: &JobCtx) -> Resul let keys: Vec = filters .iter() .scan(placed_key, |key, f| { - *key = stack_cache::filter_key(key, f); + *key = stack_cache::filter_key(key, f, sm.filter_mask.as_ref()); Some(*key) }) .collect(); diff --git a/crates/engine/src/cmd/smart_cmds/stack_cache.rs b/crates/engine/src/cmd/smart_cmds/stack_cache.rs index 372d30eaab3..69ee6515f0f 100644 --- a/crates/engine/src/cmd/smart_cmds/stack_cache.rs +++ b/crates/engine/src/cmd/smart_cmds/stack_cache.rs @@ -48,11 +48,24 @@ pub(super) fn placed_key(bytes: &[u8], fmt: PixelFormat, sm: &SmartObject, canva } /// The stage after applying `f` to stage `below`. -pub(super) fn filter_key(below: &StageKey, f: &SmartFilter) -> StageKey { +pub(super) fn filter_key(below: &StageKey, f: &SmartFilter, mask: Option<&photocraft_doc::LayerMask>) -> StageKey { let mut h = blake3::Hasher::new(); h.update(below); h.update(format!("{}\0{}\0{:?}\0", f.command, f.params, f.blend).as_bytes()); h.update(&f.opacity.to_bits().to_le_bytes()); + // Equalize's histogram depends on coverage; downstream stages inherit this key. + if f.command == "image.adjustments.equalize" + && let Some(mask) = mask.filter(|m| m.enabled) + { + h.update(format!("{:?}|{}", mask.surface.format(), mask.density).as_bytes()); + h.update(mask.surface.default_bytes()); + let mut tiles: Vec<_> = mask.surface.tiles().collect(); + tiles.sort_by_key(|(coord, _)| **coord); + for (coord, tile) in tiles { + h.update(format!("{coord:?}").as_bytes()); + h.update(&tile.bytes()); + } + } *h.finalize().as_bytes() } diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 6f4ee75a40f..d4cf59300f3 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -6,6 +6,7 @@ use super::{ Affine, Color, Document, EngineError, Fill, FillRule, Layer, LayerContent, LayerId, LiveShape, Path, PathOp, Point, Result, SHAPE_BLOCKS, Session, ShapeLayer, Value, bad, json, sel, vector, }; +use std::borrow::Cow; fn active_shape(s: &Session) -> std::result::Result<&ShapeLayer, String> { let d = s.active().ok_or("no document open")?; @@ -70,7 +71,22 @@ pub(super) fn paste_shape_stroke(s: &mut Session, p: &Value) -> Result { /// The path `shape.create` draws for live-shape params `p` (the Shape tools preview it while dragging). pub fn shape_path(p: &Value) -> Result { let kind = p.get("kind").and_then(Value::as_str).unwrap_or("rect"); - Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, p, None)?)) + let (kind, p) = triangle_as_polygon(kind, p); + Ok(vector::shapes::live_path(&live_from_params("shape.create", kind, &p, None)?)) +} + +/// `kind: "triangle"` (the Triangle tool, Create Triangle) is a 3-sided polygon: the live-shape +/// kind and params to build it from. Its own kind only names the new layer (Triangle N). +fn triangle_as_polygon<'a>(kind: &'a str, p: &'a Value) -> (&'a str, Cow<'a, Value>) { + if kind != "triangle" { + return (kind, Cow::Borrowed(p)); + } + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.insert("sides".into(), json!(3)); + o.remove("starRatio"); + } + ("polygon", Cow::Owned(q)) } fn live_kind(l: &LiveShape) -> &'static str { @@ -426,6 +442,7 @@ fn default_name(kind: &str) -> &'static str { "roundedRect" | "roundRect" => "Rounded Rectangle", "ellipse" => "Ellipse", "polygon" => "Polygon", + "triangle" => "Triangle", "star" => "Star", "line" => "Line", _ => "Shape", @@ -443,7 +460,8 @@ pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { let v = p.get("path").ok_or_else(|| bad(CMD, "kind \"path\" needs `path`"))?; (parse_path(v).map_err(|e| bad(CMD, e))?, None) } else { - let l = live_from_params(CMD, kind, p, None)?; + let (live_kind, q) = triangle_as_polygon(kind, p); + let l = live_from_params(CMD, live_kind, &q, None)?; (vector::shapes::live_path(&l), Some(l)) }; let (fill, stroke) = new_fill_stroke(s, CMD, p)?; @@ -786,6 +804,10 @@ pub(super) fn selection_to_shape(s: &mut Session, p: &Value) -> Result { shape_create(s, &q) } +#[cfg(test)] +#[path = "triangle_layer_name_tests.rs"] +mod triangle_layer_name_tests; + #[cfg(test)] mod arrow_affine_regression_tests { use super::*; diff --git a/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs new file mode 100644 index 00000000000..5cfddca5ba6 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/triangle_layer_name_tests.rs @@ -0,0 +1,70 @@ +//! The Triangle tool and Create Triangle name their shape layers Triangle N, not Polygon N (#13353). + +use serde_json::{Value, json}; + +use super::super::{LayerContent, LayerId, LiveShape, shape_path}; +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 160, "background": "white"})).unwrap(); + s +} + +/// The params the Triangle tool's drag and Create Triangle's OK send. +fn triangle(rect: [f64; 4]) -> Value { + json!({"kind": "triangle", "rect": rect}) +} + +fn name(info: &Value) -> &str { + info["name"].as_str().unwrap() +} + +#[test] +fn triangles_are_named_triangle_n() { + let mut s = session(); + let first = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let second = s.execute("shape.create", triangle([90.0, 30.0, 50.0, 50.0])).unwrap(); + assert_eq!((name(&first), name(&second)), ("Triangle 1", "Triangle 2")); +} + +#[test] +fn a_triangle_is_a_live_three_sided_polygon() { + let mut s = session(); + // Any `sides` or `starRatio` sent along is ignored: a triangle has 3 sides and no star. + let p = json!({"kind": "triangle", "rect": [20, 20, 60, 40], "sides": 7, "starRatio": 0.3, "cornerRadius": 4}); + let id = s.execute("shape.create", p.clone()).unwrap()["layer"].as_u64().unwrap(); + let LayerContent::Shape(sh) = &s.active().unwrap().doc.layer(LayerId(id)).unwrap().content else { panic!("not a shape layer") }; + assert_eq!(sh.live, Some(LiveShape::Polygon { rect: [20.0, 20.0, 60.0, 40.0], sides: 3, star_ratio: 1.0, corner_radius: 4.0 })); + // The drag's preview and Path mode draw the same outline. + let polygon = json!({"kind": "polygon", "rect": [20, 20, 60, 40], "sides": 3, "cornerRadius": 4}); + assert_eq!(shape_path(&p).unwrap(), shape_path(&polygon).unwrap()); + assert_eq!(sh.path, shape_path(&polygon).unwrap()); +} + +#[test] +fn polygons_and_triangles_count_on_their_own() { + let mut s = session(); + let tri = s.execute("shape.create", triangle([20.0, 20.0, 60.0, 40.0])).unwrap(); + let poly = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 30, 50, 50], "sides": 5})).unwrap(); + let three = s.execute("shape.create", json!({"kind": "polygon", "rect": [90, 90, 50, 50], "sides": 3})).unwrap(); + assert_eq!((name(&tri), name(&poly), name(&three)), ("Triangle 1", "Polygon 1", "Polygon 2")); +} + +#[test] +fn an_explicit_name_wins() { + let mut s = session(); + let info = s.execute("shape.create", json!({"kind": "triangle", "rect": [20, 20, 60, 40], "name": "Roof"})).unwrap(); + assert_eq!(name(&info), "Roof"); +} + +#[test] +fn a_triangle_without_a_rect_is_refused() { + let mut s = session(); + let history = s.active().unwrap().history.past_len(); + for p in [json!({"kind": "triangle"}), json!({"kind": "triangle", "rect": "x"})] { + assert!(s.execute("shape.create", p.clone()).is_err(), "{p}"); + } + assert!(shape_path(&json!({"kind": "triangle"})).is_err()); + assert_eq!(s.active().unwrap().history.past_len(), history); +} diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index ce73e2cae9b..dd263e335af 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -213,7 +213,7 @@ pub(crate) fn apply_filter_to_surface_in( } // Image › Adjustments recorded as smart filters (Levels, Curves, Shadows/Highlights… from PSD). if let Some(kind) = id.strip_prefix("image.adjustments.") { - return crate::adjust_cmds::adjust_as_filter(kind, params, surf); + return crate::adjust_cmds::adjust_as_filter(kind, params, surf, None); } // WebAssembly plug-in smart filters (plugin_cmds). if id == crate::plugin_cmds::RUN { diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 31e29abe23e..a20f0164e97 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -962,6 +962,7 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor photocraft_io::ImportOptions { max_group_depth: prefs.file_handling.rasterize_svg_groups_deeper_than as usize, demosaic: prefs.raw_defaults.demosaic.method(), + keep_raw: false, pdf_dpi: prefs.file_handling.pdf_dpi, pdf_pages: match (prefs.file_handling.pdf_first_page, prefs.file_handling.pdf_last_page) { (0, 0) => None, @@ -1260,6 +1261,8 @@ impl Session { let name_w = name.to_string(); let name_a = name.to_string(); let mut opts = import_options(self.prefs()); + // An interactive raw open keeps its sensor data for the Camera Raw dialog it may show. + opts.keep_raw = confirm_damage && self.prefs().raw_defaults.open_in_camera_raw; opts.psd_high_memory_approved = approve_high_memory; opts.psd_approved_estimate = approved_estimate; let test_memory_scope = photocraft_io::memory::TestMemoryScope::capture(); diff --git a/crates/engine/tests/it/rasterize_selected_layers.rs b/crates/engine/tests/it/rasterize_selected_layers.rs index a738b51681b..265af588943 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/format/src/noreplace.rs b/crates/format/src/noreplace.rs index 75a54350c5c..60d74d29c85 100644 --- a/crates/format/src/noreplace.rs +++ b/crates/format/src/noreplace.rs @@ -107,14 +107,11 @@ pub fn rename_noreplace(from: &Path, to: &Path) -> io::Result<()> { /// Use fallback only when the exclusive rename primitive itself is unsupported. fn unsupported_rename(error: &io::Error) -> bool { - if error.kind() == io::ErrorKind::Unsupported { - return true; - } #[cfg(unix)] if matches!(error.raw_os_error(), Some(code) if code == rustix::io::Errno::INVAL.raw_os_error() || code == rustix::io::Errno::NOSYS.raw_os_error()) { return true; } - false + error.kind() == io::ErrorKind::Unsupported } /// Linking claims an absent destination atomically; a later unlink failure is already published. diff --git a/crates/io/src/affinity.rs b/crates/io/src/affinity.rs index 6e272fd6691..927fa142d66 100644 --- a/crates/io/src/affinity.rs +++ b/crates/io/src/affinity.rs @@ -32,22 +32,36 @@ const MAX_SIDE: f64 = 300_000.0; /// container of embedded images could still decode (and keep) a surface each until the process /// dies. ORA and KRA budget their decoded pixels the same way. const MAX_PIXEL_BYTES: u64 = 1 << 30; +/// Bytes the import's optional pixel caches (shapes, type layers) may hold together. They are +/// drawn again on the first edit, so running out costs nothing but speed; raster layers and +/// embedded images are lost for good when they don't fit. A separate pool keeps thousands of +/// cheap caches early in a file from using up [`MAX_PIXEL_BYTES`] and dropping images later. +const MAX_CACHE_BYTES: u64 = 512 << 20; pub fn has_extension(name: &str) -> bool { name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e))) } -pub(crate) fn import(name: &str, bytes: &[u8]) -> Result { +pub(crate) fn import(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -> Result { match photocraft_affinity::read(bytes, photocraft_affinity::Limits::default()) { Ok(d) => { let mut b = Builder::new(name, &d)?; + b.ctl = *ctl; b.document(&d)?; + ctl.check().map_err(|_| IoError::Cancelled)?; let mut warnings: Vec = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect(); warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}."))); // Type layers draw from their model, within the import's raster bound: the sizes and - // frames come from an untrusted file. + // frames come from an untrusted file. They share the optional-cache budget with the + // shapes, so a file with thousands of type layers can't allocate without end. let mut document = b.doc; - crate::text_import::prepare(&mut document, None); + let unrendered = crate::text_import::prepare_within(&mut document, None, &mut b.cache_budget, ctl).map_err(|_| IoError::Cancelled)?; + if unrendered > 0 { + warnings.push(format!("Affinity: {unrendered} type layers beyond the import's memory limit were left without pixels until they are edited.")); + } + if b.uncached_shapes > 0 { + warnings.push(format!("Affinity: {} shapes beyond the import's memory limit were left without a pixel cache.", b.uncached_shapes)); + } // Save never writes back over the Affinity file. Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false }) } @@ -80,7 +94,7 @@ fn preview(name: &str, bytes: &[u8], native: &photocraft_affinity::Error) -> Res Ok(r) } -struct Builder { +struct Builder<'a> { doc: Document, warnings: Vec, /// Document pixels (in the canvas) per Affinity document pixel: always 1; spreads are offset. @@ -88,6 +102,12 @@ struct Builder { canvas: Rect, /// Decoded pixel bytes left for embedded images and their resampled surfaces. pixel_budget: u64, + /// Bytes left for the optional shape and type caches ([`MAX_CACHE_BYTES`]). + cache_budget: u64, + /// Shapes that went without a cache because `cache_budget` ran out. + uncached_shapes: usize, + /// Checked per layer: a cancelled import stops building. + ctl: photocraft_raster::Interrupt<'a>, } /// Deduct `cost` bytes from a decoded-pixel budget; `false` (leaving the budget alone) when it @@ -110,7 +130,7 @@ fn point(p: af::Point) -> Point { Point::new(p.x, p.y) } -impl Builder { +impl Builder<'_> { fn new(name: &str, d: &af::Document) -> Result { // Spreads (Publisher pages) side by side, 64 px apart. let mut w: f64 = 0.0; @@ -126,7 +146,16 @@ impl Builder { let mut doc = Document::new(name, size, ColorMode::Rgb, SampleType::U8); doc.resolution_dpi = d.dpi as f32; let canvas = Rect::new(0, 0, size.width as i32, size.height as i32); - Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas, pixel_budget: MAX_PIXEL_BYTES }) + Ok(Self { + doc, + warnings: Vec::new(), + format: PixelFormat::RGBA8, + canvas, + pixel_budget: MAX_PIXEL_BYTES, + cache_budget: MAX_CACHE_BYTES, + uncached_shapes: 0, + ctl: photocraft_raster::Interrupt::NONE, + }) } fn warn(&mut self, w: &str) { @@ -249,6 +278,9 @@ impl Builder { /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas. fn layer(&mut self, n: &af::Node, to_doc: Affine, top: bool) -> Option { + if self.ctl.cancelled() { + return None; + } let children: Vec = n.children.iter().filter_map(|c| self.layer(c, to_doc, false)).collect(); let mut l = match &n.kind { Kind::Layer | Kind::Group => self.group(n, children), @@ -446,13 +478,26 @@ impl Builder { // The pixel cache is optional (the shape renders from its path without it), so charge the // area it would cover to the import's pixel budget and go without it when that is spent: // geometry across a 300000 px canvas would otherwise be rasterized for every shape. - let reach = sh.stroke.as_ref().map_or(0, |s| (s.width.ceil() as i32).saturating_add(1)); - let area = frame.inflate(reach).intersect(&self.canvas); - let cost = u64::from(area.width()).saturating_mul(u64::from(area.height())).saturating_mul(self.format.bytes_per_pixel() as u64); - if charge(&mut self.pixel_budget, cost) { - sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas)); + // Once not even one tile is left nothing can be charged, so skip compiling the shape + // (flattening and stroking its path) just to throw the result away. + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), self.format.bytes_per_pixel()); + if self.cache_budget < tile { + if !sh.path.subpaths.is_empty() { + self.uncached_shapes += 1; + } + return sh; + } + // The compiled bounds are what `render` covers, an acute miter reaching past the stroke width included. + #[cfg(test)] + COMPILED_SHAPES.with(|n| n.set(n.get() + 1)); + let compiled = photocraft_vector::CompiledShape::new(&sh, photocraft_vector::DEFAULT_TOLERANCE, self.canvas); + let area = compiled.bounds().map_or(Rect::default(), |b| b.intersect(&self.canvas)); + // Whole tiles: even a 2x2 px shape keeps one, which 50 000 small shapes add up to gigabytes. + let cost = crate::text_import::cache_bytes(area, self.format.bytes_per_pixel()); + if charge(&mut self.cache_budget, cost) { + sh.cache = Some(compiled.render(self.format, self.canvas)); } else { - self.warn("shapes covering more pixels than the import's memory allows were left without a pixel cache"); + self.uncached_shapes += 1; } sh } @@ -657,6 +702,12 @@ fn color(c: ap::Color) -> Color { } } +#[cfg(test)] +thread_local! { + /// How many shapes this thread compiled for a pixel cache (for the exhausted-budget test). + static COMPILED_SHAPES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + #[cfg(test)] mod tests { use super::*; @@ -727,4 +778,166 @@ mod tests { ok.document(&d).unwrap(); assert_eq!(ok.doc.layers.len(), 1, "within the budget the image imports as a smart object"); } + + fn node(kind: Kind) -> af::Node { + af::Node { + class: photocraft_affinity::synth::tag(b"ImgN"), + name: "n".into(), + visible: true, + locked: false, + opacity: 1.0, + blend: Blend::Normal, + kind, + mask: None, + pixel_mask: None, + children: Vec::new(), + } + } + + fn page(nodes: Vec) -> af::Document { + af::Document { + dpi: 72.0, + spreads: vec![af::Spread { bounds: af::Rect { x0: 0.0, y0: 0.0, x1: 64.0, y1: 64.0 }, pages: Vec::new(), transparent: true, nodes }], + saved_by: None, + warnings: Vec::new(), + } + } + + /// A 2×2 px solid rectangle. + fn tiny_shape(i: usize) -> af::Node { + let p = |x: f64, y: f64| af::Point { x, y }; + let (x, y) = ((i % 30) as f64, (i / 30 % 30) as f64); + let corners = [p(x, y), p(x + 2.0, y), p(x + 2.0, y + 2.0), p(x, y + 2.0)]; + let sub = af::SubPath { start: corners[0], segments: (1..=4).map(|k| [corners[k % 4]; 3]).collect(), closed: true }; + node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: vec![ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 })], + strokes: Vec::new(), + even_odd: false, + }) + } + + #[test] + fn small_shapes_are_charged_a_whole_tile_each() { + // Surfaces keep whole tiles, so 2×2 px shapes cost a tile each: 50 000 of them were + // 7 GB. A budget of three tiles keeps the pixel cache of the first three only. + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.cache_budget = 3 * 256 * 256 * 4; + b.document(&d).unwrap(); + let cached = |l: &Layer| matches!(&l.content, LayerContent::Shape(s) if s.cache.is_some()); + assert_eq!(b.doc.layers.iter().filter(|l| cached(l)).count(), 3); + assert_eq!(b.doc.layers.iter().filter(|l| matches!(l.content, LayerContent::Shape(_))).count(), 10, "every shape still imports"); + assert_eq!(b.uncached_shapes, 7); + assert_eq!(b.cache_budget, 0); + assert_eq!(b.pixel_budget, MAX_PIXEL_BYTES, "caches don't draw on the pool images need"); + } + + #[test] + fn shapes_are_not_compiled_once_no_cache_tile_fits() { + // Three tiles pay for the first three shapes; the other 27 must not even be compiled. + let d = page((0..30).map(tiny_shape).collect()); + let mut b = Builder::new("shapes", &d).unwrap(); + b.cache_budget = 3 * 256 * 256 * 4; + COMPILED_SHAPES.with(|n| n.set(0)); + b.document(&d).unwrap(); + assert_eq!(COMPILED_SHAPES.with(std::cell::Cell::get), 3); + assert_eq!(b.uncached_shapes, 27, "the skipped-cache warning still counts them"); + assert_eq!(b.doc.layers.len(), 30, "every shape still imports"); + } + + #[test] + fn an_acute_miter_is_charged_for_the_tiles_it_reaches() { + // A thin spike at x = 250 with a 4 px miter stroke reaches x = 270, into the next 256 px + // tile, though the stroke width alone would stay in the first. + let p = |x: f64, y: f64| af::Point { x, y }; + let sub = af::SubPath { + start: p(250.0, 100.0), + segments: [p(200.0, 95.0), p(200.0, 105.0), p(250.0, 100.0)].iter().map(|c| [*c; 3]).collect(), + closed: true, + }; + let mut d = page(vec![node(Kind::Shape { + path: af::Path { subpaths: vec![sub] }, + fills: Vec::new(), + strokes: vec![ap::Stroke { + paint: ap::Paint::Solid(ap::Color::Rgb { r: 1.0, g: 0.0, b: 0.0, a: 1.0 }), + width: 4.0, + cap: Cap::Butt, + join: Join::Miter, + miter_limit: 20.0, + align: ap::Align::Center, + dash: None, + behind: false, + }], + even_odd: false, + })]); + d.spreads[0].bounds.x1 = 600.0; + d.spreads[0].bounds.y1 = 600.0; + let mut b = Builder::new("miter", &d).unwrap(); + let tile = crate::text_import::cache_bytes(Rect::new(0, 0, 1, 1), b.format.bytes_per_pixel()); + b.cache_budget = tile; + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 1, "two tiles do not fit a budget of one"); + assert_eq!(b.cache_budget, tile, "nothing was charged"); + let mut b2 = Builder::new("miter", &d).unwrap(); + b2.cache_budget = 2 * tile; + b2.document(&d).unwrap(); + assert_eq!(b2.uncached_shapes, 0); + assert_eq!(b2.cache_budget, 0, "charged for both tiles"); + } + + #[test] + fn a_cancelled_import_stops_building_layers() { + let d = page((0..10).map(tiny_shape).collect()); + let mut b = Builder::new("cancel", &d).unwrap(); + let cancel = || true; + b.ctl = photocraft_raster::Interrupt::cancel_only(&cancel); + b.document(&d).unwrap(); + assert!(b.doc.layers.is_empty(), "no layer is built once cancelled"); + let mut doc = Document::new("t", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let mut budget = u64::MAX; + doc.layers.push(Layer::new("t", LayerContent::Text(TextLayer { text: "x".into(), ..TextLayer::default() }))); + assert!(crate::text_import::prepare_within(&mut doc, None, &mut budget, &b.ctl).is_err()); + } + + #[test] + fn type_layers_share_the_cache_budget_and_keep_going_without_pixels() { + // Each layer's ink is charged to the budget; one that doesn't fit keeps an empty cache and + // is counted, instead of every layer of a 2000-layer file drawing its own raster. + let mut doc = Document::new("t", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + for i in 0..20 { + let text = "Budget".to_string(); + let mut t = TextLayer { text, font_family: "sans-serif".into(), size_pt: 24.0, ..TextLayer::default() }; + t.runs = vec![TextRun { len: t.text.len(), style: CharStyle { size_pt: 24.0, ..CharStyle::default() } }]; + doc.layers.push(Layer::new(format!("t{i}"), LayerContent::Text(t))); + } + // What one layer costs, then room for two and a half. + let mut probe = u64::MAX; + let mut one = doc.clone(); + one.layers.truncate(1); + crate::text_import::prepare_within(&mut one, None, &mut probe, &photocraft_raster::Interrupt::NONE).unwrap(); + let cost = u64::MAX - probe; + assert!(cost > 0); + let mut budget = cost * 5 / 2; + let skipped = crate::text_import::prepare_within(&mut doc, None, &mut budget, &photocraft_raster::Interrupt::NONE).unwrap(); + let drawn = doc.layers.iter().filter(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.as_ref().is_some_and(|c| c.tile_count() > 0))).count(); + assert_eq!((drawn, skipped), (2, 18)); + assert!(drawn + skipped == 20, "drawn {drawn} skipped {skipped}"); + assert!(doc.layers.iter().all(|l| matches!(&l.content, LayerContent::Text(t) if t.cache.is_some())), "every layer has a cache, empty or not"); + } + + #[test] + fn shape_caches_leave_room_for_images() { + // 64 shapes overrun the cache pool; the image after them still imports. + let mut nodes: Vec = (0..64).map(tiny_shape).collect(); + nodes.extend(affinity_document(vec![(64, 64, Pixels::Rgba8(vec![0; 64 * 64 * 4]))]).spreads.remove(0).nodes); + let d = page(nodes); + let mut b = Builder::new("mixed", &d).unwrap(); + b.cache_budget = 4 * 256 * 256 * 4; + b.pixel_budget = 256 * 256 * 4; // one whole tile for the image + b.document(&d).unwrap(); + assert_eq!(b.uncached_shapes, 60); + assert!(b.doc.layers.iter().any(|l| matches!(l.content, LayerContent::Smart(_) | LayerContent::Raster(_))), "the image must import"); + assert!(!b.warnings.iter().any(|w| w.contains("pixel memory")), "{:?}", b.warnings); + } } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index a04d933fbd4..3edfed2838f 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -609,6 +609,9 @@ pub struct ImportOptions { pub max_group_depth: usize, /// The demosaic method camera raws are developed with. pub demosaic: raw::Demosaic, + /// Keep a developed raw's sensor data for its open-time Camera Raw dialog + /// ([`raw::take_kept_decode`]) instead of decoding the file again there. + pub keep_raw: bool, /// PSD layer/mask/merged pixel allowance, including conversion workspace, and the /// equivalent allowance for a layered TIFF's composite and retained decoded image. May /// lower the default cap; 0 uses the adaptive budget. Does not cover metadata or @@ -641,6 +644,7 @@ impl Default for ImportOptions { ImportOptions { max_group_depth: photocraft_doc::MAX_GROUP_DEPTH, demosaic: raw::Demosaic::default(), + keep_raw: false, psd_max_pixel_bytes: 0, flat_max_pixel_bytes: 0, pdf_dpi: 300.0, @@ -1019,13 +1023,19 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o Ok(ImportResult { warnings: open_warnings(&document), document, source_read_only: false, preview_only: false }) } Route::Psd | Route::NamedPsd => import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)), - Route::Affinity => affinity::import(name, bytes), + Route::Affinity => affinity::import(name, bytes, ctl), Route::Ora => ora::import(name, bytes, ctl), Route::Kra => kra::import(name, bytes, ctl), Route::Xcf => xcf::import(name, bytes, ctl), Route::GzippedXcf => xcf::import(name, &xcf::gunzip(bytes)?, ctl), Route::Pdn => pdn::import(name, bytes, ctl), - Route::Raw => raw::import_raw_demosaic(name, bytes, opts.demosaic), + Route::Raw => { + if opts.keep_raw { + raw::import_raw_demosaic_keeping(name, bytes, opts.demosaic) + } else { + raw::import_raw_demosaic(name, bytes, opts.demosaic) + } + } Route::Svg => svg::import_svg_with_group_depth(name, bytes, opts.max_group_depth), Route::Flat => flat::import_flat_with_options(name, bytes, opts, ctl), } diff --git a/crates/io/src/raw.rs b/crates/io/src/raw.rs index 1ac0fc81e1d..b0a37dacccb 100644 --- a/crates/io/src/raw.rs +++ b/crates/io/src/raw.rs @@ -10,7 +10,7 @@ //! fit is not clearly better. use std::borrow::Cow; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use photocraft_cms::{Builtin, Intent, Profile, Transform}; use photocraft_codecs::{self as codecs, ChannelLayout, Format, Image, SampleType}; @@ -83,12 +83,31 @@ pub struct RawTuning { /// no as-shot white balance: Temperature / Tint were then not applied, and the caller keeps /// them as RGB adjustments. pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, None) +} + +/// [`import_raw_tuned`] from what the open already learned about `bytes` ([`take_kept_decode`], +/// [`RawDecode::new`]): the same pixels without decoding the file and fitting its look again. +/// A `decode` of another file is ignored. +pub fn import_raw_tuned_from(name: &str, bytes: &[u8], tuning: &RawTuning, decode: &RawDecode) -> Result<(ImportResult, bool), IoError> { + import_raw_tuned_inner(name, bytes, tuning, Some(decode)) +} + +fn import_raw_tuned_inner(name: &str, bytes: &[u8], tuning: &RawTuning, decode: Option<&RawDecode>) -> Result<(ImportResult, bool), IoError> { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); let exposure = f64::from(tuning.exposure); if !exposure.is_finite() || !(-10.0..=10.0).contains(&exposure) { return Err(IoError::Raw(RawError::Malformed(format!("exposure {} EV is out of range", tuning.exposure)))); } - let sensor = photocraft_raw::decode(bytes, &limits()).map_err(IoError::Raw)?; + let fresh; + let decode = match decode.filter(|d| d.is_of(bytes)) { + Some(d) => d, + None => { + fresh = RawDecode::new(bytes)?; + &fresh + } + }; + let sensor = &decode.sensor; let slider = |v: f32| if v.is_finite() { v.clamp(-100.0, 100.0) } else { 0.0 }; let tone = photocraft_raw::Tone { shadows: slider(tuning.shadows), @@ -99,7 +118,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< }; // The colour rendering the default open used (a look fitted to the camera's JPEG for files // without colour calibration), so re-developing changes only what the sliders change. - let camera_look = default_look(bytes, &sensor); + let camera_look = decode.look.clone(); let mut opts = DevelopOptions { limits: limits(), exposure, demosaic: tuning.demosaic, tone, camera_look, ..Default::default() }; let wb_applied = match sensor.camera_wb { Some(m) => { @@ -109,7 +128,7 @@ pub fn import_raw_tuned(name: &str, bytes: &[u8], tuning: &RawTuning) -> Result< } None => false, }; - let mut dev = photocraft_raw::develop_sensor(&sensor, &opts).map_err(IoError::Raw)?; + let mut dev = photocraft_raw::develop_sensor(sensor, &opts).map_err(IoError::Raw)?; let cropped = match tuning.crop { Some(crop) => { let o = if opts.orient { dev.info.orientation } else { 1 }; @@ -153,13 +172,116 @@ fn crop_developed(dev: &mut photocraft_raw::Developed, crop: crate::camera_raw_x /// this crate decodes). For previews of the open-time raw-stage sliders /// ([`photocraft_raw::retone`]), in linear-light knots. pub fn tone_curve(bytes: &[u8]) -> Vec<[f32; 2]> { - let Ok(sensor) = photocraft_raw::decode(bytes, &limits()) else { return Vec::new() }; - match default_look(bytes, &sensor) { - Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), - None => sensor.tone_curve, + RawDecode::new(bytes).map(|d| d.tone_curve).unwrap_or_default() +} + +/// A raw file decoded once for the open-time Camera Raw dialog: the sensor data, the look fitted +/// to the camera's JPEG (for a file without colour calibration, see [`default_look`]) and the +/// tone curve the default develop uses. The dialog's preview and its Open re-develop +/// ([`import_raw_tuned_from`]) share one instead of decoding and fitting the file again each +/// (the sensor is 2 bytes per pixel: drop it when the dialog closes). +pub struct RawDecode { + fingerprint: Fingerprint, + sensor: Sensor, + look: Option, + tone_curve: Vec<[f32; 2]>, +} + +impl std::fmt::Debug for RawDecode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Not the sensor data: tens of millions of samples. + f.debug_struct("RawDecode").field("fingerprint", &self.fingerprint).field("look", &self.look.is_some()).finish_non_exhaustive() } } +impl RawDecode { + /// Decodes `bytes` and fits its look, as a default open does. + pub fn new(bytes: &[u8]) -> Result { + let sensor = decode_sensor(bytes, &limits())?; + let look = default_look(bytes, &sensor); + Ok(RawDecode::from_parts(bytes, sensor, look)) + } + + fn from_parts(bytes: &[u8], sensor: Sensor, look: Option) -> RawDecode { + let tone_curve = match &look { + Some(look) => look.tone.as_ref().map(look_knots).unwrap_or_default(), + None => sensor.tone_curve.clone(), + }; + RawDecode { fingerprint: Fingerprint::of(bytes), sensor, look, tone_curve } + } + + /// The tone curve a default develop uses, as [`tone_curve`] returns it. + pub fn tone_curve(&self) -> &[[f32; 2]] { + &self.tone_curve + } + + /// `true` if this was decoded from `bytes`. + fn is_of(&self, bytes: &[u8]) -> bool { + self.fingerprint == Fingerprint::of(bytes) + } +} + +/// The sensor data of `bytes` under `limits`. +fn decode_sensor(bytes: &[u8], limits: &Limits) -> Result { + DECODES.with(|n| n.set(n.get() + 1)); + photocraft_raw::decode(bytes, limits).map_err(IoError::Raw) +} + +thread_local! { + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many raw files this thread has decoded so far (for tests that count decodes). +#[doc(hidden)] +pub fn decodes_on_this_thread() -> usize { + DECODES.with(std::cell::Cell::get) +} + +/// A file's length and a 64-bit digest of its bytes: tells the file a [`RawDecode`] was made +/// from from any other (not a cryptographic hash). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Fingerprint(usize, u64); + +impl Fingerprint { + fn of(bytes: &[u8]) -> Fingerprint { + const K: u64 = 0x9E37_79B9_7F4A_7C15; + let mix = |lane: u64, word: u64| (lane ^ word).wrapping_mul(K).rotate_left(29); + let mut lanes = [0x243F_6A88_85A3_08D3u64, 0x1319_8A2E_0370_7344, 0xA409_3822_299F_31D0, 0x082E_FA98_EC4E_6C89]; + let (blocks, rest) = bytes.as_chunks::<32>(); + let mut absorb = |block: &[u8; 32]| { + for (lane, word) in lanes.iter_mut().zip(block.as_chunks::<8>().0) { + *lane = mix(*lane, u64::from_le_bytes(*word)); + } + }; + blocks.iter().for_each(&mut absorb); + let mut tail = [0u8; 32]; + tail[..rest.len()].copy_from_slice(rest); + absorb(&tail); + let digest = lanes.iter().fold(bytes.len() as u64, |acc, &lane| mix(acc, lane)); + Fingerprint(bytes.len(), digest) + } +} + +/// The decodes of the last opens that await their Camera Raw dialog (see +/// [`ImportOptions::keep_raw`](crate::ImportOptions::keep_raw)): at most two, so several raws +/// opened at once each find theirs, and the oldest goes first. The dialog takes its own out. +static KEPT: Mutex>> = Mutex::new(Vec::new()); + +const KEPT_MAX: usize = 2; + +fn kept() -> std::sync::MutexGuard<'static, Vec>> { + KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + +/// Hands over (removes) the decode a default open of exactly `bytes` kept for its dialog, if it +/// is still there. Whoever takes it owns the sensor data: dropping it frees it. +pub fn take_kept_decode(bytes: &[u8]) -> Option> { + let want = Fingerprint::of(bytes); + let mut kept = kept(); + let at = kept.iter().position(|d| d.fingerprint == want)?; + Some(kept.remove(at)) +} + /// A fitted look's tone curve as knots for [`photocraft_raw::retone`] (which reads them /// log-linearly): sampled densely enough that the two agree within a fraction of a code value. fn look_knots(t: &photocraft_raw::ToneCurve) -> Vec<[f32; 2]> { @@ -225,6 +347,12 @@ pub fn import_raw_demosaic(name: &str, bytes: &[u8], demosaic: Demosaic) -> Resu import_raw_with(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }) } +/// [`import_raw_demosaic`] that also keeps the sensor data and the fitted look for the file's +/// Camera Raw dialog ([`take_kept_decode`]). +pub fn import_raw_demosaic_keeping(name: &str, bytes: &[u8], demosaic: Demosaic) -> Result { + import_raw_with_inner(name, bytes, &DevelopOptions { limits: limits(), demosaic, ..Default::default() }, true) +} + /// Smallest preview long edge preferred for the colour fit (a smaller preview decodes faster; /// the fit grid is at most `PROXY_EDGE` cells and wants about two pixels per cell). const FIT_PREVIEW_EDGE: u32 = 2 * photocraft_raw::PROXY_EDGE as u32; @@ -270,10 +398,19 @@ pub fn fit_preview_look(raw: &[u8], sensor: &Sensor, opts: &DevelopOptions) -> R photocraft_raw::fit_look(sensor, opts, &Reference { width: w, height: h, rgb: &rgb }).map_err(|e| e.to_string()) } +/// A sensor and the look fitted to it, as [`develop_fitted`] hands them back. +type Kept = (Sensor, Option); + /// Decodes and develops; a file without colour calibration gets a look fitted to its preview. -fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result { - let sensor = photocraft_raw::decode(bytes, &opts.limits)?; +/// With `keep`, also hands back the sensor and the look it fitted (the default look, when +/// `opts` named none) instead of freeing them. +fn develop_fitted(bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result<(photocraft_raw::Developed, Option), RawError> { + let sensor = decode_sensor(bytes, &opts.limits).map_err(|e| match e { + IoError::Raw(e) => e, + e => RawError::Malformed(e.to_string()), + })?; let mut opts = Cow::Borrowed(opts); + let named_look = opts.camera_look.is_some(); if opts.camera_look.is_none() && sensor.color.calibrations.is_empty() && !sensor.is_monochrome() @@ -281,7 +418,9 @@ fn develop_fitted(bytes: &[u8], opts: &DevelopOptions) -> Result Option { /// Develops a raw file with explicit settings. Without `opts.camera_look`, a file without /// colour calibration gets one fitted to its embedded JPEG when that clearly helps. pub fn import_raw_with(name: &str, bytes: &[u8], opts: &DevelopOptions) -> Result { + import_raw_with_inner(name, bytes, opts, false) +} + +fn import_raw_with_inner(name: &str, bytes: &[u8], opts: &DevelopOptions, keep: bool) -> Result { let format = photocraft_raw::identify(bytes).map(|f| f.name()).unwrap_or("camera raw"); - match develop_fitted(bytes, opts) { - Ok(dev) => { + match develop_fitted(bytes, opts, keep) { + Ok((dev, kept_parts)) => { + if let Some((sensor, look)) = kept_parts { + let mut kept = kept(); + if kept.len() == KEPT_MAX { + kept.remove(0); + } + kept.push(Arc::new(RawDecode::from_parts(bytes, sensor, look))); + } let summary = format!("{DEVELOPED_NOTE} ({} demosaic, as-shot white balance)", opts.demosaic.id()); developed_document(name, bytes, format, dev, &summary) } @@ -384,6 +534,17 @@ fn jxl_preview_image(raw: &[u8], p: photocraft_raw::DecodedPreview) -> Result u64 { + if area.is_empty() { + return 0; + } + let tile = i64::from(photocraft_geom::TILE_SIZE); + let tiles = |a: i32, b: i32| (i64::from(b) - 1).div_euclid(tile) - i64::from(a).div_euclid(tile) + 1; + let n = tiles(area.x0, area.x1) as u64 * tiles(area.y0, area.y1) as u64; + n.saturating_mul((tile * tile) as u64).saturating_mul(bytes_per_pixel as u64) +} + +/// Renders `t` from its model unless its ink would exceed [`MAX_RENDER_PIXELS`] or the +/// document-wide `budget` (bytes of cache still allowed). Returns `false` when the layer went +/// without pixels because of the budget. +fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: f32, format: photocraft_color::PixelFormat, budget: &mut u64) -> bool { + let empty = || photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format }); + let tile_bytes = cache_bytes(photocraft_geom::Rect::new(0, 0, 1, 1), photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + if *budget < tile_bytes { + // Nothing with ink fits any more: don't lay the text out just to find that out. + t.cache = Some(empty()); + return false; + } let layout = eng.layout(t, dpi); let warp = photocraft_text::render::layout_deform(&layout, t); let ink = photocraft_text::render::ink_rect_warped(&layout, &t.transform, warp.as_ref()); if u64::from(ink.width()).saturating_mul(u64::from(ink.height())) > MAX_RENDER_PIXELS { - t.cache = Some(photocraft_raster::Surface::new(photocraft_color::PixelFormat { alpha: true, ..format })); - return; + t.cache = Some(empty()); + return true; } + let cost = cache_bytes(ink, photocraft_color::PixelFormat { alpha: true, ..format }.bytes_per_pixel()); + let Some(rest) = budget.checked_sub(cost) else { + t.cache = Some(empty()); + return false; + }; + *budget = rest; let r = photocraft_text::render::rasterize_warped(&layout, &t.transform, format, t.antialias, warp.as_ref()); t.cache = Some(r.surface); + true } /// Prepares the type layers of a document that was just imported: @@ -29,14 +57,32 @@ fn render_bounded(eng: &mut photocraft_text::TextEngine, t: &mut TextLayer, dpi: /// let Photoshop re-render on open) is rendered from its model, instead of staying empty /// until it is edited. pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_data::Value>) { + let mut unlimited = u64::MAX; + let _ = prepare_within(doc, txt2, &mut unlimited, &photocraft_raster::Interrupt::NONE); +} + +/// [`prepare`] with the pixels it may draw limited to `budget` bytes for the whole document +/// (type layers past it keep empty pixels, as past [`MAX_RENDER_PIXELS`]) and stopping early +/// when `ctl` is cancelled. Returns how many layers the budget left without pixels. +pub(crate) fn prepare_within( + doc: &mut Document, + txt2: Option<&photocraft_text::engine_data::Value>, + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, +) -> Result { + #[allow(clippy::too_many_arguments)] fn visit( layers: &mut [Layer], eng: &mut photocraft_text::TextEngine, dpi: f32, format: photocraft_color::PixelFormat, txt2: Option<&photocraft_text::engine_data::Value>, - ) { + budget: &mut u64, + ctl: &photocraft_raster::Interrupt, + skipped: &mut usize, + ) -> Result<(), photocraft_raster::Cancelled> { for l in layers { + ctl.check()?; match &mut l.content { LayerContent::Text(t) => { let mut changed = false; @@ -63,17 +109,20 @@ pub(crate) fn prepare(doc: &mut Document, txt2: Option<&photocraft_text::engine_ t.sync_summary(); } photocraft_text::psd::refine_legacy_point_origin(t, dpi, eng, txt2); - if t.cache.is_none() { - render_bounded(eng, t, dpi, format); + if t.cache.is_none() && !render_bounded(eng, t, dpi, format, budget) { + *skipped += 1; } } - LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2), + LayerContent::Group(g) => visit(&mut g.children, eng, dpi, format, txt2, budget, ctl, skipped)?, _ => {} } } + Ok(()) } let dpi = doc.resolution_dpi; let format = doc.pixel_format(); let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()); - visit(&mut doc.layers, &mut eng, dpi, format, txt2); + let mut skipped = 0; + visit(&mut doc.layers, &mut eng, dpi, format, txt2, budget, ctl, &mut skipped)?; + Ok(skipped) } diff --git a/crates/io/tests/it/raw.rs b/crates/io/tests/it/raw.rs index 748aaa7c67b..6d248fe9301 100644 --- a/crates/io/tests/it/raw.rs +++ b/crates/io/tests/it/raw.rs @@ -615,3 +615,74 @@ fn a_re_develop_keeps_the_fitted_look() { let mid = curve.iter().find(|k| k[0] >= 0.18).unwrap(); assert!(mid[1] > mid[0], "{mid:?}"); } + +/// The open-time Camera Raw dialog decodes the file once, in the open: its preview curve and +/// Open's re-develop reuse that decode and fitted look, and the developed pixels are those of +/// decoding and fitting again (#9432). +#[test] +fn a_kept_decode_gives_the_same_pixels_and_decodes_once() { + use photocraft_io::raw::{ + Demosaic, RawDecode, RawTuning, decodes_on_this_thread, import_raw_demosaic_keeping, import_raw_tuned, import_raw_tuned_from, take_kept_decode, + }; + let pixels = |r: &photocraft_io::ImportResult| photocraft_io::document_to_image(&r.document, &mut Vec::new()).unwrap().data().to_vec(); + + let (w, h) = (480, 320); + let cam = patches(w, h); + let nef = nef_uncompressed(&cam, w, h, Some(camera_rendering(&cam, w, h))); + let (dw, dh) = (40, 24); + let mut dng = DngSpec::cfa(dw, dh, mosaic(&scene(dw, dh), dw, [0, 1, 1, 2], 0, 65535)); + dng.as_shot_neutral = Some([0.6, 1.0, 0.8]); + let dng = dng.build(); + let (cw, ch) = (48, 16); + let cr2 = Cr2Spec { + width: cw, + height: ch, + data: mosaic(&scene(cw, ch), cw, [0, 1, 1, 2], 256, 12000), + precision: 14, + components: 2, + slices: vec![24, 24], + borders: None, + wb_rggb: None, + orientation: 6, + model_id: None, + } + .build(); + + for (name, bytes) in [("a.nef", &nef), ("b.dng", &dng), ("c.cr2", &cr2)] { + // The open, keeping its decode: one decode in all. + let before = decodes_on_this_thread(); + let opened = import_raw_demosaic_keeping(name, bytes, Demosaic::default()).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1, "{name}: the open"); + let kept = take_kept_decode(bytes).expect("the open kept its decode"); + assert!(take_kept_decode(bytes).is_none(), "{name}: taking it removes it"); + let mut reference = pixels(&import(name, bytes).unwrap()); + assert_eq!(pixels(&opened), reference, "{name}: keeping changes nothing about the open"); + assert_eq!(kept.tone_curve(), photocraft_io::raw::tone_curve(bytes), "{name}: curve"); + + for tuning in [ + RawTuning::default(), + RawTuning { exposure: 0.5, temperature: 20.0, tint: -15.0, shadows: 30.0, clarity: 20.0, ..Default::default() }, + RawTuning { demosaic: Demosaic::Bilinear, highlights: -40.0, ..Default::default() }, + ] { + let (old, old_wb) = import_raw_tuned(name, bytes, &tuning).unwrap(); + let before = decodes_on_this_thread(); + let (new, new_wb) = import_raw_tuned_from(name, bytes, &tuning, &kept).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 0, "{name}: Open decodes nothing again"); + assert_eq!((old_wb, &old.warnings), (new_wb, &new.warnings), "{name}"); + reference = pixels(&old); + assert_eq!(pixels(&new), reference, "{name}: {tuning:?}"); + } + // A decode made from the same bytes later (a miss of the open's) is as good. + let later = RawDecode::new(bytes).unwrap(); + let (a, _) = import_raw_tuned_from(name, bytes, &RawTuning::default(), &later).unwrap(); + assert_eq!(pixels(&a), pixels(&import_raw_tuned(name, bytes, &RawTuning::default()).unwrap().0)); + } + + // A decode of another file is not used for this one. + let other = RawDecode::new(&dng).unwrap(); + let before = decodes_on_this_thread(); + let (got, _) = import_raw_tuned_from("a.nef", &nef, &RawTuning::default(), &other).unwrap(); + assert_eq!(decodes_on_this_thread() - before, 1); + assert_eq!(pixels(&got), pixels(&import_raw_tuned("a.nef", &nef, &RawTuning::default()).unwrap().0)); + assert_eq!((got.document.size.width, got.document.size.height), (w as u32, h as u32)); +} diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index b9756aa0103..ce70c53cbd7 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -42,7 +42,7 @@ pub use brush::{ pub use curve::ResponseCurve; pub use mip_cache::{mip_cache_bytes, purge_mip_cache}; pub use mixer::MixerSettings; -pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke}; +pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke, render_stroke_clipped}; pub use tile::{GrayTile, StoredTile}; /// One input sample. Missing stylus data defaults to "mouse": full pressure, no tilt/rotation. diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index ffe9b888ff7..7b1ca43f960 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -760,6 +760,39 @@ pub struct StrokeRenderer { dual_buf: Vec, all_dabs: Option>, regions: RegionPool, + /// Dabs whose rectangle misses this one are not rasterized (see [`with_clip`](Self::with_clip)). + clip: Option, + /// Dab-rectangle pixels the stroke may still rasterize (see [`MAX_STROKE_DAB_AREA`]). + area_left: u64, + /// The same budget for the Dual Brush's dabs, so primary and dual dabs are charged apart and + /// the result does not depend on how the input was chunked. + dual_area_left: u64, + /// A dab was left out for want of budget. + refused: bool, +} + +/// Most dab-rectangle pixels one stroke rasterizes: past it the stroke stops painting, so a very +/// large brush at the finest spacing over a very long path costs bounded time and memory instead +/// of growing with path length times brush area. A soft round dab costs about 1.2 ns per pixel on +/// an idle four-thread machine, so the limit is a few seconds of work. 2^31 pixels is, for +/// example, 8 000 dabs of a 500 px brush (about a 40 000 px path at 1 % spacing) or 50 000 dabs of a +/// 200 px brush; a 20 000 px scribble with a 500 px brush at 5 % spacing uses a fifth of it. +pub const MAX_STROKE_DAB_AREA: u64 = 1 << 31; + +/// Whether a dab with rectangle `rect` is painted: it reaches `clip` and fits `area_left`, which +/// it is charged against. +fn admit(clip: Option, area_left: &mut u64, refused: &mut bool, rect: Rect) -> bool { + if rect.is_empty() || clip.is_some_and(|c| c.intersect(&rect).is_empty()) { + return false; + } + let area = u64::from(rect.width()) * u64::from(rect.height()); + // A dab that does not fit is skipped; a smaller later one (pressure) may still fit. + if area > *area_left { + *refused = true; + return false; + } + *area_left -= area; + true } /// The tile buffers [`StrokeRenderer::composite`] works in, kept from one composite to the next: @@ -865,6 +898,10 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: p.clip, + area_left: p.area_left, + dual_area_left: p.dual_area_left, + refused: p.refused, }) } Some(m) => { @@ -917,9 +954,34 @@ impl StrokeRenderer { dual_buf: Vec::new(), all_dabs: None, regions: RegionPool::default(), + clip: None, + area_left: MAX_STROKE_DAB_AREA, + dual_area_left: MAX_STROKE_DAB_AREA, + refused: false, } } + /// Only paint where a dab can reach inside `clip` (the target's paintable area): a dab whose + /// rectangle misses it is counted but not rasterized, and allocates no coverage tiles. Pixels + /// inside `clip` come out exactly as without it. + pub fn with_clip(mut self, clip: Rect) -> Self { + self.clip = Some(clip); + self + } + + /// Override the dab-area budget ([`MAX_STROKE_DAB_AREA`]) for this stroke. Set it before the first + /// dab: it replaces what is left, so pixels already charged are not carried over. + pub fn with_dab_area_budget(mut self, pixels: u64) -> Self { + self.area_left = pixels; + self.dual_area_left = pixels; + self + } + + /// Whether a dab was left out because the stroke used up its dab-area budget. + pub fn budget_exhausted(&self) -> bool { + self.refused + } + /// Keep a copy of every primary dab (for tests and sequential tools). pub fn record_dabs(mut self) -> Self { self.all_dabs = Some(Vec::new()); @@ -943,6 +1005,9 @@ impl StrokeRenderer { let mut native = [0.0f32; 8]; for d in &dabs { let rect = self.ctx.dab_rect(d, false); + if !admit(self.clip, &mut self.area_left, &mut self.refused, rect) { + continue; + } // Wet Edges acts on the whole stroke (#2088): the dab records how deep it reaches each // pixel and the stroke darkens its own rim when composited, not every dab's. self.ctx.rasterize_into(d, false, rect, &mut self.scratch, wet.then_some(&mut self.depth_scratch)); @@ -960,6 +1025,9 @@ impl StrokeRenderer { if let Some(dm) = self.dual.as_mut() { for d in &duals { let rect = self.ctx.dab_rect(d, true); + if !admit(self.clip, &mut self.dual_area_left, &mut self.refused, rect) { + continue; + } self.ctx.rasterize(d, true, rect, &mut self.scratch); dm.accumulate(rect, &self.scratch, 1.0, None, None); } @@ -1048,6 +1116,10 @@ impl StrokeRenderer { dual_buf: duals, all_dabs: None, regions: RegionPool::default(), + clip: self.clip, + area_left: self.area_left, + dual_area_left: self.dual_area_left, + refused: self.refused, }; t.raster_pending(); // Tiles whose coverage the tail doesn't change still composite the same: redraw them all. @@ -1349,12 +1421,28 @@ pub fn render_stroke( selection: Option<&Surface>, lock_transparency: bool, zoom: f32, +) -> Rect { + render_stroke_clipped(target, brush, points, selection, lock_transparency, zoom, None) +} + +/// [`render_stroke`] that only rasterizes dabs reaching `clip` (see [`StrokeRenderer::with_clip`]). +pub fn render_stroke_clipped( + target: &mut Surface, + brush: &BrushSettings, + points: &[StrokePoint], + selection: Option<&Surface>, + lock_transparency: bool, + zoom: f32, + clip: Option, ) -> Rect { if points.is_empty() { return Rect::EMPTY; } let pre = target.clone(); let mut r = StrokeRenderer::new(brush, Some(target.format()), zoom); + if let Some(c) = clip { + r = r.with_clip(c); + } r.push(points); r.finish(); r.composite(&pre, target, selection, lock_transparency, true) @@ -1608,6 +1696,9 @@ mod reference; #[cfg(test)] mod coverage_tests; +#[cfg(test)] +mod budget_tests; + #[cfg(test)] #[path = "mip_cache_render_tests.rs"] mod mip_cache_tests; diff --git a/crates/paint/src/render/budget_tests.rs b/crates/paint/src/render/budget_tests.rs new file mode 100644 index 00000000000..f14c0bec09b --- /dev/null +++ b/crates/paint/src/render/budget_tests.rs @@ -0,0 +1,130 @@ +//! Stroke cost limits: the clip rectangle and the dab-area budget. + +use super::*; + +fn brush(size: f32, spacing: f32) -> BrushSettings { + BrushSettings { size, spacing, hardness: 0.5, ..BrushSettings::default() } +} + +fn line(r: &mut StrokeRenderer, from: f64, to: f64) { + r.push(&[StrokePoint::new(from, 50.0, 1.0), StrokePoint::new(to, 50.0, 1.0)]); + r.finish(); +} + +#[test] +fn clip_skips_far_dabs_and_leaves_the_pixels_inside_unchanged() { + let b = brush(20.0, 0.25); + let clip = Rect::new(0, 0, 200, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + // A path that runs 20000 px, almost all of it far outside the clip. + line(&mut plain, -100.0, 20_000.0); + line(&mut clipped, -100.0, 20_000.0); + assert_eq!(plain.dab_count(), clipped.dab_count()); + for y in clip.y0..clip.y1 { + for x in clip.x0..clip.x1 { + assert_eq!(plain.coverage_at(x, y).to_bits(), clipped.coverage_at(x, y).to_bits(), "({x},{y})"); + } + } + assert!(plain.cov.tiles.len() > 20 * clipped.cov.tiles.len(), "{} vs {}", plain.cov.tiles.len(), clipped.cov.tiles.len()); + assert_eq!(clipped.coverage_at(10_000, 50), 0.0); + assert!(clipped.bounds().x1 < 400, "{:?}", clipped.bounds()); +} + +#[test] +fn a_dab_that_straddles_the_clip_edge_is_painted_in_full_inside() { + let b = brush(40.0, 0.25); + let clip = Rect::new(0, 0, 100, 100); + let mut plain = StrokeRenderer::new(&b, None, 1.0); + let mut clipped = StrokeRenderer::new(&b, None, 1.0).with_clip(clip); + plain.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + clipped.push(&[StrokePoint::new(110.0, 50.0, 1.0)]); + plain.finish(); + clipped.finish(); + assert!(plain.coverage_at(95, 50) > 0.0); + assert_eq!(plain.coverage_at(95, 50).to_bits(), clipped.coverage_at(95, 50).to_bits()); +} + +#[test] +fn a_huge_brush_at_the_finest_spacing_over_a_long_path_stays_cheap_with_a_clip() { + // 500 px brush at the 1 % minimum spacing over 2e6 px: 400 000 dabs; only those that reach the + // clip are rasterized. + let b = brush(500.0, 0.0); + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 256, 256)); + line(&mut r, -1_000_000.0, 1_000_000.0); + assert!(r.dab_count() > 100_000, "{}", r.dab_count()); + assert!(r.cov.tiles.len() < 1000, "{}", r.cov.tiles.len()); + assert!(!r.budget_exhausted()); +} + +#[test] +fn the_budget_stops_painting_but_keeps_counting_dabs() { + let b = brush(20.0, 0.25); + // A 20 px brush has a dab rectangle of about 30x30; room for about ten of them. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(10_000); + line(&mut r, 0.0, 2_000.0); + assert!(r.budget_exhausted()); + assert!(r.dab_count() > 300, "{}", r.dab_count()); + assert!(r.coverage_at(1_000, 50) == 0.0); + assert!(r.bounds().x1 < 200, "{:?}", r.bounds()); + // The first dabs did paint. + assert!(r.coverage_at(2, 50) > 0.0); + // Further input is ignored: no growth. + let tiles = r.cov.tiles.len(); + line(&mut r, 3_000.0, 4_000.0); + assert_eq!(r.cov.tiles.len(), tiles); +} + +#[test] +fn dual_dabs_are_charged_apart_and_chunking_does_not_change_the_result() { + let mut b = brush(20.0, 0.25); + b.dual_brush.enabled = true; + b.dual_brush.size = 10.0; + let pts: Vec<_> = (0..200).map(|i| StrokePoint::new(f64::from(i) * 7.0, 50.0, 1.0)).collect(); + let run = |chunk: usize| { + let mut r = StrokeRenderer::new(&b, None, 1.0).with_dab_area_budget(20_000); + for c in pts.chunks(chunk) { + r.push(c); + } + r.finish(); + r + }; + let (whole, chunked) = (run(1000), run(3)); + assert!(whole.budget_exhausted()); + for x in 0..1400 { + assert_eq!(whole.coverage_at(x, 50).to_bits(), chunked.coverage_at(x, 50).to_bits(), "x {x}"); + assert_eq!(whole.dual.as_ref().unwrap().get(x, 50).to_bits(), chunked.dual.as_ref().unwrap().get(x, 50).to_bits(), "dual x {x}"); + } + assert!(whole.dual.as_ref().unwrap().get(2, 50) > 0.0); +} + +#[test] +fn a_dab_too_big_for_what_is_left_does_not_end_the_stroke() { + let (mut left, mut refused) = (1000, false); + assert!(!admit(None, &mut left, &mut refused, Rect::new(0, 0, 100, 100))); + assert!(refused); + assert_eq!(left, 1000); + assert!(admit(None, &mut left, &mut refused, Rect::new(0, 0, 10, 10))); + assert_eq!(left, 900); +} + +/// How much of the budget everyday strokes use, so a limit change is judged against numbers. +#[test] +fn everyday_strokes_use_a_small_part_of_the_budget() { + // (size, spacing, path length in px): a 100 px brush at 1 % spacing over 6000 px, a 500 px + // brush at 5 % over 20 000 px (a scribble across a large document), 20 px at 25 % over 1e6 px. + for (size, spacing, len) in [(100.0, 0.01, 6_000.0), (500.0, 0.05, 20_000.0), (20.0, 0.25, 1.0e6)] { + let b = brush(size, spacing); + // The clip rejects every dab, so this measures the generator and `dab_rect` only. + let mut r = StrokeRenderer::new(&b, None, 1.0).with_clip(Rect::new(0, 0, 1, 1)).record_dabs(); + r.push(&[StrokePoint::new(0.0, 0.0, 1.0), StrokePoint::new(len, 0.0, 1.0)]); + r.finish(); + let used: u64 = r.dabs().iter().map(|d| r.ctx.dab_rect(d, false)).map(|q| u64::from(q.width()) * u64::from(q.height())).sum(); + println!( + "size {size} spacing {spacing} len {len}: {} dabs, {used} px = {:.1} % of the budget", + r.dab_count(), + used as f64 * 100.0 / MAX_STROKE_DAB_AREA as f64 + ); + assert!(used < MAX_STROKE_DAB_AREA / 4, "{used}"); + } +} diff --git a/crates/raster/src/memory/system.rs b/crates/raster/src/memory/system.rs index 998720b8b52..5ad4ebf5e52 100644 --- a/crates/raster/src/memory/system.rs +++ b/crates/raster/src/memory/system.rs @@ -127,12 +127,12 @@ pub(super) mod linux { } #[derive(Clone, Debug, PartialEq, Eq)] - struct Mount { - root: String, - mount_point: String, - fstype: String, - options: String, - super_options: String, + pub(super) struct Mount { + pub(super) root: String, + pub(super) mount_point: String, + pub(super) fstype: String, + pub(super) options: String, + pub(super) super_options: String, } /// Measures available RAM and free swap from `/proc/meminfo`, capped by the process's memory @@ -206,14 +206,14 @@ pub(super) mod linux { MembershipParse::Malformed => return CgroupLimits::Unreadable, }; let mountinfo = std::fs::read_to_string(proc_root.join("self/mountinfo")).ok(); - // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) - // shows the process its membership path but no interface files, so no limit is - // observable. Failing closed there reported 0 bytes free and refused every PSD on a - // machine with tens of GB. A present directory still takes the guarded path below. - // Only a confirmed NotFound counts as absent: a stat that fails for another reason - // (permissions) leaves the directory possibly present, so that case stays fail-closed. - let sys_root_absent = matches!(std::fs::metadata(sys_root), Err(e) if e.kind() == std::io::ErrorKind::NotFound); - if sys_root_absent && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { + // A sandbox with no cgroup filesystem mounted and no `/sys/fs/cgroup` at all (Flatpak) or + // only an empty mount-point directory left by `sysfs` shows the process its membership path + // but no interface files, so no limit is observable. Failing closed there reported 0 bytes + // free and refused every PSD on a machine with tens of GB. Only a present non-empty or + // unreadable directory takes the guarded path below: a stat or read_dir that fails for + // another reason (permissions, non-directory) leaves a mounted hierarchy possibly present, + // so that case stays fail-closed. + if sys_root_absent_or_empty(sys_root) && mountinfo.as_deref().is_some_and(lists_mounts_without_cgroup) { return CgroupLimits::NotConstrained; } @@ -273,16 +273,34 @@ pub(super) mod linux { MembershipParse::Parsed(membership) } + /// Whether `/sys/fs/cgroup` is absent (`ErrorKind::NotFound`) or a readable empty directory. + /// + /// Permission errors, non-directory paths, and unreadable directories return `false` and stay + /// fail-closed. + pub(super) fn sys_root_absent_or_empty(sys_root: &Path) -> bool { + match std::fs::metadata(sys_root) { + Err(e) => e.kind() == std::io::ErrorKind::NotFound, + Ok(meta) => meta.is_dir() && std::fs::read_dir(sys_root).is_ok_and(|mut entries| entries.next().is_none()), + } + } + /// Parses `/proc/self/mountinfo` into the mount fields used to locate a cgroup hierarchy. /// /// Malformed lines are skipped; callers fail closed when no matching mount is found. - fn parse_mountinfo(text: &str) -> Vec { + pub(super) fn parse_mountinfo(text: &str) -> Vec { let mut mounts = Vec::new(); for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); let Some(separator) = fields.iter().position(|f| *f == "-") else { continue }; + let super_options = fields.get(separator + 3).copied().or_else(|| { + // `show_mountinfo` writes ` `; an empty source + // (e.g. a bubblewrap tmpfs mount) leaves two spaces between `fstype` and options. + let after = line.split_once(" - ")?.1.trim_start(); + let fstype = fields.get(separator + 1).copied()?; + after.strip_prefix(fstype)?.starts_with(" ").then(|| fields.get(separator + 2).copied()).flatten() + }); let (Some(root), Some(point), Some(fstype), Some(super_options)) = - (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), fields.get(separator + 3).copied()) + (fields.get(3).copied(), fields.get(4).copied(), fields.get(separator + 1).copied(), super_options) else { continue; }; @@ -966,6 +984,23 @@ mod tests { assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // Isolated case 1: a readable empty `/sys/fs/cgroup` mount-point directory with normal + // non-cgroup `mountinfo` also reports `NotConstrained`. + let (proc, sys) = fixture("empty-cgroup-mountpoint"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // Isolated case 2: absent `/sys/fs/cgroup` with a bubblewrap empty-source non-cgroup mount + // (`- tmpfs rw,...`) parses cleanly and reports `NotConstrained`. + let (proc, _) = fixture("absent-cgroup-empty-source"); + let sys = proc.parent().unwrap().join("absent-sys"); + write(&proc.join("self/cgroup"), "0::/app.slice/app-flatpak.scope\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::NotConstrained); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + // A truncated mount line may be the cgroup mount: with /sys/fs/cgroup absent, fail closed. let (proc, _) = fixture("truncated-mountinfo-line"); let sys = proc.parent().unwrap().join("absent-sys"); @@ -1269,4 +1304,91 @@ mod tests { assert_eq!(linux::available_at(&proc, &sys), Some((4 << 30) + (512 << 20)), "legacy helper keeps RAM + swap"); std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); } + + #[cfg(target_os = "linux")] + #[test] + fn linux_parse_mountinfo_handles_empty_mount_source() { + let tmpfs = "26 20 0:24 / /tmp rw,nosuid,nodev - tmpfs rw,nosuid,nodev,size=65536k\n"; + let cg2 = "30 20 0:26 /user.slice /sys/fs/cg\\0402 rw,relatime - cgroup2 rw,nsdelegate\n"; + let truncated = "31 20 0:27 / /sys/fs/cgroup rw - cgroup2 rw\n"; + let mounts = linux::parse_mountinfo(&format!("{tmpfs}{cg2}{truncated}")); + assert_eq!(mounts.len(), 2, "single-space line missing super_options is skipped"); + let m0 = &mounts[0]; + assert_eq!((&m0.root[..], &m0.mount_point[..], &m0.fstype[..]), ("/", "/tmp", "tmpfs")); + assert_eq!((&m0.options[..], &m0.super_options[..]), ("rw,nosuid,nodev", "rw,nosuid,nodev,size=65536k")); + let m1 = &mounts[1]; + assert_eq!((&m1.root[..], &m1.mount_point[..], &m1.fstype[..]), ("/user.slice", "/sys/fs/cg 2", "cgroup2")); + assert_eq!((&m1.options[..], &m1.super_options[..]), ("rw,relatime", "rw,nsdelegate")); + } + + /// An empty `/sys/fs/cgroup` directory only reports `NotConstrained` when `mountinfo` parses + /// cleanly with no cgroup mount; cgroup mounts (including empty-source lines), missing/empty/ + /// truncated `mountinfo`, non-empty directories, files, and unreadable directories fail closed. + #[cfg(target_os = "linux")] + #[test] + fn linux_empty_or_invalid_sys_root_fails_closed_unless_proven_unmounted() { + use std::os::unix::fs::PermissionsExt; + + let bad_mountinfo: [(&str, Option<&str>); 6] = [ + ("empty-sys-missing-mountinfo", None), + ("empty-sys-empty-mountinfo", Some("")), + ("empty-sys-garbage-mountinfo", Some("not a mountinfo line\n")), + ("empty-sys-truncated-mountinfo", Some("25 20 0:23 / /proc rw - proc proc rw\n30 20 0:26 / /sys/fs/cgroup rw - cgroup2\n")), + ("empty-sys-cgroup2-mount", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 cgroup2 rw\n")), + ("empty-sys-empty-source-cgroup2", Some("30 20 0:26 / /sys/fs/cgroup rw - cgroup2 rw\n")), + ]; + for (name, mountinfo) in bad_mountinfo { + let (proc, sys) = fixture(name); + write(&proc.join("self/cgroup"), "0::/app\n"); + if let Some(text) = mountinfo { + write(&proc.join("self/mountinfo"), text); + } + assert!(linux::sys_root_absent_or_empty(&sys), "{name}"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable, "{name}"); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + } + + // Empty `/sys/fs/cgroup` with a v1 memory mount in `mountinfo` also fails closed. + let (proc, sys) = fixture("empty-sys-cgroup-v1-mount"); + write(&proc.join("self/cgroup"), "4:memory:/app\n"); + write(&proc.join("self/mountinfo"), "31 24 0:26 / /sys/fs/cgroup/memory rw - cgroup cgroup rw,memory\n"); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // A non-empty `/sys/fs/cgroup` directory is not treated as unmounted even with non-cgroup mountinfo. + let (proc, sys) = fixture("non-empty-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + write(&sys.join("memory.max"), "1073741824\n"); + assert!(!linux::sys_root_absent_or_empty(&sys)); + assert_eq!(linux::cgroup_limits(&proc, &sys), linux::CgroupLimits::Unreadable); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // `sys_root` as a regular file and a `NotADirectory` path component return false and fail closed. + let (proc, _) = fixture("file-sys-root"); + let file_sys = proc.parent().unwrap().join("sys-as-file"); + write(&file_sys, ""); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + for path in [&file_sys, &file_sys.join("cgroup")] { + assert!(!linux::sys_root_absent_or_empty(path)); + assert_eq!(linux::cgroup_limits(&proc, path), linux::CgroupLimits::Unreadable); + } + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + + // An unreadable `/sys/fs/cgroup` directory (`read_dir` error) returns false and fails closed. + let (proc, sys) = fixture("unreadable-sys-root"); + write(&proc.join("self/cgroup"), "0::/app\n"); + write(&proc.join("self/mountinfo"), "25 20 0:23 / /proc rw - proc proc rw\n"); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o000)).unwrap(); + let read_blocked = std::fs::read_dir(&sys).is_err(); + let absent = linux::sys_root_absent_or_empty(&sys); + let limits = linux::cgroup_limits(&proc, &sys); + std::fs::set_permissions(&sys, std::fs::Permissions::from_mode(0o700)).unwrap(); + std::fs::remove_dir_all(proc.parent().unwrap()).unwrap(); + if read_blocked { + assert!(!absent); + assert_eq!(limits, linux::CgroupLimits::Unreadable); + } + } } diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index a78e2d3ea7d..ccc49156fd4 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -90,7 +90,10 @@ impl PhotocraftApp { return Ok(Vec::new()); } let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let opts = photocraft_io::ImportOptions { + keep_raw: self.session.prefs().raw_defaults.open_in_camera_raw, + ..photocraft_engine::jobs::import_options(self.session.prefs()) + }; // A PSD and a magic-detected TIFF both go through the typed IO path: only it carries // `PsdApprovalRequired` (and, for a PSD, the structured damaged flag), so a layered // TIFF's high-memory decision can raise its prompt instead of becoming a terminal diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 7b4e54e92d3..988b08d3d51 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1871,6 +1871,22 @@ fn pencil_outline_cursor(painter: &egui::Painter, xf: &ViewXform, p: Pos2, size: egui::CursorIcon::None } +/// A pen tool's cursor at screen point `p` (document point `doc`): the crosshair for precise Other +/// Cursors (#4639), the black arrow for Add Anchor Point unless a click would split a segment +/// (#12729; ⌘ is Direct Selection's arrow, ⌥ keeps the pen), else the tool's own pen icon. +fn pen_tool_cursor(app: &PhotocraftApp, ui: &egui::Ui, tool: Tool, doc: [f64; 2], p: Pos2) -> egui::CursorIcon { + if precise_other_cursor(app) { + return egui::CursorIcon::Crosshair; + } + if tool == Tool::AddAnchorPoint { + let mods = crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers)); + if !mods.alt && (mods.command || !crate::anchor_tools::adds_anchor_at(app, tool, doc)) { + return crate::tool_cursor::arrow(ui.ctx(), p); + } + } + pen_cursor(ui.ctx(), tool, p) +} + fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: &CanvasOverlayInput<'_>, resizing: bool, p: Pos2) { let painter = input.painter; let xf = input.xf; @@ -2004,10 +2020,12 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & { crate::tool_cursor::continue_path(painter, p) } + // Add Anchor Point: the pen with "+" only over a segment a click would split, else the + // black arrow (#12729); ⌘ is Direct Selection's arrow. ⌥ and Precise stay as they were. // The pen tools: their own icon with its nib on the point, or the crosshair for - // precise Other Cursors (#4639). + // precise Other Cursors (#4639); Add Anchor Point the black arrow off a segment (#12729). Tool::Pen | Tool::FreeformPen | Tool::CurvaturePen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::ConvertPoint => { - if precise_other_cursor(app) { egui::CursorIcon::Crosshair } else { pen_cursor(ui.ctx(), tool, p) } + pen_tool_cursor(app, ui, tool, xf.to_doc(p), p) } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index d600445e757..bfad6a57b8b 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 00000000000..a1f722a626e --- /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 6a3c5075c52..debcd8aee48 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/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 1b82804e3da..c30bcf1694f 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -6,6 +6,10 @@ use super::strokes::{ use super::textures::shown_as_document; use super::{PhotocraftApp, Tool, json}; +#[cfg(test)] +#[path = "rectangle_click_in_shape_tests.rs"] +mod rectangle_click_in_shape_tests; + pub(crate) fn finish_gesture(app: &mut PhotocraftApp, d: Drag) { finish(app, d, None); } @@ -110,8 +114,10 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { // mode a click adds nothing: the dialog makes a shape layer, which Path mode never draws, // and the click's few pixels of travel would add a speck of a subpath to the work path. t if crate::vector_ui::is_shape_tool(t) - && crate::shape_dialog::is_click(d.start, &d.points, app.point_zoom()) - && (crate::vector_ui::draws_path(&app.ui.tool_options) || crate::shape_dialog::open(app, t, d.start).is_some()) => {} + && crate::shape_dialog::is_tool_click(t, &app.ui.tool_options, d.start, &d.points, app.point_zoom()) + && (crate::vector_ui::draws_path(&app.ui.tool_options) + || crate::shape_dialog::click_inside_active_rectangle(app, t, d.start) + || crate::shape_dialog::open(app, t, d.start).is_some()) => {} t if crate::vector_ui::is_shape_tool(t) => crate::vector_ui::finish_shape(app, t, d.start, [end[0], end[1]], d.live), Tool::PathSelection => crate::vector_ui::path_selection_finish(app, d.start, [end[0], end[1]]), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => crate::type_tool::pointer_up(app, d.start, [end[0], end[1]]), diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index b5cfab7f2ba..55f01a0c182 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/canvas/rectangle_click_in_shape_tests.rs b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs new file mode 100644 index 00000000000..ec3c180e7f9 --- /dev/null +++ b/crates/ui-egui/src/canvas/rectangle_click_in_shape_tests.rs @@ -0,0 +1,121 @@ +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; +use serde_json::json; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.ui.tool = Tool::Rectangle; + app.ui.extras.snap = false; + app.sync_views(); + app +} + +fn shape(app: &mut PhotocraftApp, kind: &str, radius: f64) { + let radii = [radius; 4]; + app.run("shape.create", json!({"kind": kind, "rect": [400, 300, 200, 100], "radii": radii, "fill": "#ff0000"})).unwrap(); +} + +fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, mods); +} + +fn state(app: &PhotocraftApp) -> (usize, usize) { + let active = app.session.active().unwrap(); + (active.doc.layer_count(), active.history.past_len()) +} + +fn assert_create_rectangle(app: &PhotocraftApp) { + let [dialog] = app.ui.dialogs.as_slice() else { panic!("expected one Create Rectangle dialog") }; + assert_eq!(dialog.fields["__label"], "Create Rectangle"); + assert_eq!(dialog.fields["width"], 100.0); + assert_eq!(dialog.fields["height"], 100.0); + assert_eq!(dialog.fields["fromCenter"], false); +} + +#[test] +fn inside_the_active_live_rectangle_is_a_no_op() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + for end in [center, [501.0, 350.0]] { + gesture(&mut app, center, end); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + } +} + +#[test] +fn outside_the_rectangle_and_on_the_pasteboard_open_create_rectangle() { + for point in [[100.0, 500.0], [-20.0, 500.0]] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn a_pixel_layer_or_non_rectangle_shape_leaves_the_dialog_available() { + let point = [500.0, 350.0]; + for other_shape in [false, true] { + let mut app = app(); + shape(&mut app, "rect", 0.0); + if other_shape { + shape(&mut app, "ellipse", 0.0); + } else { + app.run("layer.new.layer", json!({"name": "Pixels"})).unwrap(); + } + let before = state(&app); + gesture(&mut app, point, point); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); + } +} + +#[test] +fn rounded_corners_use_the_outline() { + let mut app = app(); + shape(&mut app, "roundedRect", 30.0); + let before = state(&app); + let center = [500.0, 350.0]; + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), before); + let corner = [401.0, 301.0]; + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, corner, vec![[corner[0], corner[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); +} + +#[test] +fn other_modes_keep_their_click_behavior() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let before = state(&app); + let center = [500.0, 350.0]; + app.ui.tool_options.shape_mode = "path".into(); + gesture(&mut app, center, center); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.active().unwrap().doc.work_path.is_none()); + app.ui.tool_options.shape_mode = "pixels".into(); + super::finish_gesture(&mut app, super::Drag::new(Tool::Rectangle, center, vec![[center[0], center[1], 1.0]], egui::Modifiers::NONE, false)); + assert_create_rectangle(&app); + assert_eq!(state(&app), before); +} + +#[test] +fn more_than_one_pixel_of_travel_still_draws_a_shape() { + let mut app = app(); + shape(&mut app, "rect", 0.0); + let (layers, history) = state(&app); + gesture(&mut app, [500.0, 350.0], [502.0, 351.0]); + assert!(app.ui.dialogs.is_empty()); + assert_eq!(state(&app), (layers + 1, history + 1)); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index c7244b0c188..78108273936 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -12,6 +12,7 @@ use egui::{CursorIcon, CustomCursorImage, Painter, Pos2, Stroke, Vec2, vec2}; use crate::canvas::ViewXform; use crate::state::Tool; +mod arrow; mod bucket; mod hand; mod pen; @@ -30,9 +31,11 @@ const MAX_SIDE: u16 = if cfg!(any(target_os = "windows", target_os = "macos")) { /// What a bitmap cursor shows. `Hand` is the Hand tool's open hand, or its fist while it drags; /// `Zoom` is the Zoom tool's magnifier, with a minus when it zooms out. `Outline` is a brush tip -/// outline: closed rings of logical-point offsets from the hotspot. +/// outline: closed rings of logical-point offsets from the hotspot. `Arrow` is the black arrow +/// pointer, its tip on the hotspot. #[derive(Clone, Debug, PartialEq)] enum Shape { + Arrow, Circle { radius: f32, centre: bool }, Crosshair { length: f32, gap: f32 }, Hand { closed: bool }, @@ -405,6 +408,20 @@ fn hand_with(ctx: &egui::Context, closed: bool, bitmap: bool) -> CursorIcon { if closed { CursorIcon::Grabbing } else { CursorIcon::Grab } } +/// The black arrow pointer, its tip on the pointer (`_at`): an OS cursor bitmap on every platform +/// that takes one, the system arrow where none can be set. +pub(crate) fn arrow(ctx: &egui::Context, _at: Pos2) -> CursorIcon { + arrow_with(ctx, native(ctx)) +} + +fn arrow_with(ctx: &egui::Context, bitmap: bool) -> CursorIcon { + if bitmap && let Some(image) = cached_image(ctx, &Shape::Arrow, native_scale(ctx)) { + ctx.set_cursor_image(Some(image)); + return CursorIcon::None; + } + CursorIcon::Default +} + /// The bitmap [`hand`] hands Windows, for tests that check the Hand's pointer on every platform. #[cfg(test)] pub(crate) fn hand_bitmap(ctx: &egui::Context, closed: bool) -> Option { @@ -589,7 +606,7 @@ fn paint(painter: &Painter, at: Pos2, shape: &Shape) -> bool { } } // Only ever a bitmap: without one the OS draws its own grab cursors. - Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} + Shape::Arrow | Shape::Hand { .. } | Shape::Zoom { .. } | Shape::Pipette => {} } } true @@ -638,6 +655,7 @@ fn extent(shape: &Shape) -> Option { } if *centre { e.max(3.0) } else { e } } + Shape::Arrow => arrow::REACH, Shape::Hand { .. } => hand::HALF, Shape::Zoom { .. } => zoom::HALF, // The 24-unit SVG extends at most 22 units from (2, 22). This extra unit plus @@ -691,6 +709,10 @@ fn coverage(shape: &Shape, dx: f32, dy: f32, scale: f32) -> (f32, f32) { let (lx, ly) = (dx / scale, dy / scale); silhouette(zoom::shape(lx, ly), zoom::glyph(*out, lx, ly), 0.75, scale) } + Shape::Arrow => { + let (lx, ly) = (dx / scale, dy / scale); + silhouette(arrow::shape(lx, ly), f32::MAX, 0.0, scale) + } Shape::Pipette => (0.0, 0.0), // SVG rasterization supplies these pixels. } } @@ -804,7 +826,7 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { let hotf = f32::from(hot); let mut put = |col: usize, row: usize, cov: (f32, f32)| { if let Some(px) = row.checked_mul(n).and_then(|i| i.checked_add(col)).and_then(|i| rgba.get_mut(i * 4..i * 4 + 4)) { - px.copy_from_slice(&stroke_pixel(cov, dark, light)); + px.copy_from_slice(&if matches!(shape, Shape::Arrow) { arrow::pixel(cov) } else { stroke_pixel(cov, dark, light) }); } }; if let Shape::Outline { rings, centre } = shape { @@ -856,7 +878,8 @@ fn rasterize(shape: &Shape, scale: f32) -> Option { } } } - Some(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) + let image = CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }; + if matches!(shape, Shape::Arrow) { arrow::crop(image) } else { Some(image) } } /// Use the toolbar's actual SVG, with its lower-left tip (2, 22) at the hotspot. @@ -898,3 +921,6 @@ mod tests; #[cfg(test)] mod count_tests; + +#[cfg(test)] +mod add_anchor_cursor_tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs new file mode 100644 index 00000000000..27b746d7c80 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/add_anchor_cursor_tests.rs @@ -0,0 +1,158 @@ +//! #12729: Add Anchor Point's cursor says what a click would do. Over a segment of the targeted path +//! it is the pen with "+"; over an anchor, a handle end, empty canvas, with no path targeted and +//! over a locked shape layer's segments it is the black arrow. ⌘ keeps Direct Selection's arrow, +//! ⌥ and the Precise "Other Cursors" crosshair stay as they were. The tests drive the real canvas +//! (`document_area`) and compare the OS cursor bitmap it hands the platform with the arrow's and +//! the pen's. + +use egui::{CursorIcon, Modifiers, Pos2, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use super::{PenVariant, Shape, rasterize}; +use crate::PhotocraftApp; +use crate::anchor_tools::delete_anchor_targeted_path_tests::{select_layer, select_saved_path, setup}; +use crate::state::Tool; + +/// Path 1 is the square (50,450)-(150,550); the shape layer is the rectangle (450,100)-(650,250). +const SQUARE_TOP: [f32; 2] = [100.0, 450.0]; +const SQUARE_CORNER: [f32; 2] = [50.0, 450.0]; +const SQUARE_MIDDLE: [f32; 2] = [100.0, 500.0]; +const SHAPE_TOP: [f32; 2] = [550.0, 100.0]; + +/// The canvas at 100 % over `app`, the view centred on `view` (a document point). +fn harness(app: PhotocraftApp, view: [f32; 2]) -> Harness<'static, PhotocraftApp> { + let mut app = app; + app.sync_views(); + app.ui.extras.rulers = false; + let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = view; + v.fit_pending = false; + h.run_steps(2); + h +} + +/// Hover the document point `at` with `mods` held. +fn hover(h: &mut Harness<'static, PhotocraftApp>, at: [f32; 2], view: [f32; 2], mods: Modifiers) { + h.event(egui::Event::ModifiersChanged(mods)); + let p: Pos2 = h.state().last_canvas_rect.center() + vec2(at[0] - view[0], at[1] - view[1]); + h.hover_at(p); + h.run_steps(3); +} + +#[derive(Debug, PartialEq)] +enum Shown { + Arrow, + Pen, + Crosshair, + Other, +} + +/// Which cursor the last frame asked the platform for. +fn shown(h: &Harness<'static, PhotocraftApp>) -> Shown { + let out = &h.output().platform_output; + let scale = super::native_scale(&h.ctx); + let same = + |a: &egui::CustomCursorImage, b: Option| b.is_some_and(|b| a.size == b.size && a.hotspot == b.hotspot && a.rgba == b.rgba); + match &out.cursor_image { + Some(i) if same(i, rasterize(&Shape::Arrow, scale)) => Shown::Arrow, + Some(i) if same(i, PenVariant::from_tool(Tool::AddAnchorPoint).and_then(|v| super::pen::rasterize(v, scale))) => Shown::Pen, + Some(i) if same(i, rasterize(&super::STANDARD_CROSSHAIR, scale)) => Shown::Crosshair, + _ => Shown::Other, + } +} + +/// The square's Path 1 targeted, the pointer at `at` on it. +fn on_path_one(at: [f32; 2], mods: Modifiers) -> Shown { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, mods); + shown(&h) +} + +#[test] +fn over_a_segment_of_the_targeted_path_it_is_the_pen_with_plus() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::NONE), Shown::Pen); +} + +#[test] +fn over_an_anchor_a_handle_end_or_empty_canvas_it_is_the_black_arrow() { + assert_eq!(on_path_one(SQUARE_CORNER, Modifiers::NONE), Shown::Arrow); + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::NONE), Shown::Arrow); + // A handle end: a curved top edge's out-handle ends in empty canvas, off every segment. + let (mut app, _) = setup(Tool::AddAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [{"anchor": [50, 450], "in": [50, 450], "out": [50, 400]}, [150, 450], [150, 550], [50, 550]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, [50.0, 400.0], SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_no_path_targeted_it_is_the_black_arrow_everywhere() { + // The active layer is the pixel layer "Red": no path is targeted, whatever lies under the pointer. + for at in [SHAPE_TOP, [450.0, 100.0], [550.0, 175.0], [300.0, 150.0]] { + let (app, _) = setup(Tool::AddAnchorPoint); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, at, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow, "{at:?}"); + } +} + +#[test] +fn over_a_segment_of_a_locked_shape_layers_mask_it_is_the_black_arrow() { + let (mut app, shape) = setup(Tool::AddAnchorPoint); + select_layer(&mut app, shape); + let mut h = harness(app, SHAPE_TOP); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Pen, "unlocked, the same point is a segment"); + h.state_mut().run("layer.lockLayers", json!({"position": true})).unwrap(); + hover(&mut h, SHAPE_TOP, SHAPE_TOP, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Arrow); +} + +#[test] +fn with_ctrl_held_it_is_the_black_arrow_even_over_a_segment() { + assert_eq!(on_path_one(SQUARE_TOP, Modifiers::COMMAND), Shown::Arrow); +} + +#[test] +fn with_alt_held_it_stays_the_pen_over_empty_canvas() { + assert_eq!(on_path_one(SQUARE_MIDDLE, Modifiers::ALT), Shown::Pen); +} + +#[test] +fn the_precise_other_cursors_crosshair_keeps_working() { + for at in [SQUARE_TOP, SQUARE_MIDDLE] { + let (mut app, _) = setup(Tool::AddAnchorPoint); + select_saved_path(&mut app); + app.run("prefs.set", json!({"path": "cursors.other", "value": "precise"})).unwrap(); + let mut h = harness(app, SQUARE_MIDDLE); + hover(&mut h, at, SQUARE_MIDDLE, Modifiers::NONE); + assert_eq!(shown(&h), Shown::Crosshair, "{at:?}"); + } +} + +#[test] +fn the_arrow_bitmap_is_not_empty_and_its_hotspot_is_the_tip_at_1_1() { + let image = rasterize(&Shape::Arrow, 1.0).unwrap(); + assert_eq!(image.hotspot, [1, 1]); + let alpha = |x: usize, y: usize| image.rgba[(y * usize::from(image.size[0]) + x) * 4 + 3]; + assert!(image.rgba.chunks(4).any(|p| p[3] == 255 && p[0] == 0), "a solid black body"); + assert!(image.rgba.chunks(4).any(|p| p[3] > 0 && p[0] == 255), "a white edge"); + assert!(alpha(1, 1) > 0, "the tip pixel is covered"); + assert_eq!(super::arrow_with(&egui::Context::default(), false), CursorIcon::Default); +} diff --git a/crates/ui-egui/src/canvas/tool_cursor/arrow.rs b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs new file mode 100644 index 00000000000..b99cd208869 --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/arrow.rs @@ -0,0 +1,60 @@ +//! The black arrow pointer: a filled black arrow with a white edge, PhotoCraft's own drawing from +//! one polygon (tip at the top left, body down to the right, a short tail), as a signed distance +//! field (negative inside) in logical pixels from the tip with y pointing down. The hotspot is the +//! tip; the bitmap is cropped to the arrow so the tip sits one pixel in from its top left corner, +//! at (1, 1) at 100 %. Windows' stock arrow is white, so every platform gets this bitmap. + +use std::sync::Arc; + +use egui::CustomCursorImage; + +use super::hand::capsule; + +/// How far the polygon reaches from the tip, outline excluded. +pub(super) const REACH: f32 = 20.0; + +/// The arrow's corners, clockwise from the tip. +const OUTLINE: [[f32; 2]; 7] = [[0.0, 0.0], [11.5, 11.8], [6.7, 11.8], [9.2, 17.4], [6.6, 18.6], [4.0, 12.8], [0.0, 16.5]]; + +/// The arrow's silhouette: negative inside it. +pub(super) fn shape(x: f32, y: f32) -> f32 { + let mut distance = f32::MAX; + let mut inside = false; + for (&a, &b) in OUTLINE.iter().zip(OUTLINE.iter().cycle().skip(1)) { + distance = distance.min(capsule(x, y, a, b, 0.0)); + // Even-odd rule: a ray towards +x crossing this edge flips the answer. + if (a[1] > y) != (b[1] > y) && x < a[0] + (y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) { + inside = !inside; + } + } + if inside { -distance } else { distance } +} + +/// One bitmap pixel in straight RGBA: black `fill` over a white edge, `outline` being the coverage +/// of the whole arrow (edge included), each 0 to 1. No coverage is `[0; 4]`. +pub(super) fn pixel((fill, outline): (f32, f32)) -> [u8; 4] { + let edge = outline * (1.0 - fill); + let alpha = fill + edge; + let white = if alpha > 0.0 { (255.0 * edge / alpha).round() as u8 } else { 0 }; + [white, white, white, (255.0 * alpha).round() as u8] +} + +/// Crop `image` (the arrow centred on its hotspot) to the pixels it covers, the hotspot moving +/// with them. `None` when nothing is covered. +pub(super) fn crop(image: CustomCursorImage) -> Option { + let [w, h] = image.size.map(usize::from); + let covered = |col: usize, row: usize| image.rgba.get((row * w + col) * 4 + 3).is_some_and(|&a| a > 0); + let cols: Vec = (0..w).filter(|&c| (0..h).any(|r| covered(c, r))).collect(); + let rows: Vec = (0..h).filter(|&r| (0..w).any(|c| covered(c, r))).collect(); + let (&c0, &c1) = (cols.first()?, cols.last()?); + let (&r0, &r1) = (rows.first()?, rows.last()?); + let mut rgba = Vec::with_capacity((c1 - c0 + 1) * (r1 - r0 + 1) * 4); + for row in r0..=r1 { + rgba.extend_from_slice(image.rgba.get((row * w + c0) * 4..(row * w + c1 + 1) * 4)?); + } + Some(CustomCursorImage { + rgba: Arc::from(rgba), + size: [u16::try_from(c1 - c0 + 1).ok()?, u16::try_from(r1 - r0 + 1).ok()?], + hotspot: [image.hotspot[0].checked_sub(u16::try_from(c0).ok()?)?, image.hotspot[1].checked_sub(u16::try_from(r0).ok()?)?], + }) +} diff --git a/crates/ui-egui/src/canvas/tool_feedback.rs b/crates/ui-egui/src/canvas/tool_feedback.rs index ba7bf35cf6a..d25f587c0da 100644 --- a/crates/ui-egui/src/canvas/tool_feedback.rs +++ b/crates/ui-egui/src/canvas/tool_feedback.rs @@ -101,7 +101,14 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option (PhotocraftApp, RawOpen, Control) { bytes: Some(bytes), developed_with: Default::default(), demosaic: Default::default(), + decoded: None, crop: None, }; let mut app = PhotocraftApp::new(session, crate::Services::default()); @@ -149,7 +150,7 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() let (mut app, raw, control) = identity_app(); app.session.set_active(0); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the explicitly named RAW was queued"); assert_eq!(queued.document, raw.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&raw.name, &raw.path, &raw.bytes)); @@ -160,12 +161,12 @@ fn queue_identity_targets_an_inactive_raw_without_changing_the_active_document() #[test] fn queue_identity_rejects_a_missing_document_without_replacing_the_pending_review() { let (mut app, raw, control) = identity_app(); - queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_deref().map(Vec::as_slice), &[]).unwrap(); + queue_open_dialog(&mut app, raw.document, &raw.name, raw.path.as_deref(), raw.bytes.as_ref(), &[]).unwrap(); let pending = app.raw_shelf.first().map(|h| &h.raw).unwrap().clone(); app.session.set_active(0); let missing = photocraft_doc::DocId::fresh(); assert!(!app.session.documents().iter().any(|state| state.doc.id == missing)); - assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&[1, 2, 3]), &[]).is_err()); + assert!(queue_open_dialog(&mut app, missing, "missing.dng", Some("missing.dng"), Some(&std::sync::Arc::new(vec![1, 2, 3])), &[]).is_err()); let queued = app.raw_shelf.first().map(|h| &h.raw).expect("the existing review is preserved"); assert_eq!(queued.document, pending.document); assert_eq!((&queued.name, &queued.path, &queued.bytes), (&pending.name, &pending.path, &pending.bytes)); diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs index 2c04d0e268c..5b6721d069f 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/open.rs @@ -30,6 +30,9 @@ pub struct RawOpen { pub developed_with: photocraft_io::raw::Demosaic, /// The method chosen in the dialog: Open re-develops when it differs from `developed_with`. pub demosaic: photocraft_io::raw::Demosaic, + /// The file decoded once for the dialog's preview and for Open's re-develop (the sensor data + /// is 2 bytes per pixel): freed with the last copy of this, when the dialog closes. + pub decoded: Option>, /// The crop of the file's sidecar (in the raw's stored orientation): Open re-develops and /// crops to it. The settings have no crop, so the dialog previews the whole frame. pub crop: Option, @@ -56,7 +59,7 @@ pub fn queue_open_dialog( document: photocraft_doc::DocId, name: &str, path: Option<&str>, - bytes: Option<&[u8]>, + bytes: Option<&std::sync::Arc>>, warnings: &[String], ) -> Result<(), String> { if document_index(app, document).is_none() { @@ -72,9 +75,10 @@ pub fn queue_open_dialog( document, name: name.to_string(), path: path.map(str::to_string), - bytes: bytes.map(|b| std::sync::Arc::new(b.to_vec())), + bytes: bytes.cloned(), developed_with: method, demosaic: method, + decoded: None, // Read now: a filmstrip raw that is never shown still opens with its sidecar's crop. crop: path.and_then(read_sidecar).and_then(|(_, report, _)| report.crop), }; @@ -134,14 +138,23 @@ pub(super) fn open_raw_with(app: &mut PhotocraftApp, ctx: &egui::Context, mut ra Ok(()) } -/// Gives the open dialog its raw: the file name, and the camera tone curve it was developed with. -fn attach_raw(app: &mut PhotocraftApp, raw: RawOpen) { - let curve = match (&raw.bytes, &raw.path) { - (Some(b), _) => Some(photocraft_io::raw::tone_curve(b)), +/// Gives the open dialog its raw: the file name, the camera tone curve it was developed with, and +/// the decode (the open's kept one, else one made now) the preview and Open's re-develop share. +fn attach_raw(app: &mut PhotocraftApp, mut raw: RawOpen) { + let file = match (&raw.bytes, &raw.path) { + _ if raw.decoded.is_some() => None, + (Some(b), _) => Some(std::borrow::Cow::Borrowed(b.as_slice())), #[cfg(not(target_arch = "wasm32"))] - (None, Some(p)) => std::fs::read(p).ok().map(|b| photocraft_io::raw::tone_curve(&b)), + (None, Some(p)) => std::fs::read(p).ok().map(std::borrow::Cow::Owned), _ => None, }; + let curve = match file { + Some(b) => { + raw.decoded = photocraft_io::raw::take_kept_decode(&b).or_else(|| photocraft_io::raw::RawDecode::new(&b).ok().map(std::sync::Arc::new)); + Some(raw.decoded.as_ref().map(|d| d.tone_curve().to_vec()).unwrap_or_default()) + } + None => raw.decoded.as_ref().map(|d| d.tone_curve().to_vec()), + }; if let Some(d) = app.camera_raw.as_mut() { d.layer_name = raw.name.clone(); // The full-size preview retones the whole frame with it, as Open will. @@ -232,7 +245,7 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: return finish_open_raw(app, index, params.clone(), None, raw, &defaults); }; app.session.set_active(index); - let (name, doc_id) = (raw.name.clone(), raw.document); + let (name, doc_id, decoded) = (raw.name.clone(), raw.document, raw.decoded.clone()); let work = move |ctx: &photocraft_engine::jobs::JobCtx| -> photocraft_engine::Result<(photocraft_io::ImportResult, bool)> { ctx.progress(0.0, "Reading"); let bytes = match source { @@ -246,7 +259,11 @@ pub(super) fn commit_open_raw(app: &mut PhotocraftApp, params: &CameraRaw, raw: }; ctx.check()?; ctx.progress(0.05, "Developing"); - photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) + match &decoded { + Some(d) => photocraft_io::raw::import_raw_tuned_from(&name, &bytes, &tuning, d), + None => photocraft_io::raw::import_raw_tuned(&name, &bytes, &tuning), + } + .map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) }; let apply = move |s: &mut photocraft_engine::Session, (r, wb): (photocraft_io::ImportResult, bool)| replace_raw_document(s, doc_id, r, wb); let label = crate::i18n::fmt(tl!("Developing {name}"), &[("name", &raw.name)]); @@ -396,8 +413,16 @@ pub fn opened_without_dialog(app: &mut PhotocraftApp, index: usize, name: &str, } let Some(document) = app.session.documents().get(index).map(|st| st.doc.id) else { return }; let method = photocraft_io::raw::developed_demosaic(warnings).unwrap_or_else(|| app.session.prefs().raw_defaults.demosaic.method()); - let mut raw = - RawOpen { document, name: name.to_string(), path: path.map(str::to_string), bytes: None, developed_with: method, demosaic: method, crop: None }; + let mut raw = RawOpen { + document, + name: name.to_string(), + path: path.map(str::to_string), + bytes: None, + decoded: None, + developed_with: method, + demosaic: method, + crop: None, + }; let mut params = CameraRaw::default(); let sidecar = path.and_then(read_sidecar).map(|(loaded, report, _)| { raw.crop = report.crop; diff --git a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs index 07125c55068..eb8d75e860d 100644 --- a/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/camera_raw_ui/tests.rs @@ -428,9 +428,26 @@ fn dialog_drives_the_engine() { assert!(menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": {"set": {"exposure": "x"}}})).unwrap().is_err()); } +std::thread_local! { + /// Held by a test's thread from its first `raw_app` to the test's end. + static RAW_OPEN_TURN: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// An app whose importer is the real one, opening a synthetic DNG. +/// +/// Raw opens keep their decode in one process-wide list of two (`photocraft_io::raw`), so tests +/// that open raws take turns: a parallel test's open would otherwise evict the decode another +/// test is about to take. The turn is held until the test's thread ends (nextest runs each test +/// in its own process, where this costs nothing). fn raw_app() -> (PhotocraftApp, Vec) { use photocraft_raw::testgen::{DngSpec, mosaic, scene}; + static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(()); + RAW_OPEN_TURN.with(|held| { + let mut held = held.borrow_mut(); + if held.is_none() { + *held = Some(TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + } + }); let services = crate::Services { import: Some(Box::new(|name: &str, b: &[u8], opts: &photocraft_io::ImportOptions| { photocraft_io::import_with_options(name, b, opts).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()) @@ -486,6 +503,41 @@ fn pixels(app: &PhotocraftApp) -> Vec { (0..32).flat_map(|y| (0..48).map(move |x| (x, y))).flat_map(|(x, y)| s.rgba(x, y)).collect() } +/// #9432: a raw open decodes the file once. The dialog's preview curve and Open's re-develop +/// reuse the open's sensor data and look, give the pixels of decoding again, and let go of +/// the sensor data when the dialog closes. +#[test] +fn a_raw_open_decodes_the_file_once_and_frees_it_with_the_dialog() { + use photocraft_io::raw::decodes_on_this_thread; + let ctx = egui::Context::default(); + let develop = |reuse: bool, commit: bool| { + let (mut app, mut dng) = raw_app(); + // Kept decodes are found by file contents: other tests open the same synthetic DNG. + dng.extend_from_slice(b"a_raw_open_decodes_the_file_once"); + let before = decodes_on_this_thread(); + app.open_bytes("IMG_0007.dng", &dng).unwrap(); + let raw = take_queued(&mut app).unwrap(); + open_raw(&mut app, &ctx, raw).unwrap(); + let raw_open = app.camera_raw.as_mut().unwrap().raw_open.as_mut().unwrap(); + let sensor = raw_open.decoded.as_ref().map(std::sync::Arc::downgrade).expect("the dialog holds the open's decode"); + if !reuse { + raw_open.decoded = None; + } + assert!(sensor.upgrade().is_some() || !reuse); + let ui = if commit { json!({"set": {"exposure": 1.0, "temperature": 30}, "commit": true}) } else { json!({"cancel": true}) }; + menu(&mut app, &ctx, "filter.cameraRaw", &json!({"ui": ui})).unwrap().unwrap(); + assert!(app.camera_raw.is_none()); + assert!(sensor.upgrade().is_none(), "the sensor data is freed when the dialog is closed"); + (decodes_on_this_thread() - before, if commit { pixels(&app) } else { Vec::new() }) + }; + let (decodes, reused) = develop(true, true); + assert_eq!(decodes, 1, "open, dialog and commit share one decode"); + let (decodes, again) = develop(false, true); + assert_eq!(decodes, 2, "without the kept decode the commit decodes again"); + assert_eq!(reused, again, "the same pixels either way"); + assert_eq!(develop(true, false).0, 1, "Cancel decodes nothing more"); +} + #[test] fn the_demosaic_method_is_chosen_at_open() { let (mut app, dng) = raw_app(); @@ -526,7 +578,7 @@ fn the_demosaic_method_is_chosen_at_open() { take_queued(&mut app); app.run("prefs.set", json!({"path": "rawDefaults.demosaic", "value": "ahd"})).unwrap(); let document = app.session.active().unwrap().doc.id; - queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&dng), &warnings).unwrap(); + queue_open_dialog(&mut app, document, "IMG_0004.dng", None, Some(&std::sync::Arc::new(dng.clone())), &warnings).unwrap(); let raw = take_queued(&mut app).unwrap(); use photocraft_io::raw::Demosaic; assert_eq!((raw.developed_with, raw.demosaic), (Demosaic::Bilinear, Demosaic::Bilinear)); @@ -804,7 +856,7 @@ fn auto_tone_of_a_never_shown_raw_matches_the_dialogs() { } } let method = photocraft_io::raw::Demosaic::Ahd; - let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, developed_with: method, demosaic: method, crop: None }; + let raw = RawOpen { document, name: "pattern.dng".into(), path: None, bytes: None, decoded: None, developed_with: method, demosaic: method, crop: None }; let (unshown, _) = filmstrip::first_settings(&app, &raw); open_raw(&mut app, &ctx, raw).unwrap(); let shown = &app.camera_raw.as_ref().unwrap().params; @@ -845,6 +897,7 @@ fn cancel_closes_the_raw_and_the_preference_skips_the_dialog() { bytes: None, developed_with: Default::default(), demosaic: Default::default(), + decoded: None, crop: None } ) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index a34eae8ecda..98f7b614fe0 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -359,7 +359,7 @@ fn open(app: &mut PhotocraftApp, held: Held, action: Option<&str>) -> Result index, }; app.session.set_active(index); - crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_deref().map(Vec::as_slice))?; + crate::jobs_ui::after_open(app, document, &name, path.as_deref(), &warnings, bytes.as_ref())?; Ok(json!({"document": index, "action": action})) } diff --git a/crates/ui-egui/src/dialogs/shape_dialog.rs b/crates/ui-egui/src/dialogs/shape_dialog.rs index fc9a3e9ea67..066e5e41472 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog.rs @@ -47,10 +47,41 @@ fn valid(key: &str, v: &Value) -> bool { /// True for a press and release that never left `start` by more than a few screen pixels. pub fn is_click(start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { - let slop = 3.0 / f64::from(zoom.max(0.01)); + within_click_slop(start, points, zoom, 3.0) +} + +pub(crate) fn is_tool_click(tool: Tool, options: &crate::state::ToolOptions, start: [f64; 2], points: &[[f64; 3]], zoom: f32) -> bool { + if tool == Tool::Rectangle && options.shape_mode == "shape" { within_click_slop(start, points, zoom, 1.0) } else { is_click(start, points, zoom) } +} + +fn within_click_slop(start: [f64; 2], points: &[[f64; 3]], zoom: f32, pixels: f64) -> bool { + let slop = pixels / f64::from(zoom.max(0.01)); points.iter().all(|p| (p[0] - start[0]).hypot(p[1] - start[1]) <= slop) } +/// A Shape-mode Rectangle click inside the active live rectangle leaves the shape alone (#13340). +pub(crate) fn click_inside_active_rectangle(app: &PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { + use photocraft_doc::{LayerContent, LiveShape}; + + if tool != Tool::Rectangle || app.ui.tool_options.shape_mode != "shape" { + return false; + } + let Some(layer) = app.session.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))) else { return false }; + let LayerContent::Shape(shape) = &layer.content else { return false }; + let Some(LiveShape::Rect { rect: [x, y, w, h], radii }) = shape.live else { return false }; + let (left, top) = (x.min(x + w), y.min(y + h)); + let (right, bottom) = (x.max(x + w), y.max(y + h)); + let [px, py] = at; + if !((left..=right).contains(&px) && (top..=bottom).contains(&py)) { + return false; + } + let (l, r, t, b) = (px - left, right - px, py - top, bottom - py); + [(l, t), (r, t), (r, b), (l, b)] + .into_iter() + .zip(photocraft_vector::shapes::clamp_radii(w.abs(), h.abs(), radii)) + .all(|((dx, dy), radius)| dx >= radius || dy >= radius || (radius - dx).hypot(radius - dy) <= radius) +} + /// Open the creation dialog of `tool` for a click at `at` (document px). `None` for a tool without /// one (Line, Custom Shape). pub fn open(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> Option { @@ -124,7 +155,7 @@ pub fn geometry(f: &Map) -> Result { if radii.iter().any(|r| *r > 0.0) { json!({"kind": "roundedRect", "rect": rect, "radii": radii}) } else { json!({"kind": "rect", "rect": rect}) } } "ellipse" => json!({"kind": "ellipse", "rect": rect}), - "triangle" => json!({"kind": "polygon", "rect": rect, "sides": 3}), + "triangle" => json!({"kind": "triangle", "rect": rect}), "polygon" => { let sides = num(f, "sides").map_or(5.0, |s| s.round().clamp(3.0, 100.0)); let ratio = num(f, "starRatio").map_or(100.0, |r| r.clamp(1.0, 100.0)); diff --git a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs index 1ca5de28f72..03f65d743d1 100644 --- a/crates/ui-egui/src/dialogs/shape_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/shape_dialog/tests.rs @@ -174,7 +174,7 @@ fn a_click_with_jitter_opens_the_dialog_on_hidpi() { let i = app.session.active_index().unwrap(); app.ui.views[i].zoom = 1.0; let before = layers(&app); - press(&mut app, Tool::Rectangle, [20.0, 30.0], [24.0, 30.0]); + press(&mut app, Tool::Rectangle, [20.0, 30.0], [22.0, 30.0]); only_dialog(&app); assert_eq!(layers(&app), before, "a jittery click draws nothing"); } @@ -347,7 +347,7 @@ fn right_click_picks_the_unit_of_that_field_only_and_it_is_not_remembered() { set(&mut app, id, json!({"widthUnit": "mm", "width": 50})); crate::dialogs::confirm(&mut app, id).unwrap(); app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "cm"})).unwrap(); - press(&mut app, Tool::Rectangle, [40.0, 40.0], [40.0, 40.0]); + press(&mut app, Tool::Rectangle, [140.0, 140.0], [140.0, 140.0]); let id = only_dialog(&app); let mut f = app.ui.dialog_mut(id).unwrap().fields.clone(); assert_eq!((f.get("widthUnit"), f["width"].as_f64()), (None, Some(50.0)), "the size is remembered, the unit isn't"); diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 2cd4d5d2b48..e8f25a1e724 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -82,18 +82,13 @@ impl ThumbnailCache { /// Check if two path strings match, tolerating slash direction and Windows case differences. fn paths_match(a: &str, b: &str) -> bool { - if a == b { - return true; - } #[cfg(windows)] { - let a_norm = a.replace('\\', "/"); - let b_norm = b.replace('\\', "/"); - a_norm.eq_ignore_ascii_case(&b_norm) + a == b || a.replace('\\', "/").eq_ignore_ascii_case(&b.replace('\\', "/")) } #[cfg(not(windows))] { - false + a == b } } diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 7459f54be6a..b0c4a6569c1 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -766,7 +766,7 @@ pub(crate) fn after_open( name: &str, path: Option<&str>, warnings: &[String], - bytes: Option<&[u8]>, + bytes: Option<&Arc>>, ) -> Result<(), String> { let index = app.session.documents().iter().position(|st| st.doc.id == document).ok_or("the opened document is missing")?; app.session.set_active(index); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5fbd4f43781..b46f0503b83 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 3da894ccf73..dfe898d2981 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 a7a5a209333..277eac21070 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/retouch_mode_refusal_alert_tests.rs b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs new file mode 100644 index 00000000000..eba8c7bce4b --- /dev/null +++ b/crates/ui-egui/src/retouch_mode_refusal_alert_tests.rs @@ -0,0 +1,41 @@ +//! #12673, #13033, #12656, #12967: a press with the Burn, Sponge, Blur or Smudge tool in an Indexed +//! Color or Bitmap document opens the reference application's colour-mode alert with OK, once, and +//! paints nothing; in RGB the same press still paints. + +use serde_json::json; + +use super::brush_refusal_alert_tests::{alerts, app, refused, steps, stroke}; +use super::*; + +const TOOLS: [(Tool, &str); 4] = [(Tool::Burn, "burn tool"), (Tool::Sponge, "sponge tool"), (Tool::Blur, "blur tool"), (Tool::Smudge, "smudge tool")]; + +#[test] +fn indexed_color_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.indexedColor", json!({"palette": "exact", "dither": "none", "forced": "none"})).unwrap(); + refused(&mut app, &format!("Could not use the {name} because it does not work with Indexed Color images (convert image to RGB Color mode to edit).")); + } +} + +#[test] +fn bitmap_documents_get_the_mode_alert() { + for (tool, name) in TOOLS { + let mut app = app(tool); + app.run("image.mode.grayscale", json!({})).unwrap(); + app.run("image.mode.bitmap", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.mode, photocraft_doc::ColorMode::Bitmap); + refused(&mut app, &format!("Could not use the {name} because it does not work with Bitmap images (convert image to Grayscale mode to edit).")); + } +} + +#[test] +fn rgb_documents_keep_painting() { + for (tool, _) in TOOLS { + let mut app = app(tool); + let before = steps(&app); + stroke(&mut app); + assert!(alerts(&app).is_empty(), "{tool:?}: no alert"); + assert_eq!(steps(&app), before + 1, "{tool:?}: the stroke was applied"); + } +} 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 00000000000..3086f524677 --- /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 ee9461f6fde..d569f73f111 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.rs b/crates/ui-egui/src/tools.rs index 41ef2412339..721057faacd 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -76,6 +76,8 @@ mod gradient_options_bar_mode_tests; mod gradient_refusal_messages_tests; #[cfg(test)] mod line_tool_defaults_tests; +#[cfg(test)] +mod path_selection_shape_over_saved_path_tests; #[cfg(test)] mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 4c5aa8d6f1e..f36814934c0 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -69,6 +69,13 @@ fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path } } +/// Whether a click at `p` with Add Anchor Point (`tool`) would add an anchor: the pointer is over +/// a segment of the targeted path that the tool may edit. Read-only; the cursor and its badge +/// (#12729) ask it, so they show the pen with "+" only where a click does something. +pub(crate) fn adds_anchor_at(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> bool { + tool == Tool::AddAnchorPoint && target(app, tool, p).is_some() +} + /// The Pen's Auto Add/Delete (#4144): what a Pen click at `p` does to the active path instead of /// starting a new one, as the anchor tool that does it (Add Anchor Point on a segment, Delete /// Anchor Point on an anchor), the path and the hit. While a path is being drawn it edits that diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index ef815c66cf4..ae58b9b6113 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -148,7 +148,13 @@ fn shape_layer_paths_are_edited_and_the_added_anchor_replaces_the_selection() { #[test] fn the_cursor_shows_plus_or_minus() { use crate::tool_feedback::{Badge, badge}; - let app = app(Tool::AddAnchorPoint); + let mut app = app(Tool::AddAnchorPoint); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "no path targeted, no segment under the pointer (#12729)"); + with_path(&mut app); + app.ui.selected_path = Some("work".into()); + app.hover_doc = Some([80.0, 80.0]); + assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), None, "off the path's segments"); + app.hover_doc = Some([80.0, 120.0]); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add)); assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract)); assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract)); diff --git a/crates/ui-egui/src/tools/brush_refusal.rs b/crates/ui-egui/src/tools/brush_refusal.rs index bfa63bb3abc..0fa245f0b53 100644 --- a/crates/ui-egui/src/tools/brush_refusal.rs +++ b/crates/ui-egui/src/tools/brush_refusal.rs @@ -22,13 +22,17 @@ pub const REMOVE_LOCKED: &str = "Can't use the tool because the layer is locked. pub const INDEXED: &str = "Could not use the {tool} because it does not work with Indexed Color images (convert image to RGB Color mode to edit)."; pub const BITMAP: &str = "Could not use the {tool} because it does not work with Bitmap images (convert image to Grayscale mode to edit)."; -/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge -/// and Sharpen tools. Kept apart from [`tool_name`]: the layer alerts aren't wired for the Dodge -/// tool yet (#12685). +/// The tool's name in the colour-mode alerts, for the tools whose wording was measured: the Dodge, +/// Burn, Sponge, Blur, Sharpen and Smudge tools. Kept apart from [`tool_name`]: the layer alerts +/// aren't wired for all of them yet (#12685). fn mode_tool_name(tool: Tool) -> Option<&'static str> { match tool { Tool::Dodge => Some(tl!("dodge tool")), + Tool::Burn => Some(tl!("burn tool")), + Tool::Sponge => Some(tl!("sponge tool")), + Tool::Blur => Some(tl!("blur tool")), Tool::Sharpen => Some(tl!("sharpen tool")), + Tool::Smudge => Some(tl!("smudge tool")), _ => None, } } @@ -110,6 +114,10 @@ mod sharpen_refusal_alert_tests; #[path = "../sponge_refusal_alert_tests.rs"] mod sponge_refusal_alert_tests; +#[cfg(test)] +#[path = "../retouch_mode_refusal_alert_tests.rs"] +mod retouch_mode_refusal_alert_tests; + #[cfg(test)] #[path = "../bucket_bitmap_alert_tests.rs"] mod bucket_bitmap_alert_tests; diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 9d4bf194af5..3a88440a526 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/crates/ui-egui/src/tools/path_components.rs b/crates/ui-egui/src/tools/path_components.rs index 041279b748c..f55b6109d8a 100644 --- a/crates/ui-egui/src/tools/path_components.rs +++ b/crates/ui-egui/src/tools/path_components.rs @@ -32,6 +32,17 @@ fn target(app: &PhotocraftApp) -> Option<(PathRef, Path)> { active_paths(app).into_iter().next() } +/// A Path Selection press on a shape layer, off every component of the targeted saved path: +/// the saved path is no longer the target, so the press and drag act on the shape (#13270). +/// A press on one of the saved path's components keeps it targeted. +pub(crate) fn untarget_saved_path_off(app: &mut PhotocraftApp, at: [f64; 2], tol: f64) { + if let Some((PathRef::Saved(_), path)) = target(app) + && component_at(&path, at, tol).is_none() + { + app.ui.selected_path = None; + } +} + /// The selected components: their path and the first subpath of each, in order. `None` with /// nothing selected, a selection on a path that is not an active one any more, or a tool other /// than Path Selection (the only one that shows it, so the only one that acts on it). diff --git a/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs new file mode 100644 index 00000000000..4590657480c --- /dev/null +++ b/crates/ui-egui/src/tools/path_selection_shape_over_saved_path_tests.rs @@ -0,0 +1,70 @@ +//! #13270: with a saved path targeted in the Paths panel, a Path Selection drag on a shape layer +//! targets and moves the shape, as in the reference application; the saved path keeps its points. +//! A drag on a component of the saved path still moves that component. + +use egui::Modifiers; +use photocraft_doc::{LayerContent, LayerId, Path}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const SAVED: &str = "Path 1"; + +/// A rectangle shape at 500,100–700,200, a pixel layer "Red" above it, active, and the saved +/// path "Path 1" (a square 100,300–200,400) selected in the Paths panel, with Path Selection. +fn setup() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.run("shape.create", json!({"kind": "rect", "rect": [500, 100, 200, 100], "fill": "#2050c0"})).unwrap(); + let shape = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let square = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [200, 300], [200, 400], [100, 400]]}]}); + app.run("path.set", json!({"name": SAVED, "path": square})).unwrap(); + app.ui.selected_path = Some(SAVED.into()); + app.ui.tool = Tool::PathSelection; + (app, shape) +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, Modifiers::NONE); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + tool_event(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, Modifiers::NONE); +} + +fn saved(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == SAVED).unwrap().path.clone() +} + +fn shape_bounds(app: &PhotocraftApp, id: LayerId) -> Option<(f64, f64, f64, f64)> { + let doc = &app.session.active().unwrap().doc; + doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => sh.path.control_bounds(), + _ => None, + }) +} + +#[test] +fn a_drag_on_a_shape_moves_the_shape_not_the_targeted_saved_path() { + let (mut app, shape) = setup(); + let (path_before, shape_before) = (saved(&app), shape_bounds(&app, shape).unwrap()); + drag(&mut app, [600.0, 150.0], [650.0, 200.0]); + assert_eq!(app.session.active().unwrap().active_layer, Some(shape), "the shape is the active layer"); + assert_eq!(saved(&app), path_before, "the saved path keeps its points"); + let (x0, y0, x1, y1) = shape_before; + assert_eq!(shape_bounds(&app, shape), Some((x0 + 50.0, y0 + 50.0, x1 + 50.0, y1 + 50.0)), "the shape moved by the drag"); + assert_eq!(app.ui.selected_path, None, "the saved path is no longer the target"); +} + +#[test] +fn a_drag_on_a_component_of_the_saved_path_still_moves_it() { + let (mut app, shape) = setup(); + let shape_before = shape_bounds(&app, shape); + drag(&mut app, [150.0, 350.0], [180.0, 370.0]); + assert_eq!(saved(&app).control_bounds(), Some((130.0, 320.0, 230.0, 420.0)), "the saved path moved"); + assert_eq!(shape_bounds(&app, shape), shape_before, "the shape stays"); + assert_eq!(app.ui.selected_path.as_deref(), Some(SAVED)); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs new file mode 100644 index 00000000000..e01e64387c0 --- /dev/null +++ b/crates/ui-egui/src/tools/perspective_crop_mirrored_tests.rs @@ -0,0 +1,138 @@ +//! #12489: a Perspective Crop box flipped on one axis (⌥ dragging a corner past the opposite one +//! along x only) is wound counter-clockwise. It is drawn valid and commits mirrored, each corner +//! mapped as it lies, as in the reference application; `image.perspectiveCrop` takes the same +//! corners. Clicked corners still commit upright, a box turned 180° still commits upside down, and +//! self-crossing and degenerate quads stay invalid. + +use std::sync::Arc; + +use egui::{Modifiers, Pos2, Rect, vec2}; +use serde_json::json; + +use super::*; + +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0]; +const YELLOW: [f32; 4] = [1.0, 1.0, 0.0, 1.0]; + +/// The measured test document: 800 x 500, red (top left), green (top right), blue (bottom left) +/// and yellow (bottom right) quadrants with a black square in the middle; the Perspective Crop tool. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 500})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::PerspectiveCrop; + let surf = Arc::make_mut(&mut app.session.active_mut().unwrap().doc).layers[0].surface_mut().unwrap(); + for (x, y, c) in [(0, 0, RED), (400, 0, GREEN), (0, 250, BLUE), (400, 250, YELLOW)] { + surf.fill_rect(photocraft_geom::Rect::from_xywh(x, y, 400, 250), &c); + } + surf.fill_rect(photocraft_geom::Rect::from_xywh(395, 245, 10, 10), &[0.0, 0.0, 0.0, 1.0]); + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: Modifiers) { + assert!(pointer(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods)); + let mid = [(from[0] + to[0]) / 2.0, (from[1] + to[1]) / 2.0]; + assert!(pointer(app, ToolEvent::Move { x: mid[0], y: mid[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods)); + assert!(pointer(app, ToolEvent::Up { x: to[0], y: to[1] }, mods)); +} + +fn click(app: &mut PhotocraftApp, p: [f64; 2]) { + drag(app, p, p, Modifiers::NONE); +} + +/// The overlay `draw_overlay` paints: (shield polygons, whether the frame is red). +fn overlay(app: &PhotocraftApp) -> (usize, bool) { + let ctx = egui::Context::default(); + let xf = + ViewXform { rect: Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)), zoom: 1.0, center: [400.0, 250.0], flip: false, rotation: 0.0, aspect: 1.0 }; + let mut o = ctx.run_ui(Default::default(), |ui| draw_overlay(app, ui.painter(), &xf)); + o.textures_delta.clear(); + let shield = o.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == SHIELD)).count(); + let red = Color32::from_rgb(0xe5, 0x3e, 0x3e); + let frame_red = o.shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Path(p) if p.closed && p.stroke.color == egui::epaint::ColorMode::Solid(red))); + (shield, frame_red) +} + +/// The committed canvas's size and the colours at its four corners (TL, TR, BL, BR). +fn corners(app: &PhotocraftApp) -> ((u32, u32), [[f32; 4]; 4]) { + let doc = &app.session.active().unwrap().doc; + let (w, h) = (doc.size.width as i32, doc.size.height as i32); + let surf = doc.layers[0].surface().unwrap(); + ((doc.size.width, doc.size.height), [surf.rgba(3, 3), surf.rgba(w - 4, 3), surf.rgba(3, h - 4), surf.rgba(w - 4, h - 4)]) +} + +#[test] +fn alt_corner_drag_past_the_opposite_corner_on_one_axis_commits_mirrored() { + let mut app = app(); + // A fresh 100 x 100 box, its bottom right corner ⌥ dragged past the fixed top left one on x only. + drag(&mut app, [450.0, 220.0], [550.0, 320.0], Modifiers::NONE); + drag(&mut app, [550.0, 320.0], [350.0, 300.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 220.0], [350.0, 220.0], [350.0, 300.0], [450.0, 300.0]]), "flipped left to right"); + let (shield, red) = overlay(&app); + assert!(shield > 0 && !red, "drawn as a valid quad: accent frame and shield, not red"); + commit(&mut app); + assert!(app.ui.perspective_crop.is_none(), "committed"); + let (size, [tl, tr, bl, br]) = corners(&app); + assert_eq!(size, (100, 80)); + assert_eq!([tl, tr, bl, br], [GREEN, RED, YELLOW, BLUE], "mirrored left to right, top stays on top"); +} + +#[test] +fn the_command_takes_counter_clockwise_corners_and_mirrors() { + let mut app = app(); + let r = app.run("image.perspectiveCrop", json!({"corners": [[450, 220], [350, 220], [350, 300], [450, 300]]})).unwrap(); + assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(100), Some(80))); + assert_eq!(corners(&app).1, [GREEN, RED, YELLOW, BLUE]); + // Mirrored top to bottom the other way round. + let mut app = self::app(); + app.run("image.perspectiveCrop", json!({"corners": [[350, 300], [450, 300], [450, 220], [350, 220]]})).unwrap(); + assert_eq!(corners(&app).1, [BLUE, YELLOW, RED, GREEN]); +} + +#[test] +fn clicked_corners_commit_upright_in_any_order() { + let mut app = app(); + // Counter-clockwise clicks from the top left. + for p in [[350.0, 220.0], [350.0, 300.0], [450.0, 300.0], [450.0, 220.0]] { + click(&mut app, p); + } + assert_eq!(app.ui.perspective_crop, Some([[350.0, 220.0], [450.0, 220.0], [450.0, 300.0], [350.0, 300.0]]), "sorted clockwise"); + commit(&mut app); + assert_eq!(corners(&app), ((100, 80), [RED, GREEN, BLUE, YELLOW])); +} + +#[test] +fn a_box_turned_180_degrees_commits_upside_down() { + let mut app = app(); + drag(&mut app, [450.0, 300.0], [550.0, 400.0], Modifiers::NONE); + drag(&mut app, [550.0, 400.0], [350.0, 200.0], Modifiers::ALT); + assert_eq!(app.ui.perspective_crop, Some([[450.0, 300.0], [350.0, 300.0], [350.0, 200.0], [450.0, 200.0]])); + commit(&mut app); + assert_eq!(corners(&app), ((100, 100), [YELLOW, BLUE, GREEN, RED])); +} + +#[test] +fn self_crossing_and_degenerate_quads_stay_invalid() { + for q in [ + // Self-crossing (a bow tie), each way round. + [[350.0, 220.0], [450.0, 220.0], [350.0, 300.0], [450.0, 300.0]], + [[450.0, 220.0], [350.0, 220.0], [450.0, 300.0], [350.0, 300.0]], + // Three corners on a line, and no area. + [[350.0, 220.0], [400.0, 220.0], [450.0, 220.0], [350.0, 300.0]], + [[400.0, 250.0]; 4], + ] { + let mut app = app(); + app.ui.perspective_crop = Some(q); + let (shield, red) = overlay(&app); + assert!(shield == 0 && red, "{q:?} is drawn red without the shield"); + assert!(app.run("image.perspectiveCrop", json!({ "corners": q })).is_err(), "{q:?}"); + commit(&mut app); + assert_eq!(app.ui.perspective_crop, Some(q), "{q:?} stays for fixing"); + assert_eq!(app.session.active().unwrap().doc.size.width, 800); + } + let mut app = app(); + assert!(app.run("image.perspectiveCrop", json!({"corners": [[350, 220], [f64::NAN, 220], [450, 300], [350, 300]]})).is_err()); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 0fb77652940..aad099ee2cb 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -4,8 +4,8 @@ //! BL in document px; clicked corners are put in that order); //! - drag a corner to move it alone, onto an edge of a skewed object (a photographed page, a //! facade); drag inside the quad to move it; -//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad -//! wound like its box, which can't be committed; +//! - the quad shows its perspective grid (Show Grid) and turns red while it isn't a convex quad, +//! which can't be committed; one flipped on one axis (wound the other way) commits mirrored; //! - ↵ (or ✓) commits: `image.perspectiveCrop` maps the quad onto an upright rectangle, the whole //! document in one undo step. Its size comes from the options bar's W x H (and the resolution), //! which are the Crop tool's fields (`crop_size`), or with them empty from the rectangle the @@ -14,7 +14,7 @@ //! A pending quad belongs to the document it was drawn on, like the Crop tool's frame. use egui::{Color32, Pos2, Stroke}; -use photocraft_algo::transform::{Homography, convex_quad}; +use photocraft_algo::transform::{Homography, convex_quad, convex_quad_any_winding}; use photocraft_engine::prefs::Unit; use serde_json::{Value, json}; @@ -426,7 +426,8 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform _ => app.ui.perspective_crop, }; if let Some(q) = quad.filter(|q| q.iter().flatten().all(|v| v.is_finite())) { - let ok = convex_quad(&q); + // A quad flipped on one axis is wound counter-clockwise and commits mirrored (#12489). + let ok = convex_quad_any_winding(&q); let color = if ok { accent } else { Color32::from_rgb(0xe5, 0x3e, 0x3e) }; // The image outside the quad is dimmed (#11972), following the quad while it is dragged. if ok && let Some(size) = app.session.active().map(|d| d.doc.size) { @@ -554,6 +555,10 @@ mod perspective_crop_shield_tests; #[path = "perspective_crop_deselect_tests.rs"] mod perspective_crop_deselect_tests; +#[cfg(test)] +#[path = "perspective_crop_mirrored_tests.rs"] +mod perspective_crop_mirrored_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs new file mode 100644 index 00000000000..9c9a5bf46d3 --- /dev/null +++ b/crates/ui-egui/src/tools/rectangle_radius_target_tests.rs @@ -0,0 +1,111 @@ +//! #13338: the Rectangle tool's options-bar Radius sets the next rectangle, not the active shape. +//! It shows the tool's own radius. The Path Selection / Direct Selection Radius still edits the +//! active shape. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LiveShape}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// A document with Rectangle 1 (radius 20) as the active layer, and `tool` current. +fn bar_with(tool: Tool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("shape.create", json!({"kind": "roundedRect", "rect": [10, 10, 80, 60], "radii": [20, 20, 20, 20], "fill": "#ff0000"})).unwrap(); + app.sync_views(); + app.ui.tool = tool; + let mut h = Harness::builder().with_size(vec2(1800.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn history_len(h: &Harness<'static, PhotocraftApp>) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +/// The first radius of every rectangle shape layer, bottom to top. +fn radii(h: &Harness<'static, PhotocraftApp>) -> Vec { + let st = h.state().session.active().unwrap(); + st.doc + .walk() + .into_iter() + .filter_map(|(_, _, l)| match &l.content { + LayerContent::Shape(sh) => match &sh.live { + Some(LiveShape::Rect { radii, .. }) => Some(radii[0]), + _ => None, + }, + _ => None, + }) + .collect() +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let mods = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: (from[0] + to[0]) / 2.0, y: (from[1] + to[1]) / 2.0, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); +} + +#[test] +fn the_rectangle_tools_radius_field_leaves_the_active_shape_alone() { + let mut h = bar_with(Tool::Rectangle); + let before = history_len(&h); + type_radius(&mut h, "5000"); + assert_eq!(radii(&h), vec![20.0], "Rectangle 1 keeps its radius"); + assert_eq!(history_len(&h), before, "no History state"); + assert_eq!(h.state().ui.tool_options.corner_radius, 5000.0); +} + +#[test] +fn the_next_rectangle_takes_the_typed_radius() { + let mut h = bar_with(Tool::Rectangle); + type_radius(&mut h, "5000"); + drag(h.state_mut(), [100.0, 100.0], [180.0, 170.0]); + let all = radii(&h); + assert_eq!(all.len(), 2, "a second rectangle was drawn: {all:?}"); + assert_eq!(all[0], 20.0); + assert_eq!(all[1], 5000.0); +} + +#[test] +fn the_rectangle_tools_radius_field_shows_the_tools_radius() { + let mut h = bar_with(Tool::Rectangle); + h.state_mut().ui.tool_options.corner_radius = 0.0; + h.run_steps(3); + let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Radius:")).expect("the Radius field"); + let shown = field + .accesskit_node() + .numeric_value() + .map(|v| v as f32) + .or_else(|| field.accesskit_node().value().and_then(|v| v.trim_end_matches(" px").trim().parse().ok())); + assert_eq!(shown, Some(0.0), "the tool's radius, not the shape's 20"); +} + +#[test] +fn the_path_selection_radius_field_still_edits_the_active_shape() { + for tool in [Tool::PathSelection, Tool::DirectSelection] { + let mut h = bar_with(tool); + let before = history_len(&h); + type_radius(&mut h, "30"); + assert_eq!(radii(&h), vec![30.0], "{tool:?}: the active shape takes it"); + assert_eq!(history_len(&h), before + 1, "{tool:?}: one History state"); + } +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index d0f7e3c5a8e..966fdff212b 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -107,16 +107,12 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool crate::widgets::vline(ui, 22.0); let label = tl!("Radius:"); lbl(ui, label); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; + // The tool's own radius for the next rectangle (#13338); the active shape is not touched. + let mut r = o.corner_radius; let (resp, out_of_range) = crate::widgets::value_field_alerting(ui, label, &mut r, RADIUS_RANGE, "px", 62.0); radius_alert = out_of_range; if resp.changed() { o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); } } Tool::Polygon => { @@ -225,6 +221,10 @@ fn radius_range_alert(app: &mut PhotocraftApp, owed: bool) { #[path = "rectangle_radius_range_tests.rs"] mod rectangle_radius_range_tests; +#[cfg(test)] +#[path = "rectangle_radius_target_tests.rs"] +mod rectangle_radius_target_tests; + /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 00ecc86dae0..3adcecc2de3 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -130,7 +130,7 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: Tool::Rectangle if o.corner_radius > 0.0 => json!({"kind": "roundedRect", "rect": rect, "radii": vec![o.corner_radius; 4]}), Tool::Rectangle | Tool::CustomShape => json!({"kind": "rect", "rect": rect}), Tool::EllipseShape => json!({"kind": "ellipse", "rect": rect}), - Tool::Triangle => json!({"kind": "polygon", "rect": rect, "sides": 3}), + Tool::Triangle => json!({"kind": "triangle", "rect": rect}), // PhotoCraft's star defaults; the Star Tool's own options are not measured yet (#11377). Tool::Star => json!({"kind": "star", "rect": rect, "sides": 5, "starRatio": 0.5}), _ => json!({"kind": "polygon", "rect": rect, "sides": o.polygon_sides.max(3)}), diff --git a/crates/vector/src/trace.rs b/crates/vector/src/trace.rs index 1557af863df..38883d12528 100644 --- a/crates/vector/src/trace.rs +++ b/crates/vector/src/trace.rs @@ -10,8 +10,10 @@ //! Contours are emitted as subpaths: the first combines, the rest *exclude*, which is the //! even-odd area for nested, non-crossing contours regardless of their orientation. //! -//! [`fit_trace`] runs steps 2 and 3 on a freehand pointer trace (the Freeform Pen), open or -//! closed, with a corner window that grows with the tolerance. +//! [`fit_trace`] fits a freehand pointer trace (the Freeform Pen), open or closed, the way the +//! reference application places its anchors: corners only at turns sharper than 80°, then each +//! run segment by segment, every segment as long as one cubic follows the trace, ending on a +//! turning point in x or y (a wave's peak, a circle's top) where one is in reach. use std::collections::HashMap; @@ -190,14 +192,14 @@ fn walk(lp: &[P], i: usize, window: f64, fwd: bool, closed: bool) -> P { lp[cur] } -/// Indices of corner points: where the direction over ±`window` px turns by more than 60°. The -/// ends of an open polyline are never corners. -fn corners(lp: &[P], window: f64, closed: bool) -> Vec { +/// Indices of corner points: where the direction over ±`window` px turns by more than +/// `turn_deg`. The ends of an open polyline are never corners. +fn corners(lp: &[P], window: f64, closed: bool, turn_deg: f64) -> Vec { let n = lp.len(); if n < 3 || !window.is_finite() || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Vec::new(); } - let cos_thresh = (60f64).to_radians().cos(); + let cos_thresh = turn_deg.to_radians().cos(); let turn: Vec = (0..n) .map(|i| { if !closed && (i == 0 || i + 1 == n) { @@ -280,7 +282,7 @@ fn fit_closed(lp: &[P], tol: f64, window: f64) -> Subpath { if n < 3 || lp.iter().any(|p| !p.0.is_finite() || !p.1.is_finite()) { return Subpath { closed: true, knots: Vec::new(), op: PathOp::Combine }; } - let cs = corners(lp, window, true); + let cs = corners(lp, window, true, MASK_CORNER_TURN); let mut segs: Vec<[P; 4]> = Vec::new(); let mut corner_at_start: Vec = Vec::new(); if cs.is_empty() { @@ -329,9 +331,10 @@ pub const MAX_TRACE_POINTS: usize = 4096; /// Fits a freehand pointer trace (the Freeform Pen's drag) with cubic Béziers that stay within /// `tolerance` px of every sample: Photoshop's Curve Fit, clamped to 0.1–100 px (2 px when not -/// finite). Turns sharper than 60° over ±2 × `tolerance` become corner anchors, the other inner -/// anchors are smooth. A `closed` trace becomes a closed subpath. Non-finite samples are skipped; -/// `None` when fewer than two distinct points remain (three when `closed`). +/// finite). Turns sharper than 80° over ±2 × `tolerance` become corner anchors; the other inner +/// anchors are smooth and sit on the trace's turning points in x and y where they can. A `closed` +/// trace becomes a closed subpath whose release point stays an anchor. Non-finite samples are +/// skipped; `None` when fewer than two distinct points remain (three when `closed`). pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option { let tol = if tolerance.is_finite() { tolerance.clamp(0.1, 100.0) } else { 2.0 }; let window = (2.0 * tol).max(1.5); @@ -359,16 +362,64 @@ pub fn fit_trace(points: &[[f64; 2]], tolerance: f64, closed: bool) -> Option 3 && lp.last().zip(lp.first()).is_some_and(|(a, b)| len(sub(*a, *b)) < min_step) { lp.pop(); } - return (lp.len() >= 3).then(|| fit_closed(&lp, tol, window)); + return (lp.len() >= 3).then(|| close_trace(&lp, fit_open(&lp, tol, window), window)); } (lp.len() >= 2).then(|| fit_open(&lp, tol, window)) } +/// Corners of [`trace_mask`]'s contours: turns sharper than this many degrees. +const MASK_CORNER_TURN: f64 = 60.0; + +/// Corners of a freehand trace: turns sharper than this many degrees. The reference application +/// rounds a 67° vee with two smooth anchors (#12838); a right angle stays a corner. +const FREEFORM_CORNER_TURN: f64 = 80.0; + +/// Most a freehand segment turns, in degrees per px of Curve Fit, up to [`MAX_SEGMENT_TURN`]. A +/// smooth stroke fits within any Curve Fit with few anchors, yet the reference application adds +/// anchors as Curve Fit goes down (its 324° arc: 12 segments at 0.5 px, 5 at 1 px, 3 at 2 px, +/// #12838). 75° per px reaches the cap at the default 2 px. +const SEGMENT_TURN_PER_PX: f64 = 75.0; + +/// Most a freehand segment turns, in degrees: a longer arc gets another anchor. A 180° arc fits +/// one cubic within 2 px, but the reference application gives a whole circle five anchors and +/// 324° of it four (#12838). +const MAX_SEGMENT_TURN: f64 = 150.0; + +/// Closes an open fit of a closed trace: the release point stays an anchor, and a segment joins it +/// to the first one, smooth unless the trace has a corner there. +fn close_trace(lp: &[P], mut sp: Subpath, window: f64) -> Subpath { + sp.closed = true; + let n = lp.len(); + let seam = corners(lp, window, true, FREEFORM_CORNER_TURN); + let corner = seam.first() == Some(&0) || seam.last() == Some(&(n - 1)); + let m = sp.knots.len(); + let (Some(first), Some(last)) = (sp.knots.first().copied(), sp.knots.last().copied()) else { return sp }; + if m < 2 { + return sp; + } + let (f, l) = ((first.anchor.x, first.anchor.y), (last.anchor.x, last.anchor.y)); + let third = len(sub(f, l)) / 3.0; + let (t_out, t_in) = if corner { + (norm(sub(f, l)), norm(sub(f, l))) + } else { + // Leave the release point as the trace arrived at it, reach the start as the trace left it. + let arrive = norm(sub(l, (last.in_ctrl.x, last.in_ctrl.y))); + let leave = norm(sub((first.out_ctrl.x, first.out_ctrl.y), f)); + (if len(arrive) > 0.0 { arrive } else { norm(sub(l, lp[n - 2])) }, if len(leave) > 0.0 { leave } else { norm(sub(lp[1], f)) }) + }; + let pt = |p: P| Point::new(p.0, p.1); + sp.knots[m - 1].out_ctrl = pt(add(l, mul(t_out, third))); + sp.knots[m - 1].smooth = !corner; + sp.knots[0].in_ctrl = pt(sub(f, mul(t_in, third))); + sp.knots[0].smooth = !corner; + sp +} + /// Fits an open polyline with cubic Béziers, one run between consecutive corners at a time. fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let n = lp.len(); let mut cuts = vec![0]; - cuts.extend(corners(lp, window, false)); + cuts.extend(corners(lp, window, false, FREEFORM_CORNER_TURN)); cuts.push(n - 1); cuts.dedup(); let mut segs: Vec<[P; 4]> = Vec::new(); @@ -387,11 +438,7 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { let third = mul(sub(b, a), 1.0 / 3.0); segs.push([a, add(a, third), sub(b, third), b]); } else { - // End tangents over a stretch of the trace, not the first jittery sample. - let reach = (2.0 * window).min(len(sub(b, a)) / 3.0).max(window); - let t1 = norm(sub(walk(pts, 0, reach, true, false), a)); - let t2 = norm(sub(walk(pts, m - 1, reach, false, false), b)); - fit_cubic(pts, t1, t2, tol * tol, &mut segs, 0); + fit_run(pts, tol, window, &mut segs); } corner_at_start.extend((before..segs.len()).map(|k| k == before)); } @@ -407,6 +454,234 @@ fn fit_open(lp: &[P], tol: f64, window: f64) -> Subpath { Subpath { closed: false, knots, op: PathOp::Combine } } +/// Fits one freehand run (no corner inside) from its first sample to its last, a segment at a +/// time: each reaches as far along the trace as one cubic stays within `tol` and turns at most +/// [`SEGMENT_TURN_PER_PX`] × `tol` (up to [`MAX_SEGMENT_TURN`]), and ends on the first turning +/// point of the trace in x or y inside that reach (a wave's peak, a circle's top) when there is +/// one, as the reference application places its anchors (#12838); with the next turning point +/// just out of reach, halfway to it. Consecutive segments share their tangent, so inner anchors +/// are smooth. +fn fit_run(pts: &[P], tol: f64, window: f64, out: &mut Vec<[P; 4]>) { + let m = pts.len(); + if m < 2 { + return; + } + let max_turn = (SEGMENT_TURN_PER_PX * tol).min(MAX_SEGMENT_TURN); + let turns = turning_points(pts, tol); + let arc: Vec = pts + .iter() + .scan((0.0, pts[0]), |(acc, prev), &q| { + *acc += len(sub(q, *prev)); + *prev = q; + Some(*acc) + }) + .collect(); + // The first segment leaves as the trace does; the others continue the one before. + let mut t1: Option

= None; + // An anchor on a turning point leaves a segment of at least this length behind it. + let min_gap = 3.0 * window; + let mut a = 0; + while a + 1 < m { + let fit = |b: usize| fit_piece(pts.get(a..=b)?, t1, tol, max_turn); + // Farthest end that fits: doubling steps, then halving the gap to the first failure. The + // error does not always grow with the length (a few samples can fit worse than more), so + // a failed step looks one step further before it stops the doubling. + let mut good = a + 1; + let mut bad = m; + let mut step = 2; + while bad == m { + let b = (a + step).min(m - 1); + if b <= good { + break; + } + let ahead = (a + step.saturating_mul(2)).min(m - 1); + if fit(b).is_some() { + good = b; + } else if ahead > b && fit(ahead).is_some() { + good = ahead; + step = step.saturating_mul(2); + } else { + bad = b; + continue; + } + if good == m - 1 { + break; + } + step = step.saturating_mul(2); + } + while bad < m && bad - good > 1 { + let mid = good + (bad - good) / 2; + if fit(mid).is_some() { + good = mid; + } else { + bad = mid; + } + } + let end = if good + 1 == m { + good + } else { + let mut ahead = turns.iter().copied().filter(|&t| t > a && arc[t] - arc[a] >= min_gap); + let inside = ahead.clone().take_while(|&t| t <= good).take(4).find(|&t| fit(t).is_some()); + // A turning point within two reaches: halfway there, so no sliver is left before it. + let halfway = ahead.find(|&t| t > good).filter(|&t| arc[t] - arc[a] <= 2.0 * (arc[good] - arc[a])).and_then(|t| { + let mid = arc.partition_point(|&s| s < (arc[a] + arc[t]) / 2.0).clamp(a + 1, good); + fit(mid).map(|_| mid) + }); + inside.or(halfway).unwrap_or(good) + }; + // Two samples always fit; the chord stands in should a degenerate piece not. + let seg = fit(end).unwrap_or_else(|| thirds(pts[a], pts[end], t1)); + let into = sub(seg[3], seg[2]); + t1 = Some(if len(into) > 1e-12 { norm(into) } else { norm(sub(seg[3], seg[0])) }); + out.push(seg); + a = end; + } +} + +/// Indices where the trace turns back in x or in y by more than `tol` (a wave's peaks, a circle's +/// top, bottom and sides), in order. Jitter smaller than `tol` makes none. +fn turning_points(pts: &[P], tol: f64) -> Vec { + let mut out = Vec::new(); + for axis in 0..2 { + let v = |i: usize| if axis == 0 { pts[i].0 } else { pts[i].1 }; + // Direction of travel along the axis: 0 until the trace has moved by more than `tol`. + let mut dir = 0i8; + let (mut hi, mut lo) = (0usize, 0usize); + for i in 1..pts.len() { + if v(i) >= v(hi) { + hi = i; + } + if v(i) <= v(lo) { + lo = i; + } + if dir >= 0 && v(i) < v(hi) - tol { + if dir > 0 { + out.push(hi); + } + dir = -1; + lo = i; + } else if dir <= 0 && v(i) > v(lo) + tol { + if dir < 0 { + out.push(lo); + } + dir = 1; + hi = i; + } + } + } + out.sort_unstable(); + out.dedup(); + out +} + +/// One cubic from the first sample of `pts` to the last, leaving along `t1` when given, that stays +/// within `tol` of every sample and turns at most `max_turn` degrees. +fn fit_piece(pts: &[P], t1: Option

, tol: f64, max_turn: f64) -> Option<[P; 4]> { + let n = pts.len(); + if n < 2 { + return None; + } + let (p0, p3) = (pts[0], pts[n - 1]); + if n == 2 { + return Some(thirds(p0, p3, t1)); + } + let seg = len(sub(p3, p0)); + // A handle longer than the chord loops (a few samples leave least squares free to); even a + // 150° arc's handles are about half its chord. + let tame = |b: Option<[P; 4]>| match b { + Some(b) if len(sub(b[1], b[0])) <= seg && len(sub(b[2], b[3])) <= seg => b, + _ => thirds(p0, p3, t1), + }; + let err2 = tol * tol; + let mut u = chord_params(pts); + let mut b = tame(generate_free(pts, &u, t1)); + let mut e = max_error(pts, &b, &u).0; + for _ in 0..6 { + if e <= err2 { + break; + } + u = reparam(pts, &u, &b); + b = tame(generate_free(pts, &u, t1)); + e = max_error(pts, &b, &u).0; + } + (e <= err2 && turn_deg(&b) <= max_turn).then_some(b) +} + +/// A cubic from `p0` to `p3` with handles a third of the chord: leaving along `t1` when given, +/// otherwise along the chord, and arriving along the chord. +fn thirds(p0: P, p3: P, t1: Option

) -> [P; 4] { + let chord = sub(p3, p0); + let d = len(chord) / 3.0; + let c = norm(chord); + [p0, add(p0, mul(t1.unwrap_or(c), d)), sub(p3, mul(c, d)), p3] +} + +/// Least-squares control points through `pts` at parameters `u`. The second handle is free, so +/// how the piece arrives at its end comes from the whole piece, not from a direction estimated +/// from a few jittery samples there; the first lies along `t1` when given (a smooth join to the +/// segment before), and is free too otherwise. `None` when the samples cannot pin them down. +fn generate_free(pts: &[P], u: &[f64], t1: Option

) -> Option<[P; 4]> { + let (p0, p3) = (*pts.first()?, *pts.last()?); + let (mut a11, mut a12, mut a22) = (0.0, 0.0, 0.0); + let (mut r1, mut r2) = ((0.0, 0.0), (0.0, 0.0)); + for (q, &t) in pts.iter().zip(u) { + let mt = 1.0 - t; + let (b0, b1, b2, b3) = (mt * mt * mt, 3.0 * mt * mt * t, 3.0 * mt * t * t, t * t * t); + let res = sub(*q, add(mul(p0, b0), mul(p3, b3))); + (a11, a12, a22) = (a11 + b1 * b1, a12 + b1 * b2, a22 + b2 * b2); + r1 = add(r1, mul(res, b1)); + r2 = add(r2, mul(res, b2)); + } + if let ([_, q, _], [_, s, _], None) = (pts, u, t1) { + // One inner sample cannot pin down two free handles: the parabola through all three. + let ms = 1.0 - s; + let k = 2.0 * s * ms; + if k <= 1e-9 { + return None; + } + let c = mul(sub(*q, add(mul(p0, ms * ms), mul(p3, s * s))), 1.0 / k); + return Some([p0, add(p0, mul(sub(c, p0), 2.0 / 3.0)), add(p3, mul(sub(c, p3), 2.0 / 3.0)), p3]); + } + // b1·P1 + b2·P2 ≈ res, by least squares. + let det = a11 * a22 - a12 * a12; + if !det.is_finite() || det <= 1e-12 * a11 * a22 { + return None; + } + let Some(t) = t1 else { + let p1 = mul(sub(mul(r1, a22), mul(r2, a12)), 1.0 / det); + let p2 = mul(sub(mul(r2, a11), mul(r1, a12)), 1.0 / det); + return Some([p0, p1, p2, p3]); + }; + // P1 = P0 + α·t: solve for α and P2. + let (r1, r2) = (sub(r1, mul(p0, a11)), sub(r2, mul(p0, a12))); + let alpha = (dot(t, r1) * a22 - a12 * dot(t, r2)) / det; + if !alpha.is_finite() { + return None; + } + // A handle pointing back would cusp: the shortest that keeps the join smooth instead. + let alpha = alpha.max(1e-3 * len(sub(p3, p0))); + let p2 = mul(sub(r2, mul(t, a12 * alpha)), 1.0 / a22); + Some([p0, add(p0, mul(t, alpha)), p2, p3]) +} + +/// How far a cubic's direction turns along it, in degrees (both ways add up). +fn turn_deg(b: &[P; 4]) -> f64 { + const STEPS: usize = 32; + let mut total = 0.0; + let mut prev: Option

= None; + for k in 0..=STEPS { + let d = bezier_d1(b, k as f64 / STEPS as f64); + if len(d) < 1e-9 { + continue; + } + if let Some(p) = prev { + total += (p.0 * d.1 - p.1 * d.0).atan2(dot(p, d)).abs(); + } + prev = Some(d); + } + total.to_degrees() +} + /// Distance from `q` to the segment `a`–`b`. fn segment_distance(q: P, a: P, b: P) -> f64 { let ab = sub(b, a); @@ -662,7 +937,7 @@ mod tests { #[test] fn corners_have_bounded_work_for_many_tiny_segments() { let points: Vec

= (0..20_000).map(|i| (i as f64 * 0.01, if i % 2 == 0 { 0.0 } else { 1e-5 })).collect(); - let selected = corners(&points, 100.0, false); + let selected = corners(&points, 100.0, false, MASK_CORNER_TURN); assert!(selected.len() <= points.len()); } @@ -694,3 +969,7 @@ mod tests { } } } + +#[cfg(test)] +#[path = "trace_freeform_anchor_tests.rs"] +mod trace_freeform_anchor_tests; diff --git a/crates/vector/src/trace_freeform_anchor_tests.rs b/crates/vector/src/trace_freeform_anchor_tests.rs new file mode 100644 index 00000000000..83105442d69 --- /dev/null +++ b/crates/vector/src/trace_freeform_anchor_tests.rs @@ -0,0 +1,147 @@ +//! Freeform Pen anchors against the reference application's sample strokes (#12838): mouse moves +//! in document coordinates, fitted at Curve Fit 2 px unless said otherwise. + +use std::f64::consts::TAU; + +use super::*; + +/// (100,400) to (500,400) in 4 px steps. +fn line() -> Vec<[f64; 2]> { + (0..=100).map(|i| [100.0 + 4.0 * i as f64, 400.0]).collect() +} + +/// x from 100 to 500 in 4 px steps, y = 400 + 60·sin(2π(x − 100)/200): two periods. +fn sine() -> Vec<[f64; 2]> { + (0..=100).map(|i| 100.0 + 4.0 * i as f64).map(|x| [x, 400.0 + 60.0 * ((x - 100.0) / 200.0 * TAU).sin()]).collect() +} + +/// Centre (600,300), radius 100, `steps` of 60 around from (700,300): 60 is the whole circle +/// back to the start, 54 the open one. +fn circle(steps: usize) -> Vec<[f64; 2]> { + (0..=steps).map(|i| i as f64 * TAU / 60.0).map(|a| [600.0 + 100.0 * a.cos(), 300.0 + 100.0 * a.sin()]).collect() +} + +/// (100,450) to (250,550) to (400,450), 45 steps a leg. +fn vee() -> Vec<[f64; 2]> { + let legs = [[100.0, 450.0], [250.0, 550.0], [400.0, 450.0]]; + legs.windows(2) + .flat_map(|w| (0..45).map(move |k| k as f64 / 45.0).map(move |t| [w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t])) + .chain([legs[2]]) + .collect() +} + +/// The five strokes, with whether the drag ends on its start (closes). +fn strokes() -> [(&'static str, Vec<[f64; 2]>, bool); 5] { + [("line", line(), false), ("sine", sine(), false), ("circle", circle(60), true), ("circle-open", circle(54), false), ("vee", vee(), false)] +} + +/// The stroke as given and on the whole pixels a mouse delivers at 100 % zoom. +fn as_given_and_in_pixels(points: Vec<[f64; 2]>) -> [Vec<[f64; 2]>; 2] { + let pixels = points.iter().map(|p| [p[0].round(), p[1].round()]).collect(); + [points, pixels] +} + +fn fit(points: &[[f64; 2]], curve_fit: f64, closed: bool) -> Subpath { + let sp = fit_trace(points, curve_fit, closed); + assert!(sp.is_some(), "the stroke fits"); + sp.unwrap_or_else(|| Subpath { closed, knots: Vec::new(), op: PathOp::Combine }) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +/// Largest distance from a sample to the fitted subpath (each segment densely sampled). +fn max_deviation(sp: &Subpath, samples: &[[f64; 2]]) -> f64 { + let curve: Vec

= sp + .segments() + .iter() + .flat_map(|s| { + let b = [(s[0].x, s[0].y), (s[1].x, s[1].y), (s[2].x, s[2].y), (s[3].x, s[3].y)]; + (0..=1000).map(move |k| bezier(&b, k as f64 / 1000.0)) + }) + .collect(); + samples.iter().map(|q| curve.iter().map(|c| len(sub(*c, (q[0], q[1])))).fold(f64::MAX, f64::min)).fold(0.0, f64::max) +} + +#[test] +fn sine_anchors_sit_on_the_four_peaks() { + for samples in as_given_and_in_pixels(sine()) { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 6, "{got:?}"); + assert_eq!((got.first(), got.last()), (samples.first(), samples.last()), "press and release are anchors"); + for (a, peak) in got[1..5].iter().zip([[150.0, 460.0], [250.0, 340.0], [350.0, 460.0], [450.0, 340.0]]) { + assert!((a[0] - peak[0]).hypot(a[1] - peak[1]) <= 3.0, "{a:?} is not on the peak {peak:?}: {got:?}"); + } + assert!(sp.knots[1..5].iter().all(|k| k.smooth)); + } +} + +#[test] +fn closed_circle_has_five_anchors_and_the_open_one_four() { + for samples in as_given_and_in_pixels(circle(60)) { + let sp = fit(&samples, 2.0, true); + assert!(sp.closed); + assert_eq!(sp.knots.len(), 5, "{:?}", anchors(&sp)); + assert!(sp.knots.iter().all(|k| k.smooth), "a circle has no corners"); + } + for samples in as_given_and_in_pixels(circle(54)) { + let sp = fit(&samples, 2.0, false); + assert!(!sp.closed); + assert_eq!(sp.knots.len(), 4, "{:?}", anchors(&sp)); + assert!(sp.knots[1..3].iter().all(|k| k.smooth)); + } +} + +/// On whole pixels the first segment past the turn fits worse over a few samples than over many; +/// the fit still reaches past them to the reference application's four anchors. +#[test] +fn vee_turns_with_a_rounded_join_not_a_cusp() { + for (i, samples) in as_given_and_in_pixels(vee()).into_iter().enumerate() { + let sp = fit(&samples, 2.0, false); + let got = anchors(&sp); + assert_eq!(got.len(), 4, "{got:?}"); + assert_eq!((got[0], got[3]), ([100.0, 450.0], [400.0, 450.0])); + assert!(sp.knots[1..3].iter().all(|k| k.smooth), "no corner anchor: {got:?}"); + if i == 0 { + // As measured, both inner anchors are near the turn, not along the legs. + assert!(got[1..3].iter().all(|a| (a[0] - 250.0).hypot(a[1] - 550.0) < 60.0), "{got:?}"); + } + } +} + +#[test] +fn line_is_unchanged_one_segment_with_handles_at_a_third() { + let sp = fit(&line(), 2.0, false); + assert_eq!(anchors(&sp), [[100.0, 400.0], [500.0, 400.0]]); + let (a, b) = (&sp.knots[0], &sp.knots[1]); + assert!((a.out_ctrl.x - (100.0 + 400.0 / 3.0)).abs() < 1e-9 && a.out_ctrl.y == 400.0); + assert!((b.in_ctrl.x - (500.0 - 400.0 / 3.0)).abs() < 1e-9 && b.in_ctrl.y == 400.0); +} + +#[test] +fn a_lower_curve_fit_gives_more_anchors() { + for (name, points, closed) in [("sine", sine(), false), ("circle-open", circle(54), false)] { + let at_2 = fit(&points, 2.0, closed).knots.len(); + for curve_fit in [0.5, 1.0] { + let n = fit(&points, curve_fit, closed).knots.len(); + assert!(n > at_2, "{name}: {n} anchors at Curve Fit {curve_fit}, {at_2} at 2"); + } + } +} + +/// Today's guarantee: the path stays within Curve Fit of every sample, on the strokes as given +/// and on the whole pixels a mouse delivers. +#[test] +fn every_sample_stays_within_curve_fit() { + for (name, points, closed) in strokes() { + for samples in as_given_and_in_pixels(points) { + for curve_fit in [0.5, 1.0, 2.0, 5.0, 10.0] { + let sp = fit(&samples, curve_fit, closed); + let d = max_deviation(&sp, &samples); + assert!(d <= curve_fit + 0.05, "{name} at Curve Fit {curve_fit}: a sample {d:.3} px away"); + } + } + } +} diff --git a/docs/atn.md b/docs/atn.md index 35281b49f03..85a0c1eb21a 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.