Merge #11882 into the merge queue batch

fix(engine): the magic wand measures Tolerance in the document's own channels
This commit is contained in:
David Mann committed 2026-11-30 18:27:45 +01:00
commit 13319475bf
4 files changed
+702 -26

No files matched your search

+305
View File
@@ -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<u8> {
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<usize>,
}
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<Region> {
// 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<const CH: usize>(px: &WandPixels, seed: (i32, i32), how: &WandMatch) -> Option<Region> {
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<Option<(usize, usize)>> = {
use rayon::prelude::*;
marks.par_chunks_mut(w).enumerate().map(|(y, row)| scan(y, row)).collect()
};
#[cfg(target_arch = "wasm32")]
let spans: Vec<Option<(usize, usize)>> = 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<Surface> {
+11
View File
@@ -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");
}
+101 -26
View File
@@ -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<u8>,
channels: usize,
alpha: Option<usize>,
}
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<DocumentChannels> {
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<u32> {
@@ -153,22 +208,27 @@ fn wand_sample_size(p: &Value) -> Result<u32> {
}
/// 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<Value> {
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<CommandSpec> {
"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
),
@@ -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<u8> {
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::<Vec<_>>(), "cyan");
assert_eq!(stored(&s, 1), INKS.iter().map(|ink| ink[1]).collect::<Vec<_>>(), "magenta");
assert_eq!(stored(&s, 2), INKS.iter().map(|ink| ink[2]).collect::<Vec<_>>(), "yellow");
assert_eq!(stored(&s, 3), INKS.iter().map(|ink| ink[3]).collect::<Vec<_>>(), "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");
}