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/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 bd5228cd88..ae034e3c40 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; @@ -154,9 +154,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()))?; @@ -177,6 +187,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); } @@ -249,6 +268,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) { @@ -281,6 +315,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/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 21025b6ed9..e5e5aabdc6 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; 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/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_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 4f05ecb776..d34c2ce694 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -84,12 +84,13 @@ 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). - // On the Quick Mask channel the fill from surroundings and History are greyed too (#17488). - if quick_mask { - contents = contents.disabled_options(["contentAware", "history"]); - } else 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). On the Quick + // Mask channel the fill from surroundings and History are greyed too (#17488). + let greyed = [ + ("contentAware", quick_mask || !has_selection(app)), + ("history", quick_mask || 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"), @@ -278,6 +279,9 @@ fn keep_mode(ctx: &egui::Context, key: &str, mode: String) { #[cfg(test)] mod content_aware_greyed_tests; #[cfg(test)] +#[path = "fill_history_greyed_tests.rs"] +mod fill_history_greyed_tests; +#[cfg(test)] #[path = "fill_quick_mask_greyed_tests.rs"] mod fill_quick_mask_greyed_tests; #[cfg(test)]