diff --git a/crates/engine-paint/src/cmd/brush_cmds.rs b/crates/engine-paint/src/cmd/brush_cmds.rs index 35d6f026d9..d4d88cc2b3 100644 --- a/crates/engine-paint/src/cmd/brush_cmds.rs +++ b/crates/engine-paint/src/cmd/brush_cmds.rs @@ -1021,13 +1021,28 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { /// A `paint.colorReplacement` stroke shown while it is drawn: the same params, and the same /// recolouring per dab as the commit, so the preview at the last point is the committed result. pub fn live_color_replacement(s: &Session, p: &Value) -> Result { - let (stroke, rs, id) = color_replacement_setup(s, p)?; + let (mut stroke, rs, id) = color_replacement_setup(s, p)?; let cmyk = doc_cmyk_space(s); + // The same Anti-alias gate as the commit: only the Anti-alias-off branch of the effect reads a + // footprint's modulation map (#13160), so only that preview pays the second rasterising pass. + let keep_mods = !rs.anti_alias; + // The flag decides how each footprint is rasterised, per dab, so with Anti-alias off the + // starting points go in only after it is set: `with_effect` renders the points it is given, as + // `live_background_eraser` arranges for its transparency lock. + let first = if keep_mods { std::mem::take(&mut stroke.points) } else { Vec::new() }; // The same CMYK space as the commit, so the preview's dabs recolour the same device colours. photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || { - crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", p, stroke, Some(id), 0, |pre| { + let live = crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", p, stroke, Some(id), 0, |pre| { Box::new(color_replacement_effect(pre.clone(), rs)) - }) + })?; + let live = if keep_mods { + let mut live = live.with_footprint_mods(); + live.push(&first)?; + live + } else { + live + }; + Ok::<_, EngineError>(live) })? .with_tail_preview() } diff --git a/crates/engine-paint/src/cmd/brush_cmds/tests.rs b/crates/engine-paint/src/cmd/brush_cmds/tests.rs index 4b9e60cef0..05e9a6e242 100644 --- a/crates/engine-paint/src/cmd/brush_cmds/tests.rs +++ b/crates/engine-paint/src/cmd/brush_cmds/tests.rs @@ -332,6 +332,64 @@ fn live_color_replacement_matches_the_commit() { } } +/// The Anti-alias-off preview modulates its first dabs like the commit: `with_footprint_mods` +/// decides how a footprint is rasterised, per dab, so the points the live stroke starts with must +/// not be rendered before it is set. With Wet Edges on a soft tip the commit leaves half strength +/// inside the tip; the dabs rendered from the starting points keep the dab's strength flat there, +/// and with a wide spacing no later dab covers them again (#13160). +#[test] +fn the_live_anti_alias_off_preview_modulates_its_first_dab_like_the_commit() { + let all = [[10.0, 20.0], [30.0, 20.0], [50.0, 20.0], [70.0, 22.0]]; + let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::>(); + let opts = |v: &[[f64; 2]], wet: bool| json!({"points": v, "size": 24, "hardness": 0.0, "tolerance": 60, "mode": "color", "antiAlias": false, "spacing": 1.0, "target": "pixels", "brush": {"wetEdges": wet}}); + let fresh = |depth: u32| { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 80, "height": 40, "background": "#ff0000", "depth": depth})).unwrap(); + s.execute("tools.setColors", json!({"foreground": "#00ff00"})).unwrap(); + s + }; + let shown = |s: &Session| { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().clone() + }; + for depth in [8u32, 16u32] { + // The setup: this brush and this stroke carry a Wet Edges modulation at all - the same + // stroke with Wet Edges off leaves different pixels. + let (mut on, mut off) = (fresh(depth), fresh(depth)); + on.execute("paint.colorReplacement", opts(&all, true)).unwrap(); + off.execute("paint.colorReplacement", opts(&all, false)).unwrap(); + let (a, b) = (shown(&on), shown(&off)); + assert!((0..40).any(|y| (0..80).any(|x| a.rgba(x, y) != b.rgba(x, y))), "{depth}-bit: this stroke carries no Wet Edges modulation to compare"); + // The live stroke takes the points as the canvas route hands them out and shows the + // finishing dabs as well: every pixel of the preview is the pixel the commit paints. + let mut s = fresh(depth); + let mut live = live_color_replacement(&s, &opts(&all[..2], true)).unwrap(); + live.push(&pts(&all[2..3])).unwrap(); + live.push(&pts(&all[3..])).unwrap(); + let doc = live.doc.clone(); + s.execute("paint.colorReplacement", opts(&all, true)).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + let (a, b) = (doc.layer(id).unwrap().surface().unwrap(), shown(&s)); + let (mut worst, mut at) = (0.0f32, [0, 0]); + for y in 0..40 { + for x in 0..80 { + let (g, w) = (a.rgba(x, y), b.rgba(x, y)); + let d = (0..4).map(|c| (g[c] - w[c]).abs()).fold(0.0f32, f32::max); + if d > worst { + worst = d; + at = [x, y]; + } + } + } + assert!( + worst <= 2.0 / 255.0 + 1e-6, + "{depth}-bit: live preview and commit differ by {worst} at {:?} ({:?} vs {:?})", + at, + a.rgba(at[0], at[1]), + b.rgba(at[0], at[1]) + ); + } +} /// Color Replacement recolours layer pixels only: a mask, channel or Quick Mask target is /// refused (it would otherwise recolour the layer behind the user's back). #[test] diff --git a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs index 4ee3ca8f1d..e5fa6caca2 100644 --- a/crates/engine-paint/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine-paint/src/cmd/retouch_cmds/dab.rs @@ -606,6 +606,10 @@ pub struct LiveDab { /// The document and revision the stroke started on, for strokes started from the session's /// active document ([`Self::with_effect`]); `None` for strokes on a prepared copy. base: Option<(photocraft_doc::DocId, u64)>, + /// Whether each footprint is built with the dab's modulation map + /// ([`photocraft_paint::retouch::Footprint::mods`], #13160) — only Color Replacement with + /// Anti-alias off reads it; the second rasterising pass is not paid by the other tools. + footprint_mods: bool, /// Every point rendered so far, in order. points: Vec, } @@ -720,6 +724,7 @@ impl LiveDab { tail: Rect::EMPTY, tool: None, base: None, + footprint_mods: false, points: Vec::new(), }; live.push(&stroke.points)?; @@ -742,6 +747,14 @@ impl LiveDab { self } + /// Build each footprint of this stroke with the dab's modulation map (see + /// [`photocraft_paint::retouch::Footprint::mods`], #13160). Call it before pushing any points: + /// the flag decides how the footprints are rasterised, per dab. + pub(crate) fn with_footprint_mods(mut self) -> Self { + self.footprint_mods = true; + self + } + /// Everything the stroke has touched so far. pub fn bounds(&self) -> Rect { self.bounds @@ -761,7 +774,8 @@ impl LiveDab { continue; } let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); - (self.effect)(&mut region, &ctx.footprint(d, self.done.saturating_add(k))); + let fp = if self.footprint_mods { ctx.footprint_with_mods(d, self.done.saturating_add(k)) } else { ctx.footprint(d, self.done.saturating_add(k)) }; + (self.effect)(&mut region, &fp); self.work.write(&self.pre_surf, ®ion.crop(r)); dmg = dmg.union(&r); } @@ -807,7 +821,12 @@ impl LiveDab { if !r.is_empty() { let mut region = self.work.read(&self.pre_surf, r.inflate(self.neighborhood.halo())); for (k, d) in ds.iter().enumerate() { - (self.effect)(&mut region, &ctx.footprint(d, self.done.saturating_add(k))); + let fp = if self.footprint_mods { + ctx.footprint_with_mods(d, self.done.saturating_add(k)) + } else { + ctx.footprint(d, self.done.saturating_add(k)) + }; + (self.effect)(&mut region, &fp); } tail = Some((r, region.crop(r))); } diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index f0c51fa970..02d0b7bc06 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -450,12 +450,64 @@ impl BrushContext { } } - /// One dab's dense footprint (for the sequential retouch tools). + /// One dab's dense footprint (for the sequential retouch tools). It carries no modulation map + /// ([`Footprint::mods`] is `None`): only a tool that hardens the tip's edge asks for one. pub fn footprint(&self, d: &Dab, index: usize) -> Footprint { let rect = self.dab_rect(d, false); let mut cov = Vec::new(); self.rasterize(d, false, rect, &mut cov); - Footprint { dab: *d, index, rect, cov } + Footprint { dab: *d, index, rect, cov, mods: None } + } + + /// [`footprint`](Self::footprint), additionally building the dab's [`Footprint::mods`] map for + /// an effect that hardens the tip's edge and must keep the rest of the dab's strength + /// (Color Replacement with Anti-alias off, #13160). That is a second rasterising pass, so it is + /// asked for only where it is read; the map stays `None` for a brush without Wet Edges or + /// per-tip Texture, whose fully covered pixels take exactly the dab's alpha. + pub fn footprint_with_mods(&self, d: &Dab, index: usize) -> Footprint { + let rect = self.dab_rect(d, false); + let mut cov = Vec::new(); + self.rasterize(d, false, rect, &mut cov); + let mods = self.dab_modulations(d, rect); + Footprint { dab: *d, index, rect, cov, mods } + } + + /// The dab's strength at each pixel it covers once its own tip edge is forced to full coverage + /// (the `mods` map of [`Footprint`], #13160): the per-tip Texture combine and the Wet Edges + /// factor at the dab's depth, times the dab's alpha. `None` when the brush carries neither + /// modulation — then the value the dab leaves at a fully covered pixel is just its alpha. + fn dab_modulations(&self, d: &Dab, rect: Rect) -> Option> { + let b = &self.brush; + let wet = b.wet_edges; + let tex_tip = b.texture.enabled && b.texture.each_tip && self.texture.is_some(); + if !wet && !tex_tip { + return None; + } + // With `depth` the rasteriser leaves Wet Edges out of the coverage and reports each painted + // pixel's depth (1 − rn) inside the dab, which is exactly the rn the wet factor takes. A + // brush carrying one of the modulations takes the general loop either way. Both maps are + // w × h dense: rasterize_into sizes every output it is given from `rect`. + let mut scratch = Vec::new(); + let mut depth = Vec::new(); + self.rasterize_into(d, false, rect, &mut scratch, Some(&mut depth)); + let w = rect.width() as usize; + let mut mods = vec![0.0f32; scratch.len()]; + for (i, (sc, dp)) in scratch.iter().zip(depth.iter()).enumerate() { + if *sc <= 0.0 { + continue; + } + let mut val = 1.0f32; + if tex_tip { + // The same combine the row applies, at full tip coverage; `d.depth` is the dab's + // own texture depth, what the combine takes there too. + val = texture_combine(b.texture.mode, 1.0, self.texture_at(rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32), d.depth); + } + if wet { + val *= wet_factor(1.0 - *dp); + } + mods[i] = val * d.alpha; + } + Some(mods) } /// Stroke-level masks applied to accumulated coverage `c` at a pixel. diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index f6230719de..1b54eb508d 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -8,7 +8,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde::{Deserialize, Serialize}; use crate::Stroke; -use crate::retouch::{Footprint, Region, StrokeTooLarge, apply_dab_stroke}; +use crate::retouch::{Footprint, Region, StrokeTooLarge, apply_dab_stroke, apply_dab_stroke_with_mods}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -95,7 +95,13 @@ pub fn apply_color_replacement( lock_transparency: bool, ) -> Result { let effect = color_replacement_effect(target.clone(), rs.clone()); - apply_dab_stroke(target, stroke, selection, lock_transparency, 0, effect) + // Only the Anti-alias-off branch reads a footprint's modulation map (#13160), so only that + // route pays the second rasterising pass that builds it. + if rs.anti_alias { + apply_dab_stroke(target, stroke, selection, lock_transparency, 0, effect) + } else { + apply_dab_stroke_with_mods(target, stroke, selection, lock_transparency, 0, effect) + } } /// One Color Replacement dab's edit of a working copy, matching against `pre` (the target before @@ -273,7 +279,9 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut // With Anti-alias off the tip has a hard edge (#11917): a pixel it reaches takes // the dab's full strength (its flow and pressure), not its partial coverage. A soft // tip too, over the same reach as with Anti-alias on: the pixels its blended edge - // would change as stored, not its faint tail past them. + // would change as stored, not its faint tail past them. Only the tip's edge is + // hardened that way (#13160): modulations that are not the edge — Wet Edges and + // per-tip Texture — keep scaling the strength the dab leaves on the pixel. let k = if rs.anti_alias { k } else { @@ -281,7 +289,7 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut if enc[..n].iter().zip(px.iter()).all(|(a, b)| stored(*a) == stored(*b)) { continue; } - fp.dab.alpha * wt + fp.modulated_at(x, y) * wt }; recolor(px, k, &mut enc); px.copy_from_slice(&enc[..n]); diff --git a/crates/paint/src/replace_anti_alias_tests.rs b/crates/paint/src/replace_anti_alias_tests.rs index 75c0f8d8e9..3e7aef365f 100644 --- a/crates/paint/src/replace_anti_alias_tests.rs +++ b/crates/paint/src/replace_anti_alias_tests.rs @@ -7,7 +7,7 @@ use photocraft_color::PixelFormat; use super::*; -use crate::{BrushSettings, StrokePoint}; +use crate::{BrushSettings, Pattern, StrokePoint, Texture}; fn target() -> Surface { let fmt = PixelFormat::RGBA8; @@ -44,6 +44,47 @@ fn click_with(anti_alias: bool, flow: f32, hardness: f32) -> Surface { s } +/// The same click with a modulating brush: Wet Edges and/or a per-tip Texture with a flat mid-grey +/// tile (pattern value 0.5), hardness 1. #13160. +fn click_modulated(anti_alias: bool, wet: bool, texture: bool) -> Surface { + click_modulated_with(anti_alias, wet, texture, 1.0) +} + +fn click_modulated_with(anti_alias: bool, wet: bool, texture: bool, hardness: f32) -> Surface { + let mut s = target(); + let brush = BrushSettings { + size: 80.0, + hardness, + spacing: 0.25, + wet_edges: wet, + texture: Texture { enabled: texture, pattern: Pattern::Tile(crate::tile::GrayTile::from_fn(8, 8, |_, _| 0.5)), each_tip: true, ..Default::default() }, + pressure_size: false, + ..Default::default() + }; + let stroke = Stroke { brush, points: vec![StrokePoint::new(100.0, 120.0, 1.0)] }; + let rs = ReplaceSettings { + mode: ReplaceMode::Color, + sampling: Sampling::Continuous, + limits: Limits::Contiguous, + tolerance: 0.3, + anti_alias, + color: [0.0, 0.0, 1.0, 1.0], + ..Default::default() + }; + apply_color_replacement(&mut s, &stroke, &rs, None, false).unwrap(); + s +} + +/// The red pixel recoloured at strength `k`, stored in 8 bits (the same mix the dab runs). +fn blend_at(k: f32) -> [i32; 3] { + let mut s = target(); + let b = blend_rgb(BlendMode::Color, [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0], [0.0, 0.0, 1.0]); + let g = [220.0 / 255.0, 30.0 / 255.0, 30.0 / 255.0]; + let c = [g[0] + (b[0] - g[0]) * k, g[1] + (b[1] - g[1]) * k, g[2] + (b[2] - g[2]) * k]; + s.fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&PixelFormat::RGBA8, [c[0], c[1], c[2], 1.0])); + px(&s, 0, 0) +} + fn px(s: &Surface, x: i32, y: i32) -> [i32; 3] { let c = s.rgba(x, y); [0, 1, 2].map(|i| (c[i] * 255.0).round() as i32) @@ -138,3 +179,52 @@ fn a_soft_tip_with_anti_alias_off_replaces_fully_over_the_same_reach() { assert!(partial_on > 0, "hardness {hardness}: Anti-alias on keeps the falloff"); } } + +// #13160: the hardening with Anti-alias off is the tip's edge only. What is not the tip edge — +// Wet Edges and per-tip Texture modulation — keeps its partial-strength effect. The expected +// values are the same brush's own Anti-alias-on values at the dab centre: a hard tip covers the +// centre pixel fully there, so the strength that shows is the modulation alone. + +#[test] +fn anti_alias_off_keeps_wet_edges() { + let (on, off) = (click_modulated(true, true, false), click_modulated(false, true, false)); + // Wet Edges keeps half the paint at a dab's centre: the dab's centre pixel is at half strength + // with Anti-alias on, and with it off too — not the full replacement. + assert_eq!(px(&on, 100, 120), blend_at(0.5), "Anti-alias on: the wet edge keeps the centre at half strength"); + assert_eq!(px(&off, 100, 120), px(&on, 100, 120), "Anti-alias off keeps the wet-edge strength"); + assert_ne!(px(&off, 100, 120), full(), "the centre is not flattened to the dab's strength"); + // The edge stays hard: rim pixels near the wet rim value are fully replaced, pixels are never + // a partial mix of its own. + assert!(px(&off, 58, 120).iter().zip(&blend_at(1.0)).all(|(a, b)| (a - b).abs() <= 3), "the wet rim still reaches fully: {:?}", px(&off, 58, 120)); +} + +#[test] +fn anti_alias_off_keeps_per_tip_texture() { + // A mid-grey tile at full depth: the texture halves the coverage over the whole tip, so the + // centre is a half-strength replacement whichever way Anti-alias sits. + let (on, off) = (click_modulated(true, false, true), click_modulated(false, false, true)); + assert_eq!(px(&off, 100, 120), px(&on, 100, 120), "Anti-alias off keeps the per-tip texture strength"); + assert_ne!(px(&off, 100, 120), full(), "the centre is not flattened to the dab's strength"); + assert_ne!(px(&off, 100, 120), RED, "the centre is replaced"); +} + +#[test] +fn a_soft_tip_with_anti_alias_off_keeps_its_wet_edges_and_texture() { + // The issue's title case: a soft tip (hardness 50 %) with Anti-alias off keeps its wet edges + // and texture. The centre pixel is inside the tip's core, so the full-tip coverage and the + // modulation are the same as with Anti-alias on. + let (on, off) = (click_modulated_with(true, true, true, 0.5), click_modulated_with(false, true, true, 0.5)); + assert_eq!(px(&off, 100, 120), px(&on, 100, 120), "the soft tip keeps the wet-and-texture strength at its centre"); + assert_ne!(px(&off, 100, 120), full(), "the centre is not flattened to the dab's strength"); + // Hardened edge as before: the same pixels change with it on and off (the stored-value reach + // test cuts the faint tail); the strength levels themselves are pinned at the centre above. + for y in (60..180).step_by(3) { + for x in (20..180).step_by(3) { + let (a, b) = (px(&on, x, y), px(&off, x, y)); + if (140..160).contains(&y) { + continue; + } + assert_eq!(a != RED, b != RED, "{x},{y}: the reach differs (on {a:?}, off {b:?})"); + } + } +} diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 3735864912..e0124426f6 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -86,6 +86,12 @@ pub struct Footprint { pub rect: Rect, /// `rect.width() × rect.height()` coverage values in 0..1 (already multiplied by flow/pressure). pub cov: Vec, + /// `cov` with the tip's own edge forced to full coverage: the dab's non-edge modulation (per-tip + /// Texture combine × Wet Edges at the dab's depth) times flow/pressure, per pixel (#13160). + /// `None` when the brush carries neither, and for every footprint not built by a runner that + /// asks for the map ([`crate::BrushContext::footprint_with_mods`], [`apply_dab_stroke_with_mods`]): + /// the modulation is then 1 and the value is the dab's alpha. + pub mods: Option>, } impl Footprint { @@ -93,6 +99,16 @@ impl Footprint { pub fn at(&self, x: i32, y: i32) -> f32 { self.cov[(y - self.rect.y0) as usize * self.rect.width() as usize + (x - self.rect.x0) as usize] } + + /// The dab's strength at (x, y) with the tip's edge fully covering the pixel, modulations kept + /// (#13160; see [`Footprint::mods`]). + #[inline] + pub fn modulated_at(&self, x: i32, y: i32) -> f32 { + match &self.mods { + Some(m) => m[(y - self.rect.y0) as usize * self.rect.width() as usize + (x - self.rect.x0) as usize], + None => self.dab.alpha, + } + } } /// Bounding rectangle of a dab (1 px of anti-aliasing slack included). @@ -112,7 +128,7 @@ pub fn footprint(d: &Dab, index: usize, hardness: f32) -> Footprint { cov.push(dab_coverage(dist, d.radius, hardness) * d.alpha); } } - Footprint { dab: *d, index, rect, cov } + Footprint { dab: *d, index, rect, cov, mods: None } } /// Union of the dabs' rectangles. @@ -306,6 +322,33 @@ pub fn apply_dab_stroke( selection: Option<&Surface>, lock_transparency: bool, halo: i32, + effect: impl FnMut(&mut Region, &Footprint), +) -> Result { + apply_dab_stroke_opts(target, stroke, selection, lock_transparency, halo, false, effect) +} + +/// Like [`apply_dab_stroke`], but each [`Footprint`] also carries the dab's modulation map +/// ([`Footprint::mods`]) — for the one effect that hardens the tip's edge and must keep the rest +/// of the dab's strength (Color Replacement with Anti-alias off, #13160). It costs a second +/// rasterising pass per dab, so it is a separate entry point, not the default. +pub fn apply_dab_stroke_with_mods( + target: &mut Surface, + stroke: &Stroke, + selection: Option<&Surface>, + lock_transparency: bool, + halo: i32, + effect: impl FnMut(&mut Region, &Footprint), +) -> Result { + apply_dab_stroke_opts(target, stroke, selection, lock_transparency, halo, true, effect) +} + +fn apply_dab_stroke_opts( + target: &mut Surface, + stroke: &Stroke, + selection: Option<&Surface>, + lock_transparency: bool, + halo: i32, + mods: bool, mut effect: impl FnMut(&mut Region, &Footprint), ) -> Result { let ds = dabs(stroke); @@ -323,7 +366,8 @@ pub fn apply_dab_stroke( let orig = Region::read(target, outer); let mut work = orig.clone(); for (i, d) in ds.iter().enumerate() { - effect(&mut work, &ctx.footprint(d, i)); + let fp = if mods { ctx.footprint_with_mods(d, i) } else { ctx.footprint(d, i) }; + effect(&mut work, &fp); } mix_back(target, &orig, &work, bounds, stroke.brush.opacity, selection, lock_transparency); Ok(bounds) @@ -700,6 +744,24 @@ mod tests { } } + #[test] + fn footprints_carry_a_modulation_map_only_when_the_runner_asks() { + // #13160: the map costs a second rasterising pass, so a footprint from the plain entry + // point carries none — wet brush or not — and only a runner that reads it asks for one. + let wet = BrushSettings { size: 80.0, hardness: 1.0, wet_edges: true, pressure_size: false, ..Default::default() }; + let ctx = crate::BrushContext::new(&wet); + let d = Dab::round(Point::new(40.0, 40.0), 20.0, 0.5); + assert!(ctx.footprint(&d, 0).mods.is_none(), "the plain footprint pays no second pass"); + let asked = ctx.footprint_with_mods(&d, 0); + assert!(asked.mods.is_some(), "the asked footprint carries the wet modulation"); + // At a dab's centre Wet Edges keep half the paint: wet factor 0.5 times the dab's alpha. + assert_eq!(asked.modulated_at(40, 40), 0.25); + // A brush with neither modulation keeps no map even when asked: factor 1, the dab's alpha. + let plain = crate::BrushContext::new(&BrushSettings::default()); + assert!(plain.footprint_with_mods(&d, 0).mods.is_none(), "no modulation on this brush"); + assert_eq!(plain.footprint_with_mods(&d, 0).modulated_at(40, 40), 0.5); + } + #[test] fn a_dab_stroke_between_distant_points_is_refused_before_reading() { assert!(fits_dab_stroke_budget(Rect::new(0, 0, 4096, 4096), 4)); diff --git a/crates/ui-egui/src/canvas/color_replacement_locked_cursor_tests.rs b/crates/ui-egui/src/canvas/color_replacement_locked_cursor_tests.rs new file mode 100644 index 0000000000..242ae33de1 --- /dev/null +++ b/crates/ui-egui/src/canvas/color_replacement_locked_cursor_tests.rs @@ -0,0 +1,97 @@ +//! #17761: the Color Replacement tool shows the not-allowed cursor over a Lock All layer, as the +//! Brush and Eraser do; its size and hardness keys and the Alt+right-drag still change the tool. +//! Driven through real egui input on the real canvas. + +use craft::behavior::{Cursor, CursorIcon, PaintedCursor}; +use craft::ui::runtime::windows::WindowHost; +use egui::{Key, Modifiers, PointerButton, vec2}; +use egui_kittest::Harness; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover, screen}; +use crate::state::Tool; + +const BLOCKED: Option = Some(Cursor::System(CursorIcon::NotAllowed)); + +fn pixel_layer() -> Harness<'static, Box> { + let mut h = harness(Tool::ColorReplacement); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.state_mut().run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + h +} + +fn cursor(h: &mut Harness<'static, Box>, x: f32) -> Option { + hover(h, x, 150.0, Modifiers::NONE); + h.state().canvas_tools.last_response.as_ref().and_then(|response| response.cursor.clone()) +} + +fn lock_all(h: &mut Harness<'static, Box>, on: bool) { + h.state_mut().run("layer.lockLayers", json!({"all": on})).unwrap(); +} + +#[test] +fn lock_all_gives_the_not_allowed_cursor_on_the_image_and_pasteboard() { + let mut h = pixel_layer(); + let tip = cursor(&mut h, 100.0); + assert!(matches!(tip, Some(Cursor::Painted(PaintedCursor::Circle { .. } | PaintedCursor::Outline { .. }))), "unlocked: the tip outline, got {tip:?}"); + lock_all(&mut h, true); + for x in [100.0, -40.0] { + assert_eq!(cursor(&mut h, x), BLOCKED, "x={x}"); + assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::NotAllowed, "x={x}"); + } + lock_all(&mut h, false); + assert_eq!(cursor(&mut h, 100.0), tip, "unlocked again: the tip outline"); +} + +#[test] +fn caps_lock_still_gives_the_precise_crosshair_on_an_unlocked_layer() { + let mut h = pixel_layer(); + WindowHost::of(&h.ctx).set_caps_lock(Some(true)); + assert_eq!(cursor(&mut h, 100.0), Some(Cursor::Painted(PaintedCursor::Crosshair))); +} + +#[test] +fn partial_locks_and_a_hidden_locked_layer_keep_the_tip() { + let mut h = pixel_layer(); + let tip = cursor(&mut h, 100.0); + for lock in ["pixels", "transparency", "position"] { + h.state_mut().run("layer.lockLayers", json!({ (lock): true })).unwrap(); + assert_eq!(cursor(&mut h, 100.0), tip, "{lock}"); + h.state_mut().run("layer.lockLayers", json!({ (lock): false })).unwrap(); + } + lock_all(&mut h, true); + h.state_mut().run("layer.setProps", json!({"visible": false})).unwrap(); + assert_eq!(cursor(&mut h, 100.0), tip, "hidden Lock All layer"); +} + +#[test] +fn size_and_hardness_keys_and_the_resize_drag_work_on_a_locked_layer() { + let mut h = pixel_layer(); + lock_all(&mut h, true); + cursor(&mut h, 100.0); + let size = h.state().session.tools.brush.size; + h.key_press(Key::CloseBracket); + h.run_steps(2); + let bigger = h.state().session.tools.brush.size; + assert!(bigger > size, "] grows the tip: {size} -> {bigger}"); + h.state_mut().run("tools.setBrush", json!({"hardness": 0.0})).unwrap(); + h.key_press_modifiers(Modifiers::SHIFT, Key::CloseBracket); + h.run_steps(2); + assert!(h.state().session.tools.brush.hardness > 0.0, "Shift+] hardens the tip"); + + let from = screen(&h, 100.0, 150.0); + let alt = Modifiers::ALT; + h.event(egui::Event::ModifiersChanged(alt)); + h.event(egui::Event::PointerMoved(from)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Secondary, pressed: true, modifiers: alt }); + h.run_steps(1); + for i in 1..=6 { + h.event(egui::Event::PointerMoved(from + vec2(i as f32 * 8.0, 0.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: from + vec2(48.0, 0.0), button: PointerButton::Secondary, pressed: false, modifiers: alt }); + h.run_steps(2); + assert_ne!(h.state().session.tools.brush.size, bigger, "Alt+right-drag resizes the tip"); +} diff --git a/crates/ui-egui/src/canvas/cursor_policy.rs b/crates/ui-egui/src/canvas/cursor_policy.rs index 63c9a9ca44..6dc9865840 100644 --- a/crates/ui-egui/src/canvas/cursor_policy.rs +++ b/crates/ui-egui/src/canvas/cursor_policy.rs @@ -159,12 +159,13 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: craft::keymap::Mods) -> bool { mods.alt && !mods.ctrl && tool == Tool::MixerBrush } -/// Whether the painting tool shows the not-allowed cursor for its current target. +/// Whether the painting tool shows the not-allowed cursor for its current target. The Color +/// Replacement tool shows it on a Lock All pixel layer (#17761). pub(super) fn paint_cursor_blocked(app: &PhotocraftApp) -> bool { use photocraft_doc::LayerContent; let tool = app.ui.tool; - if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush) { + if !matches!(tool, Tool::Brush | Tool::Eraser | Tool::PaintBucket | Tool::MixerBrush | Tool::ColorReplacement) { return false; } let Some(state) = app.session.active() else { return false }; @@ -257,3 +258,7 @@ mod magic_eraser_cursor_tests; #[cfg(test)] #[path = "locked_layer_cursor_tests.rs"] mod locked_layer_cursor_tests; + +#[cfg(test)] +#[path = "color_replacement_locked_cursor_tests.rs"] +mod color_replacement_locked_cursor_tests;