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/compose/src/scripted_pattern.rs b/crates/compose/src/scripted_pattern.rs index 9def7a7493..a0263160e2 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, } } @@ -126,9 +156,44 @@ pub struct BrickFill { } /// Most tiles composited into one pixel, front to back: bounds the work of extreme overlaps. Only a pixel whose -/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. +/// frontmost tiles all let some of it through ever reaches it; an opaque tile ends the pixel at once. A tile that is +/// transparent at the pixel does not count, so it cannot use up the limit before the tiles that show there. const MAX_LAYERS: usize = 1024; +/// Most tiles looked at for one pixel, transparent there or not: the work bound when many overlapping tiles are clear +/// at that pixel (a mostly transparent pattern at the largest overlap). +const MAX_VISITS: usize = 16 * MAX_LAYERS; + +/// A repeatable value for tile `(row, col)` from `seed`, independent of the colour drift. +fn tile_bits(seed: u64, row: i64, col: i64) -> u64 { + let mut z = (seed ^ 0xD6E8_FEB8_6659_FD93) + .wrapping_add((row as u64).wrapping_mul(0xA076_1D64_78BD_642F)) + .wrapping_add((col as u64).wrapping_mul(0xE703_7ED1_A0B4_28DB)); + z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + z ^ (z >> 31) +} + +/// Adds tile colour `q`, drifted by `d`, behind what `acc` already holds (front to back: what is in front covers it). +fn blend_behind(acc: &mut [f32; 4], mut q: [f32; 4], d: [f32; 3]) { + // Without a drift a tile keeps its exact colour, also a float one past 1. + for ch in 0..3 { + if d[ch] != 0.0 { + q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); + } + } + let k = q[3] * (1.0 - acc[3]); + for ch in 0..3 { + acc[ch] += q[ch] * k; + } + acc[3] += k; +} + +/// The straight colour of a front-to-back sum; transparent where no tile covered the pixel. +fn finish(acc: [f32; 4]) -> [f32; 4] { + if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)] } else { [0.0; 4] } +} + /// The x range where the convex polygon `corners` (in order) meets the line at height `y`, if it does. fn span(corners: &[(f64, f64); 4], y: f64) -> Option<(f64, f64)> { let mut range: Option<(f64, f64)> = None; @@ -186,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 }; @@ -194,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); @@ -202,26 +267,106 @@ impl BrickFill { if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { continue; } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } layers += 1; - let mut q = tile.sample_area(&place, px, py); - let d = self.jitter.offsets(row, col); - // Without a drift a tile keeps its exact colour, also a float one past 1. - for ch in 0..3 { - if d[ch] != 0.0 { - q[ch] = (q[ch] + d[ch]).clamp(0.0, 1.0); - } - } - // Front to back: what is already in front covers this tile. - let k = q[3] * (1.0 - acc[3]); - for ch in 0..3 { - acc[ch] += q[ch] * k; - } - acc[3] += k; + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); } } - if acc[3] > 0.0 { - out[i] = [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3].min(1.0)]; + out[i] = finish(acc); + i += 1; + } + } + out + } +} + +/// Cross Weave: a basket weave on a square grid of cells, each as wide as the mean of the tile's sides plus the spacing. +/// The cells alternate like a checkerboard between the tile lying flat and the tile turned a quarter (the origin cell), +/// every tile centred half its longer side right of and below its cell's corner, so a 40 x 30 tile leaves a 5 x 5 hole +/// at every 35 px grid point. Each tile is also turned half way or not at random (flat ones lie at 0° or 180°, upright +/// ones at 90° either way), as in the reference result with no colour randomness. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrossWeave { + /// Tile size as a fraction (0.1..1.25). + pub scale: f64, + /// Pixels between neighbouring tiles; negative overlaps them. + pub spacing: f64, + pub jitter: Jitter, +} + +impl CrossWeave { + /// Whether cell `(row, col)` holds the tile turned a quarter. + pub fn upright(row: i64, col: i64) -> bool { + (row + col).rem_euclid(2) == 0 + } + + /// The tiles of a `width` x `height` pattern woven over `rect` (row-major straight RGBA, transparent in the holes). + /// Later tiles (down, then right) lie over earlier ones where they overlap. + pub fn render(&self, tile: &Tile, width: u32, height: u32, rect: Rect) -> Vec<[f32; 4]> { + let len = rect.width() as usize * rect.height() as usize; + let mut out = vec![[0.0f32; 4]; len]; + // At the f32 precision the placement maps with, so the tile bounds here are the ones it samples. + let scale = if self.scale.is_finite() && self.scale > 0.0 { f64::from(self.scale as f32) } else { 1.0 }; + let (tw, th) = (f64::from(width) * scale, f64::from(height) * scale); + if len == 0 || tw <= 0.0 || th <= 0.0 { + return out; + } + let spacing = if self.spacing.is_finite() { self.spacing } else { 0.0 }; + // At least a pixel between cells, so every layout ends. + let pitch = ((tw + th) / 2.0 + spacing).max(1.0); + // A tile's centre lies this far right of and below its cell's corner, and reaches at most this far from it. + let reach = tw.max(th) / 2.0; + let centre = |i: i64| i as f64 * pitch + reach; + let placement = |row: i64, col: i64| { + let quarter = if Self::upright(row, col) { 90.0 } else { 0.0 }; + let angle: f64 = quarter + if tile_bits(self.jitter.seed, row, col) & 1 == 1 { 180.0 } else { 0.0 }; + let (c, s) = (angle.to_radians().cos(), angle.to_radians().sin()); + // The corner the tile's (0, 0) lands on once it is turned about its centre (y down, counter-clockwise). + let (hx, hy) = (-tw / 2.0, -th / 2.0); + let origin = (centre(col) + hx * c + hy * s, centre(row) - hx * s + hy * c); + Placement::anchored(origin, true, (0.0, 0.0), scale as f32, angle as f32) + }; + let mut i = 0; + for y in rect.y0..rect.y1 { + let py = f64::from(y) + 0.5; + // Rows and columns whose tiles can reach this pixel, the last drawn (topmost) first. + let top_row = (py / pitch).floor() as i64; + let low_row = ((py - 2.0 * reach) / pitch).ceil() as i64; + for x in rect.x0..rect.x1 { + let px = f64::from(x) + 0.5; + let right = (px / pitch).floor() as i64; + let left = ((px - 2.0 * reach) / pitch).ceil() as i64; + let mut acc = [0.0f32; 4]; + let (mut layers, mut visits) = (0, 0); + 'rows: for row in (low_row..=top_row).rev() { + for col in (left..=right).rev() { + if layers >= MAX_LAYERS || visits >= MAX_VISITS || acc[3] >= 1.0 { + break 'rows; + } + // A flat tile reaches half its width across and half its height down; an upright one the other way. + let (ax, ay) = if Self::upright(row, col) { (th / 2.0, tw / 2.0) } else { (tw / 2.0, th / 2.0) }; + if (px - centre(col)).abs() > ax || (py - centre(row)).abs() > ay { + continue; + } + let place = placement(row, col); + let (u, v) = place.map(px, py); + if !(0.0..f64::from(width)).contains(&u) || !(0.0..f64::from(height)).contains(&v) { + continue; + } + visits += 1; + let q = tile.sample_area(&place, px, py); + if q[3] <= 0.0 { + continue; + } + layers += 1; + blend_behind(&mut acc, q, self.jitter.offsets(row, col)); + } } + out[i] = finish(acc); i += 1; } } diff --git a/crates/engine-core/src/cmd/multichannel_cmds.rs b/crates/engine-core/src/cmd/multichannel_cmds.rs index 77846d17c5..ebf209c7d9 100644 --- a/crates/engine-core/src/cmd/multichannel_cmds.rs +++ b/crates/engine-core/src/cmd/multichannel_cmds.rs @@ -259,6 +259,11 @@ pub fn ink_names(doc: &Document) -> Vec { doc.channels.iter().filter(|c| c.spot.is_some()).map(|c| c.name.clone()).collect() } +/// The ink (spot) channels of a Multichannel image, in order, to write into. +pub fn inks_mut(doc: &mut Document) -> impl Iterator { + doc.channels.iter_mut().filter(|c| c.spot.is_some()).map(|c| &mut c.surface) +} + pub fn specs() -> Vec { vec![CommandSpec { id: "image.mode.multichannel", diff --git a/crates/engine-paint/src/cmd/fill_cmds.rs b/crates/engine-paint/src/cmd/fill_cmds.rs index 0e9fd6ecad..90e0642902 100644 --- a/crates/engine-paint/src/cmd/fill_cmds.rs +++ b/crates/engine-paint/src/cmd/fill_cmds.rs @@ -90,6 +90,20 @@ fn flag(p: &Value, k: &str, d: bool) -> Result { } } +/// A Multichannel document as the conversion leaves it: ink channels and no layer to fill. +fn inks_only(doc: &photocraft_doc::Document) -> bool { + doc.mode == ColorMode::Multichannel && doc.layers.is_empty() +} + +/// Edit › Fill's precondition: a pixel layer or a targeted channel, or an 8-bit Multichannel document, whose ink +/// channels it fills (#17479). +pub fn enabled(s: &Session) -> std::result::Result<(), String> { + if s.active().is_some_and(|st| inks_only(&st.doc) && st.doc.depth == SampleType::U8) { + return Ok(()); + } + crate::commands::has_pixel_or_channel(s) +} + /// Edit › Fill. pub fn fill(s: &mut Session, p: &Value) -> Result { let contents = contents(p)?; @@ -100,7 +114,17 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::QuickMask { check_quick_mask(contents, mode, preserve)?; } - let id = if channel { None } else { Some(layer_param(s, p)?) }; + // A Multichannel document has no layer: a fill of its pixels goes into every ink channel (#17479). + let inks = !channel && crate::channel_cmds::gray_target(p).is_none() && s.active().is_some_and(|st| inks_only(&st.doc)); + if inks && s.active().is_some_and(|st| st.doc.depth != SampleType::U8) { + return Err(EngineError::Other("Fill into every channel of a 16- or 32-bit Multichannel document is not supported yet; target one channel".into())); + } + if inks && matches!(contents, "history" | "contentAware") { + return Err(EngineError::Other( + "Fill from History and Content-Aware Fill need a layer, and a Multichannel document has none; target one channel".into(), + )); + } + let id = if channel || inks { None } else { Some(layer_param(s, p)?) }; let st = s.active().ok_or(EngineError::NoDocument)?; check_mode_available(CMD, &st.doc, mode)?; if greyed_contents(st.doc.mode).contains(&contents) { @@ -220,9 +244,13 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { } _ => return Err(bad(format!("unknown contents `{contents}`"))), }; + // The reference writes a colour's one grey into every ink channel; it is not split into inks. // 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 inks && matches!(contents, "foreground" | "background" | "color") => { + Source::Color(multichannel_grey(s, c)) + } 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, @@ -237,6 +265,16 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { s.edit("Fill", |doc, _| { let sel = doc.selection.clone(); + if inks { + let blend = Blend { mode, opacity, keep_alpha: false, restore }; + // A pattern reaches the first ink only; the others come out white, as the reference fills them. + let white = Source::Color([1.0; 4]); + for (k, surf) in photocraft_engine_core::multichannel_cmds::inks_mut(doc).enumerate() { + let src = if k > 0 && matches!(source, Source::Pixels(..)) { &white } else { &source }; + ink_fill(surf, area, src, sel.as_ref(), blend)?; + } + return Ok(()); + } let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore })?; if bitmap { @@ -248,6 +286,52 @@ pub fn fill(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// A fill colour as a Multichannel document takes it (#17479): its grey in Gray Gamma 2.2, the one +/// value the reference writes into every channel (RGB 200,30,30 gives 104 and 30,30,200 gives 64). +/// A failed conversion keeps the colour. +fn multichannel_grey(s: &Session, c: [f32; 4]) -> [f32; 4] { + use crate::color_cmds::ColorExt; + let dst = std::sync::Arc::new(craft_cms::Builtin::GrayGamma22.profile().clone()); + let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() }; + let Ok(t) = craft_cms::cached(&s.color().working(ColorMode::Rgb), &dst, opts) else { return c }; + let mut out = [0.0f32; 16]; + if t.eval(&[c[0], c[1], c[2]], &mut out).is_err() || !out[0].is_finite() { + return c; + } + let g = out[0].clamp(0.0, 1.0); + [g, g, g, c[3]] +} + +/// Blends `src` into an ink channel, which stores density, as if over its tone. Normal blends linearly, so the +/// source is turned into density instead and the channel is filled as it is, solid tiles shared. Other modes turn +/// the channel into tone and back one tile at a time. +fn ink_fill(surf: &mut photocraft_raster::Surface, area: Rect, src: &Source, sel: Option<&photocraft_raster::Surface>, blend: Blend) -> Result<()> { + let density = |c: [f32; 4]| [1.0 - c[0], 1.0 - c[1], 1.0 - c[2], c[3]]; + match src { + Source::Color(c) if blend.mode == BlendMode::Normal => blend_into(surf, area, &Source::Color(density(*c)), sel, blend), + Source::Pixels(r, px) if blend.mode == BlendMode::Normal => { + blend_into(surf, area, &Source::Pixels(*r, px.iter().map(|c| density(*c)).collect()), sel, blend) + } + _ => { + for tc in area.tiles() { + let r = tc.rect().intersect(&area); + invert(surf, r)?; + blend_into(surf, r, src, sel, blend)?; + invert(surf, r)?; + } + Ok(()) + } + } +} + +/// Inverts `area` of a channel (density to tone and back). +fn invert(surf: &mut photocraft_raster::Surface, area: Rect) -> Result<()> { + let mut v = crate::allocation::read_region(surf, area, "filling a Multichannel channel")?; + v.iter_mut().for_each(|x| *x = 1.0 - *x); + surf.try_write_region(area, &v)?; + Ok(()) +} + /// The `script` param of a pattern fill: a [`SCRIPTS`](photocraft_compose::scripted_pattern::SCRIPTS) key, or none. fn script(p: &Value) -> Result> { use photocraft_compose::scripted_pattern::{SCRIPTS, script_key}; @@ -264,9 +348,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) { @@ -280,9 +364,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 @@ -359,6 +441,9 @@ mod fill_quick_mask_mode_gray_tests; #[path = "fill_dissolve_opacity_rounding_tests.rs"] mod fill_dissolve_opacity_rounding_tests; +#[cfg(test)] +mod multichannel_fill_tests; + #[cfg(test)] #[path = "../fill_history_missing_layer_tests.rs"] mod fill_history_missing_layer_tests; diff --git a/crates/engine-paint/src/cmd/fill_cmds/multichannel_fill_tests.rs b/crates/engine-paint/src/cmd/fill_cmds/multichannel_fill_tests.rs new file mode 100644 index 0000000000..9c082032c4 --- /dev/null +++ b/crates/engine-paint/src/cmd/fill_cmds/multichannel_fill_tests.rs @@ -0,0 +1,167 @@ +//! #17479: Edit › Fill works in a Multichannel document. With no channel targeted it writes the fill's one grey into +//! every ink channel, as the reference application does (Foreground 200,30,30 → 104 in each channel, Background +//! 30,30,200 → 64), blends per channel, and is one "Fill" history step. One targeted channel still takes the fill +//! alone. + +use super::*; +use serde_json::json; + +/// A 64×32 RGB document at `depth` bits, red on the left half and blue on the right, converted to Multichannel +/// (Cyan, Magenta, Yellow; tone 255 = no ink). +fn session(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 64, "height": 32, "mode": "rgb", "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("select.rect", json!({"x": 32, "y": 0, "width": 32, "height": 32})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#0000ff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("image.mode.multichannel", json!({})).unwrap(); + s +} + +/// The tone (0..255, 255 = no ink) of every ink channel at (x, 10). +fn tones(s: &Session, x: i32) -> Vec { + let st = s.active().unwrap(); + st.doc + .channels + .iter() + .filter(|c| c.spot.is_some()) + .map(|c| ((1.0 - c.surface.read_region(Rect::new(x, 10, x + 1, 11))[0]) * 255.0).round() as i32) + .collect() +} + +const RED: i32 = 10; +const BLUE: i32 = 50; + +fn rgb(r: u8, g: u8, b: u8) -> [f32; 4] { + [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0] +} + +/// Every ink of both halves after filling a fresh document with `params`. +fn filled(params: serde_json::Value) -> (Vec, Vec) { + let mut s = session(8); + s.tools.foreground = rgb(200, 30, 30); + s.tools.background = rgb(30, 30, 200); + s.execute("edit.fill", params).unwrap(); + (tones(&s, RED), tones(&s, BLUE)) +} + +fn near(got: &[i32], want: i32, tol: i32) -> bool { + got.iter().all(|v| (v - want).abs() <= tol) +} + +#[test] +fn starts_as_the_measured_inks() { + let s = session(8); + assert_eq!((tones(&s, RED), tones(&s, BLUE)), (vec![255, 0, 0], vec![0, 0, 255])); +} + +#[test] +fn fill_is_enabled_and_one_history_step() { + let mut s = session(8); + assert!(s.is_enabled("edit.fill"), "Edit › Fill is greyed in a Multichannel document"); + let before = s.active().unwrap().history.past_len(); + s.execute("edit.fill", json!({"contents": "white"})).unwrap(); + let st = s.active().unwrap(); + assert_eq!((st.history.past_len(), st.history.undo_label()), (before + 1, Some("Fill"))); +} + +#[test] +fn colour_fills_write_one_grey_into_every_channel() { + // (contents, the measured grey, our tolerance): the colours go through the grey, not split into inks. + for (params, want, tol) in [ + (json!({"contents": "foreground"}), 104, 1), + (json!({"contents": "background"}), 64, 1), + (json!({"contents": "color", "color": "#8c8c8c"}), 139, 1), + (json!({"color": "#8c8c8c"}), 139, 1), + (json!({"contents": "black"}), 0, 0), + (json!({"contents": "gray"}), 128, 0), + (json!({"contents": "white"}), 255, 0), + ] { + let (red, blue) = filled(params.clone()); + assert!(near(&red, want, tol) && near(&blue, want, tol), "{params}: red half {red:?}, blue half {blue:?}, want {want} in every channel"); + } +} + +#[test] +fn opacity_and_mode_blend_per_channel() { + let (red, blue) = filled(json!({"contents": "white", "opacity": 50})); + assert!(near(&red[1..], 128, 1) && red[0] == 255, "white at 50 %: red half {red:?}"); + assert!(near(&blue[..2], 128, 1) && blue[2] == 255, "white at 50 %: blue half {blue:?}"); + let (red, blue) = filled(json!({"contents": "white", "mode": "multiply"})); + assert_eq!((red, blue), (vec![255, 0, 0], vec![0, 0, 255]), "white Multiply changes nothing"); +} + +#[test] +fn a_selection_limits_the_fill() { + let mut s = session(8); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 32})).unwrap(); + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + assert_eq!((tones(&s, RED), tones(&s, BLUE)), (vec![0, 0, 0], vec![0, 0, 255])); +} + +#[test] +fn pattern_reaches_the_first_channel_and_whitens_the_rest() { + let mut s = session(8); + s.execute("edit.fill", json!({"contents": "pattern"})).unwrap(); + let st = s.active().unwrap(); + let inks: Vec> = st.doc.channels.iter().filter(|c| c.spot.is_some()).map(|c| c.surface.read_region(st.doc.bounds())).collect(); + assert!(inks[0].iter().any(|d| *d > 0.0), "the pattern left no ink in the first channel"); + for ink in &inks[1..] { + assert!(ink.iter().all(|d| *d == 0.0), "a channel after the first kept ink"); + } +} + +#[test] +fn one_targeted_channel_takes_the_fill_alone() { + let mut s = session(8); + s.execute("channel.target", json!({"channel": {"alpha": 0}})).unwrap(); + // Today's one-channel fill writes the value into the stored ink (not measured, unchanged here): White inks it. + s.execute("edit.fill", json!({"contents": "white"})).unwrap(); + let (red, blue) = (tones(&s, RED), tones(&s, BLUE)); + assert_ne!(red[0], 255, "the targeted channel did not change"); + assert_eq!((&red[1..], &blue[1..]), (&[0, 0][..], &[0, 255][..]), "the other channels changed"); +} + +#[test] +fn deeper_multichannel_refuses_without_changing_anything() { + for depth in [16, 32] { + let mut s = session(depth); + let before = (tones(&s, RED), tones(&s, BLUE), s.active().unwrap().history.past_len()); + assert!(s.execute("edit.fill", json!({"contents": "black"})).is_err(), "{depth}-bit"); + assert_eq!((tones(&s, RED), tones(&s, BLUE), s.active().unwrap().history.past_len()), before, "{depth}-bit"); + } +} + +#[test] +fn history_and_content_aware_refuse_without_changing_anything() { + let mut s = session(8); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + let before = (tones(&s, RED), tones(&s, BLUE), s.active().unwrap().history.past_len()); + for contents in ["history", "contentAware"] { + let err = s.execute("edit.fill", json!({"contents": contents})).unwrap_err().to_string(); + assert!(err.contains("Multichannel"), "{contents}: {err}"); + assert_eq!((tones(&s, RED), tones(&s, BLUE), s.active().unwrap().history.past_len()), before, "{contents}"); + } +} + +#[test] +fn non_normal_modes_blend_over_the_tone_across_tiles() { + // Wider than a tile, so the other modes' tile-by-tile tone pass meets a tile border. + let w = TILE_SIZE * 2 + 40; + let mut s = crate::session(); + s.execute("file.new", json!({"width": w, "height": 16, "mode": "rgb", "depth": 8, "background": "white"})).unwrap(); + s.execute("image.mode.multichannel", json!({})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 0, "width": w - 20, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"contents": "gray", "mode": "multiply"})).unwrap(); + let st = s.active().unwrap(); + for x in [5, 20, TILE_SIZE - 1, TILE_SIZE, w - 15, w - 5] { + let inside = (10..w - 10).contains(&x); + for c in st.doc.channels.iter().filter(|c| c.spot.is_some()) { + let tone = ((1.0 - c.surface.read_region(Rect::new(x, 8, x + 1, 9))[0]) * 255.0).round() as i32; + let want = if inside { 128 } else { 255 }; + assert!((tone - want).abs() <= 1, "x {x}: tone {tone}, want {want}"); + } + } +} diff --git a/crates/engine-paint/src/cmd/table/paint/edit_menu.rs b/crates/engine-paint/src/cmd/table/paint/edit_menu.rs index 2659b54567..23ce5b7df7 100644 --- a/crates/engine-paint/src/cmd/table/paint/edit_menu.rs +++ b/crates/engine-paint/src/cmd/table/paint/edit_menu.rs @@ -1,4 +1,4 @@ -use crate::commands::{CommandSpec, has_pixel_or_channel}; +use crate::commands::CommandSpec; /// Edit menu: Fill. pub fn specs() -> Vec { @@ -8,7 +8,7 @@ pub fn specs() -> Vec { ["Edit"], Some("Shift+F5"), r##"{"contents":"foreground|background|color|contentAware|pattern|history|black|gray|white"="color","color":"#rrggbb|[r,g,b,a]"=foreground (contents=color),"colorCmyk":[c,m,y,k]? (native inks 0..1 for contents=color),"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"state":row?,"snapshot":id? (contents=history: a History panel row as history.setSource, redo rows last, or a snapshot; default the History Brush source),"colorAdaptation":bool=true,"scaleAdaptation":bool=false,"mirror":bool=false,"rotationAdaptation":bool=false (contents=contentAware: enable quarter-turn source candidates within the sampling budget),"mode":"normal|multiply|…"="normal","opacity":0..100=100,"preserveTransparency":bool=false,"target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}?}"##, - has_pixel_or_channel, + crate::fill_cmds::enabled, crate::fill_cmds::fill )] } 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..6eb091b61d --- /dev/null +++ b/crates/engine-paint/src/fill_script_cross_weave_tests.rs @@ -0,0 +1,277 @@ +//! #17429: the Cross Weave script of Edit › Fill › Pattern weaves the pattern tile in a basket weave. With a 40 x 30 +//! tile the cells are 35 px: flat and upright tiles alternate like a checkerboard (the origin cell upright) and leave a +//! transparent 5 x 5 hole at every grid point (x, y = 0, 35, 70, ...). Each tile is turned half way or not at random. + +use serde_json::{Value, json}; + +use crate::Session; + +const RED: [u8; 3] = [255, 0, 0]; +const BLUE: [u8; 3] = [0, 0, 255]; +const GREEN: [u8; 3] = [0, 255, 0]; + +/// The probe tile: 40 x 30, left half red, right half blue, the bottom-right 20 x 15 quarter green. +fn define_probe(s: &mut Session, mode: &str, depth: u32) { + s.execute("file.new", json!({"width": 40, "height": 30, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + for (rect, color) in [([0, 0, 20, 30], "#ff0000"), ([20, 0, 20, 15], "#0000ff"), ([20, 15, 20, 15], "#00ff00")] { + s.execute("select.rect", json!({"x": rect[0], "y": rect[1], "width": rect[2], "height": rect[3]})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap(); + } + s.execute("edit.definePattern", json!({"name": "probe", "rect": [0, 0, 40, 30]})).unwrap(); +} + +/// A 600 x 400 white document of `mode` / `depth` with an empty pixel layer on top (active), the probe defined. +fn session_in(mode: &str, depth: u32) -> Session { + let mut s = crate::session(); + define_probe(&mut s, mode, depth); + s.execute("file.new", json!({"width": 600, "height": 400, "mode": mode, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s +} + +fn session() -> Session { + session_in("rgb", 8) +} + +/// Cross Weave with both randomness values at 0 and `extra` values on top. +fn weave(extra: Value) -> Value { + let mut p = json!({"contents": "pattern", "pattern": "probe", "script": "crossWeave", "colorRandomness": 0, "brightnessRandomness": 0}); + for (k, v) in extra.as_object().into_iter().flatten() { + p[k] = v.clone(); + } + p +} + +fn pixel(s: &Session, x: i32, y: i32) -> [f32; 4] { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn rgb8(px: [f32; 4]) -> [u8; 3] { + [0, 1, 2].map(|c| (px[c] * 255.0).round() as u8) +} + +fn undo_label(s: &Session) -> Option { + s.active().unwrap().history.undo_label().map(str::to_string) +} + +/// Whether the tile in the `w` x `h` box at (`x0`, `y0`) is red over half of its long side, split across the long side: +/// a flat tile is red in its left or right half, an upright one in its top or bottom half. +fn red_half(s: &Session, x0: i32, y0: i32, w: i32, h: i32) -> Option<&'static str> { + let red = |x: i32, y: i32| rgb8(pixel(s, x, y)) == RED; + let all = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| red(x, y))); + let none = |xs: std::ops::Range, ys: std::ops::Range| xs.clone().all(|x| ys.clone().all(|y| !red(x, y))); + let (a, b) = + if w > h { ((x0..x0 + w / 2, y0..y0 + h), (x0 + w / 2..x0 + w, y0..y0 + h)) } else { ((x0..x0 + w, y0..y0 + h / 2), (x0..x0 + w, y0 + h / 2..y0 + h)) }; + if all(a.0.clone(), a.1.clone()) && none(b.0.clone(), b.1.clone()) { + Some("first") + } else if none(a.0, a.1) && all(b.0, b.1) { + Some("second") + } else { + None + } +} + +#[test] +fn cross_weave_leaves_a_transparent_hole_at_every_grid_point() { + let mut s = session(); + let r = s.execute("edit.fill", weave(json!({}))).unwrap(); + assert_eq!(r["script"], "crossWeave"); + for gy in (0..400).step_by(35) { + for gx in (0..600).step_by(35) { + // The 5 x 5 hole itself, and painted pixels right after it on both sides. + for (dx, dy) in [(0, 0), (4, 0), (0, 4), (4, 4), (2, 2)] { + if gx + dx < 600 && gy + dy < 400 { + assert_eq!(pixel(&s, gx + dx, gy + dy)[3], 0.0, "hole at ({}, {})", gx + dx, gy + dy); + } + } + for (x, y) in [(gx + 5, gy + 2), (gx + 2, gy + 5)] { + if x < 600 && y < 400 { + assert!(pixel(&s, x, y)[3] > 0.99, "painted beside the hole at ({x}, {y})"); + } + } + } + } + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "the measured hole sample"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); +} + +#[test] +fn flat_and_upright_tiles_alternate_like_a_checkerboard() { + let mut s = session(); + s.execute("edit.fill", weave(json!({}))).unwrap(); + let (mut turned, mut upright_turned) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for row in 0..10 { + for col in 0..16 { + let (x, y) = (35 * col, 35 * row); + let (upright, side) = if (row + col) % 2 == 0 { + // Upright, 30 x 40: from 5 px right of the cell corner, down into the next cell. + (true, red_half(&s, x + 5, y, 30, 40)) + } else { + // Flat, 40 x 30: from the cell corner, 5 px below it, into the next cell. + (false, red_half(&s, x, y + 5, 40, 30)) + }; + let side = side.unwrap_or_else(|| panic!("cell ({row}, {col}) holds a whole {} tile", if upright { "upright" } else { "flat" })); + if upright { &mut upright_turned } else { &mut turned }.insert(side); + } + } + // Both ways round occur among flat and among upright tiles (the half turn is random per tile). + assert_eq!(turned.len(), 2, "flat tiles at 0° and 180°"); + assert_eq!(upright_turned.len(), 2, "upright tiles at 90° both ways"); + // The other colours sit in the tile's other half: blue and green in the origin cell's upright tile. + let other: Vec<[u8; 3]> = [(10, 2), (30, 2), (10, 37), (30, 37)].iter().map(|&(x, y)| rgb8(pixel(&s, x, y))).collect(); + assert!(other.contains(&BLUE) && other.contains(&GREEN), "{other:?}"); +} + +#[test] +fn the_weave_differs_from_the_plain_and_the_brick_fill() { + let mut plain = session(); + plain.execute("edit.fill", json!({"contents": "pattern", "pattern": "probe"})).unwrap(); + let mut brick = session(); + brick.execute("edit.fill", weave(json!({"script": "brickFill"}))).unwrap(); + let mut woven = session(); + woven.execute("edit.fill", weave(json!({}))).unwrap(); + for other in [&plain, &brick] { + assert!(pixel(other, 2, 2)[3] > 0.99, "the other fills cover the origin"); + } + assert_eq!(pixel(&woven, 2, 2)[3], 0.0, "the weave leaves its hole there"); +} + +#[test] +fn the_same_seed_weaves_the_same_tiles() { + let mut a = session(); + a.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut b = session(); + b.execute("edit.fill", weave(json!({"seed": 7}))).unwrap(); + let mut c = session(); + c.execute("edit.fill", weave(json!({"seed": 8}))).unwrap(); + let samples = |s: &Session| (0..10).flat_map(|r| (0..16).map(move |c| (35 * c + 15, 35 * r + 20))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + assert_eq!(samples(&a), samples(&b)); + assert_ne!(samples(&a), samples(&c), "another seed turns other tiles"); +} + +#[test] +fn spacing_and_scale_move_the_tiles() { + // Spacing 10 leaves a 10 px gap between the origin cell's upright tile (x 5-34) and the flat one beside it. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": 10}))).unwrap(); + assert!(pixel(&s, 34, 20)[3] > 0.99, "the upright tile"); + assert_eq!(pixel(&s, 40, 20)[3], 0.0, "the gap"); + assert!(pixel(&s, 45, 20)[3] > 0.99, "the flat tile after the gap"); + // Half the scale halves the tile and the cell: 2.5 px holes on a 17.5 px grid, so (35, 35) is still a hole. + let mut s = session(); + s.execute("edit.fill", weave(json!({"patternScale": 0.5}))).unwrap(); + assert_eq!(pixel(&s, 35, 35)[3], 0.0); + assert!(pixel(&s, 38, 3)[3] > 0.99, "a full-size weave has a hole here, the half-size one a tile"); + // Overlapping tiles close the holes. + let mut s = session(); + s.execute("edit.fill", weave(json!({"spacing": -10}))).unwrap(); + for (x, y) in [(2, 2), (37, 37), (72, 37)] { + assert!(pixel(&s, x, y)[3] > 0.99, "no hole at ({x}, {y})"); + } +} + +#[test] +fn randomness_varies_tiles_only_above_zero() { + let mut drift = session(); + drift.execute("edit.fill", weave(json!({"colorRandomness": 0.5, "brightnessRandomness": 0.5}))).unwrap(); + let mut exact = session(); + exact.execute("edit.fill", weave(json!({}))).unwrap(); + let colours = + |s: &Session| (0..400).step_by(7).flat_map(|y| (0..600).step_by(7).map(move |x| (x, y))).map(|(x, y)| rgb8(pixel(s, x, y))).collect::>(); + let pure = [RED, BLUE, GREEN, [0, 0, 0]]; + assert!(colours(&exact).iter().all(|c| pure.contains(c)), "at 0 every tile keeps the pattern's colours"); + assert!(colours(&drift).iter().any(|c| !pure.contains(c)), "above 0 the tiles drift"); +} + +#[test] +fn the_fill_stays_in_the_selection_with_mode_and_opacity() { + let mut s = session(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap(); + s.execute("edit.fill", weave(json!({"opacity": 50}))).unwrap(); + let inside = pixel(&s, 10, 10); + assert!((inside[3] - 0.5).abs() < 0.01, "half opacity: {inside:?}"); + assert_eq!(pixel(&s, 150, 10)[3], 0.0, "outside the selection"); + assert_eq!(pixel(&s, 10, 80)[3], 0.0, "below the selection"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill")); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "one history state"); + // Multiply over red paint keeps red only where the weave is red or transparent. + let mut s = session(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.fill", weave(json!({"mode": "multiply"}))).unwrap(); + assert_eq!(rgb8(pixel(&s, 2, 2)), RED, "the hole leaves the red paint"); + let blue_or_green = (0..600).step_by(5).any(|x| rgb8(pixel(&s, x, 10)) == [0, 0, 0]); + assert!(blue_or_green, "multiplying red by blue or green gives black"); +} + +#[test] +fn bad_values_are_errors_and_extreme_ones_never_hang_or_panic() { + let mut s = session(); + for bad in [json!({"patternScale": "big"}), json!({"spacing": [1]}), json!({"seed": -1}), json!({"colorRandomness": true})] { + assert!(s.execute("edit.fill", weave(bad.clone())).is_err(), "{bad}"); + } + assert_eq!(pixel(&s, 10, 10)[3], 0.0, "nothing filled"); + for extreme in [ + json!({"patternScale": 1e9}), + json!({"patternScale": -5}), + json!({"spacing": -1e12}), + json!({"spacing": 1e12}), + json!({"colorRandomness": 1e9, "brightnessRandomness": -1e9}), + json!({"seed": u64::MAX}), + // Offset and angle belong to Brick Fill; Cross Weave ignores them. + json!({"offsetBetweenRows": 75, "patternRotateAngle": 45}), + ] { + let mut s = session(); + s.execute("edit.fill", weave(extreme.clone())).unwrap_or_else(|e| panic!("{extreme}: {e}")); + } +} + +#[test] +fn a_long_thin_tile_reaches_far_from_its_centre() { + // A 4000 x 4 tile at the largest overlap: 2000 px cells, each tile reaching 2000 px from its centre. The flat tile + // of cell (-1, 0) lies along the top edge, the upright one of cell (-1, -1) along the left edge. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 4000, "height": 4, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "bar", "rect": [0, 0, 4000, 4]})).unwrap(); + s.execute("file.new", json!({"width": 300, "height": 200, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("edit.fill", weave(json!({"pattern": "bar", "spacing": -2}))).unwrap(); + for (x, y) in [(150, 1), (299, 0), (1, 100), (0, 199)] { + let px = pixel(&s, x, y); + assert!(px[3] > 0.99 && rgb8(px) == RED, "({x}, {y}): {px:?}"); + } + assert_eq!(pixel(&s, 150, 100)[3], 0.0, "between the tiles"); +} + +#[test] +fn cross_weave_runs_in_every_mode_and_depth() { + for (mode, depth) in [("rgb", 8), ("rgb", 16), ("rgb", 32), ("cmyk", 8), ("lab", 8), ("gray", 8), ("gray", 16)] { + let mut s = session_in(mode, depth); + s.execute("edit.fill", weave(json!({}))).unwrap_or_else(|e| panic!("{mode}/{depth}: {e}")); + assert_eq!(pixel(&s, 37, 37)[3], 0.0, "{mode}/{depth}: hole"); + assert!(pixel(&s, 20, 20)[3] > 0.99, "{mode}/{depth}: painted"); + assert_eq!(undo_label(&s).as_deref(), Some("Fill"), "{mode}/{depth}"); + } +} + +#[test] +fn tiles_clear_at_a_pixel_do_not_hide_the_ones_that_show_there() { + // A clear 100 x 100 tile with an opaque 10 x 10 middle, at the largest overlap (2 px between tiles): about 1100 + // tiles in front are clear at (0, 0) before the ones whose middle covers it. + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap(); + s.execute("select.rect", json!({"x": 45, "y": 45, "width": 10, "height": 10})).unwrap(); + s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap(); + s.execute("edit.definePattern", json!({"name": "dot", "rect": [0, 0, 100, 100]})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + // Brick Fill lays its tiles out the same way and must find them too. + for script in ["crossWeave", "brickFill"] { + s.execute("edit.fill", weave(json!({"script": script, "pattern": "dot", "spacing": -98}))).unwrap(); + let px = pixel(&s, 0, 0); + assert!(px[3] > 0.99 && rgb8(px) == RED, "{script}: {px:?}"); + s.execute("edit.undo", json!({})).unwrap(); + } +} diff --git a/crates/engine-paint/src/lib.rs b/crates/engine-paint/src/lib.rs index e5e5aabdc6..e28d4a6075 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/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index 91435bea1a..b0708f25d5 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -61,9 +61,10 @@ fn run_guarded(id: &str, p: &Value) -> Result<(), String> { } } -#[test] -#[ignore = "slow full-registry fuzz; run with --ignored"] -fn no_command_panics_or_hangs_on_adversarial_params() { +const SHARDS: usize = 8; + +fn run_panic_hunt_shard(shard: usize) { + assert!(shard < SHARDS); let params: Vec = vec![ json!({}), json!({"x": -9, "y": -9, "radius": 0, "amount": 0, "angle": 0, "opacity": 0, "scale": 0, "levels": 0, "tolerance": 0, "gamma": 0, "layer": 999999, "channel": 999, "index": 999999, "count": 0}), @@ -76,7 +77,10 @@ fn no_command_panics_or_hangs_on_adversarial_params() { json!({"subtractPoints": "none", "order": ["-"], "labMinimum": [0, 0, 0], "labMaximum": [100, 0, 0]}), ]; let mut bad: Vec = Vec::new(); - for spec in command_specs() { + for (idx, spec) in command_specs().iter().enumerate() { + if idx % SHARDS != shard { + continue; + } for p in ¶ms { // Print and Print One Copy reach real printers (lp, or the Windows driver): fuzz them // as dry runs so the hunt never prints a page. @@ -93,9 +97,28 @@ fn no_command_panics_or_hangs_on_adversarial_params() { } } } - assert!(bad.is_empty(), "{} commands panicked:\n{}", bad.len(), bad.join("\n")); + assert!(bad.is_empty(), "shard {shard}: {} commands panicked:\n{}", bad.len(), bad.join("\n")); } +macro_rules! panic_hunt_shard { + ($name:ident, $shard:expr) => { + #[test] + #[ignore = "slow full-registry fuzz; run with --ignored"] + fn $name() { + run_panic_hunt_shard($shard); + } + }; +} + +panic_hunt_shard!(panic_hunt_shard_0, 0); +panic_hunt_shard!(panic_hunt_shard_1, 1); +panic_hunt_shard!(panic_hunt_shard_2, 2); +panic_hunt_shard!(panic_hunt_shard_3, 3); +panic_hunt_shard!(panic_hunt_shard_4, 4); +panic_hunt_shard!(panic_hunt_shard_5, 5); +panic_hunt_shard!(panic_hunt_shard_6, 6); +panic_hunt_shard!(panic_hunt_shard_7, 7); + /// #4982: a panic the code under test contains still fails the run; a graceful `Err` does not. #[test] fn contained_panics_count_and_graceful_errors_do_not() { diff --git a/crates/ui-egui/src/app/framework.rs b/crates/ui-egui/src/app/framework.rs index 9c58f81255..65b2763f99 100644 --- a/crates/ui-egui/src/app/framework.rs +++ b/crates/ui-egui/src/app/framework.rs @@ -271,7 +271,8 @@ fn defaults() -> AppDefaults { } } -/// PhotoCraft's size overrides: Photoshop's panel dock width, and 12-point Label and Mono text in the compact density. +/// PhotoCraft's size overrides: Photoshop's panel dock width, a roomier dialog margin (twice the panel padding, so +/// short questions such as "Unsaved changes" do not look cramped), and 12-point Label and Mono text in the compact density. const SIZES: &[u8] = include_bytes!("sizes.json"); /// The size overrides, parsed once: the root keeps one `Arc` so the runtime's token and hit-size caches, which key on diff --git a/crates/ui-egui/src/app/sizes.json b/crates/ui-egui/src/app/sizes.json index 5727ea93d8..afa5f5a7fa 100644 --- a/crates/ui-egui/src/app/sizes.json +++ b/crates/ui-egui/src/app/sizes.json @@ -1 +1 @@ -{ "all": { "size.dock.column": 290 }, "compact": { "typography.label.size": 12, "typography.mono.size": 12 } } +{ "all": { "size.dock.column": 290 }, "compact": { "space.pad.dialog": 16, "typography.label.size": 12, "typography.mono.size": 12 }, "comfortable": { "space.pad.dialog": 24 } } diff --git a/crates/ui-egui/src/brush_picker_range_alert_tests.rs b/crates/ui-egui/src/brush_picker_range_alert_tests.rs new file mode 100644 index 0000000000..981358c5c0 --- /dev/null +++ b/crates/ui-egui/src/brush_picker_range_alert_tests.rs @@ -0,0 +1,96 @@ +//! #11817: a Size or Hardness typed past its range in the Brush Preset picker takes the closest value and opens the +//! range alert; the picker stays open under it and after OK. A value in range (a typed fraction cut off) and a slider +//! press open none. + +use crate::app::framework::BuildApp as _; +use egui::{Event, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +fn harness() -> Harness<'static, Box> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("tools.setBrush", json!({"brush": {"size": 20, "hardness": 0.5}})).unwrap(); + app.ui.tool = Tool::Brush; + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).with_step_dt(1.0 / 60.0).with_context(app.ctx().clone()).build_app( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // The canvas shows the picker itself (`canvas_tool_menu::run`). + egui::CentralPanel::default().show(ui, |ui| crate::canvas::testing::document_area(app, ui)); + crate::dialogs::run(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::AppTheme::pro()); + h.run_steps(4); + let c = h.state().last_canvas_rect.center(); + crate::brush_picker::open(h.state_mut(), [c.x, c.y]); + h.run_steps(3); + h +} + +/// Type `text` into the picker's `n`th spin field (0 Size, 1 Hardness), then Tab. +fn type_into(h: &mut Harness<'static, Box>, n: usize, text: &str) { + h.get_all_by_role(egui::accesskit::Role::SpinButton).nth(n).expect("the field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, Box>) -> usize { + h.state().framework.dialogs.open_dialogs().len() +} + +fn size_and_hardness(h: &Harness<'static, Box>) -> (f32, f32) { + let b = &h.state().session.tools.brush; + (b.size, b.hardness) +} + +#[test] +fn size_and_hardness_typed_out_of_range_alert_and_the_picker_stays_open() { + for (n, typed, want) in [(0, "9999", (5000.0, 0.5)), (0, "0", (1.0, 0.5)), (1, "150", (20.0, 1.0))] { + let mut h = harness(); + type_into(&mut h, n, typed); + assert_eq!(size_and_hardness(&h), want, "{typed}: the closest value"); + assert_eq!(alerts(&h), 1, "{typed}: one range alert"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open under the alert"); + h.get_by_label("OK").click(); + h.run_steps(4); + assert_eq!(alerts(&h), 0, "{typed}: OK closes the alert"); + assert_eq!(size_and_hardness(&h), want, "{typed}: OK keeps the closest value"); + assert!(h.state().ui.brush_picker.is_some(), "{typed}: the picker stays open after OK"); + } +} + +#[test] +fn a_value_in_range_and_a_slider_press_open_no_alert() { + let mut h = harness(); + type_into(&mut h, 0, "2.5"); + assert_eq!(size_and_hardness(&h).0, 2.0, "a typed fraction is cut off, not rounded"); + type_into(&mut h, 0, "40"); + assert_eq!(size_and_hardness(&h).0, 40.0); + let slider = h + .get_all_by_role(egui::accesskit::Role::Slider) + .find(|n| n.accesskit_node().label().as_deref() == Some("Hardness")) + .expect("the Hardness slider") + .rect(); + let at = slider.left_center() + vec2(slider.width() * 0.8, 0.0); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(size_and_hardness(&h).1 > 0.5, "the press moved Hardness"); + assert_eq!(alerts(&h), 0, "nothing was typed out of range"); +} diff --git a/crates/ui-egui/src/canvas/tools/move_tool.rs b/crates/ui-egui/src/canvas/tools/move_tool.rs index 6c49cb207c..4c53eba55d 100644 --- a/crates/ui-egui/src/canvas/tools/move_tool.rs +++ b/crates/ui-egui/src/canvas/tools/move_tool.rs @@ -353,7 +353,10 @@ impl CanvasTool for MoveRun<'_> { let at = space.view.to_doc(pointer.pos); match run.kind { Kind::Marquee => { - self.scope.with_app(|app| crate::move_box::drag_to(app, [at.x, at.y])); + self.scope.with_app(|app| { + crate::move_box::drag_to(app, [at.x, at.y]); + crate::move_box::readout(app, cx); + }); } Kind::Refused => { if !std::mem::replace(&mut run.prompted, true) { diff --git a/crates/ui-egui/src/dialogs/fill_quick_mask_greyed_tests.rs b/crates/ui-egui/src/dialogs/fill_quick_mask_greyed_tests.rs new file mode 100644 index 0000000000..72a9746407 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fill_quick_mask_greyed_tests.rs @@ -0,0 +1,120 @@ +//! #17488: in Quick Mask the Fill dialog greys what doesn't work on the channel: the fill from surroundings and History +//! in Contents, Preserve Transparency (off), and Darker Color, Lighter Color, Hue, Saturation, Color and Luminosity in +//! Mode. A remembered choice that is greyed opens on an enabled one and stays remembered; out of Quick Mask the dialog +//! is as before. + +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use photocraft_color::BlendMode; +use serde_json::json; + +use super::*; +use crate::smart_filter_dialog::tests::{cancel, confirm, set}; + +/// A white 40×30 RGB document with a pixel layer "Paint" active and a selection. +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(); + app +} + +fn quick_mask_on(app: &mut PhotocraftApp, on: bool) { + app.run("select.editInQuickMaskMode", json!({"on": on})).unwrap(); +} + +fn row(app: &PhotocraftApp, key: &str) -> Param { + rows(app, [0.0; 3], None, None).into_iter().find(|r| r.key == key).unwrap_or_else(|| panic!("a {key} row")) +} + +/// A field of the open dialog `id`, and whether it takes `value`. +fn field(app: &mut PhotocraftApp, id: DialogId, key: &str) -> serde_json::Value { + let dialog = app.framework.dialogs.get_by_id::(id).expect("a hosted dialog"); + let fields = dialog.fields(); + fields.text(key).map(|t| json!(t)).or_else(|| fields.bool(key).map(|b| json!(b))).unwrap_or(serde_json::Value::Null) +} + +fn takes(app: &mut PhotocraftApp, id: DialogId, key: &str, value: serde_json::Value) -> bool { + let ctx = app.ctx().clone(); + app.framework.dialogs.set_json_field(&ctx, id, key, value).is_ok() +} + +const CHANNEL_GREYED: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +#[test] +fn quick_mask_greys_contents_mode_and_preserve_transparency() { + let mut app = app(); + quick_mask_on(&mut app, true); + let contents = row(&app, "contents"); + for (key, _) in CONTENTS { + assert_eq!(contents.option_enabled(key), !matches!(key, "contentAware" | "history"), "Contents {key}"); + } + let mode = row(&app, "mode"); + for m in BlendMode::LAYER_MODES { + assert_eq!(mode.option_enabled(m.key()), !CHANNEL_GREYED.contains(&m), "Mode {}", m.label()); + } + assert!(!mode.option_enabled("behind") && !mode.option_enabled("clear"), "Behind and Clear greyed once listed"); + + let id = open(&mut app); + assert_eq!(field(&mut app, id, "preserveTransparency"), json!(false), "Preserve Transparency unchecked"); + assert!(!takes(&mut app, id, "preserveTransparency", json!(true)), "Preserve Transparency greyed"); + assert!(!takes(&mut app, id, "mode", json!("hue")), "Hue greyed"); + assert!(!takes(&mut app, id, "contents", json!("history")), "History greyed"); + assert!(takes(&mut app, id, "mode", json!("multiply")), "Multiply enabled"); + assert!(takes(&mut app, id, "contents", json!("pattern")), "Pattern enabled"); + cancel(&mut app, id); +} + +#[test] +fn greyed_remembered_choices_open_enabled_and_stay_remembered() { + let mut app = app(); + let id = open(&mut app); + set(&mut app, id, "mode", json!("hue")); + set(&mut app, id, "preserveTransparency", json!(true)); + set(&mut app, id, "contents", json!("black")); + confirm(&mut app, id); + + quick_mask_on(&mut app, true); + let id = open(&mut app); + assert_eq!(field(&mut app, id, "mode"), json!("normal"), "a greyed remembered Mode opens on Normal"); + assert_eq!(field(&mut app, id, "preserveTransparency"), json!(false), "and Preserve Transparency unchecked"); + set(&mut app, id, "contents", json!("white")); + confirm(&mut app, id); + quick_mask_on(&mut app, false); + + let id = open(&mut app); + assert_eq!(field(&mut app, id, "mode"), json!("hue"), "the remembered Mode is kept"); + assert_eq!(field(&mut app, id, "preserveTransparency"), json!(true), "the remembered Preserve Transparency is kept"); + cancel(&mut app, id); +} + +#[test] +fn a_remembered_mode_the_document_greys_in_quick_mask_stays_remembered() { + let mut app = app(); + let id = open(&mut app); + set(&mut app, id, "mode", json!("overlay")); + confirm(&mut app, id); + + // RGB 32 bit greys Overlay by its depth, not by the channel. + app.run("file.new", json!({"width": 40, "height": 30, "background": "white", "depth": 32})).unwrap(); + app.run("select.rect", json!({"x": 5, "y": 5, "width": 20, "height": 15})).unwrap(); + quick_mask_on(&mut app, true); + let id = open(&mut app); + assert_eq!(field(&mut app, id, "mode"), json!("normal"), "a greyed remembered Mode opens on Normal"); + set(&mut app, id, "contents", json!("white")); + confirm(&mut app, id); + let ctx = app.ctx().clone(); + assert_eq!(remembered_mode(&ctx, COMMAND).as_deref(), Some("overlay"), "OK in Quick Mask keeps the remembered Mode"); +} + +#[test] +fn out_of_quick_mask_the_dialog_is_unchanged() { + let app = app(); + let contents = row(&app, "contents"); + assert!(CONTENTS.iter().all(|(key, _)| contents.option_enabled(key)), "every Contents entry enabled with a selection"); + let mode = row(&app, "mode"); + assert!(BlendMode::LAYER_MODES.iter().all(|m| mode.option_enabled(m.key())), "every Mode enabled in RGB 8 bit"); + let pt = row(&app, "preserveTransparency"); + assert!(matches!(pt.kind, ParamKind::Bool { .. })); +} 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); +} diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 52907da103..40bd2ef4c6 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -8,7 +8,7 @@ use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult}; use craft::ui::runtime::env::Label; -use craft::ui::runtime::memory::{MemoryStage, SaveKey, set_saved_value}; +use craft::ui::runtime::memory::{MemoryStage, SaveKey, saved_value, set_saved_value}; use photocraft_color::BlendMode; use serde_json::{Value, json}; @@ -57,19 +57,42 @@ pub(crate) fn hex(c: [f32; 3]) -> String { format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2])) } +/// The blend modes Fill greys on the Quick Mask channel (#17488): the colour-only modes, which a channel can't take, +/// and Behind and Clear. +const QUICK_MASK_GREYED_MODES: [BlendMode; 6] = + [BlendMode::DarkerColor, BlendMode::LighterColor, BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity]; + +/// The target Fill edits: a layer mask or channel the panels target, else the paint target. +fn fill_target(app: &PhotocraftApp) -> Value { + let target = app.with_mask_target(COMMAND, json!({})); + target.get("target").cloned().unwrap_or_else(|| crate::canvas::paint_target(app)) +} + +/// Whether Fill opens on the Quick Mask channel. +fn quick_mask(app: &PhotocraftApp) -> bool { + fill_target(app).as_str() == Some("quickMask") +} + +/// The keys of the Mode entries greyed on the Quick Mask channel. +fn quick_mask_greyed_keys() -> impl Iterator { + QUICK_MASK_GREYED_MODES.iter().map(|m| m.key().to_string()).chain(["behind".to_string(), "clear".to_string()]) +} + /// The dialog's rows, with the Preserve Transparency the target forces. fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option, preserve: Option) -> Vec { + let quick_mask = quick_mask(app); let contents = CONTENTS.iter().map(|(k, l)| (k.to_string(), Label::from(tl!(l)))).collect(); let mut contents = Param::new("contents", tl!("Contents:"), ParamKind::choice(contents, Some(opening_contents(app).into()))); // Content-Aware fills a selection from around it: without one it is listed greyed, as in the reference (#17462). - // History is greyed whenever `edit.fill` would refuse its source, by the engine's own check (#17464). Indexed - // Color and Bitmap documents also grey the entries `edit.fill` refuses there (#17476). + // History is greyed whenever `edit.fill` would refuse its source, by the engine's own check (#17464). On the Quick + // Mask channel the fill from surroundings and History are greyed too (#17488). Indexed Color and Bitmap documents + // also grey the entries `edit.fill` refuses there (#17476). let st = app.session.active(); let mut greyed = st.map_or(&[][..], |st| photocraft_engine::fill_cmds::greyed_contents(st.doc.mode)).to_vec(); - if !has_selection(app) { + if quick_mask || !has_selection(app) { greyed.push("contentAware"); } - if st.is_none_or(|st| !photocraft_engine::history_source::fill_source_usable(st)) { + if quick_mask || st.is_none_or(|st| !photocraft_engine::history_source::fill_source_usable(st)) { greyed.push("history"); } greyed.sort_unstable(); @@ -91,6 +114,14 @@ fn rows(app: &PhotocraftApp, foreground: [f32; 3], first_pattern: Option Param::new("colorAdaptation", tl!("Color Adaptation"), ParamKind::bool(true)).visible_when("contents", "contentAware"), ]; rows.extend(blending_rows(app, preserve)); + if quick_mask { + // The modes the document greys stay greyed; the channel adds its own (#17488). + for row in rows.iter_mut().filter(|row| row.key == "mode") { + let greyed: Vec = + BlendMode::LAYER_MODES.iter().map(|m| m.key().to_string()).filter(|k| !row.option_enabled(k)).chain(quick_mask_greyed_keys()).collect(); + *row = row.clone().disabled_options(greyed); + } + } rows } @@ -113,11 +144,11 @@ fn defaults(foreground: [f32; 3], first_pattern: Option, inks: Option<[f /// Open Fill with the current editing target captured, so live UI changes cannot redirect confirmation. pub fn open(app: &mut PhotocraftApp) -> DialogId { - let target = app.with_mask_target(COMMAND, json!({})); - let target = target.get("target").cloned().unwrap_or_else(|| crate::canvas::paint_target(app)); + let target = fill_target(app); // Alpha and Quick Mask belong to the document, independently of its active layer. let layer_bound = target.as_str() != Some("quickMask") && target.get("channel").is_none(); - let preserve = forced_preserve_transparency(app, &target); + // Preserve Transparency has no meaning on the Quick Mask channel: greyed off there (#17488). + let preserve = if target.as_str() == Some("quickMask") { Some(false) } else { forced_preserve_transparency(app, &target) }; let mut held = json!({ "target": target }); if let Some(st) = app.session.active() { held["document"] = json!(st.doc.id.0); @@ -199,18 +230,25 @@ pub(crate) fn check(app: &mut PhotocraftApp, result: &ParamResult) -> Result<(), /// Fill with the confirmed choices; they are remembered only when the fill succeeded. pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) { let captured = captured(app, &result.key); + // The Mode entries the dialog greyed on the Quick Mask channel: the channel's and the document's. + let greyed: Vec = if captured.get("target").and_then(Value::as_str) == Some("quickMask") { + let document = app.session.active().map_or(&[][..], |st| photocraft_engine::fill_cmds::greyed_modes(st.doc.mode, st.doc.depth)); + quick_mask_greyed_keys().chain(document.iter().map(|m| m.key().to_string())).collect() + } else { + Vec::new() + }; let p = params(&result.fields, &captured); // With Script on, OK opens the script's dialog, whose OK fills; Cancel there fills nothing. The choice of script is // remembered either way, as the reference application reopens on the last script. if let Some(script) = p.get("script").and_then(Value::as_str).map(str::to_owned) { - remember_blending(ctx, &result); + remember_choices(ctx, &result, &greyed); if super::fill_script_ui::open(app, &script, p.clone(), &captured).is_some() { return; } } match app.run(COMMAND, p) { Ok(_) => { - remember_blending(ctx, &result); + remember_choices(ctx, &result, &greyed); // The framework remembers visible parameter rows only; keep their ink companion in the same saved tier. let mut inks = DialogFields::new(); if let Some(value) = result.fields.get(&crate::color_picker_ui::ink_field("color")) { @@ -226,12 +264,40 @@ pub(crate) fn run(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamRes } } +/// Remembers the choices of `result`. A Mode remembered before that the Quick Mask dialog `greyed` is kept for the +/// next fill elsewhere (#17488). +fn remember_choices(ctx: &egui::Context, result: &ParamResult, greyed: &[String]) { + let kept_mode = (!greyed.is_empty()).then(|| remembered_mode(ctx, &result.key)).flatten(); + remember_blending(ctx, result); + if let Some(mode) = kept_mode.filter(|mode| greyed.contains(mode)) { + keep_mode(ctx, &result.key, mode); + } +} + +/// The Mode the dialog `key` remembers. +fn remembered_mode(ctx: &egui::Context, key: &str) -> Option { + let saved = saved_value::>(ctx, &SaveKey::named(super::params::memory_scope(key)))?; + saved.text("mode").map(str::to_owned) +} + +/// Puts `mode` back as the Mode the dialog `key` remembers. +fn keep_mode(ctx: &egui::Context, key: &str, mode: String) { + let save = SaveKey::named(super::params::memory_scope(key)); + if let Some(mut saved) = saved_value::>(ctx, &save) { + saved.set("mode", mode); + set_saved_value(ctx, &save, Some(saved)); + } +} + #[cfg(test)] mod content_aware_greyed_tests; #[cfg(test)] #[path = "fill_history_greyed_tests.rs"] mod fill_history_greyed_tests; #[cfg(test)] +#[path = "fill_quick_mask_greyed_tests.rs"] +mod fill_quick_mask_greyed_tests; +#[cfg(test)] mod fill_threshold_mode_tests; #[cfg(test)] mod no_selection_fallback_tests; diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index de927bce10..10d1b57d61 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -242,7 +242,7 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Image"], "Trap…", None, "image.trap"), (&["Image"], "---", None, "---"), (&["Image", "Analysis"], "Set Measurement Scale…", None, "image.analysis.setMeasurementScale"), - (&["Image", "Analysis"], "Select Data Points…", None, "image.analysis.selectDataPoints"), + (&["Image", "Analysis", "Select Data Points"], "Custom…", None, "image.analysis.selectDataPoints"), (&["Image", "Analysis"], "---", None, "---"), (&["Image", "Analysis"], "Record Measurements", None, "image.analysis.recordMeasurements"), (&["Image", "Analysis"], "---", None, "---"), diff --git a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs index fc8e6b9e11..0aa7f6d6cc 100644 --- a/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs +++ b/crates/ui-egui/src/panels/art_history_bar_controls_tests.rs @@ -1,7 +1,8 @@ //! #12629: the Art History Brush's options bar has a Pressure for Opacity toggle right after //! Opacity, and an Angle field and a Pressure for Size toggle after Tolerance, with the reference -//! application's tooltips, off / 0° by default and after Reset Tool. They edit the tool's own -//! brush, not the History Brush's or the Brush's, and the bar has no Flow and no Airbrush. +//! application's tooltips. The toggles start off and keep their state after Reset Tool (#18335), +//! which restores the angle to 0°. The controls belong to the Art History Brush, and the bar has +//! no Flow or Airbrush. use egui::accesskit::Role; use egui::{Modifiers, Rect, vec2}; @@ -99,7 +100,7 @@ fn the_controls_carry_the_reference_tooltips() { } #[test] -fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { +fn reset_tool_restores_the_angle_and_keeps_pressure_toggles() { let mut h = bar(Tool::ArtHistoryBrush); assert_eq!(controls(h.state()), (false, 0.0, false)); assert!(angle_field(&h).and_then(|n| n.accesskit_node().numeric_value()) == Some(0.0), "the field shows 0°"); @@ -112,7 +113,7 @@ fn the_controls_are_off_and_0_by_default_and_after_reset_tool() { let ctx = h.ctx.clone(); crate::menus::invoke(h.state_mut(), &ctx, "tool.reset", json!({})).unwrap(); h.run_steps(3); - assert_eq!(controls(h.state()), (false, 0.0, false)); + assert_eq!(controls(h.state()), (true, 0.0, true)); } #[test] diff --git a/crates/ui-egui/src/panels/preset_panels/gradient_preset_classic_mode_tests.rs b/crates/ui-egui/src/panels/preset_panels/gradient_preset_classic_mode_tests.rs new file mode 100644 index 0000000000..e9b01687ec --- /dev/null +++ b/crates/ui-egui/src/panels/preset_panels/gradient_preset_classic_mode_tests.rs @@ -0,0 +1,114 @@ +//! #17494: a Gradient tool preset neither stores nor changes the Gradient / Classic gradient mode, as in the +//! reference application, and still restores the tool's other options. Reset Tool and Reset All Tools still +//! put the mode back to Gradient. + +use photocraft_engine::presets::PresetsExt; +use serde_json::{Value, json}; + +use super::{new_params, select}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Gradient; + app +} + +/// The + button's preset, made from the current Gradient tool options; its name and stored options. +fn save(app: &mut PhotocraftApp) -> (String, serde_json::Map) { + let name = app.run("tool.presets.new", new_params(app, Tool::Gradient)).unwrap()["name"].as_str().unwrap().to_string(); + let stored = app.session.presets().tool_presets.iter().find(|t| t.name == name).unwrap().options["toolOptions"].as_object().unwrap().clone(); + (name, stored) +} + +#[test] +fn a_new_gradient_preset_does_not_store_the_mode() { + for classic in [false, true] { + let mut app = app(); + app.ui.tool_options.gradient_classic = classic; + let (_, stored) = save(&mut app); + assert!(!stored.contains_key("gradient_classic"), "classic {classic}: {stored:?}"); + assert!(stored.contains_key("gradient_style"), "the tool's own options are still stored: {stored:?}"); + } +} + +/// Both ways: made in one mode, chosen in the other, the mode stays. +#[test] +fn choosing_a_gradient_preset_keeps_the_mode() { + for made_classic in [false, true] { + let mut app = app(); + app.ui.tool_options.gradient_classic = made_classic; + let (name, _) = save(&mut app); + app.ui.tool_options.gradient_classic = !made_classic; + select(&mut app, &name); + assert_eq!(app.ui.tool, Tool::Gradient); + assert_eq!(app.ui.tool_options.gradient_classic, !made_classic, "a preset made with classic {made_classic} changed the mode"); + } +} + +/// A preset saved by an older build still holds the key: choosing it leaves the mode alone too. +#[test] +fn an_older_preset_holding_the_mode_leaves_it_alone() { + for stored_classic in [false, true] { + let mut app = app(); + app.run( + "tool.presets.new", + json!({"name": "Old", "tool": "gradient", "options": {"toolOptions": {"gradient_classic": stored_classic, "gradient_style": "radial"}}}), + ) + .unwrap(); + app.ui.tool_options.gradient_classic = !stored_classic; + select(&mut app, "Old"); + assert_eq!(app.ui.tool_options.gradient_classic, !stored_classic, "an old preset with classic {stored_classic} changed the mode"); + assert_eq!(app.ui.tool_options.gradient_style, "radial", "its other options still apply"); + } +} + +#[test] +fn choosing_a_gradient_preset_restores_the_other_options() { + let mut app = app(); + let o = &mut app.ui.tool_options; + o.gradient_style = "radial".into(); + o.gradient_reverse = !o.gradient_reverse; + o.gradient_dither = !o.gradient_dither; + o.gradient_blend_mode = photocraft_color::BlendMode::Multiply; + o.fill_opacity = 50.0; + let made = (*app.ui.tool_options).clone(); + let (name, _) = save(&mut app); + + let o = &mut app.ui.tool_options; + o.gradient_style = "linear".into(); + o.gradient_reverse = !made.gradient_reverse; + o.gradient_dither = !made.gradient_dither; + o.gradient_blend_mode = photocraft_color::BlendMode::Normal; + o.fill_opacity = 100.0; + select(&mut app, &name); + let o = &app.ui.tool_options; + assert_eq!(o.gradient_style, made.gradient_style); + assert_eq!(o.gradient_reverse, made.gradient_reverse); + assert_eq!(o.gradient_dither, made.gradient_dither); + assert_eq!(o.gradient_blend_mode, made.gradient_blend_mode); + assert_eq!(o.fill_opacity, made.fill_opacity); +} + +/// Reset Tool with the Gradient tool and Reset All Tools still put the mode back to Gradient; Reset Tool on +/// another tool leaves it. +#[test] +fn reset_still_resets_the_mode() { + let mut app = app(); + let ctx = app.ctx().clone(); + app.ui.tool_options.gradient_classic = true; + app.ui.tool = Tool::Brush; + crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET, json!({})).unwrap(); + assert!(app.ui.tool_options.gradient_classic, "the Brush's Reset Tool is not the Gradient tool's"); + + app.ui.tool = Tool::Gradient; + crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET, json!({})).unwrap(); + assert!(!app.ui.tool_options.gradient_classic); + + app.ui.tool_options.gradient_classic = true; + crate::menus::invoke(&mut app, &ctx, crate::tool_reset::RESET_ALL, json!({"confirmed": true})).unwrap(); + assert!(!app.ui.tool_options.gradient_classic); +} diff --git a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs index 69a3b6bd85..aa97a057e4 100644 --- a/crates/ui-egui/src/panels/preset_panels/tool_presets.rs +++ b/crates/ui-egui/src/panels/preset_panels/tool_presets.rs @@ -6,6 +6,10 @@ use super::run; use crate::PhotocraftApp; use crate::state::Tool; +/// Options a tool preset neither stores nor applies, though Reset Tool resets them: the +/// Gradient / Classic gradient mode sits outside the reference application's tool presets (#17494). +const NOT_IN_PRESETS: &[&str] = &["gradient_classic"]; + /// Apply a tool preset: the engine sets the brush/colour, the shell switches tool and options. pub fn select(app: &mut PhotocraftApp, name: &str) { // PLAN: assumes `ToolOptions::crop` is `Clone + PartialEq` (tools-w45). @@ -27,7 +31,7 @@ pub fn select(app: &mut PhotocraftApp, name: &str) { crate::tool_memory::upgrade(&mut stored); let mut cur = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); if let (Some(c), Some(o)) = (cur.as_object_mut(), stored.as_object()) { - for (k, v) in o { + for (k, v) in o.iter().filter(|(k, _)| !NOT_IN_PRESETS.contains(&k.as_str())) { // An object option (`sample_all`, one per tool) takes only the entries the // preset stored, so the other tools' keep theirs (#5524). match (c.get_mut(k), v) { @@ -53,8 +57,11 @@ pub fn select(app: &mut PhotocraftApp, name: &str) { /// preset later leaves the other tools' settings alone. pub(crate) fn new_params(app: &PhotocraftApp, tool: Tool) -> Value { let all = serde_json::to_value(&app.ui.tool_options).unwrap_or_default(); - let mut own: serde_json::Map = - crate::tool_reset::option_keys(tool).iter().filter_map(|k| Some(((*k).to_string(), all.get(*k)?.clone()))).collect(); + let mut own: serde_json::Map = crate::tool_reset::option_keys(tool) + .iter() + .filter(|k| !NOT_IN_PRESETS.contains(k)) + .filter_map(|k| Some(((*k).to_string(), all.get(*k)?.clone()))) + .collect(); // Sample All Layers is each tool's own (#5524): store `tool`'s alone. if let Some(k) = crate::tool_reset::sample_all_key(tool) && let Some(v) = all.get("sample_all").and_then(|m| m.get(&k)) @@ -64,6 +71,10 @@ pub(crate) fn new_params(app: &PhotocraftApp, tool: Tool) -> Value { json!({"name": tool.label(), "tool": tool.id(), "options": {"toolOptions": own}}) } +#[cfg(test)] +#[path = "gradient_preset_classic_mode_tests.rs"] +mod gradient_preset_classic_mode_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs index 6f6c773b0f..5130800e16 100644 --- a/crates/ui-egui/src/panels/type_panels_ui/spelling.rs +++ b/crates/ui-egui/src/panels/type_panels_ui/spelling.rs @@ -303,3 +303,7 @@ mod tests { #[cfg(test)] #[path = "../type_spell_order_ui_tests.rs"] mod spell_order_ui_tests; + +#[cfg(test)] +#[path = "../type_spell_keys_tests.rs"] +mod spell_keys_tests; diff --git a/crates/ui-egui/src/panels/type_spell_keys_tests.rs b/crates/ui-egui/src/panels/type_spell_keys_tests.rs new file mode 100644 index 0000000000..6701c45382 --- /dev/null +++ b/crates/ui-egui/src/panels/type_spell_keys_tests.rs @@ -0,0 +1,82 @@ +//! #14179: Enter and Escape close the Check Spelling dialog like Done, keeping the changes made so +//! far; Enter in Change To does not change the word, and neither key reaches the canvas or the +//! window's keys (Escape there would deselect) while the dialog is open. + +use craft::text::ui::spelling::CheckSpellingDialog; +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +use super::*; + +type H = Harness<'static, Box>; + +/// The whole app with a type layer holding `text` and everything selected, the dialog opened +/// through the menu. +fn harness(text: &str) -> (H, u64) { + let mut h = Harness::builder().with_size(vec2(1600.0, 900.0)).with_step_dt(1.0 / 60.0).with_max_steps(64).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::Services::default()); + app.background_jobs = false; + app.run("file.new", json!({"width": 300, "height": 120, "background": "white"})).unwrap(); + app + }); + let layer = h.state_mut().run("type.create", json!({"x": 10, "y": 60, "text": text})).unwrap()["layer"].as_u64().unwrap(); + h.state_mut().run("select.all", json!({})).unwrap(); + h.run_steps(3); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.checkSpelling", json!({})).unwrap(); + h.run_steps(4); + assert!(open(&h), "Check Spelling is open"); + (h, layer) +} + +fn open(h: &H) -> bool { + h.state().framework.dialogs.is_open::() || h.state().ui.type_panels.spell.is_some() +} + +fn selected(h: &H) -> bool { + h.state().session.active().unwrap().doc.selection.is_some() +} + +#[test] +fn escape_runs_done_and_keeps_the_changes_made() { + let (mut h, layer) = harness("Teh cat. Wrold"); + // Change the first word the way the Change button does, and refresh the list. + let item = h.state().framework.dialogs.get::().unwrap().items()[0].clone(); + change(h.state_mut(), &item, "The"); + let items = relist(h.state_mut()); + h.state_mut().framework.dialogs.get_mut::().unwrap().set_items(items); + h.run_steps(2); + assert!(text_of(h.state(), layer).starts_with("The cat"), "the change was made"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(!open(&h), "Escape closed Check Spelling"); + assert!(text_of(h.state(), layer).starts_with("The cat"), "and the change stays: {}", text_of(h.state(), layer)); + assert!(selected(&h), "Escape went to the dialog, not to the window (which deselects)"); +} + +#[test] +fn enter_in_change_to_runs_done_and_does_not_change_the_word() { + let (mut h, layer) = harness("Teh cat"); + let before = text_of(h.state(), layer); + h.get_by_role_and_label(Role::TextInput, "Change To:").click(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(!open(&h), "Enter closed Check Spelling"); + assert_eq!(text_of(h.state(), layer), before, "the current word was not changed"); + assert!(selected(&h), "the selection under the dialog stays"); +} + +#[test] +fn enter_with_nothing_focused_runs_done() { + let (mut h, layer) = harness("Teh cat"); + let before = text_of(h.state(), layer); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(!open(&h), "Enter closed Check Spelling"); + assert_eq!(text_of(h.state(), layer), before, "Enter is Done, not Change"); +} diff --git a/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs new file mode 100644 index 0000000000..40783e3aa3 --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/data_points_submenu_tests.rs @@ -0,0 +1,45 @@ +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::control::{ControlRequest, Reply}; + +const COMMAND: &str = "image.analysis.selectDataPoints"; + +fn call(app: &mut PhotocraftApp, method: &str, params: Value) -> Value { + let ctx = app.ctx().clone(); + let (request, _) = ControlRequest::new(method, params); + let Reply::Done(reply) = crate::control::handle(app, &ctx, &request) else { panic!("{method} replies immediately") }; + assert_eq!(reply["ok"], true, "{method}: {reply}"); + reply["result"].clone() +} + +#[test] +fn data_points_submenu_has_only_a_checked_custom_item_and_opens_the_dialog() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 32, "height": 24})).unwrap(); + + let menu = call(&mut app, "ui.menu.list", json!({})); + let rows = menu.as_array().unwrap(); + let titled_path = json!(["Image", "Analysis", "Select Data Points"]); + let data_points: Vec<_> = rows.iter().filter(|row| row["path"] == titled_path || row["id"] == COMMAND).collect(); + assert_eq!(data_points.len(), 1, "one entry and no separator: {data_points:?}"); + let custom = data_points[0]; + assert_eq!(custom["path"], titled_path); + assert_eq!(custom["id"], COMMAND); + assert_eq!(custom["label"], "Custom…"); + assert_eq!(custom["checked"], true); + assert_eq!(custom["enabled"], true); + assert_eq!(custom["shortcut"], Value::Null); + + let opened = call(&mut app, "ui.menu.invoke", json!({"id": custom["id"]})); + assert_eq!(opened["dialog"], "dataPoints"); + assert!(app.dialog_open()); +} + +#[test] +fn data_points_submenu_keeps_the_engine_command_available_to_scripts() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let selected = call(&mut app, "engine.execute", json!({"id": COMMAND, "params": {"selection": ["area"], "ruler": [], "count": []}})); + assert_eq!(selected["dataPoints"]["selection"], json!(["area"])); + assert!(!app.dialog_open()); +} diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index fce2102caa..a567de1c71 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -30,6 +30,9 @@ mod tests; #[cfg(test)] mod sampler_menu_tests; +#[cfg(test)] +mod data_points_submenu_tests; + #[cfg(test)] #[path = "../count_readout_tests.rs"] mod count_readout_tests; @@ -120,6 +123,8 @@ pub fn checked(app: &PhotocraftApp, id: &str) -> Option { "window.panel.notes" => Some(crate::panel_docking::is_shown(app, NOTES)), "image.analysis.rulerTool" => Some(app.ui.tool == Tool::Ruler), "image.analysis.countTool" => Some(app.ui.tool == Tool::Count), + // The data point set is always Custom until named presets are supported. + "image.analysis.selectDataPoints" => Some(true), _ => { // View › Proof Setup simulations: checked while that proof is shown. // A check item with no document too: an item's kind never changes (native menus). diff --git a/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs new file mode 100644 index 0000000000..26c6cbd15a --- /dev/null +++ b/crates/ui-egui/src/tools/art_history_reset_keeps_pressure_tests.rs @@ -0,0 +1,48 @@ +use serde_json::json; + +use super::{RESET, RESET_ALL, invoke}; +use crate::PhotocraftApp; +use crate::state::{Tool, ToolOptions}; + +fn art_history_brush(pressure_size: bool, pressure_opacity: bool) -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.ui.tool = Tool::ArtHistoryBrush; + crate::paint_mouse::sync_tool_brush(&mut app); + app.run("tools.setBrush", json!({"brush": {"pressureSize": pressure_size, "pressureOpacity": pressure_opacity}})).unwrap(); + app +} + +fn pressure(app: &PhotocraftApp) -> (bool, bool) { + let brush = &app.session.tools.brush; + (brush.pressure_size, brush.pressure_opacity) +} + +#[test] +fn reset_tool_keeps_each_art_history_brush_pressure_toggle() { + let defaults = ToolOptions::default(); + for toggles in [(true, false), (false, true), (true, true), (false, false)] { + let mut app = art_history_brush(toggles.0, toggles.1); + assert_eq!(pressure(&app), toggles); + app.ui.tool_options.art_history_style = "dab".into(); + app.ui.tool_options.art_history_area = 120.0; + app.ui.tool_options.art_history_tolerance = 25.0; + + invoke(&mut app, RESET, &json!({})).unwrap().unwrap(); + + assert_eq!(pressure(&app), toggles); + assert_eq!(app.ui.tool_options.art_history_style, defaults.art_history_style); + assert_eq!(app.ui.tool_options.art_history_area, defaults.art_history_area); + assert_eq!(app.ui.tool_options.art_history_tolerance, defaults.art_history_tolerance); + } +} + +#[test] +fn reset_all_tools_clears_the_art_history_brush_pressure_toggles() { + let mut app = art_history_brush(true, true); + assert_eq!(pressure(&app), (true, true)); + + invoke(&mut app, RESET_ALL, &json!({"confirmed": true})).unwrap().unwrap(); + + assert_eq!(pressure(&app), (false, false)); +} diff --git a/crates/ui-egui/src/tools/brush_picker.rs b/crates/ui-egui/src/tools/brush_picker.rs index 16abf9696e..a0fc3024d8 100644 --- a/crates/ui-egui/src/tools/brush_picker.rs +++ b/crates/ui-egui/src/tools/brush_picker.rs @@ -98,9 +98,10 @@ fn commit_edits(app: &mut PhotocraftApp, events: &EditEvents, set: impl Fn } } -/// Runs what the picker reported: the head's edits, Escape's revert, the saved view and the picks. -/// `keys` are every row's key in list order (a reorder pick is placed by them). -pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushKey], out: BrushPresetPickerOutput) { +/// Runs what the picker reported: the head's edits, Escape's revert, the range alert for a Size or Hardness typed out +/// of range (the picker stays open under it, #11817), the saved view and the picks. `keys` are every row's key in list +/// order (a reorder pick is placed by them); `ui` words the alert's range. +pub(crate) fn apply(app: &mut PhotocraftApp, ui: &egui::Ui, keys: &[BrushKey], out: BrushPresetPickerOutput) { commit_edits(app, &out.diameter, |b, v| b.size = *v as f32); commit_edits(app, &out.hardness, |b, v| b.hardness = *v as f32); commit_edits(app, &out.tip, |b, v| { @@ -121,12 +122,15 @@ pub(crate) fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, keys: &[BrushK // One command and no history step: `tools.setBrush` without a coalesce key is a tool setting. commit_keyed(app, &now, &after, None); } + if let Some(alert) = &out.out_of_range { + crate::tools::option_cells::range_alert(app, ui, alert); + } if let Some(settings) = &out.settings { save(app, settings); } for pick in out.picks { match pick { - BrushPick::OpenSettings => open_settings(app, ctx), + BrushPick::OpenSettings => open_settings(app, ui.ctx()), other => run_picks(app, vec![other], keys), } } @@ -157,7 +161,7 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) { }; let _ = MemoView::new("brush-preset-canvas", props, canvas_view).show(ui); for CanvasEvent { out, keys, eraser, closed } in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); if let Some(rows) = eraser { commit_keyed(app, &rows.before, &rows.brush, rows.key); if app.ui.tool_options.bg_tolerance_control != rows.tolerance { @@ -249,7 +253,7 @@ pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bo }; let _ = MemoView::new("brush-preset-field", props, field_view).show(ui); for FieldEvent(out, keys) in sent { - apply(app, ui.ctx(), &keys, out); + apply(app, ui, &keys, out); } } @@ -393,3 +397,7 @@ fn toggle_view(props: &mut ToggleProps<'_>, ui: &mut egui::Ui) { #[cfg(test)] #[path = "../brush_picker_gear_menu_tests.rs"] mod gear_menu_tests; + +#[cfg(test)] +#[path = "../brush_picker_range_alert_tests.rs"] +mod range_alert_tests; diff --git a/crates/ui-egui/src/tools/move_box.rs b/crates/ui-egui/src/tools/move_box.rs index 24632762b4..b69547897c 100644 --- a/crates/ui-egui/src/tools/move_box.rs +++ b/crates/ui-egui/src/tools/move_box.rs @@ -7,6 +7,8 @@ use serde_json::json; use craft::behavior::kurbo::{Point, Rect}; +use craft::imaging::ui::select::SelectWords; +use craft::ui::canvas::ToolContext; use craft::ui::canvas_controls::Marquee; use craft::ui::contract::Show as _; @@ -85,6 +87,15 @@ pub(crate) fn cancel(app: &mut PhotocraftApp) { app.layer_box = None; } +/// The marquee's W and H beside the pointer while it is dragged, in the selection marquee's words and units +/// (Show Transformation Values hides it, as it hides the drag readout). +pub(crate) fn readout(app: &PhotocraftApp, cx: &mut ToolContext<'_>) { + let Some(b) = app.layer_box else { return }; + let rect = Rect::from_points(Point::new(b.start[0], b.start[1]), Point::new(b.end[0], b.end[1])); + let (words, units) = (cx.words::(), cx.units()); + cx.readout(vec![(words.width.clone(), units.pixels(rect.width())), (words.height.clone(), units.pixels(rect.height()))]); +} + /// The marquee being dragged, over the canvas `canvas`. pub(crate) fn show(app: &PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect) { let Some(b) = app.layer_box else { return }; @@ -205,3 +216,7 @@ mod tests { assert_eq!(app.session.active().unwrap().selected_layers(), vec![paint]); } } + +#[cfg(test)] +#[path = "move_marquee_readout_tests.rs"] +mod move_marquee_readout_tests; diff --git a/crates/ui-egui/src/tools/move_marquee_readout_tests.rs b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs new file mode 100644 index 0000000000..93e226884c --- /dev/null +++ b/crates/ui-egui/src/tools/move_marquee_readout_tests.rs @@ -0,0 +1,75 @@ +//! #18162: the Move tool's layer marquee shows its W and H beside the pointer while it is dragged, as a layer drag +//! shows its distances, and adds no history step. + +use serde_json::json; + +use crate::canvas::{ToolEvent, tool_event, tool_event_response}; +use crate::state::Tool; +use crate::{PhotocraftApp, Services}; + +/// A white document whose only layer is the locked Background, with the Move tool and Auto-Select on: a press +/// anywhere on the canvas starts the layer marquee. +fn app() -> Box { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Move; + app.ui.tool_options.move_auto_select = true; + app +} + +/// The readout rows of the pass that moves the pointer to `to`, as label and value text. +fn readout(app: &mut PhotocraftApp, to: [f64; 2]) -> Vec<(String, String)> { + tool_event_response(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, egui::Modifiers::NONE) + .readout + .expect("the layer marquee has a readout") + .rows + .into_iter() + .map(|(label, value)| (label.as_str().to_owned(), value)) + .collect() +} + +/// The number a readout value shows ("42 px" reads 42). +fn number(value: &str) -> f64 { + value.trim_end_matches("px").trim().parse().unwrap_or_else(|_| panic!("a pixel value: {value:?}")) +} + +#[test] +fn the_layer_marquee_reads_its_width_and_height_as_it_grows() { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + let first = readout(&mut app, [60.0, 50.0]); + assert!(app.layer_box.is_some(), "the press started the layer marquee"); + let [(w_label, w), (h_label, h)] = first.as_slice() else { panic!("two rows, W and H: {first:?}") }; + assert!(w_label.starts_with('W') && h_label.starts_with('H'), "{first:?}"); + assert!(w.ends_with("px") && h.ends_with("px"), "{first:?}"); + assert!(number(w) > 0.0 && number(h) > 0.0, "{first:?}"); + + let wider = readout(&mut app, [120.0, 50.0]); + assert!(number(&wider[0].1) > number(w), "a wider drag reads a larger W: {first:?} then {wider:?}"); + assert_eq!(wider[1].1, *h, "H stays while only the width changes"); + + let taller = readout(&mut app, [120.0, 110.0]); + assert!(number(&taller[1].1) > number(&wider[1].1), "a taller drag reads a larger H: {wider:?} then {taller:?}"); + + // Up and to the left of the press, the box reads its size, not a negative one. + let back = readout(&mut app, [5.0, 10.0]); + assert!(number(&back[0].1) > 0.0 && number(&back[1].1) > 0.0, "{back:?}"); +} + +#[test] +fn the_layer_marquee_adds_no_history_step_and_leaves_the_background() { + let mut app = app(); + let (steps, bg, bounds) = { + let st = app.session.active().unwrap(); + let bg = st.active_layer.unwrap(); + (st.history.past_len(), bg, st.doc.layer(bg).unwrap().surface().unwrap().content_bounds()) + }; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, egui::Modifiers::NONE); + assert!(!readout(&mut app, [90.0, 70.0]).is_empty()); + tool_event(&mut app, ToolEvent::Up { x: 90.0, y: 70.0 }, egui::Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.past_len(), steps, "no history step"); + assert_eq!(st.doc.layer(bg).unwrap().surface().unwrap().content_bounds(), bounds, "the Background did not move"); + assert!(app.layer_box.is_none()); +} diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 55ea6ef18f..4e9bf5a5be 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -90,11 +90,12 @@ fn reset_tool(app: &mut PhotocraftApp, tool: Tool) { // The session brush is the options bar's tool's: make sure it is `tool`'s before resetting. crate::paint_mouse::sync_tool_brush(app); app.ui.tool_brushes.retain(|(t, _)| *t != tool); - // The Eraser's Reset Tool resets the tip but keeps Pressure for Size and Pressure for - // Opacity as they were (#17700). The Background Eraser's keeps Pressure for Size (#18058). + // Reset the tip but keep Pressure for Size and Pressure for Opacity for the Eraser + // (#17700) and Art History Brush (#18335). Background Eraser keeps only Size (#18058). let brush = &app.session.tools.brush; - let size = matches!(tool, Tool::Eraser | Tool::BackgroundEraser).then_some(brush.pressure_size); - let opacity = (tool == Tool::Eraser).then_some(brush.pressure_opacity); + let keep_opacity = matches!(tool, Tool::Eraser | Tool::ArtHistoryBrush); + let size = (keep_opacity || tool == Tool::BackgroundEraser).then_some(brush.pressure_size); + let opacity = keep_opacity.then_some(brush.pressure_opacity); reset_session_brush(app); if size.is_some() || opacity.is_some() { let brush = &mut app.session.tools.brush; @@ -486,6 +487,10 @@ mod patch_sample_all_default_tests; #[path = "eraser_reset_keeps_pressure_tests.rs"] mod eraser_reset_keeps_pressure_tests; +#[cfg(test)] +#[path = "art_history_reset_keeps_pressure_tests.rs"] +mod art_history_reset_keeps_pressure_tests; + #[cfg(test)] #[path = "bg_eraser_reset_pressure_tests.rs"] mod bg_eraser_reset_pressure_tests;