From 2eec35506742e28c5e2e9ab5468b419fdd65467b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 30 Oct 2026 22:24:58 -0700 Subject: [PATCH 01/29] Tests: CMYK proptest regression seeds run again 7e52b713d moved crates/compose/src/cmyk_tests.rs to cmyk/tests.rs. proptest looks for saved seeds next to the source file, at proptest-regressions/cmyk/tests.txt, so the four seeds in proptest-regressions/cmyk_tests.txt stopped running. Rename the file to the new path. --- .../proptest-regressions/{cmyk_tests.txt => cmyk/tests.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename crates/compose/proptest-regressions/{cmyk_tests.txt => cmyk/tests.txt} (100%) diff --git a/crates/compose/proptest-regressions/cmyk_tests.txt b/crates/compose/proptest-regressions/cmyk/tests.txt similarity index 100% rename from crates/compose/proptest-regressions/cmyk_tests.txt rename to crates/compose/proptest-regressions/cmyk/tests.txt 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 02/29] 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 f740687c1a..0602fc16ff 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 13737e70bd..35d65b2e51 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 0000000000..3803c5e93d --- /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 03/29] 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 0602fc16ff..dc51524779 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 35d65b2e51..747a6e095f 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 3803c5e93d..7d588b1ef7 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 04/29] 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 f27b45b9fb..7e92243bf8 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 1b3312fd8c7912873b070610e00d842039649c87 Mon Sep 17 00:00:00 2001 From: DuBearte <130190089+DuBearte@users.noreply.github.com> Date: Sat, 7 Nov 2026 14:12:06 -0500 Subject: [PATCH 05/29] Brush Preset picker: Size and Hardness take whole numbers and alert when out of range Fixes #11817. Co-Authored-By: Claude Opus 5.5 --- .../src/brush_picker_range_alert_tests.rs | 88 +++++++++++++++++++ crates/ui-egui/src/lib.rs | 2 + crates/ui-egui/src/tools/brush_picker.rs | 56 ++++++++++-- 3 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/brush_picker_range_alert_tests.rs diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs new file mode 100644 index 0000000000..80fdabe2ae --- /dev/null +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -0,0 +1,88 @@ +//! #11817: the Brush Preset picker's Size and Hardness take whole numbers; a value typed past the +//! range becomes the closest one and, once the field is left, an alert with OK says so. The +//! picker stays open after OK. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::brush_picker::{HARDNESS_RANGE_ALERT, SIZE_RANGE_ALERT}; +use crate::state::DialogKind; +use crate::{PhotocraftApp, Services, Tool}; + +fn harness() -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.5}})).unwrap(); + app.ui.tool = Tool::Brush; + app + }); + h.run_steps(5); + let ctx = h.ctx.clone(); + let c = h.state().last_canvas_rect.center(); + crate::brush_picker::open(&mut h.state_mut().ui, &ctx, [c.x, c.y]); + h.run_steps(3); + h +} + +/// Type `text` into the picker field named `name`, then Tab out of it. +fn type_into(h: &mut Harness<'static, PhotocraftApp>, name: &str, text: &str) { + h.query_all_by_role(egui::accesskit::Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(name)).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alert(h: &Harness<'static, PhotocraftApp>) -> Option { + h.state().ui.dialogs.iter().find(|d| d.kind == DialogKind::Error).and_then(|d| d.fields.get("message")).and_then(|m| m.as_str()).map(str::to_owned) +} + +fn size(h: &Harness<'static, PhotocraftApp>) -> f32 { + h.state().session.tools.brush.size +} + +#[test] +fn size_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("9999", 5000.0), ("0", 1.0), ("-5", 1.0)] { + let mut h = harness(); + type_into(&mut h, "Size", typed); + assert_eq!(size(&h), want, "{typed}"); + assert_eq!(alert(&h).as_deref(), Some(SIZE_RANGE_ALERT), "{typed}"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open under the alert"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alert(&h), None, "{typed}: OK closes the alert"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open after OK"); + } +} + +#[test] +fn size_in_range_cuts_fractions_without_an_alert() { + let mut h = harness(); + type_into(&mut h, "Size", "2.5"); + assert_eq!(size(&h), 2.0); + assert_eq!(alert(&h), None); + type_into(&mut h, "Size", "abc"); + assert_eq!(size(&h), 2.0, "not a number: the value stays"); + assert_eq!(alert(&h), None); +} + +#[test] +fn hardness_past_the_range_takes_100_and_alerts() { + let mut h = harness(); + type_into(&mut h, "Hardness", "150"); + assert_eq!(h.state().session.tools.brush.hardness, 1.0); + assert_eq!(alert(&h).as_deref(), Some(HARDNESS_RANGE_ALERT)); + h.get_by_label("OK").click(); + h.run_steps(4); + assert!(h.state().ui.brush_picker.is_some()); + type_into(&mut h, "Hardness", "33.7"); + assert_eq!(h.state().session.tools.brush.hardness, 0.33, "a whole percent"); + assert_eq!(alert(&h), None); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f19ec41da9..1853c7fab3 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -997,6 +997,8 @@ mod pen_path_ownership_tests; #[cfg(test)] mod artboard_options_bar_tests; #[cfg(test)] +mod brush_picker_range_alert_tests; +#[cfg(test)] mod doc_tab_menu_tests; #[cfg(test)] mod layers_empty_area_menu_tests; diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index 3e59a90444..01e0f2404c 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -65,8 +65,15 @@ pub enum Pick { NewPreset, /// Import brushes (.abr) with the file dialog. Import, + /// A value typed out of range was replaced by the closest one: say so in an alert with OK, + /// as Photoshop does (#11817). The English message, translated when shown. + RangeAlert(&'static str), } +/// The alerts for Size and Hardness typed out of range (#11817). +pub const SIZE_RANGE_ALERT: &str = "An integer between 1 pixel and 5000 Pixels is required. Closest value inserted."; +pub const HARDNESS_RANGE_ALERT: &str = "An integer between 0% and 100% is required. Closest value inserted."; + impl Pick { /// Does this pick dismiss the picker? A double-click on a preset does (Photoshop), and so does /// anything that opens another panel or dialog. @@ -204,6 +211,17 @@ pub fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, picks: Vec) { Pick::Import => { let _ = crate::preset_files_ui::import_brushes(app); } + Pick::RangeAlert(message) => { + let message = tl!(message).to_owned(); + let shown = app + .ui + .dialogs + .iter() + .any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); + if !shown { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({ "message": message }).as_object().cloned().unwrap_or_default()); + } + } } } } @@ -231,6 +249,24 @@ pub fn settings_toggle(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } } +/// A picker field of whole numbers in `lo..=hi` (#11817): a typed fraction is cut off (2.5 → 2), +/// text that is no number leaves the value, and a value past the range becomes the closest one, +/// with `alert` once the field is left. +fn integer_field(ui: &mut egui::Ui, value: &mut f32, (lo, hi): (f32, f32), suffix: &str, name: &str, alert: &'static str, picks: &mut Vec) -> bool { + // The field's own range is wide, so the typed value reaches here unclamped. + let mut typed = *value; + let r = widgets::value_field(ui, &mut typed, -1.0e9..=1.0e9, suffix, 72.0).accessible_name(tl!(name)); + let out_id = r.id.with("out-of-range"); + if r.changed() && typed.is_finite() { + *value = typed.trunc().clamp(lo, hi); + ui.ctx().data_mut(|d| d.insert_temp(out_id, typed < lo || typed > hi)); + } + if r.lost_focus() && ui.ctx().data_mut(|d| d.remove_temp::(out_id)).unwrap_or(false) { + picks.push(Pick::RangeAlert(alert)); + } + r.changed() && typed.is_finite() +} + /// An icon button's accessible name (icon buttons have only a tooltip). pub(crate) fn named(resp: egui::Response, label: &str) -> egui::Response { resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(label))); @@ -269,10 +305,7 @@ pub fn body( ui.horizontal(|ui| { ui.label(RichText::new(tl!("Size")).color(t.text_dim)); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let mut size = b.size; - if widgets::value_field(ui, &mut size, 1.0..=MAX_BRUSH_SIZE, "px", 72.0).accessible_name(tl!("Size")).changed() { - b.size = size.round().clamp(1.0, MAX_BRUSH_SIZE); - } + integer_field(ui, &mut b.size, (1.0, MAX_BRUSH_SIZE), "px", "Size", SIZE_RANGE_ALERT, &mut picks); }); }); let mut lv = b.size.max(1.0).ln(); @@ -282,10 +315,19 @@ pub fn body( } dismiss_popup(&size_slider); if b.tip == TipShape::Round { + // Like Size: a caption and a whole-number field, then the slider. let mut hard = b.hardness * 100.0; - let hardness = widgets::slider_row(ui, "Hardness", &mut hard, 0.0..=100.0, "%", None); - if hardness.changed() { - b.hardness = (hard / 100.0).clamp(0.0, 1.0); + let mut typed = false; + ui.horizontal(|ui| { + ui.label(RichText::new(tl!("Hardness")).color(t.text_dim)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + typed = integer_field(ui, &mut hard, (0.0, 100.0), "%", "Hardness", HARDNESS_RANGE_ALERT, &mut picks); + }); + }); + let hardness = widgets::slider(ui, &mut hard, 0.0..=100.0, None); + hardness.widget_info(|| egui::WidgetInfo::slider(true, f64::from(hard), tl!("Hardness"))); + if typed || hardness.changed() { + b.hardness = (hard.round() / 100.0).clamp(0.0, 1.0); } dismiss_popup(&hardness); } From 35045e3fba3353fafb84b22fa81066afa1ac6468 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:46:17 +0100 Subject: [PATCH 06/29] #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 cb21e1f441..bea69e6d3c 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 7d588b1ef7..adb6e02a16 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 07/29] 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 7a0ba06cfb..6483aa08ee 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 5f02b53a58..aaa6e1bc41 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -829,3 +829,14 @@ fn color_matcher_tree_reservation_failure_is_reported() { assert_eq!(tree.nodes.len(), ColorBvh::node_count(n)); } } + +#[test] +fn stored_levels_bands_bound_the_f32_staging_on_wide_areas() { + // #11785 review: one parallel reader's f32 staging stays near 2 MB. A 6000 px CMYK strip + // (the Magic Eraser/Wand worst case on 24 MP documents) shrinks from 256 rows to fit; + // narrow areas keep full bands; an absurdly wide one clamps to the 16-row floor. + let rows = levels_band_rows(6000, 4); + assert!(rows >= 16 && 6000 * 4 * 4 * rows <= (2u64 << 20) as usize, "6000 px CMYK band rows: {rows}"); + assert_eq!(levels_band_rows(1, 1), 256, "narrow areas keep full 256-row bands"); + assert_eq!(levels_band_rows(100_000, 5), 16, "an extreme width clamps to the floor"); +} From e2e40c2307d42db04d4d921b28e09ebfc9243a49 Mon Sep 17 00:00:00 2001 From: Hartmut Noerenberg Date: Sat, 14 Nov 2026 18:58:14 +0100 Subject: [PATCH 08/29] 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 66309a6eed..f5d31075ac 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 09/29] 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 f5d31075ac..44cb797501 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 50e8698044c1b8793770dfdef89a5bd0e2f77698 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 18:47:22 -0800 Subject: [PATCH 10/29] Rerun CI From e88f20bedc49861694f981d713de67695ef4a65a Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:31:07 +0100 Subject: [PATCH 11/29] Hold a legacy Brightness/Contrast brightness in -100..100 With Use Legacy on, image.adjustments.brightnessContrast read brightness over -150..150 and applied {"brightness":150,"legacy":true} as is. Legacy brightness now clamps to -100..100, including a base brightness carried over when only `legacy` is set. Modern mode keeps -150..150. Refs #14350 --- crates/engine-core/src/adjust_params.rs | 8 ++++-- .../brightness_contrast_limits_tests.rs | 28 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs diff --git a/crates/engine-core/src/adjust_params.rs b/crates/engine-core/src/adjust_params.rs index 930d47c3f8..e7050d4e2b 100644 --- a/crates/engine-core/src/adjust_params.rs +++ b/crates/engine-core/src/adjust_params.rs @@ -103,8 +103,9 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color _ => (0.0, 0.0, false), }; let legacy = r.boolean("legacy", l0)?; - let (lo, hi) = if legacy { (-100.0, 100.0) } else { (-50.0, 100.0) }; - Adjustment::BrightnessContrast { brightness: r.num("brightness", b0, -150.0, 150.0)?, contrast: r.num("contrast", c0, lo, hi)?, legacy } + // Use Legacy narrows Brightness to −100..100 and widens Contrast to −100..100. + let (b_lo, b_hi, c_lo) = if legacy { (-100.0, 100.0, -100.0) } else { (-150.0, 150.0, -50.0) }; + Adjustment::BrightnessContrast { brightness: r.num("brightness", b0, b_lo, b_hi)?, contrast: r.num("contrast", c0, c_lo, 100.0)?, legacy } } "threshold" => { let l0 = match base { @@ -1301,3 +1302,6 @@ pub fn user_keys(p: &Value) -> Map { #[cfg(test)] mod tests; + +#[cfg(test)] +mod brightness_contrast_limits_tests; diff --git a/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs b/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs new file mode 100644 index 0000000000..36e4278bae --- /dev/null +++ b/crates/engine-core/src/adjust_params/brightness_contrast_limits_tests.rs @@ -0,0 +1,28 @@ +//! Brightness/Contrast limits with and without Use Legacy (#14350). + +use super::*; + +fn brightness(p: Value, base: Option<&Adjustment>) -> f32 { + match from_params("brightnessContrast", &p, base, ColorMode::Rgb).unwrap() { + Adjustment::BrightnessContrast { brightness, .. } => brightness, + other => panic!("not Brightness/Contrast: {other:?}"), + } +} + +#[test] +fn a_legacy_brightness_past_100_is_held_at_the_limit() { + assert_eq!(brightness(json!({"brightness": 150, "legacy": true}), None), 100.0); + assert_eq!(brightness(json!({"brightness": -999, "legacy": true}), None), -100.0); +} + +#[test] +fn modern_brightness_keeps_its_wider_range() { + assert_eq!(brightness(json!({"brightness": 150}), None), 150.0); + assert_eq!(brightness(json!({"brightness": -150}), None), -150.0); +} + +#[test] +fn turning_legacy_on_over_a_modern_brightness_past_100_holds_it_at_the_limit() { + let modern = from_params("brightnessContrast", &json!({"brightness": 130}), None, ColorMode::Rgb).unwrap(); + assert_eq!(brightness(json!({"legacy": true}), Some(&modern)), 100.0); +} From 2a32a22624a2f24623e1289b3fae485debfd2fed Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 15:52:21 +0100 Subject: [PATCH 12/29] Brush Preset picker: a Size or Hardness typed out of range opens the range alert (#11817) The picker's head now reports a value typed past its range (storytold/craft-libs#4273); apply opens the shared range alert for it, as the options bar does, and the picker stays open under it. Co-Authored-By: Claude Opus 5.5 --- .../src/brush_picker_range_alert_tests.rs | 92 +++++++++++++++++++ crates/ui-egui/src/tools/brush_picker.rs | 20 ++-- 2 files changed, 106 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/brush_picker_range_alert_tests.rs diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs new file mode 100644 index 0000000000..7232f03ba4 --- /dev/null +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -0,0 +1,92 @@ +//! #11817: a Size or Hardness typed past its range in the Brush Preset picker takes the closest value and opens the +//! range alert; the picker stays open under it and after OK. A value in range and a slider press open none. + +use crate::app::framework::BuildApp as _; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn harness() -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.5}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).with_context(app.ctx().clone()).build_app( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // The canvas shows the picker itself (`canvas_tool_menu::run`). + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + crate::brush_picker::open(h.state_mut(), [c.x, c.y]); + h.run_steps(3); + h +} + +/// Type `text` into the picker's `n`th spin field (0 Size, 1 Hardness), then Tab. +fn type_into(h: &mut Harness<'static, Box>, n: usize, text: &str) { + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, Box>) -> usize { + h.state().framework.dialogs.open_dialogs().len() +} + +fn size_and_hardness(h: &Harness<'static, Box>) -> (f32, f32) { + let b = &h.state().session.tools.brush; + (b.size, b.hardness) +} + +#[test] +fn size_and_hardness_typed_out_of_range_alert_and_the_picker_stays_open() { + for (n, typed, want) in [(0, "9999", (5000.0, 0.5)), (0, "0", (1.0, 0.5)), (1, "150", (20.0, 1.0))] { + let mut h = harness(); + type_into(&mut h, n, typed); + assert_eq!(size_and_hardness(&h), want, "{typed}: the closest value"); + assert_eq!(alerts(&h), 1, "{typed}: one range alert"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open under the alert"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alerts(&h), 0, "{typed}: OK closes the alert"); + assert_eq!(size_and_hardness(&h), want, "{typed}: OK keeps the closest value"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open after OK"); + } +} + +#[test] +fn a_value_in_range_and_a_slider_press_open_no_alert() { + let mut h = harness(); + type_into(&mut h, 0, "40"); + assert_eq!(size_and_hardness(&h).0, 40.0); + let slider = h + .get_all_by_role(egui::accesskit::Role::Slider) + .find(|n| n.accesskit_node().label().as_deref() == Some("Hardness")) + .expect("the Hardness slider") + .rect(); + let at = slider.left_center() + vec2(slider.width() * 0.8, 0.0); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(size_and_hardness(&h).1 > 0.5, "the press moved Hardness"); + assert_eq!(alerts(&h), 0, "nothing was typed out of range"); +} diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index 16abf9696e..a0fc3024d8 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -98,9 +98,10 @@ fn commit_edits(app: &mut PhotocraftApp, events: &EditEvents, set: impl Fn } } -/// Runs what the picker reported: the head's edits, Escape's revert, the saved view and the picks. -/// `keys` are every row's key in list order (a reorder pick is placed by them). -pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushKey], out: BrushPresetPickerOutput) { +/// Runs what the picker reported: the head's edits, Escape's revert, the range alert for a Size or Hardness typed out +/// of range (the picker stays open under it, #11817), the saved view and the picks. `keys` are every row's key in list +/// order (a reorder pick is placed by them); `ui` words the alert's range. +pub(crate) fn apply(app: &mut PhotocraftApp, ui: &egui::Ui, keys: &[BrushKey], out: BrushPresetPickerOutput) { commit_edits(app, &out.diameter, |b, v| b.size = *v as f32); commit_edits(app, &out.hardness, |b, v| b.hardness = *v as f32); commit_edits(app, &out.tip, |b, v| { @@ -121,12 +122,15 @@ pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushK // One command and no history step: `tools.setBrush` without a coalesce key is a tool setting. commit_keyed(app, &now, &after, None); } + if let Some(alert) = &out.out_of_range { + crate::tools::option_cells::range_alert(app, ui, alert); + } if let Some(settings) = &out.settings { save(app, settings); } for pick in out.picks { match pick { - BrushPick::OpenSettings => open_settings(app, ctx), + BrushPick::OpenSettings => open_settings(app, ui.ctx()), other => run_picks(app, vec![other], keys), } } @@ -157,7 +161,7 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) { }; let _ = MemoView::new("brush-preset-canvas", props, canvas_view).show(ui); for CanvasEvent { out, keys, eraser, closed } in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); if let Some(rows) = eraser { commit_keyed(app, &rows.before, &rows.brush, rows.key); if app.ui.tool_options.bg_tolerance_control != rows.tolerance { @@ -249,7 +253,7 @@ pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bo }; let _ = MemoView::new("brush-preset-field", props, field_view).show(ui); for FieldEvent(out, keys) in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); } } @@ -393,3 +397,7 @@ fn toggle_view(props: &mut ToggleProps<'_>, ui: &mut egui::Ui) { #[cfg(test)] #[path = "../brush_picker_gear_menu_tests.rs"] mod gear_menu_tests; + +#[cfg(test)] +#[path = "../brush_picker_range_alert_tests.rs"] +mod range_alert_tests; From 768592563375efe1ccd71c9fcfbf7f6e9c041877 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 21:57:23 +0100 Subject: [PATCH 13/29] Brush Preset picker range alert test: show the dialogs, so OK can be pressed Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/brush_picker_range_alert_tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs index 7232f03ba4..4ebdea739d 100644 --- a/crates/ui-egui/src/brush_picker_range_alert_tests.rs +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -23,6 +23,7 @@ fn harness() -> Harness<'static, Box> { } // The canvas shows the picker itself (`canvas_tool_menu::run`). egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); + crate::dialogs::run(app, ui); }, app, ); From 7d10e056ee66de6c3083976c2f88c710211a451b Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 23:13:46 +0100 Subject: [PATCH 14/29] 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 adb6e02a16..dde27e10c7 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]; From 8fbc6fa707b216bf7cdcad410432755ecc75e6fa Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 23:26:05 +0100 Subject: [PATCH 15/29] Fill: grey History in Contents when its source does not match (#17464) The Fill dialog asks the engine whether `edit.fill` with History would find a usable source (history_source::fill_source_usable, built on checked_source) and greys History in Contents when not, so the dropdown and the command never disagree. Today that is a source of another canvas size; a mode or depth refusal added to checked_source follows on its own. Co-Authored-By: Claude Opus 5.5 --- crates/engine-paint/src/history_source.rs | 7 + crates/engine-paint/src/lib.rs | 2 +- crates/engine/src/facade.rs | 4 +- .../src/dialogs/fill_history_greyed_tests.rs | 138 ++++++++++++++++++ crates/ui-egui/src/dialogs/fill_ui.rs | 13 +- 5 files changed, 158 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs diff --git a/crates/engine-paint/src/history_source.rs b/crates/engine-paint/src/history_source.rs index ab82fbf3b0..4bf85dbf11 100644 --- a/crates/engine-paint/src/history_source.rs +++ b/crates/engine-paint/src/history_source.rs @@ -51,6 +51,13 @@ pub fn checked_source(st: &DocState, p: &Value, cmd: &str) -> Result bool { + matches!(checked_source(st, &Value::Null, "edit.fill"), Ok(Ok(_))) +} + /// The History Brush's refusals after Image › Mode, with Photoshop's alert texts (#12842): only /// the History Brush's pairs were measured (RGB to Grayscale, a depth change), so any other change, /// or both at once, converts the source as before. Document modes are compared: the pixel format diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index e52e2c9524..a723360351 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -17,7 +17,7 @@ use photocraft_engine_core::{ use photocraft_engine_core::{command_specs, hidden_target, param_schema, prefs}; pub mod cmd; -mod history_source; +pub mod history_source; mod install; pub use cmd::adjustment_brush_cmds; diff --git a/crates/engine/src/facade.rs b/crates/engine/src/facade.rs index 87d81460e7..b719e0322d 100644 --- a/crates/engine/src/facade.rs +++ b/crates/engine/src/facade.rs @@ -16,8 +16,8 @@ pub use photocraft_engine_core::Session as CoreSession; pub use photocraft_engine_core::*; // The painting commands' modules, at the paths they had inside the engine. pub use photocraft_engine_paint::{ - adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, paint_cmds, pick_cmds, redeye_cmds, retouch_cmds, - sampler_cmds, stamp_cmds, + adjustment_brush_cmds, brush_cmds, brush_key_cmds, eraser_cmds, face_cmds, fill_cmds, fill_key_cmds, history_source, paint_cmds, pick_cmds, redeye_cmds, + retouch_cmds, sampler_cmds, stamp_cmds, }; // The vector-area commands' modules, likewise. pub use photocraft_engine_vector::{ diff --git a/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs b/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs new file mode 100644 index 0000000000..0f70e874c7 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fill_history_greyed_tests.rs @@ -0,0 +1,138 @@ +//! #17464: the Fill dialog greys History in Contents whenever `edit.fill` would refuse the History source (another +//! canvas size after Image Size, Canvas Size, Crop or Rotate 90°), by the engine's own check; with a matching source it +//! stays enabled. The other entries keep their order and state. + +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use photocraft_engine::history_source::fill_source_usable; +use serde_json::{Value, json}; + +use super::*; +use crate::smart_filter_dialog::tests::cancel; + +/// A white 40×30 document with a pixel layer "Paint" active and a selection, so only History's rule can grey an entry. +/// The current state is the History source, so the source has the layer Fill paints on. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 40, "height": 30, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({"name": "Paint"})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 15})).unwrap(); + source_current(&mut app); + app +} + +/// Make the current state the History source. +fn source_current(app: &mut PhotocraftApp) { + let current = app.session.active().unwrap().history.entries().len() - 1; + app.run("history.setSource", json!({"state": current})).unwrap(); +} + +/// The canvas changes that leave the opening state's source at another size. Each is run by [`resized`]. +fn resizes() -> Vec<(&'static str, Value)> { + vec![ + ("image.imageSize", json!({"width": 20, "height": 15})), + ("image.canvasSize", json!({"width": 50, "height": 30})), + ("image.crop", json!({"x": 0, "y": 0, "width": 30, "height": 20})), + ("image.imageRotation.90cw", json!({})), + ] +} + +/// [`app`] after `cmd`, with a selection again (Image Size drops it), so Content-Aware's own rule stays out. +fn resized(cmd: &str, p: Value) -> Box { + let mut app = app(); + app.run(cmd, p).unwrap(); + app.run("select.rect", json!({"x": 2, "y": 2, "width": 8, "height": 6})).unwrap(); + app +} + +fn contents_row(app: &PhotocraftApp) -> Param { + rows(app, [0.0; 3], None, None).into_iter().find(|r| r.key == "contents").expect("a Contents row") +} + +fn keys(row: &Param) -> Vec { + let ParamKind::Choice { options, .. } = &row.kind else { panic!("Contents is a choice row") }; + options.iter().map(|(k, _)| k.clone()).collect() +} + +fn choosable(app: &mut PhotocraftApp, id: DialogId, key: &str) -> bool { + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, "contents", json!(key)).is_ok() +} + +fn contents(app: &PhotocraftApp, id: DialogId) -> Option { + let dialog = app.framework.dialogs.get_by_id::(id).expect("a hosted dialog"); + dialog.fields().text("contents").map(str::to_string) +} + +/// Whether `edit.fill` with History succeeds, undone again so the document stays as it was. +fn history_fill_succeeds(app: &mut PhotocraftApp) -> bool { + let ok = app.run(COMMAND, json!({"contents": "history"})).is_ok(); + if ok { + app.run("edit.undo", json!({})).unwrap(); + } + ok +} + +#[test] +fn history_is_enabled_on_the_unchanged_document() { + let mut app = app(); + assert!(contents_row(&app).option_enabled("history")); + let id = open(&mut app); + assert!(choosable(&mut app, id, "history")); + cancel(&mut app, id); +} + +#[test] +fn a_source_of_another_canvas_size_greys_history_and_it_cannot_be_chosen() { + for (cmd, p) in resizes() { + let mut app = resized(cmd, p); + let row = contents_row(&app); + assert!(!row.option_enabled("history"), "{cmd}: History greyed"); + let order: Vec = CONTENTS.iter().map(|(k, _)| k.to_string()).collect(); + assert_eq!(keys(&row), order, "{cmd}: every entry listed, in the same order"); + for (key, _) in CONTENTS.iter().filter(|(k, _)| *k != "history") { + assert!(row.option_enabled(key), "{cmd}: {key} stays enabled"); + } + + let id = open(&mut app); + let before = contents(&app, id); + assert!(!choosable(&mut app, id, "history"), "{cmd}: History cannot be chosen"); + assert_eq!(contents(&app, id), before, "{cmd}: the choice is unchanged"); + cancel(&mut app, id); + } +} + +#[test] +fn a_matching_source_keeps_history_enabled() { + for (cmd, p) in resizes() { + let mut app = resized(cmd, p); + // The current state, which has the new size, becomes the source. + source_current(&mut app); + assert!(contents_row(&app).option_enabled("history"), "{cmd}: History enabled with a source of this size"); + } +} + +#[test] +fn the_dropdown_and_the_command_agree() { + let mut cases = vec![app()]; + for (cmd, p) in resizes() { + cases.push(resized(cmd, p)); + } + for mut app in cases { + let usable = fill_source_usable(app.session.active().unwrap()); + assert_eq!(contents_row(&app).option_enabled("history"), usable); + assert_eq!(history_fill_succeeds(&mut app), usable, "History offered exactly when the fill succeeds"); + } +} + +/// The framework restores only the remembered values a row accepts: a remembered History is dropped once greyed and the +/// row opens on its default, as it does for any unavailable choice; with a usable source it is kept. +#[test] +fn a_remembered_history_choice_keeps_todays_fallback_once_greyed() { + let mut saved = DialogFields::new(); + saved.set("contents", "history"); + let unchanged = ParamDialog::remembered(&rows(&app(), [0.0; 3], None, None), &saved); + assert_eq!(unchanged.text("contents"), Some("history"), "kept while usable"); + let app = resized("image.imageSize", json!({"width": 20, "height": 15})); + let greyed = ParamDialog::remembered(&rows(&app, [0.0; 3], None, None), &saved); + assert_eq!(greyed.text("contents"), None, "dropped once greyed: the row opens on Foreground Color"); +} diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 8450823468..4fa192b0e9 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -44,10 +44,14 @@ pub(crate) fn hex(c: [f32; 3]) -> String { fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option, preserve: Option) -> Vec { let contents = CONTENTS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect(); let mut contents = Param::new("contents", tl!("Contents:"), ParamKind::choice(contents, Some("foreground".into()))); + let st = app.session.active(); // Content-Aware fills a selection from around it: without one it is listed greyed, as in the reference (#17462). - if app.session.active().is_none_or(|st| st.doc.selection.is_none()) { - contents = contents.disabled_options(["contentAware"]); - } + // History is greyed whenever `edit.fill` would refuse its source, by the engine's own check (#17464). + let greyed = [ + ("contentAware", st.is_none_or(|st| st.doc.selection.is_none())), + ("history", st.is_none_or(|st| !photocraft_engine::history_source::fill_source_usable(st))), + ]; + contents = contents.disabled_options(greyed.into_iter().filter(|(_, off)| *off).map(|(key, _)| key)); let mut rows = vec![ contents, Param::new("color", tl!("Color:"), ParamKind::color(Some(foreground))).visible_when("contents", "color"), @@ -176,6 +180,9 @@ pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamRes #[cfg(test)] mod content_aware_greyed_tests; #[cfg(test)] +#[path = "fill_history_greyed_tests.rs"] +mod fill_history_greyed_tests; +#[cfg(test)] mod opacity_alert_tests; #[cfg(test)] mod preserve_transparency_state_tests; From 86c3e0cfea95c5de47d129c9cd2d35ebf2fdfd38 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 23:56:28 +0100 Subject: [PATCH 16/29] Fill: History on a layer missing from the source clears to transparent (#17465) Edit > Fill with History read the source surface by the target layer's id and failed when the source state did not have that layer (a new or duplicated layer, every layer after Flatten Image). As in the reference application, such a layer now counts as transparent in the source: the selection is cleared, and the Background after Flatten Image takes white. A mask, alpha channel or Quick Mask the source lacks is still refused. Co-Authored-By: Claude Opus 5.5 --- crates/engine-paint/src/cmd/fill_cmds.rs | 20 ++- .../src/fill_history_missing_layer_tests.rs | 147 ++++++++++++++++++ 2 files changed, 164 insertions(+), 3 deletions(-) create mode 100644 crates/engine-paint/src/fill_history_missing_layer_tests.rs diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 7968d1cc76..8e7bbba71f 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -119,9 +119,19 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { "history" => { // A History panel row `state` or a `snapshot`, else the History Brush's source. let source_doc = crate::history_source::paint_source(st, p, CMD)?; - let src = crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) - .map_err(|_| EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into()))?; - Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?) + match crate::channel_cmds::read_target_surface(source_doc.as_ref(), id, p) { + Ok(src) => Source::Pixels(area, read_rgba(src, area, "reading Fill's history source")?), + // A pixel layer the source state lacks (a new, duplicated or flattened layer) counts as transparent + // there, as in the reference application; the Background (after Flatten Image) takes white, not the + // background colour (#17465). Masks and channels the source lacks stay an error. + Err(_) + if let Some(lid) = + id.filter(|&l| crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Pixels && source_doc.layer(l).is_none()) => + { + Source::Color(if st.doc.is_background(lid) { [1.0; 4] } else { [0.0; 4] }) + } + Err(_) => return Err(EngineError::Other("the target did not exist (as pixels, a mask or a channel) in that history state".into())), + } } "contentAware" => { let sel = sel.as_ref().ok_or_else(|| EngineError::Other("Content-Aware fill needs a selection".into()))?; @@ -175,3 +185,7 @@ mod mode_by_document_tests; #[cfg(test)] #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; + +#[cfg(test)] +#[path = "../fill_history_missing_layer_tests.rs"] +mod fill_history_missing_layer_tests; diff --git a/crates/engine-paint/src/fill_history_missing_layer_tests.rs b/crates/engine-paint/src/fill_history_missing_layer_tests.rs new file mode 100644 index 0000000000..b34f5551eb --- /dev/null +++ b/crates/engine-paint/src/fill_history_missing_layer_tests.rs @@ -0,0 +1,147 @@ +//! Edit › Fill with History on a pixel layer the source state does not have: the layer counts as +//! transparent there, so the selection is cleared (white on a layer without transparency, as after +//! Flatten Image), as one "Fill" state. Masks and channels the source lacks keep refusing (#17465). + +use serde_json::{Value, json}; + +use crate::Session; + +const TRANSPARENT: [f32; 4] = [0.0; 4]; +const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; +const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; +const WHITE: [f32; 4] = [1.0; 4]; + +/// The issue's document: `Paint` with red at 0,0-200,150 and 50 % blue at 200,0-400,150 on a +/// transparent (or white Background) canvas, no selection. Returns the session and the History +/// panel row of the finished setup, the source the fills read. +fn issue_document(white: bool) -> (Session, usize) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 300, "background": if white { "white" } else { "transparent" }})).unwrap(); + if white { + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + } + rect(&mut s, [0, 0, 200, 150], "#ff0000", 100); + rect(&mut s, [200, 0, 200, 150], "#0000ff", 50); + s.execute("select.deselect", json!({})).unwrap(); + let row = steps(&s); + (s, row) +} + +fn rect(s: &mut Session, [x, y, width, height]: [i32; 4], color: &str, opacity: u32) { + s.execute("select.rect", json!({"x": x, "y": y, "width": width, "height": height})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color, "opacity": opacity})).unwrap(); +} + +fn select_issue_rect(s: &mut Session) { + s.execute("select.rect", json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +/// The active layer's pixel at (`x`, `y`). +fn px(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn near(a: [f32; 4], b: [f32; 4]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1.5 / 255.0) +} + +/// A History fill from `row` succeeds as one "Fill" state. +fn history_fill(s: &mut Session, row: usize, case: &str) { + let before = steps(s); + s.execute("edit.fill", json!({"contents": "history", "state": row})).unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(steps(s), before + 1, "{case}: one state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fill"), "{case}"); +} + +/// The selected area is cleared to `inside`, the rest keeps `outside`. +fn assert_cleared(s: &Session, inside: [f32; 4], outside: [f32; 4], case: &str) { + let (a, b) = (px(s, 150, 100), px(s, 50, 20)); + assert!(near(a, inside), "{case}: inside the selection {a:?}"); + assert!(near(b, outside), "{case}: outside the selection {b:?}"); +} + +#[test] +fn a_new_empty_layer_stays_transparent() { + let (mut s, row) = issue_document(false); + s.execute("layer.new.layer", json!({"name": "New"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "new layer"); + assert_cleared(&s, TRANSPARENT, TRANSPARENT, "new layer"); +} + +#[test] +fn a_duplicated_layer_is_cleared_inside_the_selection() { + let (mut s, row) = issue_document(false); + s.execute("layer.duplicate", json!({})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "duplicate"); + assert_cleared(&s, TRANSPARENT, GREEN, "duplicate"); +} + +#[test] +fn a_layer_added_after_the_source_layer_was_deleted_is_cleared() { + let (mut s, row) = issue_document(false); + let paint = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({"name": "New"})).unwrap(); + let new = s.active().unwrap().active_layer.unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + s.execute("layer.select", json!({"layer": paint.0})).unwrap(); + s.execute("layer.delete", json!({})).unwrap(); + s.execute("layer.select", json!({"layer": new.0})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "Paint deleted"); + assert_cleared(&s, TRANSPARENT, GREEN, "Paint deleted"); +} + +/// Measured on both variants: after Flatten Image the selected area of the Background turns white, +/// whatever the background colour; the rest keeps the flattened pixels. +#[test] +fn after_flatten_image_the_background_takes_white() { + for white in [false, true] { + let (mut s, row) = issue_document(white); + s.execute("tools.setColors", json!({"background": "#0ac81e"})).unwrap(); + s.execute("layer.flattenImage", json!({})).unwrap(); + select_issue_rect(&mut s); + let case = format!("flatten, white background {white}"); + history_fill(&mut s, row, &case); + assert_cleared(&s, WHITE, RED, &case); + } +} + +/// A layer the source has keeps today's result: back to its pixels in that state. +#[test] +fn a_layer_the_source_has_is_restored() { + let (mut s, row) = issue_document(false); + s.execute("edit.fill", json!({"contents": "color", "color": "#00ff00"})).unwrap(); + select_issue_rect(&mut s); + history_fill(&mut s, row, "Paint"); + assert_cleared(&s, RED, GREEN, "Paint"); +} + +/// Not measured, so as before: a layer mask, an alpha channel or the Quick Mask the source lacks +/// is refused, adding no state and changing nothing. +#[test] +fn masks_channels_and_the_quick_mask_keep_refusing() { + let mut cases: Vec<(&str, Session, usize, Value)> = Vec::new(); + let (mut s, row) = issue_document(false); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + cases.push(("layer mask", s, row, json!("mask"))); + let (mut s, row) = issue_document(false); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + cases.push(("alpha channel", s, row, json!({"channel": 0}))); + let (mut s, row) = issue_document(false); + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + cases.push(("Quick Mask", s, row, json!("quickMask"))); + for (what, mut s, row, target) in cases { + let (doc, before) = (s.active().unwrap().doc.clone(), steps(&s)); + assert!(s.execute("edit.fill", json!({"contents": "history", "state": row, "target": target})).is_err(), "{what}"); + assert_eq!(steps(&s), before, "{what}: no state"); + assert!(s.active().unwrap().doc == doc, "{what}: nothing changed"); + } +} From 2731e601238a4028a270f9051d4cf06362caac22 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 03:33:21 +0100 Subject: [PATCH 17/29] Fill: Quick Mask colour fills in Grayscale, CMYK and Lab take the grey profile's value (#17487) A colour filled into the Quick Mask of an 8- or 16-bit Grayscale, CMYK or Lab document now goes through the sGray conversion the Grayscale swatch already uses, so (200,30,30) writes 104 and (0,255,0) 219, as the reference application does. RGB documents, 32-bit documents, other modes and alpha channels keep the RGB weights. Co-Authored-By: Claude Opus 5.5 --- crates/engine-core/src/cmd/color_cmds.rs | 24 +++-- crates/engine-paint/src/cmd/fill_cmds.rs | 30 +++++- .../src/fill_quick_mask_mode_gray_tests.rs | 94 +++++++++++++++++++ 3 files changed, 137 insertions(+), 11 deletions(-) create mode 100644 crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs diff --git a/crates/engine-core/src/cmd/color_cmds.rs b/crates/engine-core/src/cmd/color_cmds.rs index c709bb6d43..30ad6e0fd5 100644 --- a/crates/engine-core/src/cmd/color_cmds.rs +++ b/crates/engine-core/src/cmd/color_cmds.rs @@ -843,24 +843,28 @@ pub fn document_profile(doc: &Document) -> Arc { /// document tagged with a gray profile other than that one. pub fn swatch_in_doc(s: &Session, c: [f32; 4]) -> [f32; 4] { let Some(st) = s.active().filter(|st| st.doc.mode == ColorMode::Grayscale) else { return c }; - let default_gray = Builtin::DotGain20Compat; - if s.color().settings.working_gray != default_gray.id() || document_profile(&st.doc).content_hash() != default_gray.profile().content_hash() { + if document_profile(&st.doc).content_hash() != Builtin::DotGain20Compat.profile().content_hash() { return c; } + swatch_gray(s, c).unwrap_or(c) +} + +/// A swatch colour's gray with the sRGB tone curve (sGray), the conversion [`swatch_in_doc`] makes in a Grayscale +/// document, as equal R, G and B. None outside the default Working Gray (Dot Gain 20 %) or when the conversion fails. +pub fn swatch_gray(s: &Session, c: [f32; 4]) -> Option<[f32; 4]> { + if s.color().settings.working_gray != Builtin::DotGain20Compat.id() { + return None; + } let opts = craft_cms::TransformOptions { intent: Intent::RelativeColorimetric, bpc: true, ..Default::default() }; let sgray = Arc::new(Builtin::SGray.profile().clone()); - let Ok(t) = craft_cms::cached(&working_profile(ColorMode::Rgb), &sgray, opts) else { return c }; + let t = craft_cms::cached(&working_profile(ColorMode::Rgb), &sgray, opts).ok()?; let mut out = [0.0f32; 16]; - if t.eval(&[c[0], c[1], c[2]], &mut out).is_err() { - return c; - } + t.eval(&[c[0], c[1], c[2]], &mut out).ok()?; let g = out[0]; - if g.is_finite() { + g.is_finite().then(|| { let g = g.clamp(0.0, 1.0); [g, g, g, c[3]] - } else { - c - } + }) } /// Profile describing the compositor's RGB output for this document (see the module docs). diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 7968d1cc76..3fbc872337 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -6,7 +6,7 @@ //! Every parameter is validated: a bad one is an error, never a panic. use photocraft_algo::content_aware::FillOptions; -use photocraft_color::BlendMode; +use photocraft_color::{BlendMode, ColorMode, SampleType}; use photocraft_geom::Rect; #[cfg(test)] use photocraft_geom::TILE_SIZE; @@ -142,6 +142,15 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(format!("unknown contents `{contents}`"))), }; + // A colour filled into the Quick Mask of a Grayscale, CMYK or Lab document becomes its grey through the grey + // profile, as the reference writes it: (200,30,30) gives 104, not the RGB weights' 81 (#17487). + let source = match source { + Source::Color(c) | Source::Cmyk { rgba: c, .. } if matches!(contents, "foreground" | "background" | "color") => match quick_mask_gray(s, p, c) { + Some(g) => Source::Color(g), + None => source, + }, + source => source, + }; if area.is_empty() { return Ok(out); } @@ -158,6 +167,21 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The grey a colour takes in the Quick Mask of an 8- or 16-bit Grayscale, CMYK or Lab document (the Grayscale +/// document's own swatch grey). None elsewhere: RGB documents keep the RGB weights, and 32-bit documents and the +/// other modes, which were not measured, keep them too. +fn quick_mask_gray(s: &Session, p: &Value, c: [f32; 4]) -> Option<[f32; 4]> { + let doc = &s.active()?.doc; + if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::QuickMask || doc.depth == SampleType::F32 { + return None; + } + match doc.mode { + ColorMode::Grayscale => Some(crate::color_cmds::swatch_in_doc(s, c)), + ColorMode::Cmyk | ColorMode::Lab => crate::color_cmds::swatch_gray(s, c), + _ => None, + } +} + /// A fill colour: the inks it was picked as when it was picked as CMYK (#4196), else plain sRGB. fn color_source(s: &Session, c: [f32; 4], role: usize) -> Source { match s.tools.picked_role_cmyk(role) { @@ -172,6 +196,10 @@ mod tests; #[cfg(test)] mod mode_by_document_tests; +#[cfg(test)] +#[path = "../fill_quick_mask_mode_gray_tests.rs"] +mod fill_quick_mask_mode_gray_tests; + #[cfg(test)] #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; diff --git a/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs b/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs new file mode 100644 index 0000000000..c7c301dd9d --- /dev/null +++ b/crates/engine-paint/src/fill_quick_mask_mode_gray_tests.rs @@ -0,0 +1,94 @@ +//! #17487: a colour filled into the Quick Mask of a Grayscale, CMYK or Lab document becomes its grey through the grey +//! profile, as the reference writes it: (200,30,30) gives 104 and (0,255,0) 219 (Lab 220), not the RGB weights' 81 +//! and 150. RGB documents keep 81 / 150; alpha channels and pixel layers keep what they wrote before. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [f32; 4] = [200.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0, 1.0]; + +/// A white 40×20 document of `mode` at `depth` bits, in Quick Mask mode, with (200,30,30) as both swatches. +fn session(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.tools.foreground = RED; + s.tools.background = RED; + s.execute("select.editInQuickMaskMode", json!({"on": true})).unwrap(); + s +} + +fn quick_mask_level(s: &Session) -> i32 { + let q = s.active().unwrap().doc.quick_mask.as_ref().expect("in Quick Mask mode").surface.sample_channel(30, 10, 0); + (q * 255.0).round() as i32 +} + +/// The Quick Mask level after running `cmd` with `params` in a fresh document. +fn filled(mode: &str, depth: u32, cmd: &str, params: Value) -> i32 { + let mut s = session(mode, depth); + s.execute(cmd, params).unwrap(); + quick_mask_level(&s) +} + +fn foreground() -> Value { + json!({"contents": "foreground"}) +} + +fn green() -> Value { + json!({"contents": "color", "color": "#00ff00"}) +} + +#[test] +fn gray_cmyk_and_lab_quick_masks_take_the_grey_profile_value() { + for (mode, want_green) in [("grayscale", 219), ("cmyk", 219), ("lab", 220)] { + let red = filled(mode, 8, "edit.fill", foreground()); + assert!((red - 104).abs() <= 1, "{mode}/8 Foreground (200,30,30): {red}, reference 104"); + let green = filled(mode, 8, "edit.fill", green()); + assert!((green - want_green).abs() <= 1, "{mode}/8 Color (0,255,0): {green}, reference {want_green}"); + } +} + +#[test] +fn rgb_quick_masks_keep_the_rgb_weights() { + for depth in [8, 16, 32] { + let red = filled("rgb", depth, "edit.fill", foreground()); + let green = filled("rgb", depth, "edit.fill", green()); + assert_eq!((red, green), (81, 150), "RGB/{depth}"); + } +} + +#[test] +fn background_color_and_the_fill_keys_give_the_same_grey() { + for mode in ["grayscale", "cmyk", "lab"] { + let want = filled(mode, 8, "edit.fill", foreground()); + for (cmd, params) in [ + ("edit.fill", json!({"contents": "background"})), + ("edit.fill", json!({"contents": "color", "color": "#c81e1e"})), + ("edit.fillForeground", json!({})), + ("edit.fillBackground", json!({})), + ] { + let got = filled(mode, 8, cmd, params.clone()); + assert!((got - want).abs() <= 1, "{mode} {cmd} {params}: {got}, Foreground gives {want}"); + } + } +} + +#[test] +fn black_and_white_stay_exact_in_the_quick_mask() { + for mode in ["grayscale", "cmyk", "lab"] { + assert_eq!(filled(mode, 8, "edit.fill", json!({"contents": "color", "color": "#000000"})), 0, "{mode} black"); + assert_eq!(filled(mode, 8, "edit.fill", json!({"contents": "color", "color": "#ffffff"})), 255, "{mode} white"); + } +} + +#[test] +fn an_alpha_channel_keeps_the_rgb_weights() { + // Only the Quick Mask was measured; a targeted alpha channel keeps what it wrote before. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": 8, "background": "white"})).unwrap(); + s.tools.foreground = RED; + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("edit.fill", foreground()).unwrap(); + let a = s.active().unwrap().doc.channels[0].surface.sample_channel(30, 10, 0); + assert_eq!((a * 255.0).round() as i32, 81); +} From 24272a529843f7a0308c58a6bb3a077e3ec7af92 Mon Sep 17 00:00:00 2001 From: NaufalDzz Date: Mon, 30 Nov 2026 12:52:53 +0000 Subject: [PATCH 18/29] Art History Brush: keep pressure toggles on Reset Tool (#18335) Co-authored-by: OpenBot <335604065+openbotgit[bot]@users.noreply.github.com> --- .../panels/art_history_bar_controls_tests.rs | 9 ++-- .../art_history_reset_keeps_pressure_tests.rs | 48 +++++++++++++++++++ crates/ui-egui/src/tools/tool_reset.rs | 10 ++-- 3 files changed, 60 insertions(+), 7 deletions(-) create mode 100644 crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs diff --git a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs index fc8e6b9e11..0aa7f6d6cc 100644 --- a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs +++ b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs @@ -1,7 +1,8 @@ //! #12629: the Art History Brush's options bar has a Pressure for Opacity toggle right after //! Opacity, and an Angle field and a Pressure for Size toggle after Tolerance, with the reference -//! application's tooltips, off / 0° by default and after Reset Tool. They edit the tool's own -//! brush, not the History Brush's or the Brush's, and the bar has no Flow and no Airbrush. +//! application's tooltips. The toggles start off and keep their state after Reset Tool (#18335), +//! which restores the angle to 0°. The controls belong to the Art History Brush, and the bar has +//! no Flow or Airbrush. use egui::accesskit::Role; use egui::{Modifiers, Rect, vec2}; @@ -99,7 +100,7 @@ fn the_controls_carry_the_reference_tooltips() { } #[test] -fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { +fn reset_tool_restores_the_angle_and_keeps_pressure_toggles() { let mut h = bar(Tool::ArtHistoryBrush); assert_eq!(controls(h.state()), (false, 0.0, false)); assert!(angle_field(&h).and_then(|n| n.accesskit_node().numeric_value()) == Some(0.0), "the field shows 0°"); @@ -112,7 +113,7 @@ fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); h.run_steps(3); - assert_eq!(controls(h.state()), (false, 0.0, false)); + assert_eq!(controls(h.state()), (true, 0.0, true)); } #[test] diff --git a/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs new file mode 100644 index 0000000000..26c6cbd15a --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs @@ -0,0 +1,48 @@ +use serde_json::json; + +use super::{RESET, RESET_ALL, invoke}; +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn art_history_brush(pressure_size: bool, pressure_opacity: bool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"pressureSize": pressure_size, "pressureOpacity": pressure_opacity}})).unwrap(); + app +} + +fn pressure(app: &PhotocraftApp) -> (bool, bool) { + let brush = &app.session.tools.brush; + (brush.pressure_size, brush.pressure_opacity) +} + +#[test] +fn reset_tool_keeps_each_art_history_brush_pressure_toggle() { + let defaults = ToolOptions::default(); + for toggles in [(true, false), (false, true), (true, true), (false, false)] { + let mut app = art_history_brush(toggles.0, toggles.1); + assert_eq!(pressure(&app), toggles); + app.ui.tool_options.art_history_style = "dab".into(); + app.ui.tool_options.art_history_area = 120.0; + app.ui.tool_options.art_history_tolerance = 25.0; + + invoke(&mut app, RESET, &json!({})).unwrap().unwrap(); + + assert_eq!(pressure(&app), toggles); + assert_eq!(app.ui.tool_options.art_history_style, defaults.art_history_style); + assert_eq!(app.ui.tool_options.art_history_area, defaults.art_history_area); + assert_eq!(app.ui.tool_options.art_history_tolerance, defaults.art_history_tolerance); + } +} + +#[test] +fn reset_all_tools_clears_the_art_history_brush_pressure_toggles() { + let mut app = art_history_brush(true, true); + assert_eq!(pressure(&app), (true, true)); + + invoke(&mut app, RESET_ALL, &json!({"confirmed": true})).unwrap().unwrap(); + + assert_eq!(pressure(&app), (false, false)); +} diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index f40ccc6c38..b52b42f1d0 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -90,10 +90,10 @@ fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { // The session brush is the options bar's tool's: make sure it is `tool`'s before resetting. crate::paint_mouse::sync_tool_brush(app); app.ui.tool_brushes.retain(|(t, _)| *t != tool); - // The Eraser's Reset Tool resets the tip but keeps Pressure for Size and Pressure for - // Opacity as they were (#17700). + // Reset the tip but keep Pressure for Size and Pressure for Opacity for the Eraser + // (#17700) and Art History Brush (#18335). let brush = &app.session.tools.brush; - let pressure = (tool == Tool::Eraser).then_some((brush.pressure_size, brush.pressure_opacity)); + let pressure = matches!(tool, Tool::Eraser | Tool::ArtHistoryBrush).then_some((brush.pressure_size, brush.pressure_opacity)); reset_session_brush(app); if let Some((size, opacity)) = pressure { app.session.tools.brush.pressure_size = size; @@ -483,3 +483,7 @@ mod patch_sample_all_default_tests; #[cfg(test)] #[path = "eraser_reset_keeps_pressure_tests.rs"] mod eraser_reset_keeps_pressure_tests; + +#[cfg(test)] +#[path = "art_history_reset_keeps_pressure_tests.rs"] +mod art_history_reset_keeps_pressure_tests; From 6366303ac82d70210c0c62267746d9b7e9142b5d Mon Sep 17 00:00:00 2001 From: Dan Date: Mon, 30 Nov 2026 14:42:31 +0000 Subject: [PATCH 19/29] Disable Save for Web for 32-bit and Multichannel documents --- crates/engine-core/src/cmd/web_cmds.rs | 16 +++- .../web_cmds/save_for_web_enabled_tests.rs | 81 +++++++++++++++++++ crates/engine-core/src/cmd/web_cmds/tests.rs | 4 +- crates/ui-egui/src/dialogs/file_ui.rs | 5 +- 4 files changed, 102 insertions(+), 4 deletions(-) create mode 100644 crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs diff --git a/crates/engine-core/src/cmd/web_cmds.rs b/crates/engine-core/src/cmd/web_cmds.rs index 624250e509..27949e27d3 100644 --- a/crates/engine-core/src/cmd/web_cmds.rs +++ b/crates/engine-core/src/cmd/web_cmds.rs @@ -14,7 +14,7 @@ use photocraft_algo::quantize::{self, Dither, Forced, PaletteKind}; use photocraft_doc::slices::{self, ResolvedSlice, SliceKind}; -use photocraft_doc::{DocId, Document, LayerContent, LayerId}; +use photocraft_doc::{ColorMode, DocId, Document, LayerContent, LayerId, SampleType}; use photocraft_geom::Rect; use serde_json::{Value, json}; @@ -65,6 +65,15 @@ pub fn specs() -> Vec { s.active().map(|_| ()).ok_or_else(|| "no document open".into()) } + fn save_for_web_enabled(s: &Session) -> std::result::Result<(), String> { + let doc = &s.active().ok_or("no document open")?.doc; + match (doc.mode, doc.depth) { + (ColorMode::Multichannel, _) => Err("Save for Web is unavailable in Multichannel mode".into()), + (_, SampleType::F32) => Err("Save for Web is unavailable for 32-bit documents".into()), + _ => Ok(()), + } + } + /// Generate ▸ Image Assets needs Preferences ▸ Plug-ins ▸ Enable Generator, as in /// Photoshop (where "Enable Generator" is unchecked until turned on). fn generator_enabled(s: &Session) -> std::result::Result<(), String> { @@ -81,7 +90,7 @@ pub fn specs() -> Vec { &["File", "Export"], Some("Cmd+Alt+Shift+S"), r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp|webp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"colorTable":["#rrggbb",…]? (fixed opaque source palette, 1–256 entries; 255 with transparency),"colorTableEdits":{"0":"#rrggbb",…}? (replace entries after indexing; requires colorTable),"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="none" (a preset's own: white; formats without transparency go over white),"interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60 (JPEG, lossy WebP),"lossless":bool=false (WebP),"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|allExceptCameraInfo|all"="copyright" (EXIF only with all),"convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"folder":folder? (whole image, named after the document; ignored with "path" or "dir"),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user|selected"="all" (selected requires numbers when the document has slices),"numbers":[n]? (slice numbers, each an existing slice; chooses the slices whatever the mode; with `path` or `folder` alone on a document with slices, refused: use `dir`)} → no path/dir: {bytes,width,height,colors,colorTable,transparentIndex} estimate; else {files, html, bytes, warnings}"##, - has_doc, + save_for_web_enabled, save_for_web ), spec!( @@ -117,3 +126,6 @@ pub fn specs() -> Vec { #[cfg(test)] #[path = "web_cmds/tests.rs"] mod tests; + +#[cfg(test)] +mod save_for_web_enabled_tests; diff --git a/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs b/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs new file mode 100644 index 0000000000..cd131b527b --- /dev/null +++ b/crates/engine-core/src/cmd/web_cmds/save_for_web_enabled_tests.rs @@ -0,0 +1,81 @@ +use super::*; + +const COMMAND: &str = "file.export.saveForWebLegacy"; + +fn document(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 16, "height": 16, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s +} + +fn assert_refused(s: &mut Session, reason: &str) { + let attempted = s.execute(COMMAND, json!({})); + assert!(!s.is_enabled(COMMAND), "expected a disabled command for {reason}, got {attempted:?}"); + assert!(matches!(&attempted, Err(EngineError::Disabled(id, why)) if id == COMMAND && why.contains(reason)), "{attempted:?}"); +} + +fn assert_available(s: &mut Session) { + let doc = &s.active().unwrap().doc; + assert!(s.is_enabled(COMMAND), "Save for Web is available for {:?} at {:?}", doc.mode, doc.depth); + let estimate = s.execute(COMMAND, json!({})).unwrap(); + assert!(estimate["bytes"].as_u64().is_some_and(|bytes| bytes > 0), "{estimate}"); +} + +#[test] +fn save_for_web_no_document_is_refused() { + assert_refused(&mut crate::session(), "no document open"); +} + +#[test] +fn save_for_web_float_documents_are_refused() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + let mut s = document(mode, 32); + assert_eq!(s.active().unwrap().doc.depth, SampleType::F32); + assert_refused(&mut s, "32-bit"); + } +} + +#[test] +fn save_for_web_multichannel_documents_are_refused_at_both_integer_depths() { + for depth in [8, 16] { + let mut s = document("rgb", depth); + s.execute("image.mode.multichannel", json!({})).unwrap(); + let doc = &s.active().unwrap().doc; + assert_eq!(doc.mode, ColorMode::Multichannel); + assert_eq!(doc.depth.bits(), depth); + assert_refused(&mut s, "Multichannel"); + } +} + +#[test] +fn save_for_web_reenables_after_conversion_from_float_with_layers() { + let mut s = document("rgb", 8); + s.execute("layer.new.layer", json!({})).unwrap(); + for integer_depth in ["image.mode.bits16", "image.mode.bits8"] { + s.execute("image.mode.bits32", json!({})).unwrap(); + assert_refused(&mut s, "32-bit"); + s.execute(integer_depth, json!({})).unwrap(); + assert_available(&mut s); + } +} + +#[test] +fn save_for_web_integer_documents_keep_their_estimates() { + for mode in ["rgb", "gray", "cmyk", "lab"] { + for depth in [8, 16] { + assert_available(&mut document(mode, depth)); + } + } + for (source, expected, command, params) in [ + ("rgb", ColorMode::Indexed, "image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none"})), + ("gray", ColorMode::Bitmap, "image.mode.bitmap", json!({"method": "threshold"})), + ] { + let mut s = document(source, 8); + s.execute(command, params).unwrap(); + assert_eq!(s.active().unwrap().doc.mode, expected); + assert_available(&mut s); + s.execute("image.mode.bits16", json!({})).unwrap(); + assert_eq!((s.active().unwrap().doc.mode, s.active().unwrap().doc.depth), (expected, SampleType::U16)); + assert_available(&mut s); + } +} diff --git a/crates/engine-core/src/cmd/web_cmds/tests.rs b/crates/engine-core/src/cmd/web_cmds/tests.rs index 6ed5a39ec7..c6558ea436 100644 --- a/crates/engine-core/src/cmd/web_cmds/tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/tests.rs @@ -217,7 +217,9 @@ fn estimates_every_format_at_every_depth() { let mut s = session(depth); let mut sizes = Vec::new(); for f in ["gif", "png8", "png24", "jpeg", "wbmp", "webp"] { - let r = s.execute("file.export.saveForWebLegacy", json!({"format": f, "colors": 16})).unwrap(); + let params = json!({"format": f, "colors": 16}); + // Keep testing the encoder at float depth, where the command is unavailable. + let r = if depth == 32 { save_for_web(&mut s, ¶ms) } else { s.execute("file.export.saveForWebLegacy", params) }.unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(64), Some(48)), "{f}"); assert!(r["bytes"].as_u64().unwrap() > 20, "{f}"); if f == "gif" || f == "png8" { diff --git a/crates/ui-egui/src/dialogs/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index e1685fae8c..50659bcb9d 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -43,7 +43,10 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V return None; } Some(match id { - "file.export.saveForWebLegacy" => Ok(opened(open_web(app)?)), + "file.export.saveForWebLegacy" => match app.session.precheck(id, params) { + Ok(()) => Ok(opened(open_web(app)?)), + Err(error) => Err(error.to_string()), + }, "file.print" => { app.session.active()?; Ok(opened(open_print(app))) From 25cf37a50a5ae50f88922be8856c752f7a44ee9f Mon Sep 17 00:00:00 2001 From: Dan Date: Mon, 30 Nov 2026 14:47:59 +0000 Subject: [PATCH 20/29] Preserve float-depth palette export regression coverage --- crates/engine-core/src/cmd/web_cmds/color_table_tests.rs | 4 ++-- crates/engine-core/src/cmd/web_cmds/tests.rs | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs b/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs index 0c25ce0d24..49a9b2eb19 100644 --- a/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/color_table_tests.rs @@ -44,7 +44,7 @@ fn exported_palette_edits_work_at_every_document_depth() { for depth in [8, 16, 32] { let mut s = session(depth); let mut p = json!({"format": "gif", "colors": 16, "dither": "none"}); - let estimate = s.execute("file.export.saveForWebLegacy", p.clone()).unwrap(); + let estimate = save_for_web_at_any_depth(&mut s, p.clone()).unwrap(); let table = estimate["colorTable"].as_array().unwrap(); let red = table.iter().position(|c| c == "#ff0000").unwrap(); p["colorTable"] = estimate["colorTable"].clone(); @@ -52,7 +52,7 @@ fn exported_palette_edits_work_at_every_document_depth() { let path = format!("{dir}/{depth}.gif"); p["path"] = json!(path); let original_doc = s.active().unwrap().doc.clone(); - s.execute("file.export.saveForWebLegacy", p).unwrap(); + save_for_web_at_any_depth(&mut s, p).unwrap(); assert_eq!(s.active().unwrap().doc, original_doc, "export must not edit the document"); let img = decode(&path).convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8); assert_eq!(&img.data()[(16 * 64 + 16) * 4..(16 * 64 + 16) * 4 + 4], &[0, 255, 0, 255]); diff --git a/crates/engine-core/src/cmd/web_cmds/tests.rs b/crates/engine-core/src/cmd/web_cmds/tests.rs index c6558ea436..0dcf8438b7 100644 --- a/crates/engine-core/src/cmd/web_cmds/tests.rs +++ b/crates/engine-core/src/cmd/web_cmds/tests.rs @@ -211,15 +211,18 @@ fn platform_writer_failure_stops_export_and_preserves_saved_settings() { assert_eq!(s.file_menu.last_web.as_ref(), Some(&saved)); } +// Float-depth regression tests still exercise the encoder below the command's availability rule. +fn save_for_web_at_any_depth(s: &mut Session, params: Value) -> Result { + if s.active().unwrap().doc.depth == SampleType::F32 { save_for_web(s, ¶ms) } else { s.execute("file.export.saveForWebLegacy", params) } +} + #[test] fn estimates_every_format_at_every_depth() { for depth in [8, 16, 32] { let mut s = session(depth); let mut sizes = Vec::new(); for f in ["gif", "png8", "png24", "jpeg", "wbmp", "webp"] { - let params = json!({"format": f, "colors": 16}); - // Keep testing the encoder at float depth, where the command is unavailable. - let r = if depth == 32 { save_for_web(&mut s, ¶ms) } else { s.execute("file.export.saveForWebLegacy", params) }.unwrap(); + let r = save_for_web_at_any_depth(&mut s, json!({"format": f, "colors": 16})).unwrap(); assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(64), Some(48)), "{f}"); assert!(r["bytes"].as_u64().unwrap() > 20, "{f}"); if f == "gif" || f == "png8" { From fc177b03c7baf0cf6dba97b638c703bf607f28fc Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:36:20 +0100 Subject: [PATCH 21/29] Move tool: show W and H beside the pointer while drawing the layer marquee (#18162) A Move drag that starts on empty canvas (or only on locked layers) with Auto-Select draws the layer marquee, and nothing showed its size. The marquee now asks for the same W and H readout the selection marquee shows, in its words and pixel units, on every drag step. Show Transformation Values hides it as it hides the drag readout. The release and the layers it selects are unchanged. --- crates/ui-egui/src/canvas/tools/move_tool.rs | 5 +- crates/ui-egui/src/tools/move_box.rs | 15 ++++ .../src/tools/move_marquee_readout_tests.rs | 75 +++++++++++++++++++ 3 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/tools/move_marquee_readout_tests.rs diff --git a/crates/ui-egui/src/canvas/tools/move_tool.rs b/crates/ui-egui/src/canvas/tools/move_tool.rs index 6c49cb207c..4c53eba55d 100644 --- a/crates/ui-egui/src/canvas/tools/move_tool.rs +++ b/crates/ui-egui/src/canvas/tools/move_tool.rs @@ -353,7 +353,10 @@ impl CanvasTool for MoveRun<'_> { let at = space.view.to_doc(pointer.pos); match run.kind { Kind::Marquee => { - self.scope.with_app(|app| crate::move_box::drag_to(app, [at.x, at.y])); + self.scope.with_app(|app| { + crate::move_box::drag_to(app, [at.x, at.y]); + crate::move_box::readout(app, cx); + }); } Kind::Refused => { if !std::mem::replace(&mut run.prompted, true) { diff --git a/crates/ui-egui/src/tools/move_box.rs b/crates/ui-egui/src/tools/move_box.rs index 24632762b4..b69547897c 100644 --- a/crates/ui-egui/src/tools/move_box.rs +++ b/crates/ui-egui/src/tools/move_box.rs @@ -7,6 +7,8 @@ use serde_json::json; use craft::behavior::kurbo::{Point, Rect}; +use craft::imaging::ui::select::SelectWords; +use craft::ui::canvas::ToolContext; use craft::ui::canvas_controls::Marquee; use craft::ui::contract::Show as _; @@ -85,6 +87,15 @@ pub(crate) fn cancel(app: &mut PhotocraftApp) { app.layer_box = None; } +/// The marquee's W and H beside the pointer while it is dragged, in the selection marquee's words and units +/// (Show Transformation Values hides it, as it hides the drag readout). +pub(crate) fn readout(app: &PhotocraftApp, cx: &mut ToolContext<'_>) { + let Some(b) = app.layer_box else { return }; + let rect = Rect::from_points(Point::new(b.start[0], b.start[1]), Point::new(b.end[0], b.end[1])); + let (words, units) = (cx.words::(), cx.units()); + cx.readout(vec![(words.width.clone(), units.pixels(rect.width())), (words.height.clone(), units.pixels(rect.height()))]); +} + /// The marquee being dragged, over the canvas `canvas`. pub(crate) fn show(app: &PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect) { let Some(b) = app.layer_box else { return }; @@ -205,3 +216,7 @@ mod tests { assert_eq!(app.session.active().unwrap().selected_layers(), vec![paint]); } } + +#[cfg(test)] +#[path = "move_marquee_readout_tests.rs"] +mod move_marquee_readout_tests; diff --git a/crates/ui-egui/src/tools/move_marquee_readout_tests.rs b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs new file mode 100644 index 0000000000..93e226884c --- /dev/null +++ b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs @@ -0,0 +1,75 @@ +//! #18162: the Move tool's layer marquee shows its W and H beside the pointer while it is dragged, as a layer drag +//! shows its distances, and adds no history step. + +use serde_json::json; + +use crate::canvas::{ToolEvent, tool_event, tool_event_response}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; + +/// A white document whose only layer is the locked Background, with the Move tool and Auto-Select on: a press +/// anywhere on the canvas starts the layer marquee. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + app +} + +/// The readout rows of the pass that moves the pointer to `to`, as label and value text. +fn readout(app: &mut PhotocraftApp, to: [f64; 2]) -> Vec<(String, String)> { + tool_event_response(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, egui::Modifiers::NONE) + .readout + .expect("the layer marquee has a readout") + .rows + .into_iter() + .map(|(label, value)| (label.as_str().to_owned(), value)) + .collect() +} + +/// The number a readout value shows ("42 px" reads 42). +fn number(value: &str) -> f64 { + value.trim_end_matches("px").trim().parse().unwrap_or_else(|_| panic!("a pixel value: {value:?}")) +} + +#[test] +fn the_layer_marquee_reads_its_width_and_height_as_it_grows() { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + let first = readout(&mut app, [60.0, 50.0]); + assert!(app.layer_box.is_some(), "the press started the layer marquee"); + let [(w_label, w), (h_label, h)] = first.as_slice() else { panic!("two rows, W and H: {first:?}") }; + assert!(w_label.starts_with('W') && h_label.starts_with('H'), "{first:?}"); + assert!(w.ends_with("px") && h.ends_with("px"), "{first:?}"); + assert!(number(w) > 0.0 && number(h) > 0.0, "{first:?}"); + + let wider = readout(&mut app, [120.0, 50.0]); + assert!(number(&wider[0].1) > number(w), "a wider drag reads a larger W: {first:?} then {wider:?}"); + assert_eq!(wider[1].1, *h, "H stays while only the width changes"); + + let taller = readout(&mut app, [120.0, 110.0]); + assert!(number(&taller[1].1) > number(&wider[1].1), "a taller drag reads a larger H: {wider:?} then {taller:?}"); + + // Up and to the left of the press, the box reads its size, not a negative one. + let back = readout(&mut app, [5.0, 10.0]); + assert!(number(&back[0].1) > 0.0 && number(&back[1].1) > 0.0, "{back:?}"); +} + +#[test] +fn the_layer_marquee_adds_no_history_step_and_leaves_the_background() { + let mut app = app(); + let (steps, bg, bounds) = { + let st = app.session.active().unwrap(); + let bg = st.active_layer.unwrap(); + (st.history.past_len(), bg, st.doc.layer(bg).unwrap().surface().unwrap().content_bounds()) + }; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(!readout(&mut app, [90.0, 70.0]).is_empty()); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 70.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps, "no history step"); + assert_eq!(st.doc.layer(bg).unwrap().surface().unwrap().content_bounds(), bounds, "the Background did not move"); + assert!(app.layer_box.is_none()); +} From e0ccf638cd2bb1e9813bfa1d5eb60456f6ca56a9 Mon Sep 17 00:00:00 2001 From: dholzric Date: Mon, 30 Nov 2026 09:41:23 -0600 Subject: [PATCH 22/29] Layer Align: name each History state after its entry (#18283) All six layer.align.* commands recorded their step as "Align". Each now records the entry's name, such as "Align Left Edges", as the reference application does. Distribute keeps its name. Co-Authored-By: Claude Fable 5.2 --- .../src/cmd/layer_multi_cmds/align.rs | 15 ++- .../align_history_names_tests.rs | 103 ++++++++++++++++++ 2 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs index 07fcdf4f03..d3835c136a 100644 --- a/crates/engine-core/src/cmd/layer_multi_cmds/align.rs +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align.rs @@ -53,7 +53,16 @@ pub(super) fn align(s: &mut Session, p: &Value, kind: &str) -> Result { let sel = selected(s); let to = p.get("to").and_then(Value::as_str).unwrap_or("auto").to_string(); let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let moved = s.edit("Align", |doc, _| { + // The History state is named after the entry (#18283). + let name = match edge { + Edge::Top => "Align Top Edges", + Edge::VCenter => "Align Vertical Centers", + Edge::Bottom => "Align Bottom Edges", + Edge::Left => "Align Left Edges", + Edge::HCenter => "Align Horizontal Centers", + Edge::Right => "Align Right Edges", + }; + let moved = s.edit(name, |doc, _| { let items = bounded_selection(doc, &sel); if items.is_empty() { return Err(EngineError::Other("the selected layers have no content to align".into())); @@ -160,3 +169,7 @@ pub(super) fn distribute(s: &mut Session, kind: &str) -> Result { })?; Ok(json!({"moved": moved})) } + +#[cfg(test)] +#[path = "align_history_names_tests.rs"] +mod align_history_names_tests; diff --git a/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs b/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs new file mode 100644 index 0000000000..f6c762c433 --- /dev/null +++ b/crates/engine-core/src/cmd/layer_multi_cmds/align_history_names_tests.rs @@ -0,0 +1,103 @@ +//! #18283: each Layer › Align entry leaves one History state named after the entry, such as "Align Left Edges", +//! with and without a pixel selection, instead of "Align" for all six. A run that a position-locked layer refuses +//! records no state. The Distribute entries were not measured and keep their name. + +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::Session; + +/// The command's last id segment and the History state the reference application records for it. +const NAMES: [(&str, &str); 6] = [ + ("topEdges", "Align Top Edges"), + ("verticalCenters", "Align Vertical Centers"), + ("bottomEdges", "Align Bottom Edges"), + ("leftEdges", "Align Left Edges"), + ("horizontalCenters", "Align Horizontal Centers"), + ("rightEdges", "Align Right Edges"), +]; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80})).unwrap(); + s +} + +/// A new pixel layer with an opaque rectangle. +fn rect_layer(s: &mut Session, r: Rect) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + id +} + +fn select(s: &mut Session, ids: &[LayerId]) { + s.execute("layer.select", json!({"layer": ids[0].0})).unwrap(); + for id in &ids[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "toggle"})).unwrap(); + } +} + +/// Two layers that share no edge and no centre, so every Align entry moves one of them. +fn two_layers(s: &mut Session) -> [LayerId; 2] { + [rect_layer(s, Rect::new(10, 5, 20, 15)), rect_layer(s, Rect::new(40, 30, 70, 60))] +} + +/// How many History states there are, and the name of the newest. +fn history(s: &Session) -> (usize, Option) { + let history = &s.active().unwrap().history; + (history.past_len(), history.undo_label().map(String::from)) +} + +#[test] +fn each_align_entry_names_its_one_history_state() { + for (kind, name) in NAMES { + // Several layers, aligned to each other. + let mut s = session(); + let layers = two_layers(&mut s); + select(&mut s, &layers); + let states = history(&s).0; + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some(name.to_string())), "{kind}"); + // One layer, aligned to a pixel selection. + let mut s = session(); + rect_layer(&mut s, Rect::new(10, 5, 20, 15)); + s.execute("select.rect", json!({"x": 50, "y": 40, "width": 30, "height": 30})).unwrap(); + let states = history(&s).0; + s.execute(&format!("layer.align.{kind}"), json!({})).unwrap(); + assert_eq!(history(&s), (states + 1, Some(name.to_string())), "{kind} to a selection"); + } +} + +#[test] +fn a_run_refused_by_a_position_locked_layer_records_no_state() { + for all in [false, true] { + let mut s = session(); + let layers = two_layers(&mut s); + // Top Edges has to move the lower rectangle, which is locked: Lock position, then Lock all. + s.edit("lock", |doc, _| { + let locks = &mut doc.layer_mut(layers[1]).unwrap().locks; + (locks.position, locks.all) = (true, all); + Ok(()) + }) + .unwrap(); + select(&mut s, &layers); + let before = history(&s); + assert!(s.execute("layer.align.topEdges", json!({})).is_err(), "lock all: {all}"); + assert_eq!(history(&s), before, "lock all: {all}"); + } +} + +/// Not measured, so it keeps the name it had. +#[test] +fn distribute_keeps_its_name() { + let mut s = session(); + let layers = [rect_layer(&mut s, Rect::new(0, 0, 10, 10)), rect_layer(&mut s, Rect::new(20, 30, 30, 40)), rect_layer(&mut s, Rect::new(80, 60, 90, 70))]; + select(&mut s, &layers); + s.execute("layer.distribute.leftEdges", json!({})).unwrap(); + assert_eq!(history(&s).1.as_deref(), Some("Distribute")); +} From 71cc84045daab454147289caa4151e8bf363e71f Mon Sep 17 00:00:00 2001 From: Dan Date: Mon, 30 Nov 2026 17:09:12 +0000 Subject: [PATCH 23/29] Open Select Data Points from a checked Custom submenu item --- crates/ui-egui/src/menu_catalog.rs | 2 +- .../analysis/data_points_submenu_tests.rs | 45 +++++++++++++++++++ crates/ui-egui/src/tools/analysis/mod.rs | 5 +++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index de927bce10..10d1b57d61 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -242,7 +242,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Image"], "Trap…", None, "image.trap"), (&["Image"], "---", None, "---"), (&["Image", "Analysis"], "Set Measurement Scale…", None, "image.analysis.setMeasurementScale"), - (&["Image", "Analysis"], "Select Data Points…", None, "image.analysis.selectDataPoints"), + (&["Image", "Analysis", "Select Data Points"], "Custom…", None, "image.analysis.selectDataPoints"), (&["Image", "Analysis"], "---", None, "---"), (&["Image", "Analysis"], "Record Measurements", None, "image.analysis.recordMeasurements"), (&["Image", "Analysis"], "---", None, "---"), diff --git a/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs new file mode 100644 index 0000000000..40783e3aa3 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs @@ -0,0 +1,45 @@ +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply}; + +const COMMAND: &str = "image.analysis.selectDataPoints"; + +fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = app.ctx().clone(); + let (request, _) = ControlRequest::new(method, params); + let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { panic!("{method} replies immediately") }; + assert_eq!(reply["ok"], true, "{method}: {reply}"); + reply["result"].clone() +} + +#[test] +fn data_points_submenu_has_only_a_checked_custom_item_and_opens_the_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 24})).unwrap(); + + let menu = call(&mut app, "ui.menu.list", json!({})); + let rows = menu.as_array().unwrap(); + let titled_path = json!(["Image", "Analysis", "Select Data Points"]); + let data_points: Vec<_> = rows.iter().filter(|row| row["path"] == titled_path || row["id"] == COMMAND).collect(); + assert_eq!(data_points.len(), 1, "one entry and no separator: {data_points:?}"); + let custom = data_points[0]; + assert_eq!(custom["path"], titled_path); + assert_eq!(custom["id"], COMMAND); + assert_eq!(custom["label"], "Custom…"); + assert_eq!(custom["checked"], true); + assert_eq!(custom["enabled"], true); + assert_eq!(custom["shortcut"], Value::Null); + + let opened = call(&mut app, "ui.menu.invoke", json!({"id": custom["id"]})); + assert_eq!(opened["dialog"], "dataPoints"); + assert!(app.dialog_open()); +} + +#[test] +fn data_points_submenu_keeps_the_engine_command_available_to_scripts() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let selected = call(&mut app, "engine.execute", json!({"id": COMMAND, "params": {"selection": ["area"], "ruler": [], "count": []}})); + assert_eq!(selected["dataPoints"]["selection"], json!(["area"])); + assert!(!app.dialog_open()); +} diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index fce2102caa..a567de1c71 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -30,6 +30,9 @@ mod tests; #[cfg(test)] mod sampler_menu_tests; +#[cfg(test)] +mod data_points_submenu_tests; + #[cfg(test)] #[path = "../count_readout_tests.rs"] mod count_readout_tests; @@ -120,6 +123,8 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { "window.panel.notes" => Some(crate::panel_docking::is_shown(app, NOTES)), "image.analysis.rulerTool" => Some(app.ui.tool == Tool::Ruler), "image.analysis.countTool" => Some(app.ui.tool == Tool::Count), + // The data point set is always Custom until named presets are supported. + "image.analysis.selectDataPoints" => Some(true), _ => { // View › Proof Setup simulations: checked while that proof is shown. // A check item with no document too: an item's kind never changes (native menus). From f2ed4c6dfd24a7d6269d2b9f203c7229d4b1a10e Mon Sep 17 00:00:00 2001 From: Dan Date: Mon, 30 Nov 2026 17:37:51 +0000 Subject: [PATCH 24/29] Retry Windows CI after texture page order failure From 93a120630d162b8ad889318b81c3a81d30a16678 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 19:08:58 +0100 Subject: [PATCH 25/29] Brush Preset picker range alert test: a typed Size fraction is cut off Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/brush_picker_range_alert_tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs index 4ebdea739d..981358c5c0 100644 --- a/crates/ui-egui/src/brush_picker_range_alert_tests.rs +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -1,5 +1,6 @@ //! #11817: a Size or Hardness typed past its range in the Brush Preset picker takes the closest value and opens the -//! range alert; the picker stays open under it and after OK. A value in range and a slider press open none. +//! range alert; the picker stays open under it and after OK. A value in range (a typed fraction cut off) and a slider +//! press open none. use crate::app::framework::BuildApp as _; use egui::{Event, Modifiers, vec2}; @@ -74,6 +75,8 @@ fn size_and_hardness_typed_out_of_range_alert_and_the_picker_stays_open() { #[test] fn a_value_in_range_and_a_slider_press_open_no_alert() { let mut h = harness(); + type_into(&mut h, 0, "2.5"); + assert_eq!(size_and_hardness(&h).0, 2.0, "a typed fraction is cut off, not rounded"); type_into(&mut h, 0, "40"); assert_eq!(size_and_hardness(&h).0, 40.0); let slider = h From 1bd46c520d103225ebde666a3669b417d7e13498 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 19:48:10 +0100 Subject: [PATCH 26/29] ui-egui: give dialogs a roomier margin (#18416) PhotoCraft left the shared space.pad.dialog token at its default (12 px Comfortable, 8 px Compact), so title, message and buttons sat right at the dialog's edge. Set it to 24 and 16 px in the app's size overrides; only dialogs read this token. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/app/framework.rs | 3 ++- crates/ui-egui/src/app/sizes.json | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 9c58f81255..65b2763f99 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -271,7 +271,8 @@ fn defaults() -> AppDefaults { } } -/// PhotoCraft's size overrides: Photoshop's panel dock width, and 12-point Label and Mono text in the compact density. +/// PhotoCraft's size overrides: Photoshop's panel dock width, a roomier dialog margin (twice the panel padding, so +/// short questions such as "Unsaved changes" do not look cramped), and 12-point Label and Mono text in the compact density. const SIZES: &[u8] = include_bytes!("sizes.json"); /// The size overrides, parsed once: the root keeps one `Arc` so the runtime's token and hit-size caches, which key on diff --git a/crates/ui-egui/src/app/sizes.json b/crates/ui-egui/src/app/sizes.json index 5727ea93d8..afa5f5a7fa 100644 --- a/crates/ui-egui/src/app/sizes.json +++ b/crates/ui-egui/src/app/sizes.json @@ -1 +1 @@ -{ "all": { "size.dock.column": 290 }, "compact": { "typography.label.size": 12, "typography.mono.size": 12 } } +{ "all": { "size.dock.column": 290 }, "compact": { "space.pad.dialog": 16, "typography.label.size": 12, "typography.mono.size": 12 }, "comfortable": { "space.pad.dialog": 24 } } From 965aebff55cb8da55eacf7268162e411a211c742 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 20:16:29 +0100 Subject: [PATCH 27/29] Fill: Cross Weave script (#17429) Edit > Fill > Pattern > Script > Cross Weave weaves the pattern tile in a basket weave: square cells of the mean tile side plus Spacing alternate between a flat and an upright tile like a checkerboard, leaving a 5 x 5 transparent hole at every 35 px grid point for a 40 x 30 tile, each tile turned half way or not at random (repeatable by seed). edit.fill and the dialog preview both lay scripts out through one render() in scripted_pattern.rs. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/scripted_pattern.rs | 166 +++++++++-- crates/engine-paint/src/cmd/fill_cmds.rs | 10 +- .../src/fill_script_brick_tests.rs | 4 +- .../src/fill_script_cross_weave_tests.rs | 257 ++++++++++++++++++ crates/engine-paint/src/lib.rs | 2 + crates/ui-egui/src/dialogs/fill_script_ui.rs | 21 +- .../src/dialogs/fill_script_ui_tests.rs | 52 +++- 7 files changed, 477 insertions(+), 35 deletions(-) create mode 100644 crates/engine-paint/src/fill_script_cross_weave_tests.rs diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index 9def7a7493..2e40e1da93 100644 --- a/crates/compose/src/scripted_pattern.rs +++ b/crates/compose/src/scripted_pattern.rs @@ -1,5 +1,6 @@ //! Scripted patterns: Edit › Fill › Pattern with Script on lays the chosen pattern out as separate tiles instead of a -//! plain repeat. Brick Fill is the first script; the others extend [`SCRIPTS`] and [`controls`] with their own layout. +//! plain repeat. Brick Fill and Cross Weave paint today; the others extend [`SCRIPTS`], [`controls`] and [`render`] with +//! their own layout. //! //! Every script shares the per-tile Color and Brightness randomness ([`Jitter`]): at 0 a tile keeps the pattern's //! exact colours, above 0 each placed tile drifts by its own random amount. Areas no tile covers stay transparent. @@ -19,7 +20,7 @@ pub const SCRIPTS: [(&str, &str); 6] = [ ]; /// The scripts that paint today; the rest are listed but answer "not supported yet". -pub const SUPPORTED: [&str; 1] = ["brickFill"]; +pub const SUPPORTED: [&str; 2] = ["brickFill", "crossWeave"]; /// The parameter value of a script name, matched without regard to case. pub fn script_key(name: &str) -> Option<&'static str> { @@ -70,6 +71,35 @@ pub fn controls(script: &str, width: u32, height: u32) -> Option> { Control::new("patternRotateAngle", 0.0, -180.0, 180.0, 0), ]) } + "crossWeave" => { + let (lo, hi) = spacing_range(width, height); + Some(vec![ + Control::new("patternScale", 1.0, 0.1, 1.25, 2), + Control::new("spacing", 0.0, lo, hi, 0), + Control::new("colorRandomness", 0.05, 0.0, 1.0, 2), + Control::new("brightnessRandomness", 0.1, 0.0, 1.0, 2), + ]) + } + _ => None, + } +} + +/// `script` laid out over `rect` with a `width` x `height` pattern: `value` gives each of its [`controls`] (in range), +/// `seed` makes the per-tile randomness repeatable. `None` for a script that does not paint yet. +pub fn render(script: &str, value: impl Fn(&str) -> f64, seed: u64, tile: &Tile, width: u32, height: u32, rect: Rect) -> Option> { + let jitter = Jitter { color: value("colorRandomness") as f32, brightness: value("brightnessRandomness") as f32, seed }; + match script { + "brickFill" => { + let brick = BrickFill { + scale: value("patternScale"), + spacing: value("spacing"), + offset: value("offsetBetweenRows"), + angle: value("patternRotateAngle"), + jitter, + }; + Some(brick.render(tile, width, height, rect)) + } + "crossWeave" => Some(CrossWeave { scale: value("patternScale"), spacing: value("spacing"), jitter }.render(tile, width, height, rect)), _ => None, } } @@ -129,6 +159,36 @@ pub struct BrickFill { /// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. const MAX_LAYERS: usize = 1024; +/// A repeatable value for tile `(row, col)` from `seed`, independent of the colour drift. +fn tile_bits(seed: u64, row: i64, col: i64) -> u64 { + let mut z = (seed ^ 0xD6E8_FEB8_6659_FD93) + .wrapping_add((row as u64).wrapping_mul(0xA076_1D64_78BD_642F)) + .wrapping_add((col as u64).wrapping_mul(0xE703_7ED1_A0B4_28DB)); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Adds tile colour `q`, drifted by `d`, behind what `acc` already holds (front to back: what is in front covers it). +fn blend_behind(acc: &mut [f32; 4], mut q: [f32; 4], d: [f32; 3]) { + // Without a drift a tile keeps its exact colour, also a float one past 1. + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + let k = q[3] * (1.0 - acc[3]); + for ch in 0..3 { + acc[ch] += q[ch] * k; + } + acc[3] += k; +} + +/// The straight colour of a front-to-back sum; transparent where no tile covered the pixel. +fn finish(acc: [f32; 4]) -> [f32; 4] { + if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)] } else { [0.0; 4] } +} + /// The x range where the convex polygon `corners` (in order) meets the line at height `y`, if it does. fn span(corners: &[(f64, f64); 4], y: f64) -> Option<(f64, f64)> { let mut range: Option<(f64, f64)> = None; @@ -203,25 +263,95 @@ impl BrickFill { continue; } layers += 1; - let mut q = tile.sample_area(&place, px, py); - let d = self.jitter.offsets(row, col); - // Without a drift a tile keeps its exact colour, also a float one past 1. - for ch in 0..3 { - if d[ch] != 0.0 { - q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); - } - } - // Front to back: what is already in front covers this tile. - let k = q[3] * (1.0 - acc[3]); - for ch in 0..3 { - acc[ch] += q[ch] * k; - } - acc[3] += k; + blend_behind(&mut acc, tile.sample_area(&place, px, py), self.jitter.offsets(row, col)); } } - if acc[3] > 0.0 { - out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)]; + out[i] = finish(acc); + i += 1; + } + } + out + } +} + +/// Cross Weave: a basket weave on a square grid of cells, each as wide as the mean of the tile's sides plus the spacing. +/// The cells alternate like a checkerboard between the tile lying flat and the tile turned a quarter (the origin cell), +/// every tile centred half its longer side right of and below its cell's corner, so a 40 x 30 tile leaves a 5 x 5 hole +/// at every 35 px grid point. Each tile is also turned half way or not at random (flat ones lie at 0° or 180°, upright +/// ones at 90° either way), as in the reference result with no colour randomness. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrossWeave { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels between neighbouring tiles; negative overlaps them. + pub spacing: f64, + pub jitter: Jitter, +} + +impl CrossWeave { + /// Whether cell `(row, col)` holds the tile turned a quarter. + pub fn upright(row: i64, col: i64) -> bool { + (row + col).rem_euclid(2) == 0 + } + + /// The tiles of a `width` x `height` pattern woven over `rect` (row-major straight RGBA, transparent in the holes). + /// Later tiles (down, then right) lie over earlier ones where they overlap. + pub fn render(&self, tile: &Tile, width: u32, height: u32, rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + // At the f32 precision the placement maps with, so the tile bounds here are the ones it samples. + let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 }; + let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale); + if len == 0 || tw <= 0.0 || th <= 0.0 { + return out; + } + let spacing = if self.spacing.is_finite() { self.spacing } else { 0.0 }; + // At least a pixel between cells, so every layout ends. + let pitch = ((tw + th) / 2.0 + spacing).max(1.0); + // A tile's centre lies this far right of and below its cell's corner, and reaches at most this far from it. + let reach = tw.max(th) / 2.0; + let centre = |i: i64| i as f64 * pitch + reach; + let placement = |row: i64, col: i64| { + let quarter = if Self::upright(row, col) { 90.0 } else { 0.0 }; + let angle: f64 = quarter + if tile_bits(self.jitter.seed, row, col) & 1 == 1 { 180.0 } else { 0.0 }; + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + // The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise). + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (centre(col) + hx * c + hy * s, centre(row) - hx * s + hy * c); + Placement::anchored(origin, true, (0.0, 0.0), scale as f32, angle as f32) + }; + let mut i = 0; + for y in rect.y0..rect.y1 { + let py = f64::from(y) + 0.5; + // Rows and columns whose tiles can reach this pixel, the last drawn (topmost) first. + let top_row = (py / pitch).floor() as i64; + let low_row = ((py - 2.0 * reach) / pitch).ceil() as i64; + for x in rect.x0..rect.x1 { + let px = f64::from(x) + 0.5; + let right = (px / pitch).floor() as i64; + let left = ((px - 2.0 * reach) / pitch).ceil() as i64; + let mut acc = [0.0f32; 4]; + let mut layers = 0; + 'rows: for row in (low_row..=top_row).rev() { + for col in (left..=right).rev() { + if layers >= MAX_LAYERS || acc[3] >= 1.0 { + break 'rows; + } + // A flat tile reaches half its width across and half its height down; an upright one the other way. + let (ax, ay) = if Self::upright(row, col) { (th / 2.0, tw / 2.0) } else { (tw / 2.0, th / 2.0) }; + if (px - centre(col)).abs() > ax || (py - centre(row)).abs() > ay { + continue; + } + let place = placement(row, col); + let (u, v) = place.map(px, py); + if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { + continue; + } + layers += 1; + blend_behind(&mut acc, tile.sample_area(&place, px, py), self.jitter.offsets(row, col)); + } } + out[i] = finish(acc); i += 1; } } diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index bd5228cd88..f4d46ee4ad 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -212,9 +212,9 @@ fn script(p: &Value) -> Result> { /// The scripted pattern `script` laid out over `area`, with its values from `p` (each clamped to its range, the factory /// value when missing) and an optional whole-number `seed` for the per-tile randomness. fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, pat: &photocraft_doc::pattern::Pattern, area: Rect) -> Result> { - use photocraft_compose::scripted_pattern::{BrickFill, Jitter, controls}; - let controls = - controls(script, pat.width, pat.height).ok_or_else(|| bad(format!("the `{script}` script is not supported yet; only brickFill paints today")))?; + use photocraft_compose::scripted_pattern::{SUPPORTED, controls, render}; + let unsupported = || bad(format!("the `{script}` script is not supported yet; only {} paint today", SUPPORTED.join(" and "))); + let controls = controls(script, pat.width, pat.height).ok_or_else(unsupported)?; let mut values = std::collections::HashMap::new(); for c in &controls { let v = match p.get(c.key) { @@ -228,9 +228,7 @@ fn scripted(p: &Value, script: &str, tile: &photocraft_compose::pattern::Tile, p Some(v) => v.as_u64().ok_or_else(|| bad(format!("`seed` must be a whole number, not {v}")))?, }; let get = |k: &str| values.get(k).copied().unwrap_or_default(); - let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed }; - let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter }; - Ok(brick.render(tile, pat.width, pat.height, area)) + render(script, get, seed, tile, pat.width, pat.height, area).ok_or_else(unsupported) } /// The reference application refuses Fill on the Quick Mask with a colour-only blend mode, Preserve Transparency or diff --git a/crates/engine-paint/src/fill_script_brick_tests.rs b/crates/engine-paint/src/fill_script_brick_tests.rs index a541190710..b3d04899e4 100644 --- a/crates/engine-paint/src/fill_script_brick_tests.rs +++ b/crates/engine-paint/src/fill_script_brick_tests.rs @@ -1,6 +1,6 @@ //! #17428: Edit › Fill › Pattern with Script on lays the pattern out tile by tile. `edit.fill` takes `script` and the //! script's values; Brick Fill paints rows of whole tiles from the canvas origin with every second row shifted left by -//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the five +//! the row offset (50 % of the tile width by default). An unknown script is an error, not a plain fill; the //! listed scripts without a layout yet answer "not supported". use serde_json::{Value, json}; @@ -163,7 +163,7 @@ fn an_unknown_script_is_an_error_and_the_unbuilt_ones_are_unsupported() { let before = undo_label(&s); let err = s.execute("edit.fill", brick(json!({"script": "noSuchScript"}))).unwrap_err().to_string(); assert!(err.contains("unknown script"), "{err}"); - for script in ["crossWeave", "placeAlongPath", "randomFill", "spiral", "symmetryFill"] { + for script in ["placeAlongPath", "randomFill", "spiral", "symmetryFill"] { let err = s.execute("edit.fill", brick(json!({"script": script}))).unwrap_err().to_string(); assert!(err.contains("not supported"), "{script}: {err}"); } diff --git a/crates/engine-paint/src/fill_script_cross_weave_tests.rs b/crates/engine-paint/src/fill_script_cross_weave_tests.rs new file mode 100644 index 0000000000..ae63a4e309 --- /dev/null +++ b/crates/engine-paint/src/fill_script_cross_weave_tests.rs @@ -0,0 +1,257 @@ +//! #17429: the Cross Weave script of Edit › Fill › Pattern weaves the pattern tile in a basket weave. With a 40 x 30 +//! tile the cells are 35 px: flat and upright tiles alternate like a checkerboard (the origin cell upright) and leave a +//! transparent 5 x 5 hole at every grid point (x, y = 0, 35, 70, ...). Each tile is turned half way or not at random. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const GREEN: [u8; 3] = [0, 255, 0]; + +/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green. +fn define_probe(s: &mut Session, mode: &str, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] { + s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap(); +} + +/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined. +fn session_in(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + define_probe(&mut s, mode, depth); + s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn session() -> Session { + session_in("rgb", 8) +} + +/// Cross Weave with both randomness values at 0 and `extra` values on top. +fn weave(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "crossWeave", "colorRandomness": 0, "brightnessRandomness": 0}); + for (k, v) in extra.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p +} + +fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn rgb8(px: [f32; 4]) -> [u8; 3] { + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +fn undo_label(s: &Session) -> Option { + s.active().unwrap().history.undo_label().map(str::to_string) +} + +/// Whether the tile in the `w` x `h` box at (`x0`, `y0`) is red over half of its long side, split across the long side: +/// a flat tile is red in its left or right half, an upright one in its top or bottom half. +fn red_half(s: &Session, x0: i32, y0: i32, w: i32, h: i32) -> Option<&'static str> { + let red = |x: i32, y: i32| rgb8(pixel(s, x, y)) == RED; + let all = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| red(x, y))); + let none = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| !red(x, y))); + let (a, b) = + if w > h { ((x0..x0 + w / 2, y0..y0 + h), (x0 + w / 2..x0 + w, y0..y0 + h)) } else { ((x0..x0 + w, y0..y0 + h / 2), (x0..x0 + w, y0 + h / 2..y0 + h)) }; + if all(a.0.clone(), a.1.clone()) && none(b.0.clone(), b.1.clone()) { + Some("first") + } else if none(a.0, a.1) && all(b.0, b.1) { + Some("second") + } else { + None + } +} + +#[test] +fn cross_weave_leaves_a_transparent_hole_at_every_grid_point() { + let mut s = session(); + let r = s.execute("edit.fill", weave(json!({}))).unwrap(); + assert_eq!(r["script"], "crossWeave"); + for gy in (0..400).step_by(35) { + for gx in (0..600).step_by(35) { + // The 5 x 5 hole itself, and painted pixels right after it on both sides. + for (dx, dy) in [(0, 0), (4, 0), (0, 4), (4, 4), (2, 2)] { + if gx + dx < 600 && gy + dy < 400 { + assert_eq!(pixel(&s, gx + dx, gy + dy)[3], 0.0, "hole at ({}, {})", gx + dx, gy + dy); + } + } + for (x, y) in [(gx + 5, gy + 2), (gx + 2, gy + 5)] { + if x < 600 && y < 400 { + assert!(pixel(&s, x, y)[3] > 0.99, "painted beside the hole at ({x}, {y})"); + } + } + } + } + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "the measured hole sample"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn flat_and_upright_tiles_alternate_like_a_checkerboard() { + let mut s = session(); + s.execute("edit.fill", weave(json!({}))).unwrap(); + let (mut turned, mut upright_turned) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for row in 0..10 { + for col in 0..16 { + let (x, y) = (35 * col, 35 * row); + let (upright, side) = if (row + col) % 2 == 0 { + // Upright, 30 x 40: from 5 px right of the cell corner, down into the next cell. + (true, red_half(&s, x + 5, y, 30, 40)) + } else { + // Flat, 40 x 30: from the cell corner, 5 px below it, into the next cell. + (false, red_half(&s, x, y + 5, 40, 30)) + }; + let side = side.unwrap_or_else(|| panic!("cell ({row}, {col}) holds a whole {} tile", if upright { "upright" } else { "flat" })); + if upright { &mut upright_turned } else { &mut turned }.insert(side); + } + } + // Both ways round occur among flat and among upright tiles (the half turn is random per tile). + assert_eq!(turned.len(), 2, "flat tiles at 0° and 180°"); + assert_eq!(upright_turned.len(), 2, "upright tiles at 90° both ways"); + // The other colours sit in the tile's other half: blue and green in the origin cell's upright tile. + let other: Vec<[u8; 3]> = [(10, 2), (30, 2), (10, 37), (30, 37)].iter().map(|&(x, y)| rgb8(pixel(&s, x, y))).collect(); + assert!(other.contains(&BLUE) && other.contains(&GREEN), "{other:?}"); +} + +#[test] +fn the_weave_differs_from_the_plain_and_the_brick_fill() { + let mut plain = session(); + plain.execute("edit.fill", json!({"contents": "pattern", "pattern": "probe"})).unwrap(); + let mut brick = session(); + brick.execute("edit.fill", weave(json!({"script": "brickFill"}))).unwrap(); + let mut woven = session(); + woven.execute("edit.fill", weave(json!({}))).unwrap(); + for other in [&plain, &brick] { + assert!(pixel(other, 2, 2)[3] > 0.99, "the other fills cover the origin"); + } + assert_eq!(pixel(&woven, 2, 2)[3], 0.0, "the weave leaves its hole there"); +} + +#[test] +fn the_same_seed_weaves_the_same_tiles() { + let mut a = session(); + a.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut b = session(); + b.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut c = session(); + c.execute("edit.fill", weave(json!({"seed": 8}))).unwrap(); + let samples = |s: &Session| (0..10).flat_map(|r| (0..16).map(move |c| (35 * c + 15, 35 * r + 20))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + assert_eq!(samples(&a), samples(&b)); + assert_ne!(samples(&a), samples(&c), "another seed turns other tiles"); +} + +#[test] +fn spacing_and_scale_move_the_tiles() { + // Spacing 10 leaves a 10 px gap between the origin cell's upright tile (x 5-34) and the flat one beside it. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": 10}))).unwrap(); + assert!(pixel(&s, 34, 20)[3] > 0.99, "the upright tile"); + assert_eq!(pixel(&s, 40, 20)[3], 0.0, "the gap"); + assert!(pixel(&s, 45, 20)[3] > 0.99, "the flat tile after the gap"); + // Half the scale halves the tile and the cell: 2.5 px holes on a 17.5 px grid, so (35, 35) is still a hole. + let mut s = session(); + s.execute("edit.fill", weave(json!({"patternScale": 0.5}))).unwrap(); + assert_eq!(pixel(&s, 35, 35)[3], 0.0); + assert!(pixel(&s, 38, 3)[3] > 0.99, "a full-size weave has a hole here, the half-size one a tile"); + // Overlapping tiles close the holes. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": -10}))).unwrap(); + for (x, y) in [(2, 2), (37, 37), (72, 37)] { + assert!(pixel(&s, x, y)[3] > 0.99, "no hole at ({x}, {y})"); + } +} + +#[test] +fn randomness_varies_tiles_only_above_zero() { + let mut drift = session(); + drift.execute("edit.fill", weave(json!({"colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap(); + let mut exact = session(); + exact.execute("edit.fill", weave(json!({}))).unwrap(); + let colours = + |s: &Session| (0..400).step_by(7).flat_map(|y| (0..600).step_by(7).map(move |x| (x, y))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + let pure = [RED, BLUE, GREEN, [0, 0, 0]]; + assert!(colours(&exact).iter().all(|c| pure.contains(c)), "at 0 every tile keeps the pattern's colours"); + assert!(colours(&drift).iter().any(|c| !pure.contains(c)), "above 0 the tiles drift"); +} + +#[test] +fn the_fill_stays_in_the_selection_with_mode_and_opacity() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + s.execute("edit.fill", weave(json!({"opacity": 50}))).unwrap(); + let inside = pixel(&s, 10, 10); + assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}"); + assert_eq!(pixel(&s, 150, 10)[3], 0.0, "outside the selection"); + assert_eq!(pixel(&s, 10, 80)[3], 0.0, "below the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "one history state"); + // Multiply over red paint keeps red only where the weave is red or transparent. + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.fill", weave(json!({"mode": "multiply"}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 2, 2)), RED, "the hole leaves the red paint"); + let blue_or_green = (0..600).step_by(5).any(|x| rgb8(pixel(&s, x, 10)) == [0, 0, 0]); + assert!(blue_or_green, "multiplying red by blue or green gives black"); +} + +#[test] +fn bad_values_are_errors_and_extreme_ones_never_hang_or_panic() { + let mut s = session(); + for bad in [json!({"patternScale": "big"}), json!({"spacing": [1]}), json!({"seed": -1}), json!({"colorRandomness": true})] { + assert!(s.execute("edit.fill", weave(bad.clone())).is_err(), "{bad}"); + } + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "nothing filled"); + for extreme in [ + json!({"patternScale": 1e9}), + json!({"patternScale": -5}), + json!({"spacing": -1e12}), + json!({"spacing": 1e12}), + json!({"colorRandomness": 1e9, "brightnessRandomness": -1e9}), + json!({"seed": u64::MAX}), + // Offset and angle belong to Brick Fill; Cross Weave ignores them. + json!({"offsetBetweenRows": 75, "patternRotateAngle": 45}), + ] { + let mut s = session(); + s.execute("edit.fill", weave(extreme.clone())).unwrap_or_else(|e| panic!("{extreme}: {e}")); + } +} + +#[test] +fn a_long_thin_tile_reaches_far_from_its_centre() { + // A 4000 x 4 tile at the largest overlap: 2000 px cells, each tile reaching 2000 px from its centre. The flat tile + // of cell (-1, 0) lies along the top edge, the upright one of cell (-1, -1) along the left edge. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap(); + s.execute("file.new", json!({"width": 300, "height": 200, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", weave(json!({"pattern": "bar", "spacing": -2}))).unwrap(); + for (x, y) in [(150, 1), (299, 0), (1, 100), (0, 199)] { + let px = pixel(&s, x, y); + assert!(px[3] > 0.99 && rgb8(px) == RED, "({x}, {y}): {px:?}"); + } + assert_eq!(pixel(&s, 150, 100)[3], 0.0, "between the tiles"); +} + +#[test] +fn cross_weave_runs_in_every_mode_and_depth() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] { + let mut s = session_in(mode, depth); + s.execute("edit.fill", weave(json!({}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "{mode}/{depth}: hole"); + assert!(pixel(&s, 20, 20)[3] > 0.99, "{mode}/{depth}: painted"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}"); + } +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index 21025b6ed9..2645cfe41e 100644 --- a/crates/engine-paint/src/lib.rs +++ b/crates/engine-paint/src/lib.rs @@ -48,6 +48,8 @@ mod fill_quick_mask_refusals_tests; #[cfg(test)] mod fill_script_brick_tests; #[cfg(test)] +mod fill_script_cross_weave_tests; +#[cfg(test)] mod mixer_indexed_bitmap_tests; #[cfg(test)] mod mixer_toggle_commands_tests; diff --git a/crates/ui-egui/src/dialogs/fill_script_ui.rs b/crates/ui-egui/src/dialogs/fill_script_ui.rs index 4d042d0eff..77ecf122bc 100644 --- a/crates/ui-egui/src/dialogs/fill_script_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_script_ui.rs @@ -11,7 +11,7 @@ use craft::ui::runtime::env::Label; use craft::ui::runtime::memory::{MemoryStage, SaveKey}; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::value_drag::SliderScale; -use photocraft_compose::scripted_pattern::{BrickFill, Control, Jitter, SCRIPTS, controls}; +use photocraft_compose::scripted_pattern::{Control, SCRIPTS, controls, render}; use serde_json::{Map, Value, json}; use crate::PhotocraftApp; @@ -236,7 +236,7 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { if let Some(held) = app.framework.captured.get_mut(&key) { held["lastPreset"] = json!(now); } - let picture = pattern.and_then(|p| preview(ctx, id, &p, &shown, &controls)); + let picture = pattern.and_then(|p| preview(ctx, id, script_of(&key), &p, &shown, &controls)); if let Some(dialog) = app.framework.dialogs.get_mut_by_id::(id) { dialog.set_preview(Some(match picture { Some(texture) => PreviewState::Ready(egui::load::SizedTexture::from_handle(&texture)), @@ -246,9 +246,16 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) { } } -/// The preview of the values `f`: the script laid out over a sample area with pattern `p`, on white. The texture is -/// kept per dialog and drawn again only when the values or the pattern change. -fn preview(ctx: &egui::Context, id: DialogId, p: &photocraft_doc::Pattern, f: &DialogFields, controls: &[Control]) -> Option { +/// The preview of the values `f`: `script` laid out over a sample area with pattern `p`, on white. The texture is kept +/// per dialog and drawn again only when the values or the pattern change. +fn preview( + ctx: &egui::Context, + id: DialogId, + script: &str, + p: &photocraft_doc::Pattern, + f: &DialogFields, + controls: &[Control], +) -> Option { let values: Vec = controls.iter().map(|c| c.clamp(f.number(c.key).unwrap_or(c.default))).collect(); let stamp = format!("{}:{values:?}", p.id); let cache = egui::Id::unique(("fill-script-preview", id.value())); @@ -259,9 +266,7 @@ fn preview(ctx: &egui::Context, id: DialogId, p: &photocraft_doc::Pattern, f: &D } let tile = photocraft_compose::pattern::Tile::new(p)?; let get = |k: &str| controls.iter().zip(&values).find(|(c, _)| c.key == k).map_or(0.0, |(_, v)| *v); - let jitter = Jitter { color: get("colorRandomness") as f32, brightness: get("brightnessRandomness") as f32, seed: 1 }; - let brick = BrickFill { scale: get("patternScale"), spacing: get("spacing"), offset: get("offsetBetweenRows"), angle: get("patternRotateAngle"), jitter }; - let px = brick.render(&tile, p.width, p.height, photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32)); + let px = render(script, get, 1, &tile, p.width, p.height, photocraft_geom::Rect::new(0, 0, PREVIEW as i32, PREVIEW as i32))?; let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; let rgba: Vec = px.iter().flat_map(|q| [0, 1, 2].map(|c| level(q[c] * q[3] + (1.0 - q[3]))).into_iter().chain([255])).collect(); let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &rgba); diff --git a/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs b/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs index c689e76018..4fda381962 100644 --- a/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs +++ b/crates/ui-egui/src/dialogs/fill_script_ui_tests.rs @@ -1,6 +1,7 @@ //! #17428: Fill › Pattern has a Script check box and list (greyed until ticked); OK with Script on opens the script's own //! dialog and only that dialog's OK fills. Preset › Default sets the factory values, a changed value turns Preset to -//! Custom, Reset puts back the opening values, and the values are remembered per script. +//! Custom, Reset puts back the opening values, and the values are remembered per script. Cross Weave +//! (#17429) opens its own four values. use craft::ui::patterns::form_dialogs::HostedParamDialog; use egui::accesskit::Role; @@ -207,3 +208,52 @@ fn a_typed_value_past_the_range_is_clamped_with_the_range_alert() { let script = dialogs.iter().find(|d| d.key.as_deref() == Some("edit.fill.script.brickFill")).map(|d| d.id).unwrap(); assert_eq!(h.state().framework.dialogs.get_by_id::(script).unwrap().fields().number("patternScale"), Some(1.25)); } + +#[test] +fn cross_weave_opens_its_dialog_with_its_four_values() { + let mut app = app(); + let before = past(&app); + fill_with_script(&mut app, "crossWeave"); + assert_eq!(top_key(&app).as_deref(), Some("edit.fill.script.crossWeave")); + for (key, default) in [("patternScale", 1.0), ("spacing", 0.0), ("colorRandomness", 0.05), ("brightnessRandomness", 0.1)] { + assert_eq!(field(&app, key), Some(default), "{key}"); + } + let h = harness(app); + assert!(h.query_all_by_role(Role::Dialog).any(|n| n.accesskit_node().label().as_deref() == Some("Cross Weave")), "titled with the script's name"); + // Each value's field and its range, top to bottom; Brick Fill's row offset and angle are not there. + let fields: Vec<(String, Option, Option)> = h + .query_all_by_role(Role::SpinButton) + .filter_map(|n| { + let node = n.accesskit_node(); + Some((node.label()?.to_string(), node.min_numeric_value(), node.max_numeric_value())) + }) + .collect(); + let labels: Vec<&str> = fields.iter().map(|(l, _, _)| l.as_str()).collect(); + let order = ["Pattern Scale", "Spacing", "Color randomness", "Brightness randomness"]; + let at: Vec> = order.iter().map(|o| labels.iter().position(|l| l.starts_with(o))).collect(); + assert!(at.iter().all(Option::is_some) && at.windows(2).all(|w| w[0] < w[1]), "{labels:?}"); + assert!(!labels.iter().any(|l| l.starts_with("Offset between rows") || l.starts_with("Pattern rotate angle")), "{labels:?}"); + let range = |name: &str| fields.iter().find(|(l, _, _)| l.starts_with(name)).map(|(_, lo, hi)| (*lo, *hi)); + assert_eq!(range("Pattern Scale"), Some((Some(0.1), Some(1.25)))); + assert_eq!(range("Color randomness"), Some((Some(0.0), Some(1.0)))); + assert_eq!(range("Brightness randomness"), Some((Some(0.0), Some(1.0)))); + let spacing = range("Spacing").unwrap(); + assert!(spacing.0.is_some_and(|lo| lo < 0.0) && spacing.1.is_some_and(|hi| hi > 0.0), "tiles may overlap or stand apart: {spacing:?}"); + // OK fills once, as "Fill". + let mut app = h.into_state(); + let top = newest(&app); + confirm(&mut app, top); + assert_eq!(past(&app), before + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Fill")); +} + +#[test] +fn cancel_in_cross_weave_fills_nothing() { + let mut app = app(); + let before = past(&app); + fill_with_script(&mut app, "crossWeave"); + let top = newest(&app); + cancel(&mut app, top); + assert_eq!(open_count(&app), 0); + assert_eq!(past(&app), before); +} From 67f8cdb20241cf41150eaabe77a6abfec9f88865 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 30 Nov 2026 22:27:43 +0100 Subject: [PATCH 28/29] Fill scripts: tiles clear at a pixel do not use up the layer limit (#17429) A tile that covers a pixel but is transparent there counted toward the 1024-layer cap, so with a mostly clear pattern at the largest overlap the cap ran out before the tiles that show at that pixel were reached and the pixel stayed empty. Only visible samples count now; a separate, larger visit cap keeps the work per pixel bounded. Applies to Brick Fill and Cross Weave alike. Co-Authored-By: Claude Opus 5.5 --- crates/compose/src/scripted_pattern.rs | 29 ++++++++++++++----- .../src/fill_script_cross_weave_tests.rs | 20 +++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index 2e40e1da93..a0263160e2 100644 --- a/crates/compose/src/scripted_pattern.rs +++ b/crates/compose/src/scripted_pattern.rs @@ -156,9 +156,14 @@ pub struct BrickFill { } /// Most tiles composited into one pixel, front to back: bounds the work of extreme overlaps. Only a pixel whose -/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. +/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. A tile that is +/// transparent at the pixel does not count, so it cannot use up the limit before the tiles that show there. const MAX_LAYERS: usize = 1024; +/// Most tiles looked at for one pixel, transparent there or not: the work bound when many overlapping tiles are clear +/// at that pixel (a mostly transparent pattern at the largest overlap). +const MAX_VISITS: usize = 16 * MAX_LAYERS; + /// A repeatable value for tile `(row, col)` from `seed`, independent of the colour drift. fn tile_bits(seed: u64, row: i64, col: i64) -> u64 { let mut z = (seed ^ 0xD6E8_FEB8_6659_FD93) @@ -246,7 +251,7 @@ impl BrickFill { for x in rect.x0..rect.x1 { let px = f64::from(x) + 0.5; let mut acc = [0.0f32; 4]; - let mut layers = 0; + let (mut layers, mut visits) = (0, 0); 'rows: for row in (low_row..=top_row).rev() { // Only the tiles of this row whose centre lies in the turned rectangle around the pixel cover it. let Some((lo, hi)) = span(&corners, row as f64 * pitch_y + th / 2.0 - py) else { continue }; @@ -254,7 +259,7 @@ impl BrickFill { let right = ((px + hi + row_shift - tw / 2.0) / pitch_x).floor() as i64; let left = ((px + lo + row_shift - tw / 2.0) / pitch_x).ceil() as i64; for col in (left..=right).rev() { - if layers >= MAX_LAYERS || acc[3] >= 1.0 { + if layers >= MAX_LAYERS || visits >= MAX_VISITS || acc[3] >= 1.0 { break 'rows; } let place = placement(row, col); @@ -262,8 +267,13 @@ impl BrickFill { if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { continue; } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } layers += 1; - blend_behind(&mut acc, tile.sample_area(&place, px, py), self.jitter.offsets(row, col)); + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); } } out[i] = finish(acc); @@ -331,10 +341,10 @@ impl CrossWeave { let right = (px / pitch).floor() as i64; let left = ((px - 2.0 * reach) / pitch).ceil() as i64; let mut acc = [0.0f32; 4]; - let mut layers = 0; + let (mut layers, mut visits) = (0, 0); 'rows: for row in (low_row..=top_row).rev() { for col in (left..=right).rev() { - if layers >= MAX_LAYERS || acc[3] >= 1.0 { + if layers >= MAX_LAYERS || visits >= MAX_VISITS || acc[3] >= 1.0 { break 'rows; } // A flat tile reaches half its width across and half its height down; an upright one the other way. @@ -347,8 +357,13 @@ impl CrossWeave { if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { continue; } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } layers += 1; - blend_behind(&mut acc, tile.sample_area(&place, px, py), self.jitter.offsets(row, col)); + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); } } out[i] = finish(acc); diff --git a/crates/engine-paint/src/fill_script_cross_weave_tests.rs b/crates/engine-paint/src/fill_script_cross_weave_tests.rs index ae63a4e309..6eb091b61d 100644 --- a/crates/engine-paint/src/fill_script_cross_weave_tests.rs +++ b/crates/engine-paint/src/fill_script_cross_weave_tests.rs @@ -255,3 +255,23 @@ fn cross_weave_runs_in_every_mode_and_depth() { assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}"); } } + +#[test] +fn tiles_clear_at_a_pixel_do_not_hide_the_ones_that_show_there() { + // A clear 100 x 100 tile with an opaque 10 x 10 middle, at the largest overlap (2 px between tiles): about 1100 + // tiles in front are clear at (0, 0) before the ones whose middle covers it. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); + s.execute("select.rect", json!({"x": 45, "y": 45, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "dot", "rect": [0, 0, 100, 100]})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // Brick Fill lays its tiles out the same way and must find them too. + for script in ["crossWeave", "brickFill"] { + s.execute("edit.fill", weave(json!({"script": script, "pattern": "dot", "spacing": -98}))).unwrap(); + let px = pixel(&s, 0, 0); + assert!(px[3] > 0.99 && rgb8(px) == RED, "{script}: {px:?}"); + s.execute("edit.undo", json!({})).unwrap(); + } +} From 7cbe48c80f28190341a70d929d970ecfc6571019 Mon Sep 17 00:00:00 2001 From: Elvis33LE <67311580+Elvis33LE@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:46:01 +0100 Subject: [PATCH 29/29] CI: Split the panic hunt and cap Linux Rayon pools (#18439) Run the existing panic hunt as eight ignored Nextest cases in one test binary, preserving every command and input, the harness self-test, and the 180-second deadline per test process. Set RAYON_NUM_THREADS=4 for the Linux gate and no-HEIF job. That limits the default global Rayon pool per process; it does not cap total Nextest concurrency or demonstrate that cluster contention or OOMs are fixed. The eight cases and self-test passed in hosted Ubuntu and Windows on the earlier merge preview and in the scoped current-main Linux validation. The latter used Rayon two. --- .github/workflows/ci.yml | 2 ++ crates/engine/tests/panic_hunt.rs | 33 ++++++++++++++++++++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47c0dc60c0..922fa9b659 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -206,6 +206,7 @@ jobs: CARGO_PROFILE_TEST_STRIP=symbols PHOTOCRAFT_CI_EXCLUDE=${{ needs.platforms.outputs.linux_skip }} PHOTOCRAFT_CORPUS_TESTS=1 + RAYON_NUM_THREADS=4 timeout-minutes: 100 cache-workspace-crates: true lint-cache: false @@ -347,6 +348,7 @@ jobs: CARGO_NET_RETRY: 10 CARGO_PROFILE_DEV_DEBUG: "0" CARGO_PROFILE_TEST_STRIP: symbols + RAYON_NUM_THREADS: "4" steps: - name: Harden runner uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 91435bea1a..b0708f25d5 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -61,9 +61,10 @@ fn run_guarded(id: &str, p: &Value) -> Result<(), String> { } } -#[test] -#[ignore = "slow full-registry fuzz; run with --ignored"] -fn no_command_panics_or_hangs_on_adversarial_params() { +const SHARDS: usize = 8; + +fn run_panic_hunt_shard(shard: usize) { + assert!(shard < SHARDS); let params: Vec = vec![ json!({}), json!({"x": -9, "y": -9, "radius": 0, "amount": 0, "angle": 0, "opacity": 0, "scale": 0, "levels": 0, "tolerance": 0, "gamma": 0, "layer": 999999, "channel": 999, "index": 999999, "count": 0}), @@ -76,7 +77,10 @@ fn no_command_panics_or_hangs_on_adversarial_params() { json!({"subtractPoints": "none", "order": ["-"], "labMinimum": [0, 0, 0], "labMaximum": [100, 0, 0]}), ]; let mut bad: Vec = Vec::new(); - for spec in command_specs() { + for (idx, spec) in command_specs().iter().enumerate() { + if idx % SHARDS != shard { + continue; + } for p in ¶ms { // Print and Print One Copy reach real printers (lp, or the Windows driver): fuzz them // as dry runs so the hunt never prints a page. @@ -93,9 +97,28 @@ fn no_command_panics_or_hangs_on_adversarial_params() { } } } - assert!(bad.is_empty(), "{} commands panicked:\n{}", bad.len(), bad.join("\n")); + assert!(bad.is_empty(), "shard {shard}: {} commands panicked:\n{}", bad.len(), bad.join("\n")); } +macro_rules! panic_hunt_shard { + ($name:ident, $shard:expr) => { + #[test] + #[ignore = "slow full-registry fuzz; run with --ignored"] + fn $name() { + run_panic_hunt_shard($shard); + } + }; +} + +panic_hunt_shard!(panic_hunt_shard_0, 0); +panic_hunt_shard!(panic_hunt_shard_1, 1); +panic_hunt_shard!(panic_hunt_shard_2, 2); +panic_hunt_shard!(panic_hunt_shard_3, 3); +panic_hunt_shard!(panic_hunt_shard_4, 4); +panic_hunt_shard!(panic_hunt_shard_5, 5); +panic_hunt_shard!(panic_hunt_shard_6, 6); +panic_hunt_shard!(panic_hunt_shard_7, 7); + /// #4982: a panic the code under test contains still fails the run; a graceful `Err` does not. #[test] fn contained_panics_count_and_graceful_errors_do_not() {