diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47c0dc60c0..922fa9b659 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -206,6 +206,7 @@ jobs: CARGO_PROFILE_TEST_STRIP=symbols PHOTOCRAFT_CI_EXCLUDE=${{ needs.platforms.outputs.linux_skip }} PHOTOCRAFT_CORPUS_TESTS=1 + RAYON_NUM_THREADS=4 timeout-minutes: 100 cache-workspace-crates: true lint-cache: false @@ -347,6 +348,7 @@ jobs: CARGO_NET_RETRY: 10 CARGO_PROFILE_DEV_DEBUG: "0" CARGO_PROFILE_TEST_STRIP: symbols + RAYON_NUM_THREADS: "4" steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 8b741fcb61..742ca5085a 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -279,6 +279,52 @@ pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { img } +/// The surface's own stored channels over `area` as 0–255 levels: `channels()` bytes per pixel, +/// no colour conversion and no reordering. Unlike [`rgba8_image`], which reads the picture as +/// RGB, a Lab surface gives its stored Lightness, a and b and a CMYK surface its four inks, the +/// alpha last when the surface has one. Read in parallel bands like [`rgba8_image`]. +/// +/// The Magic Wand measures a document's Tolerance on these channels for the modes and depths the +/// reference measures it there (#11785), where reading the picture as RGB would measure the +/// Tolerance in a colour space the document is not in. For an 8-bit surface the levels are the +/// stored bytes exactly; a deeper surface is quantized to the 8-bit grid here, so where this is +/// the right read stays the caller's decision. +/// Band rows for the parallel readers of [`stored_levels_planes`]: `read_region_into` hands back +/// f32 samples, so an unrestricted 256-row band stages ~25 MB per worker on a wide multi-channel +/// area (6000 px CMYK: 16 workers × ~24 MB of floats before quantizing). Keep one worker's f32 +/// staging near 2 MB; the u8 output plane is the larger fixed cost either way (#11785 review). +fn levels_band_rows(w: usize, ch: usize) -> usize { + let per_row = (w * ch * 4).max(1); + (2u64 << 20).checked_div(per_row as u64).unwrap_or(256).clamp(16, 256) as usize +} + +pub fn stored_levels_planes(s: &Surface, area: Rect) -> Vec { + let (w, h, ch) = (area.width() as usize, area.height() as usize, s.channels()); + let mut data = vec![0u8; w * h * ch]; + if w == 0 || h == 0 { + return data; + } + let band = levels_band_rows(w, ch); + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let read = |bi: usize, chunk: &mut [u8]| { + let y0 = area.y0 + (bi * band) as i32; + let rows = chunk.len() / (w * ch); + let mut px = Vec::new(); + s.read_region_into(Rect::new(area.x0, y0, area.x1, y0 + rows as i32), &mut px); + for (d, v) in chunk.iter_mut().zip(px) { + *d = q(v); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + data.par_chunks_mut(w * band * ch).enumerate().for_each(|(bi, c)| read(bi, c)); + } + #[cfg(target_arch = "wasm32")] + data.chunks_mut(w * band * ch).enumerate().for_each(|(bi, c)| read(bi, c)); + data +} + /// A selected region: 8-bit coverage over `bbox` (row-major), the bounding box of the pixels /// touched (including the anti-aliased fringe). #[derive(Clone, Debug, PartialEq)] @@ -299,6 +345,38 @@ impl Region { } } +/// Whether a difference of exactly `tolerance` levels still matches a Magic Wand seed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WandBound { + /// A difference of at most `tolerance` levels matches (≤). What the tools that sample the + /// picture as 8-bit RGBA do, and what their Tolerance has always meant. + AtMost, + /// A difference of *below* `tolerance` levels matches (<), with Tolerance 0 and 1 both + /// meaning "the same colour". The wand uses this on a document's own colour channels, where + /// the reference's Tolerance is measured finer than the document's 8-bit grid (#11785: see + /// [`wand_region_on`]). + Below, +} + +/// Integer greatest difference still matching `bound`, in stored levels. +fn wand_max_diff(tolerance: f32, bound: WandBound) -> i32 { + match bound { + WandBound::AtMost => (tolerance + 1e-3).floor().max(0.0) as i32, + // `d < tolerance` on whole levels, so Tolerance 5 keeps differences 0..=4. A NaN or a + // negative Tolerance keeps exactly the same colour rather than selecting nothing, and a + // Tolerance past the scale keeps every difference. + WandBound::Below => { + if tolerance.is_nan() || tolerance <= 1.0 { + 0 + } else if tolerance >= 256.0 { + 255 + } else { + tolerance.ceil() as i32 - 1 + } + } + } +} + /// How a wand-style fill measures how far an 8-bit colour is from the clicked one. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ColorDistance { @@ -320,6 +398,28 @@ impl ColorDistance { } } +/// The most channels the Magic Wand compares at once: a CMYK document's four inks and an alpha. +pub const MAX_WAND_CHANNELS: usize = 5; + +/// The picture the Magic Wand measures its Tolerance on: `channels` stored levels (0–255) per +/// pixel over `area`, with `alpha` the index of the alpha channel when the picture has one. +/// [`rgba8_image`] reads the picture as RGB; [`stored_levels_planes`] gives a document its own +/// colour channels. +#[derive(Clone, Copy, Debug)] +pub struct WandPixels<'a> { + pub area: Rect, + pub data: &'a [u8], + pub channels: usize, + pub alpha: Option, +} + +impl<'a> WandPixels<'a> { + /// Straight 8-bit RGBA over `area`: what [`rgba8_image`] reads, as `w * h * 4` bytes. + pub fn rgba(area: Rect, data: &'a [u8]) -> Self { + Self { area, data, channels: 4, alpha: Some(3) } + } +} + /// Magic wand on 8-bit pixels: a scanline flood fill (or a global match) that only allocates a /// byte mark per pixel, then anti-aliases just the edges inside the touched bounding box. /// Matches [`magic_wand`] for 8-bit sources. `None` if the seed is outside `area`. @@ -542,6 +642,211 @@ fn region_by_rule( Some(Region { bbox, mask }) } +/// How [`wand_region_on`] matches pixels against the clicked one. +#[derive(Clone, Copy, Debug)] +pub struct WandMatch<'a> { + pub tolerance: f32, + pub contiguous: bool, + pub anti_alias: bool, + /// Whether a difference of exactly `tolerance` still matches. + pub bound: WandBound, + /// The selection's coverage over the area, which a contiguous fill stays inside (#11779). + pub within: Option<&'a [f32]>, + /// How an RGBA picture's colour difference is measured; other pictures compare each channel. + pub distance: ColorDistance, + /// The colour every pixel is compared against instead of the clicked pixel's, one level per + /// channel of the picture (the rest ignored): the Magic Wand's Sample Size average (#11777). + /// The clicked pixel must itself be within Tolerance of it, or the fill finds nothing. + pub reference: Option<[u8; MAX_WAND_CHANNELS]>, +} + +impl WandMatch<'_> { + /// A plain match: no selection limit, the largest channel difference. + pub fn new(tolerance: f32, contiguous: bool, anti_alias: bool, bound: WandBound) -> Self { + Self { tolerance, contiguous, anti_alias, bound, within: None, distance: ColorDistance::LargestChannel, reference: None } + } +} + +/// [`wand_region`] over any [`WandPixels`] with the Tolerance bound chosen: RGBA with +/// [`WandBound::AtMost`] is [`wand_region`] itself; [`WandBound::Below`] is how the Magic Wand +/// measures a document's own colour channels (#11785). `None` when the seed is outside the area +/// or the picture is not something the wand can compare. +/// +/// Why the document-channel comparison is exclusive at the bound: the reference measures Tolerance +/// on the document's channels, finer than an 8-bit document stores them. Its Lab row (8-bit +/// document, grey ramp of ten 40 px blocks 100, 105, … 145, click on the 100 block) says +/// Tolerance 5 reaches only the 100 block and Tolerance 32 up to the 130 block, while this +/// document stores Lightness 108, 113, 118, 124, … 153 (L\* / 100 × 255): steps of 0, 5, 10, 16, +/// …, 31, 36 levels, of which 5 (5.2 unrounded) must not match at Tolerance 5 and 31 (30.6) must +/// at Tolerance 32. The re-measured dither-free CMYK ramp (same issue, comment 6705983844) has +/// largest ink steps of 7, 13, 19, 25, 31, 37 from the seed, and its two required cells — +/// Tolerance 5 to x 100-140 and Tolerance 32 to x 100-340 — fall out either way, so the document +/// channels share this one bound. +pub fn wand_region_on(px: &WandPixels, seed: (i32, i32), how: &WandMatch) -> Option { + // RGBA under the inclusive bound is the RGB Magic Wand: it keeps the very fill the Paint + // Bucket and the Magic Eraser share. A generic per-channel fill measured 1.2-1.6x slower on a + // full 24 MP contiguous fill (#11882 review), so only the document channels take it. + if px.channels == 4 && px.alpha == Some(3) && how.bound == WandBound::AtMost { + let (img, _) = px.data.as_chunks::<4>(); + let reference = how.reference.map(|r| [r[0], r[1], r[2], r[3]]); + return region_by_rule(img, px.area, seed, reference, how.tolerance, how.contiguous, how.anti_alias, how.within, how.distance, MatchRule::Wand); + } + if !px.area.contains(seed.0, seed.1) || px.channels == 0 || px.channels > MAX_WAND_CHANNELS { + return None; + } + // One fill per channel count: the comparison runs per pixel over the canvas. + match px.channels { + 1 => wand_fill::<1>(px, seed, how), + 2 => wand_fill::<2>(px, seed, how), + 3 => wand_fill::<3>(px, seed, how), + 4 => wand_fill::<4>(px, seed, how), + _ => wand_fill::<5>(px, seed, how), + } +} + +/// [`wand_region_on`] for `CH` stored channels per pixel, under the wand rule. +fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch) -> Option { + let (contiguous, anti_alias) = (how.contiguous, how.anti_alias); + let (w, h) = (px.area.width() as usize, px.area.height() as usize); + if w.checked_mul(h).is_none_or(|n| n > px.data.len() / CH) { + return None; + } + let within = how.within.filter(|_| how.contiguous).filter(|m| m.len() >= w * h); + let inside = |i: usize| within.is_none_or(|m| m.get(i).is_some_and(|v| *v >= 0.5)); + let seed_i = (seed.1 - px.area.y0) as usize * w + (seed.0 - px.area.x0) as usize; + if !inside(seed_i) { + return None; + } + let so = seed_i * CH; + let mut target = [0u8; CH]; + match how.reference { + Some(r) => target.copy_from_slice(&r[..CH]), + None => target.copy_from_slice(px.data.get(so..so + CH)?), + } + let alpha = px.alpha.filter(|&a| a < CH); + let tol = wand_max_diff(how.tolerance, how.bound); + let rgba = CH == 4 && alpha == Some(3); + // How far pixel `i` is from the clicked one in colour (alpha left out), and the lower of the + // two opacities (0-255; 255 without an alpha channel). + let colour_diff = |i: usize| -> Option<(i32, f32)> { + let v = px.data.get(i * CH..i * CH + CH)?; + let d = if rgba { + how.distance.rgb([v[0], v[1], v[2], v[3]], [target[0], target[1], target[2], target[3]]) + } else { + (0..CH).filter(|&c| Some(c) != alpha).map(|c| (v[c] as i32 - target[c] as i32).abs()).max().unwrap_or(0) + }; + Some((d, alpha.map_or(255.0, |a| f32::from(v[a].min(target[a]))))) + }; + // Copying a selection can leave colour under zero alpha. Those invisible colours must not + // split a transparent region into pieces, as if the copied source were still visible. + let similar = |i: usize| -> bool { + let o = i * CH; + let Some(v) = px.data.get(o..o + CH) else { return false }; + let d = colour_diff(i).map_or(i32::MAX, |(d, _)| d); + let alpha_ok = alpha.is_none_or(|a| (v[a] as i32 - target[a] as i32).abs() <= tol); + alpha.is_some_and(|a| target[a] == 0 && v[a] == 0) || (alpha_ok && d <= tol) + }; + // A clicked pixel that is not similar to the reference starts no region. Without a separate + // reference it is the reference, so this only matters for Sample Size. + if !similar(seed_i) { + return None; + } + let mut marks = vec![0u8; w * h]; + let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); + if contiguous { + // Span fill: fill a run, then scan the rows above and below it for new seeds. + let mut stack = vec![((seed.0 - px.area.x0) as usize, (seed.1 - px.area.y0) as usize)]; + while let Some((x, y)) = stack.pop() { + let row = y * w; + if marks[row + x] != 0 { + continue; + } + let (mut l, mut r) = (x, x); + while l > 0 && marks[row + l - 1] == 0 && similar(row + l - 1) && inside(row + l - 1) { + l -= 1; + } + while r + 1 < w && marks[row + r + 1] == 0 && similar(row + r + 1) && inside(row + r + 1) { + r += 1; + } + marks[row + l..=row + r].fill(255); + (bx0, bx1, by0, by1) = (bx0.min(l), bx1.max(r), by0.min(y), by1.max(y)); + for ny in [y.wrapping_sub(1), y + 1] { + if ny >= h { + continue; + } + let nrow = ny * w; + let mut in_run = false; + for nx in l..=r { + let ok = marks[nrow + nx] == 0 && similar(nrow + nx) && inside(nrow + nx); + if ok && !in_run { + stack.push((nx, ny)); + } + in_run = ok; + } + } + } + } else { + let scan = |y: usize, row: &mut [u8]| -> Option<(usize, usize)> { + let mut span: Option<(usize, usize)> = None; + for (x, m) in row.iter_mut().enumerate() { + if similar(y * w + x) { + *m = 255; + span = Some(span.map_or((x, x), |(a, _)| (a, x))); + } + } + span + }; + #[cfg(not(target_arch = "wasm32"))] + let spans: Vec> = { + use rayon::prelude::*; + marks.par_chunks_mut(w).enumerate().map(|(y, row)| scan(y, row)).collect() + }; + #[cfg(target_arch = "wasm32")] + let spans: Vec> = marks.chunks_mut(w).enumerate().map(|(y, row)| scan(y, row)).collect(); + for (y, sp) in spans.iter().enumerate() { + if let Some((a, b)) = sp { + (bx0, bx1, by0, by1) = (bx0.min(*a), bx1.max(*b), by0.min(y), by1.max(y)); + } + } + } + if bx0 == usize::MAX { + return None; + } + // One pixel of fringe for anti-aliasing, clamped to the area. + let pad = anti_alias as usize; + let (x0, y0) = (bx0.saturating_sub(pad), by0.saturating_sub(pad)); + let (x1, y1) = ((bx1 + 1 + pad).min(w), (by1 + 1 + pad).min(h)); + let bw = x1 - x0; + let at = |x: usize, y: usize| marks[y * w + x]; + let mut mask = vec![0u8; bw * (y1 - y0)]; + let fill_row = |yy: usize, out: &mut [u8]| { + let y = y0 + yy; + for (xx, o) in out.iter_mut().enumerate() { + let x = x0 + xx; + let v = at(x, y); + *o = v; + // Same rule as `magic_wand`: the region stays fully selected; a pixel just outside + // it gets a fringe by how far its colour is past the tolerance. + if anti_alias + && v == 0 + && touches_region(x, y, w, h, |nx, ny| at(nx, ny) != 0) + && let Some((d, a)) = colour_diff(y * w + x) + { + *o = fringe_coverage((d - tol) as f32, a); + } + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + mask.par_chunks_mut(bw).enumerate().for_each(|(yy, row)| fill_row(yy, row)); + } + #[cfg(target_arch = "wasm32")] + mask.chunks_mut(bw).enumerate().for_each(|(yy, row)| fill_row(yy, row)); + let bbox = Rect::new(px.area.x0 + x0 as i32, px.area.y0 + y0 as i32, px.area.x0 + x1 as i32, px.area.y0 + y1 as i32); + Some(Region { bbox, mask }) +} + /// Combines a [`Region`] with the current selection, touching only the region's box (outside it /// the new mask is zero). Returns `None` when nothing remains selected. pub fn combine_region(old: Option<&Surface>, new: Option<&Region>, mode: SelectionMode) -> Option { diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 5f02b53a58..aaa6e1bc41 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -829,3 +829,14 @@ fn color_matcher_tree_reservation_failure_is_reported() { assert_eq!(tree.nodes.len(), ColorBvh::node_count(n)); } } + +#[test] +fn stored_levels_bands_bound_the_f32_staging_on_wide_areas() { + // #11785 review: one parallel reader's f32 staging stays near 2 MB. A 6000 px CMYK strip + // (the Magic Eraser/Wand worst case on 24 MP documents) shrinks from 256 rows to fit; + // narrow areas keep full bands; an absurdly wide one clamps to the 16-row floor. + let rows = levels_band_rows(6000, 4); + assert!(rows >= 16 && 6000 * 4 * 4 * rows <= (2u64 << 20) as usize, "6000 px CMYK band rows: {rows}"); + assert_eq!(levels_band_rows(1, 1), 256, "narrow areas keep full 256-row bands"); + assert_eq!(levels_band_rows(100_000, 5), 16, "an extreme width clamps to the floor"); +} diff --git a/crates/compose/proptest-regressions/cmyk/tests.txt b/crates/compose/proptest-regressions/cmyk/tests.txt index 98770e5156..306ecf2019 100644 --- a/crates/compose/proptest-regressions/cmyk/tests.txt +++ b/crates/compose/proptest-regressions/cmyk/tests.txt @@ -4,4 +4,8 @@ # # It is recommended to check this file in to source control so that # everyone who runs the test benefits from these saved cases. +cc a795914e4492bef1e662315563d48d54f09030c48e046df95329465c86dde4b4 # shrinks to s = Spec { w: 4, h: 6, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [1.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 1.0105422, 0.0, 0.7] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }] } +cc e14b02709a87770da2637c28678c4fa761b5628f402e0c6d60fe66f1aa4d4bfa # shrinks to s = Spec { w: 3, h: 2, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Group { children: [Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 0.3, 0.0, 0.7] }), blend: Dissolve, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.8972109, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } +cc 4eeba1f8db987228717b932b82d043d61e82fd897a33ea9e2ce68d6c61d7f491 # shrinks to s = Spec { w: 3, h: 5, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 0.026626235, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Invert), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } +cc 33fb5c528e97f31669a82a4634930230f903c97e58ce59fc88fd733ac097089c # shrinks to s = Spec { w: 6, h: 4, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 5, y1: 3 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: VividLight, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Text, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: true, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } cc 9cd32fd3b0d418f70a3535174d06eccab73fdd2345cf51e50b53c9f2e006043e # shrinks to s = Spec { w: 2, h: 2, layers: [Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.54360455, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Curves { channel: 2, points: [(0.4490113, 1.0), (1.0, 0.0)] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.6871668, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } diff --git a/crates/compose/proptest-regressions/cmyk_tests.txt b/crates/compose/proptest-regressions/cmyk_tests.txt deleted file mode 100644 index 2498f3013c..0000000000 --- a/crates/compose/proptest-regressions/cmyk_tests.txt +++ /dev/null @@ -1,10 +0,0 @@ -# Seeds for failure cases proptest has generated in the past. It is -# automatically read and these particular cases re-run before any -# novel cases are generated. -# -# It is recommended to check this file in to source control so that -# everyone who runs the test benefits from these saved cases. -cc a795914e4492bef1e662315563d48d54f09030c48e046df95329465c86dde4b4 # shrinks to s = Spec { w: 4, h: 6, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [1.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 1.0105422, 0.0, 0.7] }), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }] } -cc e14b02709a87770da2637c28678c4fa761b5628f402e0c6d60fe66f1aa4d4bfa # shrinks to s = Spec { w: 3, h: 2, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }, Group { children: [Pixels { kind: Adjust(Levels { channel: 0, levels: [0.0, 0.6, 0.3, 0.0, 0.7] }), blend: Dissolve, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.8972109, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } -cc 4eeba1f8db987228717b932b82d043d61e82fd897a33ea9e2ce68d6c61d7f491 # shrinks to s = Spec { w: 3, h: 5, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 0.026626235, clipped: false, visible: true, mask: None }, Pixels { kind: Adjust(Invert), blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 0.0])], opacity: 0.0, fill: 0.0, clipped: false, visible: true, mask: None }], pass_through: true, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } -cc 33fb5c528e97f31669a82a4634930230f903c97e58ce59fc88fd733ac097089c # shrinks to s = Spec { w: 6, h: 4, layers: [Group { children: [Pixels { kind: Raster, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 5, y1: 3 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }, Group { children: [Pixels { kind: Solid, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 1.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: false, visible: true, mask: None }], pass_through: false, blend: VividLight, opacity: 1.0, fill: 1.0, mask: None }, Pixels { kind: Text, blend: Normal, fills: [(Rect { x0: 0, y0: 0, x1: 1, y1: 1 }, [0.0, 0.0, 0.0, 0.0, 1.0])], opacity: 1.0, fill: 1.0, clipped: true, visible: true, mask: None }], pass_through: false, blend: Normal, opacity: 1.0, fill: 1.0, mask: None }] } diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index 58fe9750d8..28619ffaaf 100644 --- a/crates/compose/src/scripted_pattern.rs +++ b/crates/compose/src/scripted_pattern.rs @@ -1,5 +1,6 @@ //! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a -//! plain repeat. Brick Fill and Random Fill paint today; the others extend [`SCRIPTS`], [`controls`] and [`render`] with +//! plain repeat. Brick Fill, Cross Weave and Random Fill paint today; the others extend [`SCRIPTS`], [`controls`] and +//! [`render`] with //! their own layout. //! //! Every script shares the per-tile Color and Brightness randomness ([`Jitter`]): at 0 a tile keeps the pattern's @@ -23,7 +24,7 @@ pub const SCRIPTS: [(&str, &str); 6] = [ ]; /// The scripts that paint today; the rest are listed but answer "not supported yet". -pub const SUPPORTED: [&str; 2] = ["brickFill", "randomFill"]; +pub const SUPPORTED: [&str; 3] = ["brickFill", "crossWeave", "randomFill"]; /// Whether `script` keeps its tiles near the selected path when there is one. pub fn uses_path(script: &str) -> bool { @@ -85,6 +86,15 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option> { Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0), ]) } + "crossWeave" => { + let (lo, hi) = spacing_range(width, height); + Some(vec![ + Control::new("patternScale", 1.0, 0.1, 1.25, 2), + Control::new("spacing", 0.0, lo, hi, 0), + Control::new("colorRandomness", 0.05, 0.0, 1.0, 2), + Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), + ]) + } "randomFill" => Some(vec![ Control::new("density", 2.0, 0.1, 10.0, 1), Control::new("minimumScaleFactor", 0.5, 0.1, 3.0, 2), @@ -150,9 +160,44 @@ pub struct BrickFill { } /// Most tiles composited into one pixel, front to back: bounds the work of extreme overlaps. Only a pixel whose -/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. +/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. A tile that is +/// transparent at the pixel does not count, so it cannot use up the limit before the tiles that show there. const MAX_LAYERS: usize = 1024; +/// Most tiles looked at for one pixel, transparent there or not: the work bound when many overlapping tiles are clear +/// at that pixel (a mostly transparent pattern at the largest overlap). +const MAX_VISITS: usize = 16 * MAX_LAYERS; + +/// A repeatable value for tile `(row, col)` from `seed`, independent of the colour drift. +fn tile_bits(seed: u64, row: i64, col: i64) -> u64 { + let mut z = (seed ^ 0xD6E8_FEB8_6659_FD93) + .wrapping_add((row as u64).wrapping_mul(0xA076_1D64_78BD_642F)) + .wrapping_add((col as u64).wrapping_mul(0xE703_7ED1_A0B4_28DB)); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Adds tile colour `q`, drifted by `d`, behind what `acc` already holds (front to back: what is in front covers it). +fn blend_behind(acc: &mut [f32; 4], mut q: [f32; 4], d: [f32; 3]) { + // Without a drift a tile keeps its exact colour, also a float one past 1. + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + let k = q[3] * (1.0 - acc[3]); + for ch in 0..3 { + acc[ch] += q[ch] * k; + } + acc[3] += k; +} + +/// The straight colour of a front-to-back sum; transparent where no tile covered the pixel. +fn finish(acc: [f32; 4]) -> [f32; 4] { + if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)] } else { [0.0; 4] } +} + /// The x range where the convex polygon `corners` (in order) meets the line at height `y`, if it does. fn span(corners: &[(f64, f64); 4], y: f64) -> Option<(f64, f64)> { let mut range: Option<(f64, f64)> = None; @@ -210,7 +255,7 @@ impl BrickFill { for x in rect.x0..rect.x1 { let px = f64::from(x) + 0.5; let mut acc = [0.0f32; 4]; - let mut layers = 0; + let (mut layers, mut visits) = (0, 0); 'rows: for row in (low_row..=top_row).rev() { // Only the tiles of this row whose centre lies in the turned rectangle around the pixel cover it. let Some((lo, hi)) = span(&corners, row as f64 * pitch_y + th / 2.0 - py) else { continue }; @@ -218,7 +263,7 @@ impl BrickFill { let right = ((px + hi + row_shift - tw / 2.0) / pitch_x).floor() as i64; let left = ((px + lo + row_shift - tw / 2.0) / pitch_x).ceil() as i64; for col in (left..=right).rev() { - if layers >= MAX_LAYERS || acc[3] >= 1.0 { + if layers >= MAX_LAYERS || visits >= MAX_VISITS || acc[3] >= 1.0 { break 'rows; } let place = placement(row, col); @@ -226,26 +271,106 @@ impl BrickFill { if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { continue; } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } layers += 1; - let mut q = tile.sample_area(&place, px, py); - let d = self.jitter.offsets(row, col); - // Without a drift a tile keeps its exact colour, also a float one past 1. - for ch in 0..3 { - if d[ch] != 0.0 { - q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); - } - } - // Front to back: what is already in front covers this tile. - let k = q[3] * (1.0 - acc[3]); - for ch in 0..3 { - acc[ch] += q[ch] * k; - } - acc[3] += k; + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); } } - if acc[3] > 0.0 { - out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)]; + out[i] = finish(acc); + i += 1; + } + } + out + } +} + +/// Cross Weave: a basket weave on a square grid of cells, each as wide as the mean of the tile's sides plus the spacing. +/// The cells alternate like a checkerboard between the tile lying flat and the tile turned a quarter (the origin cell), +/// every tile centred half its longer side right of and below its cell's corner, so a 40 x 30 tile leaves a 5 x 5 hole +/// at every 35 px grid point. Each tile is also turned half way or not at random (flat ones lie at 0° or 180°, upright +/// ones at 90° either way), as in the reference result with no colour randomness. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrossWeave { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels between neighbouring tiles; negative overlaps them. + pub spacing: f64, + pub jitter: Jitter, +} + +impl CrossWeave { + /// Whether cell `(row, col)` holds the tile turned a quarter. + pub fn upright(row: i64, col: i64) -> bool { + (row + col).rem_euclid(2) == 0 + } + + /// The tiles of a `width` x `height` pattern woven over `rect` (row-major straight RGBA, transparent in the holes). + /// Later tiles (down, then right) lie over earlier ones where they overlap. + pub fn render(&self, tile: &Tile, width: u32, height: u32, rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + // At the f32 precision the placement maps with, so the tile bounds here are the ones it samples. + let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 }; + let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale); + if len == 0 || tw <= 0.0 || th <= 0.0 { + return out; + } + let spacing = if self.spacing.is_finite() { self.spacing } else { 0.0 }; + // At least a pixel between cells, so every layout ends. + let pitch = ((tw + th) / 2.0 + spacing).max(1.0); + // A tile's centre lies this far right of and below its cell's corner, and reaches at most this far from it. + let reach = tw.max(th) / 2.0; + let centre = |i: i64| i as f64 * pitch + reach; + let placement = |row: i64, col: i64| { + let quarter = if Self::upright(row, col) { 90.0 } else { 0.0 }; + let angle: f64 = quarter + if tile_bits(self.jitter.seed, row, col) & 1 == 1 { 180.0 } else { 0.0 }; + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + // The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise). + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (centre(col) + hx * c + hy * s, centre(row) - hx * s + hy * c); + Placement::anchored(origin, true, (0.0, 0.0), scale as f32, angle as f32) + }; + let mut i = 0; + for y in rect.y0..rect.y1 { + let py = f64::from(y) + 0.5; + // Rows and columns whose tiles can reach this pixel, the last drawn (topmost) first. + let top_row = (py / pitch).floor() as i64; + let low_row = ((py - 2.0 * reach) / pitch).ceil() as i64; + for x in rect.x0..rect.x1 { + let px = f64::from(x) + 0.5; + let right = (px / pitch).floor() as i64; + let left = ((px - 2.0 * reach) / pitch).ceil() as i64; + let mut acc = [0.0f32; 4]; + let (mut layers, mut visits) = (0, 0); + 'rows: for row in (low_row..=top_row).rev() { + for col in (left..=right).rev() { + if layers >= MAX_LAYERS || visits >= MAX_VISITS || acc[3] >= 1.0 { + break 'rows; + } + // A flat tile reaches half its width across and half its height down; an upright one the other way. + let (ax, ay) = if Self::upright(row, col) { (th / 2.0, tw / 2.0) } else { (tw / 2.0, th / 2.0) }; + if (px - centre(col)).abs() > ax || (py - centre(row)).abs() > ay { + continue; + } + let place = placement(row, col); + let (u, v) = place.map(px, py); + if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { + continue; + } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } + layers += 1; + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); + } } + out[i] = finish(acc); i += 1; } } @@ -278,6 +403,7 @@ pub fn render( }; Some(brick.render(tile, width, height, rect)) } + "crossWeave" => Some(CrossWeave { scale: value("patternScale"), spacing: value("spacing"), jitter }.render(tile, width, height, rect)), "randomFill" => { let random = RandomFill { density: value("density"), diff --git a/crates/engine-core/src/adjust_params.rs b/crates/engine-core/src/adjust_params.rs index 930d47c3f8..e7050d4e2b 100644 --- a/crates/engine-core/src/adjust_params.rs +++ b/crates/engine-core/src/adjust_params.rs @@ -103,8 +103,9 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color _ => (0.0, 0.0, false), }; let legacy = r.boolean("legacy", l0)?; - let (lo, hi) = if legacy { (-100.0, 100.0) } else { (-50.0, 100.0) }; - Adjustment::BrightnessContrast { brightness: r.num("brightness", b0, -150.0, 150.0)?, contrast: r.num("contrast", c0, lo, hi)?, legacy } + // Use Legacy narrows Brightness to −100..100 and widens Contrast to −100..100. + let (b_lo, b_hi, c_lo) = if legacy { (-100.0, 100.0, -100.0) } else { (-150.0, 150.0, -50.0) }; + Adjustment::BrightnessContrast { brightness: r.num("brightness", b0, b_lo, b_hi)?, contrast: r.num("contrast", c0, c_lo, 100.0)?, legacy } } "threshold" => { let l0 = match base { @@ -1301,3 +1302,6 @@ pub fn user_keys(p: &Value) -> Map { #[cfg(test)] mod tests; + +#[cfg(test)] +mod brightness_contrast_limits_tests; diff --git a/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs b/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs new file mode 100644 index 0000000000..36e4278bae --- /dev/null +++ b/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs @@ -0,0 +1,28 @@ +//! Brightness/Contrast limits with and without Use Legacy (#14350). + +use super::*; + +fn brightness(p: Value, base: Option<&Adjustment>) -> f32 { + match from_params("brightnessContrast", &p, base, ColorMode::Rgb).unwrap() { + Adjustment::BrightnessContrast { brightness, .. } => brightness, + other => panic!("not Brightness/Contrast: {other:?}"), + } +} + +#[test] +fn a_legacy_brightness_past_100_is_held_at_the_limit() { + assert_eq!(brightness(json!({"brightness": 150, "legacy": true}), None), 100.0); + assert_eq!(brightness(json!({"brightness": -999, "legacy": true}), None), -100.0); +} + +#[test] +fn modern_brightness_keeps_its_wider_range() { + assert_eq!(brightness(json!({"brightness": 150}), None), 150.0); + assert_eq!(brightness(json!({"brightness": -150}), None), -150.0); +} + +#[test] +fn turning_legacy_on_over_a_modern_brightness_past_100_holds_it_at_the_limit() { + let modern = from_params("brightnessContrast", &json!({"brightness": 130}), None, ColorMode::Rgb).unwrap(); + assert_eq!(brightness(json!({"legacy": true}), Some(&modern)), 100.0); +} diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index f78d32f82b..b3897b2184 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -850,19 +850,30 @@ pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { if s.color().settings.working_gray != default_gray.id() || document_profile(&st.doc).content_hash() != default_gray.profile().content_hash() { return c; } - let opts = craft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; - let Ok(t) = craft_cms::cached(&working_profile(ColorMode::Rgb), &Arc::new(target.profile().clone()), opts) else { return c }; - let mut out = [0.0f32; 16]; - if t.eval(&[c[0], c[1], c[2]], &mut out).is_err() { - return c; + swatch_to_gray(target, c).unwrap_or(c) +} + +/// A swatch colour's gray with the sRGB tone curve (sGray), the conversion [`swatch_in_doc`] makes in a Grayscale +/// document, as equal R, G and B. None outside the default Working Gray (Dot Gain 20 %) or when the conversion fails. +pub fn swatch_sgray(s: &Session, c: [f32; 4]) -> Option<[f32; 4]> { + if s.color().settings.working_gray != Builtin::DotGain20Compat.id() { + return None; } + swatch_to_gray(Builtin::SGray, c) +} + +/// A swatch colour converted to the gray profile `target` (relative colorimetric with black point compensation), as +/// equal R, G and B; None when the conversion fails. +fn swatch_to_gray(target: Builtin, c: [f32; 4]) -> Option<[f32; 4]> { + let opts = craft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let t = craft_cms::cached(&working_profile(ColorMode::Rgb), &Arc::new(target.profile().clone()), opts).ok()?; + let mut out = [0.0f32; 16]; + t.eval(&[c[0], c[1], c[2]], &mut out).ok()?; let g = out[0]; - if g.is_finite() { + g.is_finite().then(|| { let g = g.clamp(0.0, 1.0); [g, g, g, c[3]] - } else { - c - } + }) } /// The gray [`swatch_in_doc`] converts swatches to: sGray in Grayscale, gamma 2.2 in 8-bit Monotone. diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index 07fcdf4f03..d3835c136a 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -53,7 +53,16 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { let sel = selected(s); let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Align", |doc, _| { + // The History state is named after the entry (#18283). + let name = match edge { + Edge::Top => "Align Top Edges", + Edge::VCenter => "Align Vertical Centers", + Edge::Bottom => "Align Bottom Edges", + Edge::Left => "Align Left Edges", + Edge::HCenter => "Align Horizontal Centers", + Edge::Right => "Align Right Edges", + }; + let moved = s.edit(name, |doc, _| { let items = bounded_selection(doc, &sel); if items.is_empty() { return Err(EngineError::Other("the selected layers have no content to align".into())); @@ -160,3 +169,7 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { })?; Ok(json!({"moved": moved})) } + +#[cfg(test)] +#[path = "align_history_names_tests.rs"] +mod align_history_names_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs new file mode 100644 index 0000000000..f6c762c433 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs @@ -0,0 +1,103 @@ +//! #18283: each Layer › Align entry leaves one History state named after the entry, such as "Align Left Edges", +//! with and without a pixel selection, instead of "Align" for all six. A run that a position-locked layer refuses +//! records no state. The Distribute entries were not measured and keep their name. + +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// The command's last id segment and the History state the reference application records for it. +const NAMES: [(&str, &str); 6] = [ + ("topEdges", "Align Top Edges"), + ("verticalCenters", "Align Vertical Centers"), + ("bottomEdges", "Align Bottom Edges"), + ("leftEdges", "Align Left Edges"), + ("horizontalCenters", "Align Horizontal Centers"), + ("rightEdges", "Align Right Edges"), +]; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + s +} + +/// A new pixel layer with an opaque rectangle. +fn rect_layer(s: &mut Session, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +/// Two layers that share no edge and no centre, so every Align entry moves one of them. +fn two_layers(s: &mut Session) -> [LayerId; 2] { + [rect_layer(s, Rect::new(10, 5, 20, 15)), rect_layer(s, Rect::new(40, 30, 70, 60))] +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +#[test] +fn each_align_entry_names_its_one_history_state() { + for (kind, name) in NAMES { + // Several layers, aligned to each other. + let mut s = session(); + let layers = two_layers(&mut s); + select(&mut s, &layers); + let states = history(&s).0; + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some(name.to_string())), "{kind}"); + // One layer, aligned to a pixel selection. + let mut s = session(); + rect_layer(&mut s, Rect::new(10, 5, 20, 15)); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); + let states = history(&s).0; + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some(name.to_string())), "{kind} to a selection"); + } +} + +#[test] +fn a_run_refused_by_a_position_locked_layer_records_no_state() { + for all in [false, true] { + let mut s = session(); + let layers = two_layers(&mut s); + // Top Edges has to move the lower rectangle, which is locked: Lock position, then Lock all. + s.edit("lock", |doc, _| { + let locks = &mut doc.layer_mut(layers[1]).unwrap().locks; + (locks.position, locks.all) = (true, all); + Ok(()) + }) + .unwrap(); + select(&mut s, &layers); + let before = history(&s); + assert!(s.execute("layer.align.topEdges", json!({})).is_err(), "lock all: {all}"); + assert_eq!(history(&s), before, "lock all: {all}"); + } +} + +/// Not measured, so it keeps the name it had. +#[test] +fn distribute_keeps_its_name() { + let mut s = session(); + let layers = [rect_layer(&mut s, Rect::new(0, 0, 10, 10)), rect_layer(&mut s, Rect::new(20, 30, 30, 40)), rect_layer(&mut s, Rect::new(80, 60, 90, 70))]; + select(&mut s, &layers); + s.execute("layer.distribute.leftEdges", json!({})).unwrap(); + assert_eq!(history(&s).1.as_deref(), Some("Distribute")); +} diff --git a/crates/engine-core/src/cmd/selection_cmds.rs b/crates/engine-core/src/cmd/selection_cmds.rs index 96bb5f3481..4af971c7f7 100644 --- a/crates/engine-core/src/cmd/selection_cmds.rs +++ b/crates/engine-core/src/cmd/selection_cmds.rs @@ -19,6 +19,8 @@ mod color_range_performance; #[cfg(test)] mod color_range_window_tests; #[cfg(test)] +mod wand_color_mode_tests; +#[cfg(test)] mod wand_sample_size_tests; #[cfg(test)] mod wand_seed_outside_tests; @@ -138,6 +140,59 @@ pub fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[u8; 4]> } } +/// The Magic Wand's picture in a document's own colour channels (#11785): the stored levels of +/// the active layer, `channels` of them per pixel with the alpha last. +struct DocumentChannels { + area: Rect, + levels: Vec, + channels: usize, + alpha: Option, +} + +impl DocumentChannels { + fn pixels(&self) -> sel::WandPixels<'_> { + sel::WandPixels { area: self.area, data: &self.levels, channels: self.channels, alpha: self.alpha } + } +} + +/// What the wand measures its Tolerance on: the picture as 8-bit RGBA, or a document's own +/// stored colour channels with the bound that goes with them. +enum WandPicture { + Rgba(Rect, Vec<[u8; 4]>), + Channels(DocumentChannels), +} + +/// The Magic Wand's sampling in an 8-bit Lab or CMYK document's own colour channels (#11785); +/// `None` when the wand samples the picture as 8-bit RGBA, as before. +/// +/// The reference measures the wand's Tolerance on the channels a document is in, on a grey ramp +/// of ten 40 px blocks (100, 105, … 145) clicked on the 100 block, with Anti-alias off: +/// +/// - Lab 8-bit: Tolerance 5 reaches only the 100 block and Tolerance 32 up to the 130 block, +/// while the RGB picture (steps of 5) reaches x 100-180 and x 100-380. +/// - CMYK 8-bit: Tolerance 5 reaches x 100-140 and Tolerance 32 x 100-340; the largest of the +/// four ink differences is what counts (#11785's re-measured, dither-free ramp and the ink +/// table in its comment 6705983844, which the tests fill directly so no profile is involved). +/// +/// The rest of the table keeps today's sampling, because that is what it says: RGB and Grayscale +/// documents at 8, 16 and 32 bits, Lab and CMYK documents at 16 and 32 bits and Sample All Layers +/// are all marked *not measured* there. +fn wand_document_channels(s: &Session, all_layers: bool) -> Option { + let d = s.active()?; + if all_layers || d.doc.depth != photocraft_doc::SampleType::U8 || !matches!(d.doc.mode, photocraft_doc::ColorMode::Lab | photocraft_doc::ColorMode::Cmyk) { + return None; + } + let surf = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface())?; + let fmt = surf.format(); + // The layer has to hold the document's model at 8 bits, and the wand compares at most four + // colour channels and an alpha; anything else samples as the RGB picture. + if fmt.mode != d.doc.mode || fmt.sample != photocraft_doc::SampleType::U8 || fmt.channels() > sel::MAX_WAND_CHANNELS { + return None; + } + let area = d.doc.bounds(); + Some(DocumentChannels { area, levels: sel::stored_levels_planes(surf, area), channels: fmt.channels(), alpha: fmt.alpha.then_some(fmt.channels() - 1) }) +} + /// The Magic Wand's `sampleSize` param: 1 (Point Sample, the default) or the side of the /// averaged square, one of `sample_cmds::SAMPLE_SIZES`. fn wand_sample_size(p: &Value) -> Result { @@ -153,22 +208,27 @@ fn wand_sample_size(p: &Value) -> Result { } /// The Sample Size reference colour: the average of the `size` by `size` square around the -/// clicked pixel (clipped to `area`), weighted by alpha so transparent pixels don't pull it, -/// with the clicked pixel's own alpha. `None` for Point Sample, a seed outside `area`, or a -/// square with nothing opaque in it (the clicked pixel then stays the reference). -fn wand_average(img: &[[u8; 4]], area: Rect, (x, y): (i32, i32), size: u32) -> Option<[u8; 4]> { - if size <= 1 || !area.contains(x, y) { +/// clicked pixel (clipped to the picture), weighted by alpha so transparent pixels don't pull it, +/// with the clicked pixel's own alpha. Averaged in whatever channels the wand measures (RGB, or a +/// Lab or CMYK document's own). `None` for Point Sample, a seed outside the picture, or a square +/// with nothing opaque in it (the clicked pixel then stays the reference). +fn wand_average(px: &sel::WandPixels, (x, y): (i32, i32), size: u32) -> Option<[u8; sel::MAX_WAND_CHANNELS]> { + let (area, ch) = (px.area, px.channels); + if size <= 1 || !area.contains(x, y) || ch == 0 || ch > sel::MAX_WAND_CHANNELS { return None; } let square = crate::sample_cmds::sample_rect(f64::from(x), f64::from(y), size, area)?; let w = area.width() as usize; - let at = |px: i32, py: i32| img.get((py - area.y0) as usize * w + (px - area.x0) as usize).copied(); - let (mut sum, mut weight) = ([0u64; 3], 0u64); - for py in square.y0..square.y1 { - for px in square.x0..square.x1 { - let Some(p) = at(px, py) else { continue }; - let a = u64::from(p[3]); - for c in 0..3 { + let at = |qx: i32, qy: i32| { + let i = ((qy - area.y0) as usize * w + (qx - area.x0) as usize) * ch; + px.data.get(i..i + ch) + }; + let (mut sum, mut weight) = ([0u64; sel::MAX_WAND_CHANNELS], 0u64); + for qy in square.y0..square.y1 { + for qx in square.x0..square.x1 { + let Some(p) = at(qx, qy) else { continue }; + let a = px.alpha.map_or(255, |a| u64::from(p[a])); + for c in (0..ch).filter(|&c| Some(c) != px.alpha) { sum[c] += u64::from(p[c]) * a; } weight += a; @@ -176,34 +236,49 @@ fn wand_average(img: &[[u8; 4]], area: Rect, (x, y): (i32, i32), size: u32) -> O } let seed = at(x, y)?; (weight > 0).then(|| { - let avg = sum.map(|v| ((v + weight / 2) / weight).min(255) as u8); - [avg[0], avg[1], avg[2], seed[3]] + let mut out = [0u8; sel::MAX_WAND_CHANNELS]; + for (c, o) in out.iter_mut().enumerate().take(ch) { + *o = if Some(c) == px.alpha { seed[c] } else { ((sum[c] + weight / 2) / weight).min(255) as u8 }; + } + out }) } fn magic_wand(s: &mut Session, p: &Value) -> Result { let (x, y) = (f(p, "x", 0.0).floor() as i32, f(p, "y", 0.0).floor() as i32); let size = wand_sample_size(p)?; - let (area, img) = match shown_gray(s) { - Some(plane) => plane, - None => sample_rgba8(s, b(p, "sampleAllLayers", false))?, + let all_layers = b(p, "sampleAllLayers", false); + // What the Tolerance is measured on: a mask or alpha plane shown as the picture, else the + // document's own channels where the reference measures them there (#11785), else the 8-bit + // RGBA `sample_rgba8` also hands the Paint Bucket and the Magic Eraser. + let picture = match shown_gray(s) { + Some((area, img)) => WandPicture::Rgba(area, img), + None => match wand_document_channels(s, all_layers) { + Some(d) => WandPicture::Channels(d), + None => { + let (area, img) = sample_rgba8(s, all_layers)?; + WandPicture::Rgba(area, img) + } + }, + }; + let (pixels, bound) = match &picture { + WandPicture::Rgba(area, img) => (sel::WandPixels::rgba(*area, img.as_flattened()), sel::WandBound::AtMost), + WandPicture::Channels(d) => (d.pixels(), sel::WandBound::Below), }; // Sample Size: the fill compares against the square's average instead of the clicked pixel; // the image itself stays as it is. - let reference = wand_average(&img, area, (x, y), size); + let reference = wand_average(&pixels, (x, y), size); let m = mode(p); // Subtract and Intersect grow the region from the seed through the selection only (#11779). // A global match (Contiguous off) ignores the limit, so it skips the full-area mask. let contiguous = b(p, "contiguous", true); let within = (contiguous && matches!(m, SelectionMode::Subtract | SelectionMode::Intersect)) - .then(|| s.active().and_then(|st| st.doc.selection.as_ref()).map(|sel| sel::mask_from_surface(Some(sel), area))) + .then(|| s.active().and_then(|st| st.doc.selection.as_ref()).map(|sel| sel::mask_from_surface(Some(sel), pixels.area))) .flatten(); - let (tolerance, anti_alias) = (f(p, "tolerance", 32.0), b(p, "antiAlias", true)); - let region = match reference { - Some(reference) => sel::wand_region_with_reference(&img, area, (x, y), reference, tolerance, contiguous, anti_alias, within.as_deref()), - None => sel::wand_region_within(&img, area, (x, y), tolerance, contiguous, anti_alias, within.as_deref()), - }; - drop(img); + let how = + sel::WandMatch { within: within.as_deref(), reference, ..sel::WandMatch::new(f(p, "tolerance", 32.0), contiguous, b(p, "antiAlias", true), bound) }; + let region = sel::wand_region_on(&pixels, (x, y), &how); + drop(picture); let selected = s.edit("Magic Wand", |doc, _| { doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m); Ok(doc.selection.is_some()) @@ -800,7 +875,7 @@ pub fn specs() -> Vec { "select.magicWand", "Magic Wand", [], - r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"sampleSize":1|3|5|11|31|51|101=1,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture; sampleSize 1 is Point Sample, else the side of the averaged square)"##, + r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"sampleSize":1|3|5|11|31|51|101=1,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture; an 8-bit Lab or CMYK document with sampleAllLayers off measures it on the active layer's own stored channels: Lightness/a/b, or the four inks with the largest difference counting; sampleAllLayers samples the RGB composite; sampleSize 1 is Point Sample, else the side of the averaged square)"##, has_doc, magic_wand ), diff --git a/crates/engine-core/src/cmd/selection_cmds/wand_color_mode_tests.rs b/crates/engine-core/src/cmd/selection_cmds/wand_color_mode_tests.rs new file mode 100644 index 0000000000..73618bd8eb --- /dev/null +++ b/crates/engine-core/src/cmd/selection_cmds/wand_color_mode_tests.rs @@ -0,0 +1,285 @@ +//! The Magic Wand's Tolerance in the document's own colour channels (#11785). +//! +//! The fixtures are the reference's tests. The grey ramp is ten 40 px blocks (grey 100, 105, … +//! 145) from x 100, clicked on the 100 block, with Contiguous on; the CMYK row is the re-measured +//! dither-free ramp, filled block by block with the reference's own ink levels so no colour +//! profile sits between the fixture and the assertion (#11785 comment 6705983844). +//! +//! The reference reads the reached range off the selection bounds in x and counts the block it +//! stops on, so a range is written here as `lo..hi` with `hi` one past the last selected column: +//! one 40 px block at x 100 is `100..140`, which is the table's "x 100-140". Anti-alias is off in +//! these tests: with it on the wand adds its one-pixel soft fringe to the bounds, which is the +//! same in every mode and not what the table measures. + +use super::*; +use photocraft_doc::{ColorMode, SampleType}; + +const W: i32 = 500; +const H: i32 = 8; +const X0: i32 = 100; +const BLOCK: i32 = 40; + +/// The reference's dither-free CMYK ramp: the ink levels (0-255) of the ten grey blocks, in the +/// order Cyan, Magenta, Yellow, Black. +const INKS: [[u8; 4]; 10] = [ + [111, 138, 139, 169], + [114, 141, 143, 176], + [117, 144, 145, 182], + [121, 148, 149, 188], + [124, 150, 152, 194], + [127, 154, 155, 200], + [131, 158, 158, 206], + [135, 161, 161, 210], + [139, 164, 164, 215], + [143, 167, 167, 220], +]; + +/// The grey at block `k` of the ramp. +fn grey(k: u8) -> u8 { + 100 + 5 * k +} + +/// The ramp document: painted as grey in an RGB document, then converted to `mode` by its Image +/// › Mode command (the reference's "Lab document" and "CMYK document" rows), or left as the +/// `create` mode (its RGB and Grayscale rows). +fn ramp(create: &str, depth: u32, mode: Option<&str>) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": W, "height": H, "mode": create, "depth": depth})).unwrap(); + paint_ramp(&mut s, &|k| { + let v = grey(k) as f32 / 255.0; + [v, v, v, 1.0, 1.0] + }); + if let Some(cmd) = mode { + s.execute(cmd, json!({})).unwrap(); + } + s +} + +/// An 8-bit CMYK document with each block filled directly with its ink from [`INKS`]: one fill +/// per block, so the blocks are uniform and no conversion or dither is involved (#11785). +fn ink_ramp() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": 8})).unwrap(); + paint_ramp(&mut s, &|k| { + let mut v = [1.0f32; 5]; + v[..4].copy_from_slice(&INKS[usize::from(k)].map(|x| f32::from(x) / 255.0)); + v + }); + s +} + +/// Fill the ten blocks across the canvas with one colour each, `pixel` of block `k` as the +/// surface's own channels (a CMYK surface has five, an RGB one four; the extra is ignored). A +/// grey surface has two, grey and alpha: it gets the first value and the fourth (the alpha), so +/// the ramp stays opaque. +fn paint_ramp(s: &mut Session, pixel: &dyn Fn(u8) -> [f32; 5]) { + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + let n = bg.channels().min(5); + for k in 0..10u8 { + let v = pixel(k); + let v: &[f32] = if n == 2 { &[v[0], v[3]] } else { &v[..n] }; + bg.fill_rect(Rect::new(X0 + BLOCK * i32::from(k), 0, X0 + BLOCK * (i32::from(k) + 1), H), v); + } + Ok(()) + }) + .unwrap(); +} + +/// Click block 0 with `tolerance`. +fn wand(s: &mut Session, tolerance: f32) { + s.execute("select.magicWand", json!({"x": X0 + 5, "y": 1, "tolerance": tolerance, "contiguous": true, "antiAlias": false})).unwrap(); +} + +/// The x-range the selection covers, as `lo..hi` (`hi` one past the last selected column), or +/// `None` when the click selected nothing. +fn reach(s: &Session) -> Option<(i32, i32)> { + let mask = s.active()?.doc.selection.as_ref()?; + let (mut lo, mut hi) = (i32::MAX, i32::MIN); + for x in 0..W { + if mask.sample_channel(x, 1, 0) > 0.0 { + lo = lo.min(x); + hi = hi.max(x); + } + } + (lo <= hi).then(|| (lo, hi + 1)) +} + +/// The levels the background layer stores for the ramp, one per block, in `channel` of the +/// document's own colour model. +fn stored(s: &Session, channel: usize) -> Vec { + let surf = s.active().unwrap().doc.layers[0].surface().unwrap(); + (0..10u8).map(|k| ((surf.pixel(X0 + BLOCK * i32::from(k) + 5, 1)[channel]) * 255.0).round() as u8).collect() +} + +/// #11785: in an 8-bit Lab document the wand measures Tolerance on the document's Lightness, a +/// and b, not on the RGB it shows. +#[test] +fn lab_document_measures_tolerance_in_its_own_channels() { + let mut s = ramp("rgb", 8, Some("image.mode.lab")); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Lab); + assert_eq!(s.active().unwrap().doc.depth, SampleType::U8); + // The ramp as this document stores it: Lightness 108, 113, 118, 124, … 153 (L* / 100 × 255), + // a and b neutral. Steps from the seed: 0, 5, 10, 16, 21, 26, 31, 36, 41, 45 levels. + assert_eq!(stored(&s, 0), [108, 113, 118, 124, 129, 134, 139, 144, 149, 153], "the Lightness the ramp is stored at"); + assert_eq!(stored(&s, 1), [128; 10], "neutral a"); + assert_eq!(stored(&s, 2), [128; 10], "neutral b"); + + // The two measured rows of #11785's table. + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 140)), "Tolerance 5 reaches only the 100 block, not the 105 one"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 380)), "Tolerance 32 reaches the 130 block, not the 135 one"); + + // Derived from the same table, and what says the comparison happens in Lab rather than only + // at a different bound: on the RGB picture (100, 105, … 145, steps of 5) Tolerance 16 reaches + // the 115 block (x 100-260); on the Lightness steps above, where that step is 16 levels and + // does not match, it stops after the 120 block. + wand(&mut s, 16.0); + assert_eq!(reach(&s), Some((100, 220)), "Tolerance 16 stops after a 16-level Lightness step"); + + // Tolerance 0 and 1 both mean the same colour: the clicked block, and nothing beside it. + for tolerance in [0.0, 1.0] { + wand(&mut s, tolerance); + assert_eq!(reach(&s), Some((100, 140)), "Tolerance {tolerance} keeps the same colour"); + } + + // Without Contiguous the same Lab measure applies wherever it is on the canvas. + s.execute("select.magicWand", json!({"x": X0 + 5, "y": 1, "tolerance": 32.0, "contiguous": false, "antiAlias": false})).unwrap(); + assert_eq!(reach(&s), Some((100, 380))); +} + +/// Sample Size (#11777) in an 8-bit Lab document averages the document's own channels too, so +/// the reference colour sits between the stored Lightness levels of the blocks it covers. +#[test] +fn lab_document_averages_sample_size_in_its_own_channels() { + // The last column of the 100 block (Lightness 108), next to the 105 block (113). Tolerance 4 + // keeps differences up to 3 levels: the clicked pixel alone reaches only its own block. + let click = |s: &mut Session, size: u32| { + s.execute("select.magicWand", json!({"x": X0 + BLOCK - 1, "y": 1, "tolerance": 4.0, "sampleSize": size, "antiAlias": false})).unwrap(); + reach(s) + }; + let mut s = ramp("rgb", 8, Some("image.mode.lab")); + let point = click(&mut s, 1); + assert_eq!(point, Some((100, 140)), "Point Sample stops before the 5-level Lightness step"); + // The 3 by 3 square holds two columns of 108 and one of 113: Lightness 110, within reach of + // both blocks. + let average = click(&mut s, 3); + assert!(average.is_some_and(|(lo, hi)| lo == 100 && hi > 140), "the Lightness average reaches the next block: {average:?}"); +} + +/// #11785 as re-measured without dither: in an 8-bit CMYK document the wand measures Tolerance on +/// the document's inks, and the largest of the four differences is what counts. +#[test] +fn cmyk_document_measures_tolerance_on_the_largest_ink_difference() { + let mut s = ink_ramp(); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Cmyk); + assert_eq!(s.active().unwrap().doc.depth, SampleType::U8); + // The blocks hold the reference's levels exactly: filled one colour per block, not converted. + assert_eq!(stored(&s, 0), INKS.iter().map(|ink| ink[0]).collect::>(), "cyan"); + assert_eq!(stored(&s, 1), INKS.iter().map(|ink| ink[1]).collect::>(), "magenta"); + assert_eq!(stored(&s, 2), INKS.iter().map(|ink| ink[2]).collect::>(), "yellow"); + assert_eq!(stored(&s, 3), INKS.iter().map(|ink| ink[3]).collect::>(), "black"); + + // The largest ink difference from the 100 block is 7, 13, 19, 25, 31, 37, 41, 46, 51 levels + // (Black moves most), so Tolerance 5 stops after the first block and Tolerance 32 reaches the + // 125 block: the two cells #11785's "Done when" asks for. + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 140)), "Tolerance 5 stops before the 7-level ink step"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 340)), "Tolerance 32 reaches the 31-level block, not the 37-level one"); + + // Tolerance 0 keeps the same inks; the RGB picture of these blocks would step only 5 levels + // to the next block, so these two ranges are the inks' and not the picture's. + wand(&mut s, 0.0); + assert_eq!(reach(&s), Some((100, 140)), "Tolerance 0 keeps the same inks"); + s.execute("select.magicWand", json!({"x": X0 + 5, "y": 1, "tolerance": 32.0, "contiguous": false, "antiAlias": false})).unwrap(); + assert_eq!(reach(&s), Some((100, 340)), "the same ink measure without Contiguous"); +} + +/// The same ink measure on an 8-bit CMYK document converted from grey with the working profile. +/// Its inks are not the reference's, but the rule is: Black moves most, by 9, 17, 25, 32, 38 … +/// levels, so Tolerance 32 stops one block earlier than the RGB picture would. +#[test] +fn a_converted_cmyk_document_measures_the_same_ink_difference() { + let mut s = ramp("rgb", 8, Some("image.mode.cmyk")); + assert_eq!(stored(&s, 0), [95, 96, 97, 97, 97, 96, 95, 94, 93, 91], "cyan"); + assert_eq!(stored(&s, 3), [81, 72, 64, 56, 49, 43, 36, 31, 25, 20], "black"); + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 140)), "converted CMYK, Tolerance 5"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 260)), "converted CMYK, Tolerance 32 stops at the 32-level ink step"); +} + +/// #11785's unchanged rows: RGB documents keep the selection they make today, at every depth. +#[test] +fn rgb_documents_keep_measuring_tolerance_in_rgb() { + for depth in [8u32, 16, 32] { + let mut s = ramp("rgb", depth, None); + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 180)), "rgb {depth}: Tolerance 5 reaches 100 and 105"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 380)), "rgb {depth}: Tolerance 32 reaches the 130 block"); + } +} + +/// #11785's unchanged rows: Grayscale documents, at every depth. +#[test] +fn grayscale_documents_keep_their_selection_at_every_depth() { + for depth in [8u32, 16, 32] { + let mut s = ramp("gray", depth, None); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Grayscale); + let bg = s.active().unwrap().doc.layers[0].surface().unwrap(); + for k in 0..10 { + assert_eq!(bg.rgba(X0 + BLOCK * k + 1, 1)[3], 1.0, "gray {depth}: block {k} is opaque"); + } + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 180)), "gray {depth}"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 380)), "gray {depth}"); + } +} + +/// Lab and CMYK above 8 bits are marked *not measured* in #11785, so they keep today's sampling. +/// If those rows get measured, this is the test to change with them. +#[test] +fn documents_above_8_bits_keep_todays_sampling() { + for (cmd, name, tol5, tol32) in [("image.mode.lab", "lab", (100, 180), (100, 380)), ("image.mode.cmyk", "cmyk", (100, 140), (100, 380))] { + for depth in [16u32, 32] { + let mut s = ramp("rgb", depth, Some(cmd)); + assert_eq!(s.active().unwrap().doc.depth, if depth == 16 { SampleType::U16 } else { SampleType::F32 }); + // The Lab Lightness is 108.06, 113.26, …, so a Lab comparison would stop as in 8-bit; + // today's RGB sampling reaches the 105 block at Tolerance 5 instead, and stays. + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some(tol5), "{name} {depth} keeps today's Tolerance 5 reach"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some(tol32), "{name} {depth} keeps today's Tolerance 32 reach"); + } + } +} + +/// The shared sampler the Paint Bucket, the Magic Eraser and the Background Eraser go through is +/// untouched: both document modes still hand it the RGB picture, and Sample All Layers keeps the +/// RGB composite for the wand too. +#[test] +fn the_shared_rgba8_sample_path_still_reads_rgb() { + let s = ramp("rgb", 8, Some("image.mode.lab")); + let (area, img) = sample_rgba8(&s, false).unwrap(); + let at = |k: u8| img[(X0 + BLOCK * i32::from(k) + 5 - area.x0) as usize]; + for k in 0..10u8 { + assert_eq!(at(k)[0], grey(k), "block {k} still samples as RGB for the other tools"); + assert_eq!(at(k)[1], grey(k)); + assert_eq!(at(k)[2], grey(k)); + assert_eq!(at(k)[3], 255); + } + assert!(wand_document_channels(&s, false).is_some(), "the wand's own Lab route is in use here"); + assert!(wand_document_channels(&s, true).is_none(), "Sample All Layers is not measured, so it keeps the RGB composite"); + + let s = ink_ramp(); + let (area, img) = sample_rgba8(&s, false).unwrap(); + let seed = img[(X0 + 5 - area.x0) as usize]; + assert_ne!(seed[..4].to_vec(), INKS[0].to_vec(), "the other tools sample the CMYK picture as RGB, not as inks"); + assert_eq!(seed[3], 255); + assert!(wand_document_channels(&s, false).is_some(), "the wand's own ink route is in use here"); + assert!(wand_document_channels(&s, true).is_none(), "and not with Sample All Layers"); +} diff --git a/crates/engine-core/src/cmd/web_cmds.rs b/crates/engine-core/src/cmd/web_cmds.rs index 624250e509..27949e27d3 100644 --- a/crates/engine-core/src/cmd/web_cmds.rs +++ b/crates/engine-core/src/cmd/web_cmds.rs @@ -14,7 +14,7 @@ use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind}; use photocraft_doc::slices::{self, ResolvedSlice, SliceKind}; -use photocraft_doc::{DocId, Document, LayerContent, LayerId}; +use photocraft_doc::{ColorMode, DocId, Document, LayerContent, LayerId, SampleType}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -65,6 +65,15 @@ pub fn specs() -> Vec { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } + fn save_for_web_enabled(s: &Session) -> std::result::Result<(), String> { + let doc = &s.active().ok_or("no document open")?.doc; + match (doc.mode, doc.depth) { + (ColorMode::Multichannel, _) => Err("Save for Web is unavailable in Multichannel mode".into()), + (_, SampleType::F32) => Err("Save for Web is unavailable for 32-bit documents".into()), + _ => Ok(()), + } + } + /// Generate ▸ Image Assets needs Preferences ▸ Plug-ins ▸ Enable Generator, as in /// Photoshop (where "Enable Generator" is unchecked until turned on). fn generator_enabled(s: &Session) -> std::result::Result<(), String> { @@ -81,7 +90,7 @@ pub fn specs() -> Vec { &["File", "Export"], Some("Cmd+Alt+Shift+S"), r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user|selected"="all" (selected requires numbers when the document has slices),"numbers":[n]? (slice numbers, each an existing slice; chooses the slices whatever the mode; with `path` or `folder` alone on a document with slices, refused: use `dir`)} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, - has_doc, + save_for_web_enabled, save_for_web ), spec!( @@ -117,3 +126,6 @@ pub fn specs() -> Vec { #[cfg(test)] #[path = "web_cmds/tests.rs"] mod tests; + +#[cfg(test)] +mod save_for_web_enabled_tests; diff --git a/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs b/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs index 0c25ce0d24..49a9b2eb19 100644 --- a/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs @@ -44,7 +44,7 @@ fn exported_palette_edits_work_at_every_document_depth() { for depth in [8, 16, 32] { let mut s = session(depth); let mut p = json!({"format": "gif", "colors": 16, "dither": "none"}); - let estimate = s.execute("file.export.saveForWebLegacy", p.clone()).unwrap(); + let estimate = save_for_web_at_any_depth(&mut s, p.clone()).unwrap(); let table = estimate["colorTable"].as_array().unwrap(); let red = table.iter().position(|c| c == "#ff0000").unwrap(); p["colorTable"] = estimate["colorTable"].clone(); @@ -52,7 +52,7 @@ fn exported_palette_edits_work_at_every_document_depth() { let path = format!("{dir}/{depth}.gif"); p["path"] = json!(path); let original_doc = s.active().unwrap().doc.clone(); - s.execute("file.export.saveForWebLegacy", p).unwrap(); + save_for_web_at_any_depth(&mut s, p).unwrap(); assert_eq!(s.active().unwrap().doc, original_doc, "export must not edit the document"); let img = decode(&path).convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); assert_eq!(&img.data()[(16 * 64 + 16) * 4..(16 * 64 + 16) * 4 + 4], &[0, 255, 0, 255]); diff --git a/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs b/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs new file mode 100644 index 0000000000..cd131b527b --- /dev/null +++ b/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs @@ -0,0 +1,81 @@ +use super::*; + +const COMMAND: &str = "file.export.saveForWebLegacy"; + +fn document(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s +} + +fn assert_refused(s: &mut Session, reason: &str) { + let attempted = s.execute(COMMAND, json!({})); + assert!(!s.is_enabled(COMMAND), "expected a disabled command for {reason}, got {attempted:?}"); + assert!(matches!(&attempted, Err(EngineError::Disabled(id, why)) if id == COMMAND && why.contains(reason)), "{attempted:?}"); +} + +fn assert_available(s: &mut Session) { + let doc = &s.active().unwrap().doc; + assert!(s.is_enabled(COMMAND), "Save for Web is available for {:?} at {:?}", doc.mode, doc.depth); + let estimate = s.execute(COMMAND, json!({})).unwrap(); + assert!(estimate["bytes"].as_u64().is_some_and(|bytes| bytes > 0), "{estimate}"); +} + +#[test] +fn save_for_web_no_document_is_refused() { + assert_refused(&mut crate::session(), "no document open"); +} + +#[test] +fn save_for_web_float_documents_are_refused() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + let mut s = document(mode, 32); + assert_eq!(s.active().unwrap().doc.depth, SampleType::F32); + assert_refused(&mut s, "32-bit"); + } +} + +#[test] +fn save_for_web_multichannel_documents_are_refused_at_both_integer_depths() { + for depth in [8, 16] { + let mut s = document("rgb", depth); + s.execute("image.mode.multichannel", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.mode, ColorMode::Multichannel); + assert_eq!(doc.depth.bits(), depth); + assert_refused(&mut s, "Multichannel"); + } +} + +#[test] +fn save_for_web_reenables_after_conversion_from_float_with_layers() { + let mut s = document("rgb", 8); + s.execute("layer.new.layer", json!({})).unwrap(); + for integer_depth in ["image.mode.bits16", "image.mode.bits8"] { + s.execute("image.mode.bits32", json!({})).unwrap(); + assert_refused(&mut s, "32-bit"); + s.execute(integer_depth, json!({})).unwrap(); + assert_available(&mut s); + } +} + +#[test] +fn save_for_web_integer_documents_keep_their_estimates() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for depth in [8, 16] { + assert_available(&mut document(mode, depth)); + } + } + for (source, expected, command, params) in [ + ("rgb", ColorMode::Indexed, "image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})), + ("gray", ColorMode::Bitmap, "image.mode.bitmap", json!({"method": "threshold"})), + ] { + let mut s = document(source, 8); + s.execute(command, params).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, expected); + assert_available(&mut s); + s.execute("image.mode.bits16", json!({})).unwrap(); + assert_eq!((s.active().unwrap().doc.mode, s.active().unwrap().doc.depth), (expected, SampleType::U16)); + assert_available(&mut s); + } +} diff --git a/crates/engine-core/src/cmd/web_cmds/tests.rs b/crates/engine-core/src/cmd/web_cmds/tests.rs index 6ed5a39ec7..0dcf8438b7 100644 --- a/crates/engine-core/src/cmd/web_cmds/tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/tests.rs @@ -211,13 +211,18 @@ fn platform_writer_failure_stops_export_and_preserves_saved_settings() { assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved)); } +// Float-depth regression tests still exercise the encoder below the command's availability rule. +fn save_for_web_at_any_depth(s: &mut Session, params: Value) -> Result { + if s.active().unwrap().doc.depth == SampleType::F32 { save_for_web(s, ¶ms) } else { s.execute("file.export.saveForWebLegacy", params) } +} + #[test] fn estimates_every_format_at_every_depth() { for depth in [8, 16, 32] { let mut s = session(depth); let mut sizes = Vec::new(); for f in ["gif", "png8", "png24", "jpeg", "wbmp", "webp"] { - let r = s.execute("file.export.saveForWebLegacy", json!({"format": f, "colors": 16})).unwrap(); + let r = save_for_web_at_any_depth(&mut s, json!({"format": f, "colors": 16})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(64), Some(48)), "{f}"); assert!(r["bytes"].as_u64().unwrap() > 20, "{f}"); if f == "gif" || f == "png8" { diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index a3bd65ff9f..58db1b71ad 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -6,7 +6,7 @@ //! Every parameter is validated: a bad one is an error, never a panic. use photocraft_algo::content_aware::FillOptions; -use photocraft_color::{BlendMode, ColorMode}; +use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_geom::Rect; #[cfg(test)] use photocraft_geom::TILE_SIZE; @@ -155,9 +155,19 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { "Fill with History needs a source of the document's colour mode and bit depth: set a matching source in the History panel".into(), )); } - let src = crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) - .map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()))?; - Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?) + match crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) { + Ok(src) => Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?), + // A pixel layer the source state lacks (a new, duplicated or flattened layer) counts as transparent + // there, as in the reference application; the Background (after Flatten Image) takes white, not the + // background colour (#17465). Masks and channels the source lacks stay an error. + Err(_) + if let Some(lid) = + id.filter(|&l| crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels && source_doc.layer(l).is_none()) => + { + Source::Color(if st.doc.is_background(lid) { [1.0; 4] } else { [0.0; 4] }) + } + Err(_) => return Err(EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into())), + } } "contentAware" => { let sel = sel.as_ref().ok_or_else(|| EngineError::Other("Content-Aware fill needs a selection".into()))?; @@ -178,6 +188,15 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(format!("unknown contents `{contents}`"))), }; + // A colour filled into the Quick Mask of a Grayscale, CMYK or Lab document becomes its grey through the grey + // profile, as the reference writes it: (200,30,30) gives 104, not the RGB weights' 81 (#17487). + let source = match source { + Source::Color(c) | Source::Cmyk { rgba: c, .. } if matches!(contents, "foreground" | "background" | "color") => match quick_mask_gray(s, p, c) { + Some(g) => Source::Color(g), + None => source, + }, + source => source, + }; if area.is_empty() { return Ok(out); } @@ -222,7 +241,7 @@ fn scripted( lines: Option<&[photocraft_compose::scripted_pattern::Polyline]>, ) -> Result> { use photocraft_compose::scripted_pattern::{SUPPORTED, controls, render}; - let unsupported = || bad(format!("the `{script}` script is not supported yet; only {} paint today", SUPPORTED.join(" and "))); + let unsupported = || bad(format!("the `{script}` script is not supported yet; only {} paint today", SUPPORTED.join(", "))); let controls = controls(script, pat.width, pat.height).ok_or_else(unsupported)?; let mut values = std::collections::HashMap::new(); for c in &controls { @@ -271,6 +290,21 @@ fn check_quick_mask(contents: &str, mode: BlendMode, preserve: bool) -> Result<( Ok(()) } +/// The grey a colour takes in the Quick Mask of an 8- or 16-bit Grayscale, CMYK or Lab document (the Grayscale +/// document's own swatch grey). None elsewhere: RGB documents keep the RGB weights, and 32-bit documents and the +/// other modes, which were not measured, keep them too. +fn quick_mask_gray(s: &Session, p: &Value, c: [f32; 4]) -> Option<[f32; 4]> { + let doc = &s.active()?.doc; + if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::QuickMask || doc.depth == SampleType::F32 { + return None; + } + match doc.mode { + ColorMode::Grayscale => Some(crate::color_cmds::swatch_in_doc(s, c)), + ColorMode::Cmyk | ColorMode::Lab => crate::color_cmds::swatch_sgray(s, c), + _ => None, + } +} + /// A fill colour: the inks it was picked as when it was picked as CMYK (#4196), else plain sRGB. fn color_source(s: &Session, c: [f32; 4], role: usize) -> Source { match s.tools.picked_role_cmyk(role) { @@ -303,6 +337,14 @@ mod grayscale_color_tests; #[cfg(test)] mod duotone_grey_value_tests; +#[cfg(test)] +#[path = "../fill_quick_mask_mode_gray_tests.rs"] +mod fill_quick_mask_mode_gray_tests; + #[cfg(test)] #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; + +#[cfg(test)] +#[path = "../fill_history_missing_layer_tests.rs"] +mod fill_history_missing_layer_tests; diff --git a/crates/engine-paint/src/fill_history_missing_layer_tests.rs b/crates/engine-paint/src/fill_history_missing_layer_tests.rs new file mode 100644 index 0000000000..b34f5551eb --- /dev/null +++ b/crates/engine-paint/src/fill_history_missing_layer_tests.rs @@ -0,0 +1,147 @@ +//! Edit › Fill with History on a pixel layer the source state does not have: the layer counts as +//! transparent there, so the selection is cleared (white on a layer without transparency, as after +//! Flatten Image), as one "Fill" state. Masks and channels the source lacks keep refusing (#17465). + +use serde_json::{Value, json}; + +use crate::Session; + +const TRANSPARENT: [f32; 4] = [0.0; 4]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const WHITE: [f32; 4] = [1.0; 4]; + +/// The issue's document: `Paint` with red at 0,0-200,150 and 50 % blue at 200,0-400,150 on a +/// transparent (or white Background) canvas, no selection. Returns the session and the History +/// panel row of the finished setup, the source the fills read. +fn issue_document(white: bool) -> (Session, usize) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "background": if white { "white" } else { "transparent" }})).unwrap(); + if white { + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + } + rect(&mut s, [0, 0, 200, 150], "#ff0000", 100); + rect(&mut s, [200, 0, 200, 150], "#0000ff", 50); + s.execute("select.deselect", json!({})).unwrap(); + let row = steps(&s); + (s, row) +} + +fn rect(s: &mut Session, [x, y, width, height]: [i32; 4], color: &str, opacity: u32) { + s.execute("select.rect", json!({"x": x, "y": y, "width": width, "height": height})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color, "opacity": opacity})).unwrap(); +} + +fn select_issue_rect(s: &mut Session) { + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +/// The active layer's pixel at (`x`, `y`). +fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) +} + +/// A History fill from `row` succeeds as one "Fill" state. +fn history_fill(s: &mut Session, row: usize, case: &str) { + let before = steps(s); + s.execute("edit.fill", json!({"contents": "history", "state": row})).unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(steps(s), before + 1, "{case}: one state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fill"), "{case}"); +} + +/// The selected area is cleared to `inside`, the rest keeps `outside`. +fn assert_cleared(s: &Session, inside: [f32; 4], outside: [f32; 4], case: &str) { + let (a, b) = (px(s, 150, 100), px(s, 50, 20)); + assert!(near(a, inside), "{case}: inside the selection {a:?}"); + assert!(near(b, outside), "{case}: outside the selection {b:?}"); +} + +#[test] +fn a_new_empty_layer_stays_transparent() { + let (mut s, row) = issue_document(false); + s.execute("layer.new.layer", json!({"name": "New"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "new layer"); + assert_cleared(&s, TRANSPARENT, TRANSPARENT, "new layer"); +} + +#[test] +fn a_duplicated_layer_is_cleared_inside_the_selection() { + let (mut s, row) = issue_document(false); + s.execute("layer.duplicate", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "duplicate"); + assert_cleared(&s, TRANSPARENT, GREEN, "duplicate"); +} + +#[test] +fn a_layer_added_after_the_source_layer_was_deleted_is_cleared() { + let (mut s, row) = issue_document(false); + let paint = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "New"})).unwrap(); + let new = s.active().unwrap().active_layer.unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + s.execute("layer.select", json!({"layer": paint.0})).unwrap(); + s.execute("layer.delete", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": new.0})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "Paint deleted"); + assert_cleared(&s, TRANSPARENT, GREEN, "Paint deleted"); +} + +/// Measured on both variants: after Flatten Image the selected area of the Background turns white, +/// whatever the background colour; the rest keeps the flattened pixels. +#[test] +fn after_flatten_image_the_background_takes_white() { + for white in [false, true] { + let (mut s, row) = issue_document(white); + s.execute("tools.setColors", json!({"background": "#0ac81e"})).unwrap(); + s.execute("layer.flattenImage", json!({})).unwrap(); + select_issue_rect(&mut s); + let case = format!("flatten, white background {white}"); + history_fill(&mut s, row, &case); + assert_cleared(&s, WHITE, RED, &case); + } +} + +/// A layer the source has keeps today's result: back to its pixels in that state. +#[test] +fn a_layer_the_source_has_is_restored() { + let (mut s, row) = issue_document(false); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "Paint"); + assert_cleared(&s, RED, GREEN, "Paint"); +} + +/// Not measured, so as before: a layer mask, an alpha channel or the Quick Mask the source lacks +/// is refused, adding no state and changing nothing. +#[test] +fn masks_channels_and_the_quick_mask_keep_refusing() { + let mut cases: Vec<(&str, Session, usize, Value)> = Vec::new(); + let (mut s, row) = issue_document(false); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + cases.push(("layer mask", s, row, json!("mask"))); + let (mut s, row) = issue_document(false); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + cases.push(("alpha channel", s, row, json!({"channel": 0}))); + let (mut s, row) = issue_document(false); + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + cases.push(("Quick Mask", s, row, json!("quickMask"))); + for (what, mut s, row, target) in cases { + let (doc, before) = (s.active().unwrap().doc.clone(), steps(&s)); + assert!(s.execute("edit.fill", json!({"contents": "history", "state": row, "target": target})).is_err(), "{what}"); + assert_eq!(steps(&s), before, "{what}: no state"); + assert!(s.active().unwrap().doc == doc, "{what}: nothing changed"); + } +} diff --git a/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs b/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs new file mode 100644 index 0000000000..c7c301dd9d --- /dev/null +++ b/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs @@ -0,0 +1,94 @@ +//! #17487: a colour filled into the Quick Mask of a Grayscale, CMYK or Lab document becomes its grey through the grey +//! profile, as the reference writes it: (200,30,30) gives 104 and (0,255,0) 219 (Lab 220), not the RGB weights' 81 +//! and 150. RGB documents keep 81 / 150; alpha channels and pixel layers keep what they wrote before. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [f32; 4] = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + +/// A white 40×20 document of `mode` at `depth` bits, in Quick Mask mode, with (200,30,30) as both swatches. +fn session(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.tools.foreground = RED; + s.tools.background = RED; + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + s +} + +fn quick_mask_level(s: &Session) -> i32 { + let q = s.active().unwrap().doc.quick_mask.as_ref().expect("in Quick Mask mode").surface.sample_channel(30, 10, 0); + (q * 255.0).round() as i32 +} + +/// The Quick Mask level after running `cmd` with `params` in a fresh document. +fn filled(mode: &str, depth: u32, cmd: &str, params: Value) -> i32 { + let mut s = session(mode, depth); + s.execute(cmd, params).unwrap(); + quick_mask_level(&s) +} + +fn foreground() -> Value { + json!({"contents": "foreground"}) +} + +fn green() -> Value { + json!({"contents": "color", "color": "#00ff00"}) +} + +#[test] +fn gray_cmyk_and_lab_quick_masks_take_the_grey_profile_value() { + for (mode, want_green) in [("grayscale", 219), ("cmyk", 219), ("lab", 220)] { + let red = filled(mode, 8, "edit.fill", foreground()); + assert!((red - 104).abs() <= 1, "{mode}/8 Foreground (200,30,30): {red}, reference 104"); + let green = filled(mode, 8, "edit.fill", green()); + assert!((green - want_green).abs() <= 1, "{mode}/8 Color (0,255,0): {green}, reference {want_green}"); + } +} + +#[test] +fn rgb_quick_masks_keep_the_rgb_weights() { + for depth in [8, 16, 32] { + let red = filled("rgb", depth, "edit.fill", foreground()); + let green = filled("rgb", depth, "edit.fill", green()); + assert_eq!((red, green), (81, 150), "RGB/{depth}"); + } +} + +#[test] +fn background_color_and_the_fill_keys_give_the_same_grey() { + for mode in ["grayscale", "cmyk", "lab"] { + let want = filled(mode, 8, "edit.fill", foreground()); + for (cmd, params) in [ + ("edit.fill", json!({"contents": "background"})), + ("edit.fill", json!({"contents": "color", "color": "#c81e1e"})), + ("edit.fillForeground", json!({})), + ("edit.fillBackground", json!({})), + ] { + let got = filled(mode, 8, cmd, params.clone()); + assert!((got - want).abs() <= 1, "{mode} {cmd} {params}: {got}, Foreground gives {want}"); + } + } +} + +#[test] +fn black_and_white_stay_exact_in_the_quick_mask() { + for mode in ["grayscale", "cmyk", "lab"] { + assert_eq!(filled(mode, 8, "edit.fill", json!({"contents": "color", "color": "#000000"})), 0, "{mode} black"); + assert_eq!(filled(mode, 8, "edit.fill", json!({"contents": "color", "color": "#ffffff"})), 255, "{mode} white"); + } +} + +#[test] +fn an_alpha_channel_keeps_the_rgb_weights() { + // Only the Quick Mask was measured; a targeted alpha channel keeps what it wrote before. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": 8, "background": "white"})).unwrap(); + s.tools.foreground = RED; + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("edit.fill", foreground()).unwrap(); + let a = s.active().unwrap().doc.channels[0].surface.sample_channel(30, 10, 0); + assert_eq!((a * 255.0).round() as i32, 81); +} diff --git a/crates/engine-paint/src/fill_script_brick_tests.rs b/crates/engine-paint/src/fill_script_brick_tests.rs index ac23ea8fbb..48f671a58d 100644 --- a/crates/engine-paint/src/fill_script_brick_tests.rs +++ b/crates/engine-paint/src/fill_script_brick_tests.rs @@ -1,6 +1,6 @@ //! #17428: Edit › Fill › Pattern with Script on lays the pattern out tile by tile. `edit.fill` takes `script` and the //! script's values; Brick Fill paints rows of whole tiles from the canvas origin with every second row shifted left by -//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the four +//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the //! listed scripts without a layout yet answer "not supported". use serde_json::{Value, json}; @@ -163,7 +163,7 @@ fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() { let before = undo_label(&s); let err = s.execute("edit.fill", brick(json!({"script": "noSuchScript"}))).unwrap_err().to_string(); assert!(err.contains("unknown script"), "{err}"); - for script in ["crossWeave", "placeAlongPath", "spiral", "symmetryFill"] { + for script in ["placeAlongPath", "spiral", "symmetryFill"] { let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string(); assert!(err.contains("not supported"), "{script}: {err}"); } diff --git a/crates/engine-paint/src/fill_script_cross_weave_tests.rs b/crates/engine-paint/src/fill_script_cross_weave_tests.rs new file mode 100644 index 0000000000..6eb091b61d --- /dev/null +++ b/crates/engine-paint/src/fill_script_cross_weave_tests.rs @@ -0,0 +1,277 @@ +//! #17429: the Cross Weave script of Edit › Fill › Pattern weaves the pattern tile in a basket weave. With a 40 x 30 +//! tile the cells are 35 px: flat and upright tiles alternate like a checkerboard (the origin cell upright) and leave a +//! transparent 5 x 5 hole at every grid point (x, y = 0, 35, 70, ...). Each tile is turned half way or not at random. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const GREEN: [u8; 3] = [0, 255, 0]; + +/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green. +fn define_probe(s: &mut Session, mode: &str, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] { + s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap(); +} + +/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined. +fn session_in(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + define_probe(&mut s, mode, depth); + s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn session() -> Session { + session_in("rgb", 8) +} + +/// Cross Weave with both randomness values at 0 and `extra` values on top. +fn weave(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "crossWeave", "colorRandomness": 0, "brightnessRandomness": 0}); + for (k, v) in extra.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p +} + +fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn rgb8(px: [f32; 4]) -> [u8; 3] { + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +fn undo_label(s: &Session) -> Option { + s.active().unwrap().history.undo_label().map(str::to_string) +} + +/// Whether the tile in the `w` x `h` box at (`x0`, `y0`) is red over half of its long side, split across the long side: +/// a flat tile is red in its left or right half, an upright one in its top or bottom half. +fn red_half(s: &Session, x0: i32, y0: i32, w: i32, h: i32) -> Option<&'static str> { + let red = |x: i32, y: i32| rgb8(pixel(s, x, y)) == RED; + let all = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| red(x, y))); + let none = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| !red(x, y))); + let (a, b) = + if w > h { ((x0..x0 + w / 2, y0..y0 + h), (x0 + w / 2..x0 + w, y0..y0 + h)) } else { ((x0..x0 + w, y0..y0 + h / 2), (x0..x0 + w, y0 + h / 2..y0 + h)) }; + if all(a.0.clone(), a.1.clone()) && none(b.0.clone(), b.1.clone()) { + Some("first") + } else if none(a.0, a.1) && all(b.0, b.1) { + Some("second") + } else { + None + } +} + +#[test] +fn cross_weave_leaves_a_transparent_hole_at_every_grid_point() { + let mut s = session(); + let r = s.execute("edit.fill", weave(json!({}))).unwrap(); + assert_eq!(r["script"], "crossWeave"); + for gy in (0..400).step_by(35) { + for gx in (0..600).step_by(35) { + // The 5 x 5 hole itself, and painted pixels right after it on both sides. + for (dx, dy) in [(0, 0), (4, 0), (0, 4), (4, 4), (2, 2)] { + if gx + dx < 600 && gy + dy < 400 { + assert_eq!(pixel(&s, gx + dx, gy + dy)[3], 0.0, "hole at ({}, {})", gx + dx, gy + dy); + } + } + for (x, y) in [(gx + 5, gy + 2), (gx + 2, gy + 5)] { + if x < 600 && y < 400 { + assert!(pixel(&s, x, y)[3] > 0.99, "painted beside the hole at ({x}, {y})"); + } + } + } + } + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "the measured hole sample"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn flat_and_upright_tiles_alternate_like_a_checkerboard() { + let mut s = session(); + s.execute("edit.fill", weave(json!({}))).unwrap(); + let (mut turned, mut upright_turned) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for row in 0..10 { + for col in 0..16 { + let (x, y) = (35 * col, 35 * row); + let (upright, side) = if (row + col) % 2 == 0 { + // Upright, 30 x 40: from 5 px right of the cell corner, down into the next cell. + (true, red_half(&s, x + 5, y, 30, 40)) + } else { + // Flat, 40 x 30: from the cell corner, 5 px below it, into the next cell. + (false, red_half(&s, x, y + 5, 40, 30)) + }; + let side = side.unwrap_or_else(|| panic!("cell ({row}, {col}) holds a whole {} tile", if upright { "upright" } else { "flat" })); + if upright { &mut upright_turned } else { &mut turned }.insert(side); + } + } + // Both ways round occur among flat and among upright tiles (the half turn is random per tile). + assert_eq!(turned.len(), 2, "flat tiles at 0° and 180°"); + assert_eq!(upright_turned.len(), 2, "upright tiles at 90° both ways"); + // The other colours sit in the tile's other half: blue and green in the origin cell's upright tile. + let other: Vec<[u8; 3]> = [(10, 2), (30, 2), (10, 37), (30, 37)].iter().map(|&(x, y)| rgb8(pixel(&s, x, y))).collect(); + assert!(other.contains(&BLUE) && other.contains(&GREEN), "{other:?}"); +} + +#[test] +fn the_weave_differs_from_the_plain_and_the_brick_fill() { + let mut plain = session(); + plain.execute("edit.fill", json!({"contents": "pattern", "pattern": "probe"})).unwrap(); + let mut brick = session(); + brick.execute("edit.fill", weave(json!({"script": "brickFill"}))).unwrap(); + let mut woven = session(); + woven.execute("edit.fill", weave(json!({}))).unwrap(); + for other in [&plain, &brick] { + assert!(pixel(other, 2, 2)[3] > 0.99, "the other fills cover the origin"); + } + assert_eq!(pixel(&woven, 2, 2)[3], 0.0, "the weave leaves its hole there"); +} + +#[test] +fn the_same_seed_weaves_the_same_tiles() { + let mut a = session(); + a.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut b = session(); + b.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut c = session(); + c.execute("edit.fill", weave(json!({"seed": 8}))).unwrap(); + let samples = |s: &Session| (0..10).flat_map(|r| (0..16).map(move |c| (35 * c + 15, 35 * r + 20))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + assert_eq!(samples(&a), samples(&b)); + assert_ne!(samples(&a), samples(&c), "another seed turns other tiles"); +} + +#[test] +fn spacing_and_scale_move_the_tiles() { + // Spacing 10 leaves a 10 px gap between the origin cell's upright tile (x 5-34) and the flat one beside it. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": 10}))).unwrap(); + assert!(pixel(&s, 34, 20)[3] > 0.99, "the upright tile"); + assert_eq!(pixel(&s, 40, 20)[3], 0.0, "the gap"); + assert!(pixel(&s, 45, 20)[3] > 0.99, "the flat tile after the gap"); + // Half the scale halves the tile and the cell: 2.5 px holes on a 17.5 px grid, so (35, 35) is still a hole. + let mut s = session(); + s.execute("edit.fill", weave(json!({"patternScale": 0.5}))).unwrap(); + assert_eq!(pixel(&s, 35, 35)[3], 0.0); + assert!(pixel(&s, 38, 3)[3] > 0.99, "a full-size weave has a hole here, the half-size one a tile"); + // Overlapping tiles close the holes. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": -10}))).unwrap(); + for (x, y) in [(2, 2), (37, 37), (72, 37)] { + assert!(pixel(&s, x, y)[3] > 0.99, "no hole at ({x}, {y})"); + } +} + +#[test] +fn randomness_varies_tiles_only_above_zero() { + let mut drift = session(); + drift.execute("edit.fill", weave(json!({"colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap(); + let mut exact = session(); + exact.execute("edit.fill", weave(json!({}))).unwrap(); + let colours = + |s: &Session| (0..400).step_by(7).flat_map(|y| (0..600).step_by(7).map(move |x| (x, y))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + let pure = [RED, BLUE, GREEN, [0, 0, 0]]; + assert!(colours(&exact).iter().all(|c| pure.contains(c)), "at 0 every tile keeps the pattern's colours"); + assert!(colours(&drift).iter().any(|c| !pure.contains(c)), "above 0 the tiles drift"); +} + +#[test] +fn the_fill_stays_in_the_selection_with_mode_and_opacity() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + s.execute("edit.fill", weave(json!({"opacity": 50}))).unwrap(); + let inside = pixel(&s, 10, 10); + assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}"); + assert_eq!(pixel(&s, 150, 10)[3], 0.0, "outside the selection"); + assert_eq!(pixel(&s, 10, 80)[3], 0.0, "below the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "one history state"); + // Multiply over red paint keeps red only where the weave is red or transparent. + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.fill", weave(json!({"mode": "multiply"}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 2, 2)), RED, "the hole leaves the red paint"); + let blue_or_green = (0..600).step_by(5).any(|x| rgb8(pixel(&s, x, 10)) == [0, 0, 0]); + assert!(blue_or_green, "multiplying red by blue or green gives black"); +} + +#[test] +fn bad_values_are_errors_and_extreme_ones_never_hang_or_panic() { + let mut s = session(); + for bad in [json!({"patternScale": "big"}), json!({"spacing": [1]}), json!({"seed": -1}), json!({"colorRandomness": true})] { + assert!(s.execute("edit.fill", weave(bad.clone())).is_err(), "{bad}"); + } + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "nothing filled"); + for extreme in [ + json!({"patternScale": 1e9}), + json!({"patternScale": -5}), + json!({"spacing": -1e12}), + json!({"spacing": 1e12}), + json!({"colorRandomness": 1e9, "brightnessRandomness": -1e9}), + json!({"seed": u64::MAX}), + // Offset and angle belong to Brick Fill; Cross Weave ignores them. + json!({"offsetBetweenRows": 75, "patternRotateAngle": 45}), + ] { + let mut s = session(); + s.execute("edit.fill", weave(extreme.clone())).unwrap_or_else(|e| panic!("{extreme}: {e}")); + } +} + +#[test] +fn a_long_thin_tile_reaches_far_from_its_centre() { + // A 4000 x 4 tile at the largest overlap: 2000 px cells, each tile reaching 2000 px from its centre. The flat tile + // of cell (-1, 0) lies along the top edge, the upright one of cell (-1, -1) along the left edge. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap(); + s.execute("file.new", json!({"width": 300, "height": 200, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", weave(json!({"pattern": "bar", "spacing": -2}))).unwrap(); + for (x, y) in [(150, 1), (299, 0), (1, 100), (0, 199)] { + let px = pixel(&s, x, y); + assert!(px[3] > 0.99 && rgb8(px) == RED, "({x}, {y}): {px:?}"); + } + assert_eq!(pixel(&s, 150, 100)[3], 0.0, "between the tiles"); +} + +#[test] +fn cross_weave_runs_in_every_mode_and_depth() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] { + let mut s = session_in(mode, depth); + s.execute("edit.fill", weave(json!({}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "{mode}/{depth}: hole"); + assert!(pixel(&s, 20, 20)[3] > 0.99, "{mode}/{depth}: painted"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}"); + } +} + +#[test] +fn tiles_clear_at_a_pixel_do_not_hide_the_ones_that_show_there() { + // A clear 100 x 100 tile with an opaque 10 x 10 middle, at the largest overlap (2 px between tiles): about 1100 + // tiles in front are clear at (0, 0) before the ones whose middle covers it. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); + s.execute("select.rect", json!({"x": 45, "y": 45, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "dot", "rect": [0, 0, 100, 100]})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // Brick Fill lays its tiles out the same way and must find them too. + for script in ["crossWeave", "brickFill"] { + s.execute("edit.fill", weave(json!({"script": script, "pattern": "dot", "spacing": -98}))).unwrap(); + let px = pixel(&s, 0, 0); + assert!(px[3] > 0.99 && rgb8(px) == RED, "{script}: {px:?}"); + s.execute("edit.undo", json!({})).unwrap(); + } +} diff --git a/crates/engine-paint/src/history_source.rs b/crates/engine-paint/src/history_source.rs index 45c3542a76..ef1bda6221 100644 --- a/crates/engine-paint/src/history_source.rs +++ b/crates/engine-paint/src/history_source.rs @@ -51,6 +51,14 @@ pub fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result bool { + matches!(checked_source(st, &Value::Null, "edit.fill"), Ok(Ok(source)) if same_mode_and_depth(st, &source)) +} + /// Fill › History's rule beyond the canvas size: the source must have the document's colour mode /// and bit depth, whatever happened in between (8 to 16 to 8 bit fills again). Document modes are /// compared, so an Indexed document refuses its RGB source. Unlike [`refuse_other_format`], every diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index ea426dd4f6..aa073a08aa 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -17,7 +17,7 @@ use photocraft_engine_core::{ use photocraft_engine_core::{command_specs, hidden_target, param_schema, prefs}; pub mod cmd; -mod history_source; +pub mod history_source; mod install; pub use cmd::adjustment_brush_cmds; @@ -48,6 +48,8 @@ mod fill_quick_mask_refusals_tests; #[cfg(test)] mod fill_script_brick_tests; #[cfg(test)] +mod fill_script_cross_weave_tests; +#[cfg(test)] mod fill_script_random_fill_tests; #[cfg(test)] mod mixer_indexed_bitmap_tests; diff --git a/crates/engine/src/facade.rs b/crates/engine/src/facade.rs index 87d81460e7..b719e0322d 100644 --- a/crates/engine/src/facade.rs +++ b/crates/engine/src/facade.rs @@ -16,8 +16,8 @@ pub use photocraft_engine_core::Session as CoreSession; pub use photocraft_engine_core::*; // The painting commands' modules, at the paths they had inside the engine. pub use photocraft_engine_paint::{ - adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, paint_cmds, pick_cmds, redeye_cmds, retouch_cmds, - sampler_cmds, stamp_cmds, + adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, history_source, paint_cmds, pick_cmds, redeye_cmds, + retouch_cmds, sampler_cmds, stamp_cmds, }; // The vector-area commands' modules, likewise. pub use photocraft_engine_vector::{ diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 91435bea1a..b0708f25d5 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -61,9 +61,10 @@ fn run_guarded(id: &str, p: &Value) -> Result<(), String> { } } -#[test] -#[ignore = "slow full-registry fuzz; run with --ignored"] -fn no_command_panics_or_hangs_on_adversarial_params() { +const SHARDS: usize = 8; + +fn run_panic_hunt_shard(shard: usize) { + assert!(shard < SHARDS); let params: Vec = vec![ json!({}), json!({"x": -9, "y": -9, "radius": 0, "amount": 0, "angle": 0, "opacity": 0, "scale": 0, "levels": 0, "tolerance": 0, "gamma": 0, "layer": 999999, "channel": 999, "index": 999999, "count": 0}), @@ -76,7 +77,10 @@ fn no_command_panics_or_hangs_on_adversarial_params() { json!({"subtractPoints": "none", "order": ["-"], "labMinimum": [0, 0, 0], "labMaximum": [100, 0, 0]}), ]; let mut bad: Vec = Vec::new(); - for spec in command_specs() { + for (idx, spec) in command_specs().iter().enumerate() { + if idx % SHARDS != shard { + continue; + } for p in ¶ms { // Print and Print One Copy reach real printers (lp, or the Windows driver): fuzz them // as dry runs so the hunt never prints a page. @@ -93,9 +97,28 @@ fn no_command_panics_or_hangs_on_adversarial_params() { } } } - assert!(bad.is_empty(), "{} commands panicked:\n{}", bad.len(), bad.join("\n")); + assert!(bad.is_empty(), "shard {shard}: {} commands panicked:\n{}", bad.len(), bad.join("\n")); } +macro_rules! panic_hunt_shard { + ($name:ident, $shard:expr) => { + #[test] + #[ignore = "slow full-registry fuzz; run with --ignored"] + fn $name() { + run_panic_hunt_shard($shard); + } + }; +} + +panic_hunt_shard!(panic_hunt_shard_0, 0); +panic_hunt_shard!(panic_hunt_shard_1, 1); +panic_hunt_shard!(panic_hunt_shard_2, 2); +panic_hunt_shard!(panic_hunt_shard_3, 3); +panic_hunt_shard!(panic_hunt_shard_4, 4); +panic_hunt_shard!(panic_hunt_shard_5, 5); +panic_hunt_shard!(panic_hunt_shard_6, 6); +panic_hunt_shard!(panic_hunt_shard_7, 7); + /// #4982: a panic the code under test contains still fails the run; a graceful `Err` does not. #[test] fn contained_panics_count_and_graceful_errors_do_not() { diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 9c58f81255..65b2763f99 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -271,7 +271,8 @@ fn defaults() -> AppDefaults { } } -/// PhotoCraft's size overrides: Photoshop's panel dock width, and 12-point Label and Mono text in the compact density. +/// PhotoCraft's size overrides: Photoshop's panel dock width, a roomier dialog margin (twice the panel padding, so +/// short questions such as "Unsaved changes" do not look cramped), and 12-point Label and Mono text in the compact density. const SIZES: &[u8] = include_bytes!("sizes.json"); /// The size overrides, parsed once: the root keeps one `Arc` so the runtime's token and hit-size caches, which key on diff --git a/crates/ui-egui/src/app/sizes.json b/crates/ui-egui/src/app/sizes.json index 5727ea93d8..afa5f5a7fa 100644 --- a/crates/ui-egui/src/app/sizes.json +++ b/crates/ui-egui/src/app/sizes.json @@ -1 +1 @@ -{ "all": { "size.dock.column": 290 }, "compact": { "typography.label.size": 12, "typography.mono.size": 12 } } +{ "all": { "size.dock.column": 290 }, "compact": { "space.pad.dialog": 16, "typography.label.size": 12, "typography.mono.size": 12 }, "comfortable": { "space.pad.dialog": 24 } } diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs new file mode 100644 index 0000000000..981358c5c0 --- /dev/null +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -0,0 +1,96 @@ +//! #11817: a Size or Hardness typed past its range in the Brush Preset picker takes the closest value and opens the +//! range alert; the picker stays open under it and after OK. A value in range (a typed fraction cut off) and a slider +//! press open none. + +use crate::app::framework::BuildApp as _; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn harness() -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.5}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).with_context(app.ctx().clone()).build_app( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // The canvas shows the picker itself (`canvas_tool_menu::run`). + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + crate::brush_picker::open(h.state_mut(), [c.x, c.y]); + h.run_steps(3); + h +} + +/// Type `text` into the picker's `n`th spin field (0 Size, 1 Hardness), then Tab. +fn type_into(h: &mut Harness<'static, Box>, n: usize, text: &str) { + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, Box>) -> usize { + h.state().framework.dialogs.open_dialogs().len() +} + +fn size_and_hardness(h: &Harness<'static, Box>) -> (f32, f32) { + let b = &h.state().session.tools.brush; + (b.size, b.hardness) +} + +#[test] +fn size_and_hardness_typed_out_of_range_alert_and_the_picker_stays_open() { + for (n, typed, want) in [(0, "9999", (5000.0, 0.5)), (0, "0", (1.0, 0.5)), (1, "150", (20.0, 1.0))] { + let mut h = harness(); + type_into(&mut h, n, typed); + assert_eq!(size_and_hardness(&h), want, "{typed}: the closest value"); + assert_eq!(alerts(&h), 1, "{typed}: one range alert"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open under the alert"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alerts(&h), 0, "{typed}: OK closes the alert"); + assert_eq!(size_and_hardness(&h), want, "{typed}: OK keeps the closest value"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open after OK"); + } +} + +#[test] +fn a_value_in_range_and_a_slider_press_open_no_alert() { + let mut h = harness(); + type_into(&mut h, 0, "2.5"); + assert_eq!(size_and_hardness(&h).0, 2.0, "a typed fraction is cut off, not rounded"); + type_into(&mut h, 0, "40"); + assert_eq!(size_and_hardness(&h).0, 40.0); + let slider = h + .get_all_by_role(egui::accesskit::Role::Slider) + .find(|n| n.accesskit_node().label().as_deref() == Some("Hardness")) + .expect("the Hardness slider") + .rect(); + let at = slider.left_center() + vec2(slider.width() * 0.8, 0.0); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(size_and_hardness(&h).1 > 0.5, "the press moved Hardness"); + assert_eq!(alerts(&h), 0, "nothing was typed out of range"); +} diff --git a/crates/ui-egui/src/canvas/tools/move_tool.rs b/crates/ui-egui/src/canvas/tools/move_tool.rs index 6c49cb207c..4c53eba55d 100644 --- a/crates/ui-egui/src/canvas/tools/move_tool.rs +++ b/crates/ui-egui/src/canvas/tools/move_tool.rs @@ -353,7 +353,10 @@ impl CanvasTool for MoveRun<'_> { let at = space.view.to_doc(pointer.pos); match run.kind { Kind::Marquee => { - self.scope.with_app(|app| crate::move_box::drag_to(app, [at.x, at.y])); + self.scope.with_app(|app| { + crate::move_box::drag_to(app, [at.x, at.y]); + crate::move_box::readout(app, cx); + }); } Kind::Refused => { if !std::mem::replace(&mut run.prompted, true) { diff --git a/crates/ui-egui/src/dialogs/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index e1685fae8c..50659bcb9d 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -43,7 +43,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V return None; } Some(match id { - "file.export.saveForWebLegacy" => Ok(opened(open_web(app)?)), + "file.export.saveForWebLegacy" => match app.session.precheck(id, params) { + Ok(()) => Ok(opened(open_web(app)?)), + Err(error) => Err(error.to_string()), + }, "file.print" => { app.session.active()?; Ok(opened(open_print(app))) diff --git a/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs b/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs new file mode 100644 index 0000000000..454c3d3e3e --- /dev/null +++ b/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs @@ -0,0 +1,143 @@ +//! #17464: the Fill dialog greys History in Contents whenever `edit.fill` would refuse the History source (another +//! canvas size after Image Size, Canvas Size, Crop or Rotate 90°; another colour mode or bit depth, #17463), by the +//! engine's own check; with a matching source it stays enabled. The other entries keep their order and state. + +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use photocraft_engine::history_source::fill_source_usable; +use serde_json::{Value, json}; + +use super::*; +use crate::smart_filter_dialog::tests::cancel; + +/// A white 40×30 document with a pixel layer "Paint" active and a selection, so only History's rule can grey an entry. +/// The current state is the History source, so the source has the layer Fill paints on. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 15})).unwrap(); + source_current(&mut app); + app +} + +/// Make the current state the History source. +fn source_current(app: &mut PhotocraftApp) { + let current = app.session.active().unwrap().history.entries().len() - 1; + app.run("history.setSource", json!({"state": current})).unwrap(); +} + +/// The canvas changes that leave the opening state's source at another size. Each is run by [`resized`]. +fn resizes() -> Vec<(&'static str, Value)> { + vec![ + ("image.imageSize", json!({"width": 20, "height": 15})), + ("image.canvasSize", json!({"width": 50, "height": 30})), + ("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 20})), + ("image.imageRotation.90cw", json!({})), + ] +} + +/// The conversions that leave the source in another colour mode or bit depth. +fn conversions() -> Vec<(&'static str, Value)> { + vec![("image.mode.bits16", json!({})), ("image.mode.grayscale", json!({}))] +} + +/// [`app`] after `cmd`, with a selection again (Image Size drops it), so Content-Aware's own rule stays out. +fn resized(cmd: &str, p: Value) -> Box { + let mut app = app(); + app.run(cmd, p).unwrap(); + app.run("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 6})).unwrap(); + app +} + +fn contents_row(app: &PhotocraftApp) -> Param { + rows(app, [0.0; 3], None, None).into_iter().find(|r| r.key == "contents").expect("a Contents row") +} + +fn keys(row: &Param) -> Vec { + let ParamKind::Choice { options, .. } = &row.kind else { panic!("Contents is a choice row") }; + options.iter().map(|(k, _)| k.clone()).collect() +} + +fn choosable(app: &mut PhotocraftApp, id: DialogId, key: &str) -> bool { + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, "contents", json!(key)).is_ok() +} + +fn contents(app: &PhotocraftApp, id: DialogId) -> Option { + let dialog = app.framework.dialogs.get_by_id::(id).expect("a hosted dialog"); + dialog.fields().text("contents").map(str::to_string) +} + +/// Whether `edit.fill` with History succeeds, undone again so the document stays as it was. +fn history_fill_succeeds(app: &mut PhotocraftApp) -> bool { + let ok = app.run(COMMAND, json!({"contents": "history"})).is_ok(); + if ok { + app.run("edit.undo", json!({})).unwrap(); + } + ok +} + +#[test] +fn history_is_enabled_on_the_unchanged_document() { + let mut app = app(); + assert!(contents_row(&app).option_enabled("history")); + let id = open(&mut app); + assert!(choosable(&mut app, id, "history")); + cancel(&mut app, id); +} + +#[test] +fn a_source_that_does_not_match_greys_history_and_it_cannot_be_chosen() { + for (cmd, p) in resizes().into_iter().chain(conversions()) { + let mut app = resized(cmd, p); + let row = contents_row(&app); + assert!(!row.option_enabled("history"), "{cmd}: History greyed"); + let order: Vec = CONTENTS.iter().map(|(k, _)| k.to_string()).collect(); + assert_eq!(keys(&row), order, "{cmd}: every entry listed, in the same order"); + for (key, _) in CONTENTS.iter().filter(|(k, _)| *k != "history") { + assert!(row.option_enabled(key), "{cmd}: {key} stays enabled"); + } + + let id = open(&mut app); + let before = contents(&app, id); + assert!(!choosable(&mut app, id, "history"), "{cmd}: History cannot be chosen"); + assert_eq!(contents(&app, id), before, "{cmd}: the choice is unchanged"); + cancel(&mut app, id); + } +} + +#[test] +fn a_matching_source_keeps_history_enabled() { + for (cmd, p) in resizes().into_iter().chain(conversions()) { + let mut app = resized(cmd, p); + // The current state, which has the new size, becomes the source. + source_current(&mut app); + assert!(contents_row(&app).option_enabled("history"), "{cmd}: History enabled with a source of this size"); + } +} + +#[test] +fn the_dropdown_and_the_command_agree() { + let mut cases = vec![app()]; + for (cmd, p) in resizes().into_iter().chain(conversions()) { + cases.push(resized(cmd, p)); + } + for mut app in cases { + let usable = fill_source_usable(app.session.active().unwrap()); + assert_eq!(contents_row(&app).option_enabled("history"), usable); + assert_eq!(history_fill_succeeds(&mut app), usable, "History offered exactly when the fill succeeds"); + } +} + +/// The framework restores only the remembered values a row accepts: a remembered History is dropped once greyed and the +/// row opens on its default, as it does for any unavailable choice; with a usable source it is kept. +#[test] +fn a_remembered_history_choice_keeps_todays_fallback_once_greyed() { + let mut saved = DialogFields::new(); + saved.set("contents", "history"); + let unchanged = ParamDialog::remembered(&rows(&app(), [0.0; 3], None, None), &saved); + assert_eq!(unchanged.text("contents"), Some("history"), "kept while usable"); + let app = resized("image.imageSize", json!({"width": 20, "height": 15})); + let greyed = ParamDialog::remembered(&rows(&app, [0.0; 3], None, None), &saved); + assert_eq!(greyed.text("contents"), None, "dropped once greyed: the row opens on Foreground Color"); +} diff --git a/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs b/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs index e4fc3d8982..9218a084d1 100644 --- a/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs +++ b/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs @@ -1,6 +1,7 @@ //! #17428: Fill › Pattern has a Script check box and list (greyed until ticked); OK with Script on opens the script's own //! dialog and only that dialog's OK fills. Preset › Default sets the factory values, a changed value turns Preset to -//! Custom, Reset puts back the opening values, and the values are remembered per script. +//! Custom, Reset puts back the opening values, and the values are remembered per script. Cross Weave +//! (#17429) opens its own four values. use craft::ui::patterns::form_dialogs::HostedParamDialog; use egui::accesskit::Role; @@ -208,6 +209,55 @@ fn a_typed_value_past_the_range_is_clamped_with_the_range_alert() { assert_eq!(h.state().framework.dialogs.get_by_id::(script).unwrap().fields().number("patternScale"), Some(1.25)); } +#[test] +fn cross_weave_opens_its_dialog_with_its_four_values() { + let mut app = app(); + let before = past(&app); + fill_with_script(&mut app, "crossWeave"); + assert_eq!(top_key(&app).as_deref(), Some("edit.fill.script.crossWeave")); + for (key, default) in [("patternScale", 1.0), ("spacing", 0.0), ("colorRandomness", 0.05), ("brightnessRandomness", 0.1)] { + assert_eq!(field(&app, key), Some(default), "{key}"); + } + let h = harness(app); + assert!(h.query_all_by_role(Role::Dialog).any(|n| n.accesskit_node().label().as_deref() == Some("Cross Weave")), "titled with the script's name"); + // Each value's field and its range, top to bottom; Brick Fill's row offset and angle are not there. + let fields: Vec<(String, Option, Option)> = h + .query_all_by_role(Role::SpinButton) + .filter_map(|n| { + let node = n.accesskit_node(); + Some((node.label()?.to_string(), node.min_numeric_value(), node.max_numeric_value())) + }) + .collect(); + let labels: Vec<&str> = fields.iter().map(|(l, _, _)| l.as_str()).collect(); + let order = ["Pattern Scale", "Spacing", "Color randomness", "Brightness randomness"]; + let at: Vec> = order.iter().map(|o| labels.iter().position(|l| l.starts_with(o))).collect(); + assert!(at.iter().all(Option::is_some) && at.windows(2).all(|w| w[0] < w[1]), "{labels:?}"); + assert!(!labels.iter().any(|l| l.starts_with("Offset between rows") || l.starts_with("Pattern rotate angle")), "{labels:?}"); + let range = |name: &str| fields.iter().find(|(l, _, _)| l.starts_with(name)).map(|(_, lo, hi)| (*lo, *hi)); + assert_eq!(range("Pattern Scale"), Some((Some(0.1), Some(1.25)))); + assert_eq!(range("Color randomness"), Some((Some(0.0), Some(1.0)))); + assert_eq!(range("Brightness randomness"), Some((Some(0.0), Some(1.0)))); + let spacing = range("Spacing").unwrap(); + assert!(spacing.0.is_some_and(|lo| lo < 0.0) && spacing.1.is_some_and(|hi| hi > 0.0), "tiles may overlap or stand apart: {spacing:?}"); + // OK fills once, as "Fill". + let mut app = h.into_state(); + let top = newest(&app); + confirm(&mut app, top); + assert_eq!(past(&app), before + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Fill")); +} + +#[test] +fn cancel_in_cross_weave_fills_nothing() { + let mut app = app(); + let before = past(&app); + fill_with_script(&mut app, "crossWeave"); + let top = newest(&app); + cancel(&mut app, top); + assert_eq!(open_count(&app), 0); + assert_eq!(past(&app), before); +} + /// Whether the Max distance from path field of the open script dialog is greyed. fn distance_greyed(app: Box) -> (bool, Box) { let h = harness(app); diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 22e43dc8d7..40f8dea2d4 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -62,9 +62,10 @@ fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option let contents = CONTENTS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect(); let mut contents = Param::new("contents", tl!("Contents:"), ParamKind::choice(contents, Some(opening_contents(app).into()))); // Content-Aware fills a selection from around it: without one it is listed greyed, as in the reference (#17462). - if !has_selection(app) { - contents = contents.disabled_options(["contentAware"]); - } + // History is greyed whenever `edit.fill` would refuse its source, by the engine's own check (#17464). + let greyed = + [("contentAware", !has_selection(app)), ("history", app.session.active().is_none_or(|st| !photocraft_engine::history_source::fill_source_usable(st)))]; + contents = contents.disabled_options(greyed.into_iter().filter(|(_, off)| *off).map(|(key, _)| key)); let mut rows = vec![ contents, Param::new("color", tl!("Color:"), ParamKind::color(Some(foreground))).visible_when("contents", "color"), @@ -213,6 +214,9 @@ pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamRes #[cfg(test)] mod content_aware_greyed_tests; #[cfg(test)] +#[path = "fill_history_greyed_tests.rs"] +mod fill_history_greyed_tests; +#[cfg(test)] mod no_selection_fallback_tests; #[cfg(test)] mod opacity_alert_tests; diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index de927bce10..10d1b57d61 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -242,7 +242,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Image"], "Trap…", None, "image.trap"), (&["Image"], "---", None, "---"), (&["Image", "Analysis"], "Set Measurement Scale…", None, "image.analysis.setMeasurementScale"), - (&["Image", "Analysis"], "Select Data Points…", None, "image.analysis.selectDataPoints"), + (&["Image", "Analysis", "Select Data Points"], "Custom…", None, "image.analysis.selectDataPoints"), (&["Image", "Analysis"], "---", None, "---"), (&["Image", "Analysis"], "Record Measurements", None, "image.analysis.recordMeasurements"), (&["Image", "Analysis"], "---", None, "---"), diff --git a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs index fc8e6b9e11..0aa7f6d6cc 100644 --- a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs +++ b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs @@ -1,7 +1,8 @@ //! #12629: the Art History Brush's options bar has a Pressure for Opacity toggle right after //! Opacity, and an Angle field and a Pressure for Size toggle after Tolerance, with the reference -//! application's tooltips, off / 0° by default and after Reset Tool. They edit the tool's own -//! brush, not the History Brush's or the Brush's, and the bar has no Flow and no Airbrush. +//! application's tooltips. The toggles start off and keep their state after Reset Tool (#18335), +//! which restores the angle to 0°. The controls belong to the Art History Brush, and the bar has +//! no Flow or Airbrush. use egui::accesskit::Role; use egui::{Modifiers, Rect, vec2}; @@ -99,7 +100,7 @@ fn the_controls_carry_the_reference_tooltips() { } #[test] -fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { +fn reset_tool_restores_the_angle_and_keeps_pressure_toggles() { let mut h = bar(Tool::ArtHistoryBrush); assert_eq!(controls(h.state()), (false, 0.0, false)); assert!(angle_field(&h).and_then(|n| n.accesskit_node().numeric_value()) == Some(0.0), "the field shows 0°"); @@ -112,7 +113,7 @@ fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); h.run_steps(3); - assert_eq!(controls(h.state()), (false, 0.0, false)); + assert_eq!(controls(h.state()), (true, 0.0, true)); } #[test] diff --git a/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs new file mode 100644 index 0000000000..40783e3aa3 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs @@ -0,0 +1,45 @@ +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply}; + +const COMMAND: &str = "image.analysis.selectDataPoints"; + +fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = app.ctx().clone(); + let (request, _) = ControlRequest::new(method, params); + let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { panic!("{method} replies immediately") }; + assert_eq!(reply["ok"], true, "{method}: {reply}"); + reply["result"].clone() +} + +#[test] +fn data_points_submenu_has_only_a_checked_custom_item_and_opens_the_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 24})).unwrap(); + + let menu = call(&mut app, "ui.menu.list", json!({})); + let rows = menu.as_array().unwrap(); + let titled_path = json!(["Image", "Analysis", "Select Data Points"]); + let data_points: Vec<_> = rows.iter().filter(|row| row["path"] == titled_path || row["id"] == COMMAND).collect(); + assert_eq!(data_points.len(), 1, "one entry and no separator: {data_points:?}"); + let custom = data_points[0]; + assert_eq!(custom["path"], titled_path); + assert_eq!(custom["id"], COMMAND); + assert_eq!(custom["label"], "Custom…"); + assert_eq!(custom["checked"], true); + assert_eq!(custom["enabled"], true); + assert_eq!(custom["shortcut"], Value::Null); + + let opened = call(&mut app, "ui.menu.invoke", json!({"id": custom["id"]})); + assert_eq!(opened["dialog"], "dataPoints"); + assert!(app.dialog_open()); +} + +#[test] +fn data_points_submenu_keeps_the_engine_command_available_to_scripts() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let selected = call(&mut app, "engine.execute", json!({"id": COMMAND, "params": {"selection": ["area"], "ruler": [], "count": []}})); + assert_eq!(selected["dataPoints"]["selection"], json!(["area"])); + assert!(!app.dialog_open()); +} diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index fce2102caa..a567de1c71 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -30,6 +30,9 @@ mod tests; #[cfg(test)] mod sampler_menu_tests; +#[cfg(test)] +mod data_points_submenu_tests; + #[cfg(test)] #[path = "../count_readout_tests.rs"] mod count_readout_tests; @@ -120,6 +123,8 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { "window.panel.notes" => Some(crate::panel_docking::is_shown(app, NOTES)), "image.analysis.rulerTool" => Some(app.ui.tool == Tool::Ruler), "image.analysis.countTool" => Some(app.ui.tool == Tool::Count), + // The data point set is always Custom until named presets are supported. + "image.analysis.selectDataPoints" => Some(true), _ => { // View › Proof Setup simulations: checked while that proof is shown. // A check item with no document too: an item's kind never changes (native menus). diff --git a/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs new file mode 100644 index 0000000000..26c6cbd15a --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs @@ -0,0 +1,48 @@ +use serde_json::json; + +use super::{RESET, RESET_ALL, invoke}; +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn art_history_brush(pressure_size: bool, pressure_opacity: bool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"pressureSize": pressure_size, "pressureOpacity": pressure_opacity}})).unwrap(); + app +} + +fn pressure(app: &PhotocraftApp) -> (bool, bool) { + let brush = &app.session.tools.brush; + (brush.pressure_size, brush.pressure_opacity) +} + +#[test] +fn reset_tool_keeps_each_art_history_brush_pressure_toggle() { + let defaults = ToolOptions::default(); + for toggles in [(true, false), (false, true), (true, true), (false, false)] { + let mut app = art_history_brush(toggles.0, toggles.1); + assert_eq!(pressure(&app), toggles); + app.ui.tool_options.art_history_style = "dab".into(); + app.ui.tool_options.art_history_area = 120.0; + app.ui.tool_options.art_history_tolerance = 25.0; + + invoke(&mut app, RESET, &json!({})).unwrap().unwrap(); + + assert_eq!(pressure(&app), toggles); + assert_eq!(app.ui.tool_options.art_history_style, defaults.art_history_style); + assert_eq!(app.ui.tool_options.art_history_area, defaults.art_history_area); + assert_eq!(app.ui.tool_options.art_history_tolerance, defaults.art_history_tolerance); + } +} + +#[test] +fn reset_all_tools_clears_the_art_history_brush_pressure_toggles() { + let mut app = art_history_brush(true, true); + assert_eq!(pressure(&app), (true, true)); + + invoke(&mut app, RESET_ALL, &json!({"confirmed": true})).unwrap().unwrap(); + + assert_eq!(pressure(&app), (false, false)); +} diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index 16abf9696e..a0fc3024d8 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -98,9 +98,10 @@ fn commit_edits(app: &mut PhotocraftApp, events: &EditEvents, set: impl Fn } } -/// Runs what the picker reported: the head's edits, Escape's revert, the saved view and the picks. -/// `keys` are every row's key in list order (a reorder pick is placed by them). -pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushKey], out: BrushPresetPickerOutput) { +/// Runs what the picker reported: the head's edits, Escape's revert, the range alert for a Size or Hardness typed out +/// of range (the picker stays open under it, #11817), the saved view and the picks. `keys` are every row's key in list +/// order (a reorder pick is placed by them); `ui` words the alert's range. +pub(crate) fn apply(app: &mut PhotocraftApp, ui: &egui::Ui, keys: &[BrushKey], out: BrushPresetPickerOutput) { commit_edits(app, &out.diameter, |b, v| b.size = *v as f32); commit_edits(app, &out.hardness, |b, v| b.hardness = *v as f32); commit_edits(app, &out.tip, |b, v| { @@ -121,12 +122,15 @@ pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushK // One command and no history step: `tools.setBrush` without a coalesce key is a tool setting. commit_keyed(app, &now, &after, None); } + if let Some(alert) = &out.out_of_range { + crate::tools::option_cells::range_alert(app, ui, alert); + } if let Some(settings) = &out.settings { save(app, settings); } for pick in out.picks { match pick { - BrushPick::OpenSettings => open_settings(app, ctx), + BrushPick::OpenSettings => open_settings(app, ui.ctx()), other => run_picks(app, vec![other], keys), } } @@ -157,7 +161,7 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) { }; let _ = MemoView::new("brush-preset-canvas", props, canvas_view).show(ui); for CanvasEvent { out, keys, eraser, closed } in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); if let Some(rows) = eraser { commit_keyed(app, &rows.before, &rows.brush, rows.key); if app.ui.tool_options.bg_tolerance_control != rows.tolerance { @@ -249,7 +253,7 @@ pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bo }; let _ = MemoView::new("brush-preset-field", props, field_view).show(ui); for FieldEvent(out, keys) in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); } } @@ -393,3 +397,7 @@ fn toggle_view(props: &mut ToggleProps<'_>, ui: &mut egui::Ui) { #[cfg(test)] #[path = "../brush_picker_gear_menu_tests.rs"] mod gear_menu_tests; + +#[cfg(test)] +#[path = "../brush_picker_range_alert_tests.rs"] +mod range_alert_tests; diff --git a/crates/ui-egui/src/tools/move_box.rs b/crates/ui-egui/src/tools/move_box.rs index 24632762b4..b69547897c 100644 --- a/crates/ui-egui/src/tools/move_box.rs +++ b/crates/ui-egui/src/tools/move_box.rs @@ -7,6 +7,8 @@ use serde_json::json; use craft::behavior::kurbo::{Point, Rect}; +use craft::imaging::ui::select::SelectWords; +use craft::ui::canvas::ToolContext; use craft::ui::canvas_controls::Marquee; use craft::ui::contract::Show as _; @@ -85,6 +87,15 @@ pub(crate) fn cancel(app: &mut PhotocraftApp) { app.layer_box = None; } +/// The marquee's W and H beside the pointer while it is dragged, in the selection marquee's words and units +/// (Show Transformation Values hides it, as it hides the drag readout). +pub(crate) fn readout(app: &PhotocraftApp, cx: &mut ToolContext<'_>) { + let Some(b) = app.layer_box else { return }; + let rect = Rect::from_points(Point::new(b.start[0], b.start[1]), Point::new(b.end[0], b.end[1])); + let (words, units) = (cx.words::(), cx.units()); + cx.readout(vec![(words.width.clone(), units.pixels(rect.width())), (words.height.clone(), units.pixels(rect.height()))]); +} + /// The marquee being dragged, over the canvas `canvas`. pub(crate) fn show(app: &PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect) { let Some(b) = app.layer_box else { return }; @@ -205,3 +216,7 @@ mod tests { assert_eq!(app.session.active().unwrap().selected_layers(), vec![paint]); } } + +#[cfg(test)] +#[path = "move_marquee_readout_tests.rs"] +mod move_marquee_readout_tests; diff --git a/crates/ui-egui/src/tools/move_marquee_readout_tests.rs b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs new file mode 100644 index 0000000000..93e226884c --- /dev/null +++ b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs @@ -0,0 +1,75 @@ +//! #18162: the Move tool's layer marquee shows its W and H beside the pointer while it is dragged, as a layer drag +//! shows its distances, and adds no history step. + +use serde_json::json; + +use crate::canvas::{ToolEvent, tool_event, tool_event_response}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; + +/// A white document whose only layer is the locked Background, with the Move tool and Auto-Select on: a press +/// anywhere on the canvas starts the layer marquee. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + app +} + +/// The readout rows of the pass that moves the pointer to `to`, as label and value text. +fn readout(app: &mut PhotocraftApp, to: [f64; 2]) -> Vec<(String, String)> { + tool_event_response(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, egui::Modifiers::NONE) + .readout + .expect("the layer marquee has a readout") + .rows + .into_iter() + .map(|(label, value)| (label.as_str().to_owned(), value)) + .collect() +} + +/// The number a readout value shows ("42 px" reads 42). +fn number(value: &str) -> f64 { + value.trim_end_matches("px").trim().parse().unwrap_or_else(|_| panic!("a pixel value: {value:?}")) +} + +#[test] +fn the_layer_marquee_reads_its_width_and_height_as_it_grows() { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + let first = readout(&mut app, [60.0, 50.0]); + assert!(app.layer_box.is_some(), "the press started the layer marquee"); + let [(w_label, w), (h_label, h)] = first.as_slice() else { panic!("two rows, W and H: {first:?}") }; + assert!(w_label.starts_with('W') && h_label.starts_with('H'), "{first:?}"); + assert!(w.ends_with("px") && h.ends_with("px"), "{first:?}"); + assert!(number(w) > 0.0 && number(h) > 0.0, "{first:?}"); + + let wider = readout(&mut app, [120.0, 50.0]); + assert!(number(&wider[0].1) > number(w), "a wider drag reads a larger W: {first:?} then {wider:?}"); + assert_eq!(wider[1].1, *h, "H stays while only the width changes"); + + let taller = readout(&mut app, [120.0, 110.0]); + assert!(number(&taller[1].1) > number(&wider[1].1), "a taller drag reads a larger H: {wider:?} then {taller:?}"); + + // Up and to the left of the press, the box reads its size, not a negative one. + let back = readout(&mut app, [5.0, 10.0]); + assert!(number(&back[0].1) > 0.0 && number(&back[1].1) > 0.0, "{back:?}"); +} + +#[test] +fn the_layer_marquee_adds_no_history_step_and_leaves_the_background() { + let mut app = app(); + let (steps, bg, bounds) = { + let st = app.session.active().unwrap(); + let bg = st.active_layer.unwrap(); + (st.history.past_len(), bg, st.doc.layer(bg).unwrap().surface().unwrap().content_bounds()) + }; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(!readout(&mut app, [90.0, 70.0]).is_empty()); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 70.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps, "no history step"); + assert_eq!(st.doc.layer(bg).unwrap().surface().unwrap().content_bounds(), bounds, "the Background did not move"); + assert!(app.layer_box.is_none()); +} diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 55ea6ef18f..4e9bf5a5be 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -90,11 +90,12 @@ fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { // The session brush is the options bar's tool's: make sure it is `tool`'s before resetting. crate::paint_mouse::sync_tool_brush(app); app.ui.tool_brushes.retain(|(t, _)| *t != tool); - // The Eraser's Reset Tool resets the tip but keeps Pressure for Size and Pressure for - // Opacity as they were (#17700). The Background Eraser's keeps Pressure for Size (#18058). + // Reset the tip but keep Pressure for Size and Pressure for Opacity for the Eraser + // (#17700) and Art History Brush (#18335). Background Eraser keeps only Size (#18058). let brush = &app.session.tools.brush; - let size = matches!(tool, Tool::Eraser | Tool::BackgroundEraser).then_some(brush.pressure_size); - let opacity = (tool == Tool::Eraser).then_some(brush.pressure_opacity); + let keep_opacity = matches!(tool, Tool::Eraser | Tool::ArtHistoryBrush); + let size = (keep_opacity || tool == Tool::BackgroundEraser).then_some(brush.pressure_size); + let opacity = keep_opacity.then_some(brush.pressure_opacity); reset_session_brush(app); if size.is_some() || opacity.is_some() { let brush = &mut app.session.tools.brush; @@ -486,6 +487,10 @@ mod patch_sample_all_default_tests; #[path = "eraser_reset_keeps_pressure_tests.rs"] mod eraser_reset_keeps_pressure_tests; +#[cfg(test)] +#[path = "art_history_reset_keeps_pressure_tests.rs"] +mod art_history_reset_keeps_pressure_tests; + #[cfg(test)] #[path = "bg_eraser_reset_pressure_tests.rs"] mod bg_eraser_reset_pressure_tests;