From fd19b63c4cf5e3ce97f1b06e6a93e93757459275 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 11:21:39 +0100 Subject: [PATCH 1/8] fix(engine): measure the wand's Tolerance in the document's channels An 8-bit Lab document compares colours on its Lightness, a and b channels in the reference application, while PhotoCraft sampled the picture as 8-bit RGB whatever the document's mode, so the Tolerance was measured in a colour space the document is not in: on a grey ramp, Tolerance 5 reaches two blocks in a Lab document where the reference reaches one (#11785). The wand now reads the stored channels of an 8-bit Lab document through a route of its own, and keeps today's selection everywhere else, because that is what the measured table covers: RGB and Grayscale at 8, 16 and 32 bits, Lab and CMYK above 8-bit, and Sample All Layers. `sample_rgba8` is untouched, so the Paint Bucket, the Magic Eraser and the Background Eraser still sample RGB. The two 8-bit CMYK rows wait for an answer on the issue: their reached ranges are not on the ramp's 40 px block grid, so no per-ink comparison of a block-uniform ramp can produce them. --- crates/algo/src/selection.rs | 106 +++++++++- crates/engine/src/cmd/selection_cmds.rs | 46 ++++- .../selection_cmds/wand_color_mode_tests.rs | 186 ++++++++++++++++++ 3 files changed, 332 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index f740687c1ad..0602fc16ff8 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -246,6 +246,54 @@ pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { img } +/// The surface's own stored channels over `area` as 0–255 levels, up to four channels (a missing +/// fourth, e.g. no alpha, reads 255 so it never splits a region), read in parallel bands like +/// [`rgba8_image`]. +/// +/// Unlike [`rgba8_image`] this converts nothing: a Lab document gives its stored Lightness, a and +/// b, a CMYK document its inks. The Magic Wand measures Tolerance on those channels for the +/// document modes the reference measures that way (#11785), where reading the picture as RGB +/// would measure the Tolerance in a colour space the document is not in. +/// +/// The wand calls this on 8-bit documents, where the levels are the stored bytes exactly; a +/// deeper surface is quantized to the 8-bit grid here, which is why the mode-aware sampling is +/// the caller's decision, not this function's. +pub fn stored_levels_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { + let (w, h) = (area.width() as usize, area.height() as usize); + let mut img = vec![[0u8; 4]; w * h]; + if w == 0 || h == 0 { + return img; + } + let stride = s.channels().max(1); + let take = stride.min(4); + // A surface without a stored alpha is fully opaque, like every other read of one. + let opaque = !s.format().alpha; + let band = 256usize; + let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let read = |bi: usize, chunk: &mut [[u8; 4]]| { + let y0 = area.y0 + (bi * band) as i32; + let mut px = Vec::new(); + s.read_region_into(Rect::new(area.x0, y0, area.x1, y0 + (chunk.len() / w) as i32), &mut px); + for (d, src) in chunk.iter_mut().zip(px.chunks_exact(stride)) { + for (k, v) in src.iter().take(take).enumerate() { + d[k] = q(*v); + } + if opaque { + d[3] = 255; + } + } + }; + + #[cfg(not(target_arch = "wasm32"))] + { + use rayon::prelude::*; + img.par_chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c)); + } + #[cfg(target_arch = "wasm32")] + img.chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c)); + img +} + /// 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)] @@ -266,10 +314,66 @@ 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_bound`]). + 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 + } + } + } +} + /// 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`. pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { + wand_region_bound(img, area, seed, tolerance, contiguous, anti_alias, WandBound::AtMost) +} + +/// [`wand_region`] with the Tolerance bound chosen: [`WandBound::AtMost`] is [`wand_region`] +/// itself, [`WandBound::Below`] is what the Magic Wand measures a document's own colour channels +/// at (#11785). +/// +/// Why the wand's 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 table +/// (#11785, 8-bit Lab 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 reaches up to the +/// 130 block. Here that ramp stores Lightness 108, 113, 118, 124, … 153 (L\* / 100 × 255), so +/// the steps from the seed are 0, 5, 10, 16, …, 31, 36, …: 5 levels must not match at +/// Tolerance 5 (unrounded they are 5.2), while 31 do at Tolerance 32 (unrounded 30.6). On the +/// stored grid that is a difference below the Tolerance, not at most it. +pub fn wand_region_bound( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + bound: WandBound, +) -> Option { if !area.contains(seed.0, seed.1) { return None; } @@ -278,7 +382,7 @@ pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32 return None; } let target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize]; - let tol = (tolerance + 1e-3).floor().max(0.0) as i32; + let tol = wand_max_diff(tolerance, bound); // Copying a selection can leave RGB under zero alpha. Those invisible colours must not // split a transparent region into pieces, as if the copied source were still visible. let similar = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol); diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 13737e70bd4..35d65b2e51d 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -17,6 +17,8 @@ mod modify_window; mod color_range_performance; #[cfg(test)] mod color_range_window_tests; +#[cfg(test)] +mod wand_color_mode_tests; fn has_doc(s: &Session) -> std::result::Result<(), String> { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) @@ -133,13 +135,47 @@ pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[ } } +/// The Magic Wand's sampling in an 8-bit Lab 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, an 8-bit Lab document at +/// Tolerance 5 reaches only that block, while the RGB picture (100, 105, …) reaches two of them +/// (#11785's table). The other rows of that table keep today's sampling: 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. 8-bit CMYK waits for the answer to the question +/// about its numbers (see `wand_color_mode_tests`), so the ink comparison is not in yet. +fn wand_document_channels(s: &Session, all_layers: bool) -> Option<(Rect, Vec<[u8; 4]>)> { + let d = s.active()?; + if all_layers || d.doc.mode != photocraft_doc::ColorMode::Lab || d.doc.depth != photocraft_doc::SampleType::U8 { + return None; + } + let surf = d.active_layer.and_then(|id| d.doc.layer(id)).and_then(|l| l.surface())?; + let fmt = surf.format(); + if fmt.mode != photocraft_doc::ColorMode::Lab || fmt.sample != photocraft_doc::SampleType::U8 { + return None; + } + let area = d.doc.bounds(); + Some((area, sel::stored_levels_image(surf, area))) +} + 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 (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 (area, img, bound) = match shown_gray(s) { + Some((area, img)) => (area, img, sel::WandBound::AtMost), + None => match wand_document_channels(s, all_layers) { + Some((area, img)) => (area, img, sel::WandBound::Below), + None => { + let (area, img) = sample_rgba8(s, all_layers)?; + (area, img, sel::WandBound::AtMost) + } + }, }; - let region = sel::wand_region(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true)); + let region = sel::wand_region_bound(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true), bound); drop(img); let m = mode(p); let selected = s.edit("Magic Wand", |doc, _| { @@ -713,7 +749,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,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture)"##, + r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture; an 8-bit Lab document measures the Tolerance on its own Lightness/a/b channels)"##, has_doc, magic_wand ), diff --git a/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs new file mode 100644 index 00000000000..3803c5e93df --- /dev/null +++ b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs @@ -0,0 +1,186 @@ +//! The Magic Wand's Tolerance in the document's own colour channels (#11785). +//! +//! The fixture is the reference's test: a grey ramp of ten 40 px blocks (grey 100, 105, … 145) +//! from x 100, clicked on the 100 block, with Contiguous on. 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 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 = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": create, "depth": depth})).unwrap(); + s.edit("paint", |doc, _| { + let bg = doc.layers[0].surface_mut().unwrap(); + for k in 0..10u8 { + let v = grey(k) as f32 / 255.0; + bg.fill_rect(Rect::new(X0 + BLOCK * i32::from(k), 0, X0 + BLOCK * (i32::from(k) + 1), H), &[v, v, v, 1.0]); + } + Ok(()) + }) + .unwrap(); + if let Some(cmd) = mode { + s.execute(cmd, json!({})).unwrap(); + } + s +} + +/// 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))); +} + +/// #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); + 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 at 16 and 32 bits is marked *not measured* in #11785, so it keeps today's sampling. If the +/// rows get measured, this is the test to change with them. +#[test] +fn lab_documents_above_8_bits_keep_todays_sampling() { + for depth in [16u32, 32] { + let mut s = ramp("rgb", depth, Some("image.mode.lab")); + assert_eq!(s.active().unwrap().doc.depth, if depth == 16 { SampleType::U16 } else { SampleType::F32 }); + // Its 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. + assert_eq!(stored(&s, 0), [108, 113, 118, 124, 129, 134, 139, 144, 149, 153], "lab {depth} Lightness"); + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 180)), "lab {depth} keeps today's Tolerance 5 reach"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 380)), "lab {depth} keeps today's Tolerance 32 reach"); + } +} + +/// CMYK 8-bit is left on today's sampling for now: the reference's two CMYK numbers cannot come +/// from a per-ink comparison on this ramp, so the ink channels are not compared yet (the question +/// is on #11785). This pins what the wand does there today, and records the ink values an ink +/// comparison would measure, so the difference is on the table when that row is settled. +#[test] +fn cmyk_document_keeps_todays_sampling_until_its_numbers_are_settled() { + let mut s = ramp("rgb", 8, Some("image.mode.cmyk")); + assert_eq!(s.active().unwrap().doc.mode, ColorMode::Cmyk); + // Grey 100 … 145 as coated-CMYK inks: the cyan hovers near 96 while the black ink falls from + // 81 to 20, so the seed's steps in the inks are 0, 9, 17, 25, 32, 38, 45, 50, 56, 61. + 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"); + // On these inks Tolerance 5 would reach 100-140 and Tolerance 32 100-260, and on today's RGB + // picture (100, 105/106, 110/111, …) it reaches 100-140 and 100-380. The table's numbers, + // 100-146 and 100-341, are inside neither: they are not on the 40 px block grid. + wand(&mut s, 5.0); + assert_eq!(reach(&s), Some((100, 140)), "cmyk keeps today's Tolerance 5 reach"); + wand(&mut s, 32.0); + assert_eq!(reach(&s), Some((100, 380)), "cmyk keeps today's Tolerance 32 reach"); +} + +/// The shared sampler the Paint Bucket, the Magic Eraser and the Background Eraser go through is +/// untouched: an 8-bit Lab document still hands it the RGB picture. +#[test] +fn the_shared_rgba8_sample_path_still_reads_rgb_in_a_lab_document() { + 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"); +} From 99497886226f7e03929cacb2f194ca7e8526f9e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 14:11:11 +0100 Subject: [PATCH 2/8] fix(engine): the wand measures a CMYK document's Tolerance on its inks The reporter re-measured the CMYK row of #11785 without dither and answered the question on the issue: on a document whose blocks hold the ink levels of their comment, the reach is x 100-140 at Tolerance 5 and x 100-340 at Tolerance 32, and the rule they endorse is the largest difference over the four stored inks, so the wand's document-channel route now covers CMYK as well as Lab and measures the layer's own channels instead of the RGB the picture shows. Comparing a CMYK surface takes five channels -- four inks and an alpha -- which is why the fill moved from `[[u8; 4]]` pixels to `WandPixels` with a channel count: `wand_region` is the same RGBA fill as before, so `sample_rgba8` and with it the Paint Bucket, the Magic Eraser and the Background Eraser stay untouched, and RGB and Grayscale, Lab and CMYK above 8 bits and Sample All Layers keep today's sampling as the table's *not measured* rows ask. --- crates/algo/src/selection.rs | 157 +++++++++------- crates/engine/src/cmd/selection_cmds.rs | 73 ++++++-- .../selection_cmds/wand_color_mode_tests.rs | 177 +++++++++++++----- 3 files changed, 269 insertions(+), 138 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 0602fc16ff8..dc51524779f 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -246,52 +246,41 @@ pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { img } -/// The surface's own stored channels over `area` as 0–255 levels, up to four channels (a missing -/// fourth, e.g. no alpha, reads 255 so it never splits a region), read in parallel bands like -/// [`rgba8_image`]. +/// 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`]. /// -/// Unlike [`rgba8_image`] this converts nothing: a Lab document gives its stored Lightness, a and -/// b, a CMYK document its inks. The Magic Wand measures Tolerance on those channels for the -/// document modes the reference measures that way (#11785), where reading the picture as RGB -/// would measure the Tolerance in a colour space the document is not in. -/// -/// The wand calls this on 8-bit documents, where the levels are the stored bytes exactly; a -/// deeper surface is quantized to the 8-bit grid here, which is why the mode-aware sampling is -/// the caller's decision, not this function's. -pub fn stored_levels_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { - let (w, h) = (area.width() as usize, area.height() as usize); - let mut img = vec![[0u8; 4]; w * h]; +/// 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. +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 img; + return data; } - let stride = s.channels().max(1); - let take = stride.min(4); - // A surface without a stored alpha is fully opaque, like every other read of one. - let opaque = !s.format().alpha; let band = 256usize; let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let read = |bi: usize, chunk: &mut [[u8; 4]]| { + 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 + (chunk.len() / w) as i32), &mut px); - for (d, src) in chunk.iter_mut().zip(px.chunks_exact(stride)) { - for (k, v) in src.iter().take(take).enumerate() { - d[k] = q(*v); - } - if opaque { - d[3] = 255; - } + 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::*; - img.par_chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c)); + data.par_chunks_mut(w * band * ch).enumerate().for_each(|(bi, c)| read(bi, c)); } #[cfg(target_arch = "wasm32")] - img.chunks_mut(w * band).enumerate().for_each(|(bi, c)| read(bi, c)); - img + 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 @@ -323,7 +312,7 @@ pub enum WandBound { /// 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_bound`]). + /// [`wand_region_on`]). Below, } @@ -346,61 +335,97 @@ fn wand_max_diff(tolerance: f32, bound: WandBound) -> i32 { } } +/// 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`. pub fn wand_region(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { - wand_region_bound(img, area, seed, tolerance, contiguous, anti_alias, WandBound::AtMost) + wand_region_on(&WandPixels::rgba(area, img.as_flattened()), seed, tolerance, contiguous, anti_alias, WandBound::AtMost) } -/// [`wand_region`] with the Tolerance bound chosen: [`WandBound::AtMost`] is [`wand_region`] -/// itself, [`WandBound::Below`] is what the Magic Wand measures a document's own colour channels -/// at (#11785). +/// [`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 wand's 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 table -/// (#11785, 8-bit Lab 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 reaches up to the -/// 130 block. Here that ramp stores Lightness 108, 113, 118, 124, … 153 (L\* / 100 × 255), so -/// the steps from the seed are 0, 5, 10, 16, …, 31, 36, …: 5 levels must not match at -/// Tolerance 5 (unrounded they are 5.2), while 31 do at Tolerance 32 (unrounded 30.6). On the -/// stored grid that is a difference below the Tolerance, not at most it. -pub fn wand_region_bound( - img: &[[u8; 4]], - area: Rect, - seed: (i32, i32), - tolerance: f32, - contiguous: bool, - anti_alias: bool, - bound: WandBound, -) -> Option { - if !area.contains(seed.0, seed.1) { +/// 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), tolerance: f32, contiguous: bool, anti_alias: bool, bound: WandBound) -> Option { + if !px.area.contains(seed.0, seed.1) || px.channels == 0 || px.channels > MAX_WAND_CHANNELS { return None; } - let (w, h) = (area.width() as usize, area.height() as usize); - if w.checked_mul(h).is_none_or(|n| n > img.len()) { + // One fill per channel count: the comparison runs per pixel over the canvas. + match px.channels { + 1 => wand_fill::<1>(px, seed, tolerance, contiguous, anti_alias, bound), + 2 => wand_fill::<2>(px, seed, tolerance, contiguous, anti_alias, bound), + 3 => wand_fill::<3>(px, seed, tolerance, contiguous, anti_alias, bound), + 4 => wand_fill::<4>(px, seed, tolerance, contiguous, anti_alias, bound), + _ => wand_fill::<5>(px, seed, tolerance, contiguous, anti_alias, bound), + } +} + +/// [`wand_region_on`] for `CH` stored channels per pixel. +fn wand_fill(px: &WandPixels, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool, bound: WandBound) -> Option { + 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 target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize]; + let so = ((seed.1 - px.area.y0) as usize * w + (seed.0 - px.area.x0) as usize) * CH; + let mut target = [0u8; CH]; + target.copy_from_slice(px.data.get(so..so + CH)?); + let alpha = px.alpha.filter(|&a| a < CH); let tol = wand_max_diff(tolerance, bound); - // Copying a selection can leave RGB under zero alpha. Those invisible colours must not + // 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 = |p: [u8; 4]| (target[3] == 0 && p[3] == 0) || (0..4).all(|c| (p[c] as i32 - target[c] as i32).abs() <= tol); + let similar = |i: usize| -> bool { + let o = i * CH; + let Some(v) = px.data.get(o..o + CH) else { return false }; + (alpha.is_some_and(|a| target[a] == 0 && v[a] == 0)) || (0..CH).all(|c| (v[c] as i32 - target[c] as i32).abs() <= tol) + }; 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 - area.x0) as usize, (seed.1 - area.y0) as usize)]; + 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(img[row + l - 1]) { + while l > 0 && marks[row + l - 1] == 0 && similar(row + l - 1) { l -= 1; } - while r + 1 < w && marks[row + r + 1] == 0 && similar(img[row + r + 1]) { + while r + 1 < w && marks[row + r + 1] == 0 && similar(row + r + 1) { r += 1; } marks[row + l..=row + r].fill(255); @@ -412,7 +437,7 @@ pub fn wand_region_bound( let nrow = ny * w; let mut in_run = false; for nx in l..=r { - let ok = marks[nrow + nx] == 0 && similar(img[nrow + nx]); + let ok = marks[nrow + nx] == 0 && similar(nrow + nx); if ok && !in_run { stack.push((nx, ny)); } @@ -424,7 +449,7 @@ pub fn wand_region_bound( 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(img[y * w + x]) { + if similar(y * w + x) { *m = 255; span = Some(span.map_or((x, x), |(a, _)| (a, x))); } @@ -489,7 +514,7 @@ pub fn wand_region_bound( } #[cfg(target_arch = "wasm32")] mask.chunks_mut(bw).enumerate().for_each(|(yy, row)| fill_row(yy, row)); - let bbox = Rect::new(area.x0 + x0 as i32, area.y0 + y0 as i32, area.x0 + x1 as i32, area.y0 + y1 as i32); + 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 }) } diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 35d65b2e51d..747a6e095f9 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -135,28 +135,57 @@ pub(crate) fn sample_rgba8(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[ } } -/// The Magic Wand's sampling in an 8-bit Lab document's own colour channels (#11785); `None` -/// when the wand samples the picture as 8-bit RGBA, as before. +/// 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, an 8-bit Lab document at -/// Tolerance 5 reaches only that block, while the RGB picture (100, 105, …) reaches two of them -/// (#11785's table). The other rows of that table keep today's sampling: 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. 8-bit CMYK waits for the answer to the question -/// about its numbers (see `wand_color_mode_tests`), so the ink comparison is not in yet. -fn wand_document_channels(s: &Session, all_layers: bool) -> Option<(Rect, Vec<[u8; 4]>)> { +/// 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.mode != photocraft_doc::ColorMode::Lab || d.doc.depth != photocraft_doc::SampleType::U8 { + 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(); - if fmt.mode != photocraft_doc::ColorMode::Lab || fmt.sample != photocraft_doc::SampleType::U8 { + // 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((area, sel::stored_levels_image(surf, area))) + Some(DocumentChannels { area, levels: sel::stored_levels_planes(surf, area), channels: fmt.channels(), alpha: fmt.alpha.then_some(fmt.channels() - 1) }) } fn magic_wand(s: &mut Session, p: &Value) -> Result { @@ -165,18 +194,22 @@ fn magic_wand(s: &mut Session, p: &Value) -> Result { // 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 (area, img, bound) = match shown_gray(s) { - Some((area, img)) => (area, img, sel::WandBound::AtMost), + let picture = match shown_gray(s) { + Some((area, img)) => WandPicture::Rgba(area, img), None => match wand_document_channels(s, all_layers) { - Some((area, img)) => (area, img, sel::WandBound::Below), + Some(d) => WandPicture::Channels(d), None => { let (area, img) = sample_rgba8(s, all_layers)?; - (area, img, sel::WandBound::AtMost) + WandPicture::Rgba(area, img) } }, }; - let region = sel::wand_region_bound(&img, area, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true), bound); - drop(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), + }; + let region = sel::wand_region_on(&pixels, (x, y), f(p, "tolerance", 32.0), b(p, "contiguous", true), b(p, "antiAlias", true), bound); + drop(picture); let m = mode(p); let selected = s.edit("Magic Wand", |doc, _| { doc.selection = sel::combine_region(doc.selection.as_ref(), region.as_ref(), m); @@ -749,7 +782,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,"mode":"replace|add|subtract|intersect"="replace"} (samples the visible alpha, Quick Mask, or layer mask when that is the picture; an 8-bit Lab document measures the Tolerance on its own Lightness/a/b channels)"##, + r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"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 measures it on its own stored channels: Lightness/a/b, or the four inks with the largest difference counting)"##, has_doc, magic_wand ), diff --git a/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs index 3803c5e93df..7d588b1ef7f 100644 --- a/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs +++ b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs @@ -1,12 +1,15 @@ //! The Magic Wand's Tolerance in the document's own colour channels (#11785). //! -//! The fixture is the reference's test: a grey ramp of ten 40 px blocks (grey 100, 105, … 145) -//! from x 100, clicked on the 100 block, with Contiguous on. 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. +//! 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}; @@ -16,6 +19,21 @@ 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 @@ -27,21 +45,44 @@ fn grey(k: u8) -> u8 { fn ramp(create: &str, depth: u32, mode: Option<&str>) -> Session { let mut s = Session::new(); s.execute("file.new", json!({"width": W, "height": H, "mode": create, "depth": depth})).unwrap(); - s.edit("paint", |doc, _| { - let bg = doc.layers[0].surface_mut().unwrap(); - for k in 0..10u8 { - let v = grey(k) as f32 / 255.0; - bg.fill_rect(Rect::new(X0 + BLOCK * i32::from(k), 0, X0 + BLOCK * (i32::from(k) + 1), H), &[v, v, v, 1.0]); - } - Ok(()) - }) - .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 = Session::new(); + 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). +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); + bg.fill_rect(Rect::new(X0 + BLOCK * i32::from(k), 0, X0 + BLOCK * (i32::from(k) + 1), H), &v[..n]); + } + 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(); @@ -105,6 +146,49 @@ fn lab_document_measures_tolerance_in_its_own_channels() { assert_eq!(reach(&s), Some((100, 380))); } +/// #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() { @@ -130,48 +214,29 @@ fn grayscale_documents_keep_their_selection_at_every_depth() { } } -/// Lab at 16 and 32 bits is marked *not measured* in #11785, so it keeps today's sampling. If the -/// rows get measured, this is the test to change with them. +/// 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 lab_documents_above_8_bits_keep_todays_sampling() { - for depth in [16u32, 32] { - let mut s = ramp("rgb", depth, Some("image.mode.lab")); - assert_eq!(s.active().unwrap().doc.depth, if depth == 16 { SampleType::U16 } else { SampleType::F32 }); - // Its 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. - assert_eq!(stored(&s, 0), [108, 113, 118, 124, 129, 134, 139, 144, 149, 153], "lab {depth} Lightness"); - wand(&mut s, 5.0); - assert_eq!(reach(&s), Some((100, 180)), "lab {depth} keeps today's Tolerance 5 reach"); - wand(&mut s, 32.0); - assert_eq!(reach(&s), Some((100, 380)), "lab {depth} keeps today's Tolerance 32 reach"); +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"); + } } } -/// CMYK 8-bit is left on today's sampling for now: the reference's two CMYK numbers cannot come -/// from a per-ink comparison on this ramp, so the ink channels are not compared yet (the question -/// is on #11785). This pins what the wand does there today, and records the ink values an ink -/// comparison would measure, so the difference is on the table when that row is settled. -#[test] -fn cmyk_document_keeps_todays_sampling_until_its_numbers_are_settled() { - let mut s = ramp("rgb", 8, Some("image.mode.cmyk")); - assert_eq!(s.active().unwrap().doc.mode, ColorMode::Cmyk); - // Grey 100 … 145 as coated-CMYK inks: the cyan hovers near 96 while the black ink falls from - // 81 to 20, so the seed's steps in the inks are 0, 9, 17, 25, 32, 38, 45, 50, 56, 61. - 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"); - // On these inks Tolerance 5 would reach 100-140 and Tolerance 32 100-260, and on today's RGB - // picture (100, 105/106, 110/111, …) it reaches 100-140 and 100-380. The table's numbers, - // 100-146 and 100-341, are inside neither: they are not on the 40 px block grid. - wand(&mut s, 5.0); - assert_eq!(reach(&s), Some((100, 140)), "cmyk keeps today's Tolerance 5 reach"); - wand(&mut s, 32.0); - assert_eq!(reach(&s), Some((100, 380)), "cmyk keeps today's Tolerance 32 reach"); -} - /// The shared sampler the Paint Bucket, the Magic Eraser and the Background Eraser go through is -/// untouched: an 8-bit Lab document still hands it the RGB picture. +/// 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_in_a_lab_document() { +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]; @@ -183,4 +248,12 @@ fn the_shared_rgba8_sample_path_still_reads_rgb_in_a_lab_document() { } 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"); } From ba6ae336f35a4bb8df64994691893cf35735b1b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Sat, 7 Nov 2026 15:42:50 +0100 Subject: [PATCH 3/8] Regenerate the scorecard after merging main --- docs/scorecard.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/scorecard.md b/docs/scorecard.md index f27b45b9fb9..7e92243bf85 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 51 | 85 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 47 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 193 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 194 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 3 | 3 | 661 of 661 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -209,7 +209,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 193** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 194** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. From 35045e3fba3353fafb84b22fa81066afa1ac6468 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:46:17 +0100 Subject: [PATCH 4/8] #11882: opaque grayscale ramp in the wand tests; Magic Wand params name the Sample All Layers case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ramp fixture wrote the grey value into a grey surface's alpha; it is opaque now and the Grayscale test checks it. The params text says the document-channel comparison is for sampleAllLayers off on the active layer. Co-Authored-By: Hartmut Nörenberg Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/selection_cmds.rs | 2 +- .../src/cmd/selection_cmds/wand_color_mode_tests.rs | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index cb21e1f4417..bea69e6d3c3 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -814,7 +814,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,"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 measures it on its own stored channels: Lightness/a/b, or the four inks with the largest difference counting)"##, + r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"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)"##, has_doc, magic_wand ), diff --git a/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs index 7d588b1ef7f..adb6e02a163 100644 --- a/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs +++ b/crates/engine/src/cmd/selection_cmds/wand_color_mode_tests.rs @@ -69,14 +69,17 @@ fn ink_ramp() -> Session { } /// 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). +/// 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); - bg.fill_rect(Rect::new(X0 + BLOCK * i32::from(k), 0, X0 + BLOCK * (i32::from(k) + 1), H), &v[..n]); + 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(()) }) @@ -207,6 +210,10 @@ 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); From 07aa2d08539fa3e5084d2e8a9b750cfb818bb143 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hartmut=20N=C3=B6renberg?= Date: Fri, 13 Nov 2026 18:51:45 +0100 Subject: [PATCH 5/8] perf(algo): bound the f32 staging bands of the stored-levels reader --- crates/algo/src/selection.rs | 21 ++++++++++++++++----- crates/algo/src/selection/tests.rs | 11 +++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 7a0ba06cfb1..6483aa08ee3 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -289,13 +289,22 @@ pub fn rgba8_image(s: &Surface, area: Rect) -> Vec<[u8; 4]> { /// 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 = 256usize; + 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; @@ -614,10 +623,12 @@ fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch *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) { - if let Some((d, a)) = colour_diff(y * w + x) { - *o = fringe_coverage((d - tol) as f32, a); - } + 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); } } }; diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 5f02b53a58e..aaa6e1bc410 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"); +} From e2e40c2307d42db04d4d921b28e09ebfc9243a49 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 18:58:14 +0100 Subject: [PATCH 6/8] Port the Paint Bucket match rule into the channel-generic wand fill The merge of upstream/main put upstream's MatchRule (Wand/Bucket, #12529) beside this branch's WandPixels/wand_fill. The merge commit left the rule not threaded through wand_fill, so it did not compile. wand_fill now takes the rule: the Bucket rule is applied for RGBA pictures (the only ones the bucket paints on), every other picture and the wand use the wand rule as before. --- crates/algo/src/selection.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 66309a6eedc..f5d31075acb 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -538,16 +538,16 @@ fn wand_region_rule(px: &WandPixels, seed: (i32, i32), how: &WandMatch, rule: Ma } // 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), + 1 => wand_fill::<1>(px, seed, how, rule), + 2 => wand_fill::<2>(px, seed, how, rule), + 3 => wand_fill::<3>(px, seed, how, rule), + 4 => wand_fill::<4>(px, seed, how, rule), + _ => wand_fill::<5>(px, seed, how, rule), } } /// [`wand_region_on`] for `CH` stored channels per pixel. -fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch) -> Option { +fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch, rule: MatchRule) -> 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) { From 97de98dcd12aa57701c38f66bc6b3ea6bf711d93 Mon Sep 17 00:00:00 2001 From: hnoerenberg Date: Wed, 18 Nov 2026 23:07:56 +0100 Subject: [PATCH 7/8] perf(algo): keep the RGBA wand fill the Paint Bucket and Magic Eraser share The generic per-channel fill made an RGBA contiguous fill 1.2-1.6x slower on a 24 MP image (Magic Wand, Paint Bucket, Magic Eraser). wand_region_by, wand_region_bucket and wand_region_on with an RGBA picture under the inclusive bound now run the unchanged region_by_rule again; only a document's own Lab or CMYK channels take the generic fill, which no longer carries the bucket rule. Results are hash-identical to the fill before this PR. --- crates/algo/src/selection.rs | 178 +++++++++++++++++++++++++++++------ 1 file changed, 148 insertions(+), 30 deletions(-) diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index f5d31075acb..44cb797501f 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -455,8 +455,7 @@ pub fn wand_region_by( within: Option<&[f32]>, distance: ColorDistance, ) -> Option { - let how = WandMatch { tolerance, contiguous, anti_alias, bound: WandBound::AtMost, within, distance }; - wand_region_rule(&WandPixels::rgba(area, img.as_flattened()), seed, &how, MatchRule::Wand) + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, within, distance, MatchRule::Wand) } /// Which pixels count as "similar" to the clicked one. @@ -465,8 +464,7 @@ enum MatchRule { /// The Magic Wand / Magic Eraser rule: colour and alpha each within Tolerance, except that /// two fully transparent pixels always match. Wand, - /// The Paint Bucket rule, see [`wand_region_bucket`]. Only RGBA pictures have it; any other - /// picture is compared by the wand rule. + /// The Paint Bucket rule, see [`wand_region_bucket`]. Bucket, } @@ -487,8 +485,136 @@ enum MatchRule { /// Only that one semi-transparent case was measured; unmeasured cases keep the previous /// behaviour. [`wand_region`] and [`wand_region_within`] are unchanged. pub(crate) fn wand_region_bucket(img: &[[u8; 4]], area: Rect, seed: (i32, i32), tolerance: f32, contiguous: bool, anti_alias: bool) -> Option { - let how = WandMatch::new(tolerance, contiguous, anti_alias, WandBound::AtMost); - wand_region_rule(&WandPixels::rgba(area, img.as_flattened()), seed, &how, MatchRule::Bucket) + region_by_rule(img, area, seed, tolerance, contiguous, anti_alias, None, ColorDistance::LargestChannel, MatchRule::Bucket) +} + +#[allow(clippy::too_many_arguments)] +fn region_by_rule( + img: &[[u8; 4]], + area: Rect, + seed: (i32, i32), + tolerance: f32, + contiguous: bool, + anti_alias: bool, + within: Option<&[f32]>, + distance: ColorDistance, + rule: MatchRule, +) -> Option { + if !area.contains(seed.0, seed.1) { + return None; + } + let (w, h) = (area.width() as usize, area.height() as usize); + if w.checked_mul(h).is_none_or(|n| n > img.len()) { + return None; + } + let within = within.filter(|_| 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)); + if !inside((seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize) { + return None; + } + let target = img[(seed.1 - area.y0) as usize * w + (seed.0 - area.x0) as usize]; + let tol = (tolerance + 1e-3).floor().max(0.0) as i32; + // Copying a selection can leave RGB under zero alpha. Those invisible colours must not + // split a transparent region into pieces, as if the copied source were still visible. + let similar = |p: [u8; 4]| match rule { + MatchRule::Wand => (target[3] == 0 && p[3] == 0) || (distance.rgb(p, target) <= tol && (p[3] as i32 - target[3] as i32).abs() <= tol), + MatchRule::Bucket => match target[3] { + 0 => p[3] == 0, + 255 => distance.rgb(p, target) <= tol && (p[3] as i32 - 255).abs() <= tol, + _ => p[3] != 0 && distance.rgb(p, target) <= tol && (p[..3] == target[..3] || (p[3] as i32 - target[3] as i32).abs() <= tol), + }, + }; + 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 - area.x0) as usize, (seed.1 - 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(img[row + l - 1]) && inside(row + l - 1) { + l -= 1; + } + while r + 1 < w && marks[row + r + 1] == 0 && similar(img[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(img[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(img[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 p = img[y * w + x]; + *o = fringe_coverage((distance.rgb(p, target) - tol) as f32, f32::from(p[3].min(target[3]))); + } + } + }; + #[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(area.x0 + x0 as i32, area.y0 + y0 as i32, area.x0 + x1 as i32, area.y0 + y1 as i32); + Some(Region { bbox, mask }) } /// How [`wand_region_on`] matches pixels against the clicked one. @@ -528,26 +654,28 @@ impl WandMatch<'_> { /// 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 { - wand_region_rule(px, seed, how, MatchRule::Wand) -} - -/// [`wand_region_on`] under a [`MatchRule`]. -fn wand_region_rule(px: &WandPixels, seed: (i32, i32), how: &WandMatch, rule: MatchRule) -> 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>(); + return region_by_rule(img, px.area, seed, 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, rule), - 2 => wand_fill::<2>(px, seed, how, rule), - 3 => wand_fill::<3>(px, seed, how, rule), - 4 => wand_fill::<4>(px, seed, how, rule), - _ => wand_fill::<5>(px, seed, how, rule), + 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. -fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch, rule: MatchRule) -> Option { +/// [`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) { @@ -582,18 +710,8 @@ fn wand_fill(px: &WandPixels, seed: (i32, i32), how: &WandMatch 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); - match (rule, alpha) { - // The Paint Bucket rule is measured on RGBA pictures only. - (MatchRule::Bucket, Some(a)) if rgba => match target[a] { - 0 => v[a] == 0, - 255 => d <= tol && (v[a] as i32 - 255).abs() <= tol, - _ => v[a] != 0 && d <= tol && (v[..a] == target[..a] || (v[a] as i32 - target[a] as i32).abs() <= tol), - }, - _ => { - 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) - } - } + 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) }; let mut marks = vec![0u8; w * h]; let (mut bx0, mut by0, mut bx1, mut by1) = (usize::MAX, usize::MAX, 0usize, 0usize); From 7d10e056ee66de6c3083976c2f88c710211a451b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 23:13:46 +0100 Subject: [PATCH 8/8] test(engine-core): start the wand colour-mode tests from an installed session Main split the engine; engine-core tests get their commands from crate::session(). Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/selection_cmds/wand_color_mode_tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index adb6e02a163..dde27e10c7e 100644 --- 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 @@ -43,7 +43,7 @@ fn grey(k: u8) -> u8 { /// › 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 = Session::new(); + 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; @@ -58,7 +58,7 @@ fn ramp(create: &str, depth: u32, mode: Option<&str>) -> Session { /// 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 = Session::new(); + 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];