diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index 186cd3edeb..fb7f005106 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -5,12 +5,16 @@ use photocraft_geom::Rect; use photocraft_raster::{Surface, from_rgba_into}; use serde::{Deserialize, Serialize}; -/// How a fill lays down its colour: blended with a mode, or Clear, which erases what it covers -/// (the Paint Bucket's Mode › Clear). +/// How a fill lays down its colour: blended with a mode, Clear, which erases what it covers +/// (the Paint Bucket's Mode › Clear), or Behind, which paints only into the pixels' transparency. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FillMode { Blend(BlendMode), Clear, + /// The fill goes under each pixel at `fill α × coverage × (1 − α)`, as the Brush's Behind + /// lays it: opaque pixels keep what they have, transparent ones take the fill as in Normal + /// (#12531). Locked transparency leaves the layer as it is. + Behind, } /// Gradient tool shape. @@ -93,7 +97,7 @@ fn composite_area( for x in r.x0..r.x1 { let mut k = coverage(x, y); let on_rim = match rim { - Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_)) => rim(x, y), + Some(rim) if k <= 0.0 && !lock_transparency && matches!(mode, FillMode::Blend(_) | FillMode::Behind) => rim(x, y), _ => 0.0, }; if k <= 0.0 && on_rim <= 0.0 { @@ -113,18 +117,25 @@ fn composite_area( continue; } } + // Behind leaves opaque and transparency-locked pixels unchanged; skip the + // encode and write, whose CMYK round trip can shift their inks (#12531 review). + if mode == FillMode::Behind && (lock_transparency || d[3] >= 1.0) { + continue; + } let o = match mode { FillMode::Blend(m) if lock_transparency => blend::composite_atop(m, d, color(x, y), k), FillMode::Blend(m) => blend::composite(m, d, color(x, y), k), // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. FillMode::Clear if lock_transparency => d, FillMode::Clear => [d[0], d[1], d[2], d[3] * (1.0 - k.min(1.0))], + FillMode::Behind if lock_transparency => d, + FillMode::Behind => behind(d, color(x, y), k), }; from_rgba_into(&fmt, o, &mut enc); // A colour picked as CMYK inks replaces fully covered pixels of a CMYK target as it is. if let Some(i) = inks && fmt.mode == photocraft_color::ColorMode::Cmyk - && mode == FillMode::Blend(BlendMode::Normal) + && (mode == FillMode::Blend(BlendMode::Normal) || (mode == FillMode::Behind && d[3] <= 0.0)) && k >= 1.0 { enc[..4].copy_from_slice(&i); @@ -146,6 +157,19 @@ fn composite_area( } } +/// [`FillMode::Behind`] for one pixel: `src` laid under `d` at coverage `k`, with the Brush's +/// Behind formula (`photocraft_paint`'s render): the fill's share is `src α × k × (1 − d α)`. +fn behind(d: [f32; 4], src: [f32; 4], k: f32) -> [f32; 4] { + let da = d[3].clamp(0.0, 1.0); + let underneath = src[3].clamp(0.0, 1.0) * k.clamp(0.0, 1.0) * (1.0 - da); + let alpha = da + underneath; + if da >= 1.0 || alpha <= 0.0 || alpha.is_nan() { + return d; + } + let mix = |c: usize| (d[c] * da + src[c] * underneath) / alpha; + [mix(0), mix(1), mix(2), alpha] +} + /// Gradient tool over `area` (the selection bounds or canvas). #[allow(clippy::too_many_arguments)] pub fn paint_gradient( @@ -312,7 +336,7 @@ fn fill_region( // The ring is only ever read for an unlocked Blend fill (see composite_area), and it is // empty when the region covers every pixel, so do not build it in those cases: on a large // canvas it is a bool per pixel plus a full scan of the mask. - let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_)) && region.mask.contains(&0); + let use_rim = rim && !lock_transparency && matches!(mode, FillMode::Blend(_) | FillMode::Behind) && region.mask.contains(&0); let ring = if use_rim { rim_ring(region) } else { Vec::new() }; let on_ring = |x: i32, y: i32| { let at = usize::try_from(y - b.y0).ok().zip(usize::try_from(x - b.x0).ok()).filter(|_| b.contains(x, y)); @@ -485,6 +509,29 @@ mod tests { assert!(!is_inks(&raw(&s, 3)), "a blended destination keeps its own encoding: {:?}", raw(&s, 3)); } + /// #12531 review: Behind returns an opaque or transparency-locked pixel unchanged, so + /// composite_area must not run it through the RGB encode at all — on a CMYK target the + /// round trip is lossy and shifts the inks of artwork Behind cannot touch. The stored + /// channels stay byte for byte. + #[test] + fn behind_leaves_opaque_and_locked_cmyk_pixels_as_stored() { + let a = Rect::new(0, 0, 8, 1); + let green = |_, _| [0.0, 1.0, 0.0, 1.0]; + // Opaque inks off the conversion lattice: a CMYK -> RGB -> CMYK trip moves them. + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(a, &[0.13, 0.37, 0.71, 0.29, 1.0]); + let before = s.read_region(a); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 255.0, false, false, 1.0, None, false, green, None, FillMode::Behind)); + assert_eq!(s.read_region(a), before, "opaque pixels keep their stored inks"); + + // Locked transparency: a partly transparent pixel is likewise returned unchanged. + let mut s = Surface::new(PixelFormat::CMYKA8); + s.fill_rect(a, &[0.13, 0.37, 0.71, 0.29, 0.5]); + let before = s.read_region(a); + assert!(bucket_fill_inks(&mut s, a, (1, 0), 255.0, false, false, 1.0, None, true, green, None, FillMode::Behind)); + assert_eq!(s.read_region(a), before, "locked pixels keep their stored inks"); + } + /// #11354 review: the soft rim a Clear leaves rises only partly. The reference application /// takes rim alphas 187, 56 and 3 to 204, 211 and 253; the rule here, `α + (1 − α)²`, gives /// 205, 211 and 252, each within one level of it (fit in PR #11354's review round). The rim pixel diff --git a/crates/engine-paint/src/cmd/paint_cmds.rs b/crates/engine-paint/src/cmd/paint_cmds.rs index 7c6c90753b..a787746098 100644 --- a/crates/engine-paint/src/cmd/paint_cmds.rs +++ b/crates/engine-paint/src/cmd/paint_cmds.rs @@ -41,17 +41,18 @@ fn opacity(p: &Value, cmd: &str) -> Result { Ok(crate::eraser_cmds::number(p, cmd, "opacity", 100.0, 1.0..=100.0)? as f32 / 100.0) } -/// The Paint Bucket's `mode`: a blend mode (not Pass Through, a group's) or `clear`. +/// The Paint Bucket's `mode`: a blend mode (not Pass Through, a group's), `behind` or `clear`. fn fill_mode(p: &Value) -> Result { let bad = |msg: String| EngineError::BadParams { cmd: "paint.bucket".into(), msg }; match p.get("mode") { None | Some(Value::Null) => Ok(FillMode::Blend(photocraft_color::BlendMode::Normal)), Some(Value::String(m)) if m.eq_ignore_ascii_case("clear") => Ok(FillMode::Clear), + Some(Value::String(m)) if m.eq_ignore_ascii_case("behind") => Ok(FillMode::Behind), Some(Value::String(m)) => parse_blend(m) .filter(|m| *m != photocraft_color::BlendMode::PassThrough) .map(FillMode::Blend) .ok_or_else(|| bad(format!("unknown blend mode `{m}`"))), - Some(v) => Err(bad(format!("`mode` must be a blend mode name or `clear`, not {v}"))), + Some(v) => Err(bad(format!("`mode` must be a blend mode name, `behind` or `clear`, not {v}"))), } } @@ -275,7 +276,7 @@ pub fn specs() -> Vec { label: "Paint Bucket", menu: &[], shortcut: None, - params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"contents":"foreground|pattern"="foreground","color":"#rrggbb"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":1..100=100,"mode":"normal|multiply|…|clear (erases the filled area)"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, + params: r##"{"x":px,"y":px,"tolerance":0..255=32,"contiguous":bool=true,"antiAlias":bool=true,"sampleAllLayers":bool=false,"contents":"foreground|pattern"="foreground","color":"#rrggbb"=foreground,"pattern":id|name (contents=pattern),"scale":%=100,"angle":deg,"opacity":1..100=100,"mode":"normal|multiply|…|behind (fills only transparency)|clear (erases the filled area)"="normal","target":"pixels"|"mask"|"filterMask"|"quickMask"|{"channel":i}=Channels panel target}"##, enabled: crate::cmd::has_paintable, run: bucket, journal: true, @@ -301,3 +302,6 @@ mod bucket_no_op_history_tests; #[cfg(test)] mod bucket_bitmap_tests; + +#[cfg(test)] +mod bucket_behind_tests; diff --git a/crates/engine-paint/src/cmd/paint_cmds/bucket_behind_tests.rs b/crates/engine-paint/src/cmd/paint_cmds/bucket_behind_tests.rs new file mode 100644 index 0000000000..5425a9fc15 --- /dev/null +++ b/crates/engine-paint/src/cmd/paint_cmds/bucket_behind_tests.rs @@ -0,0 +1,114 @@ +//! #12531: the Paint Bucket's Mode › Behind. +//! +//! The issue's document (800 x 600, white Background, an opaque red square on the active layer +//! "Top", foreground green, Tolerance 32, Anti-alias and Contiguous on) is shrunk to 80 x 60 with +//! the square at 40..60 x 10..30. Measured: Behind changes nothing on the opaque square and fills +//! a transparent area exactly like Normal. Unmeasured cases (semi-transparent pixels, Opacity +//! below 100 %) follow the Brush's Behind: the fill goes under the pixel at +//! `fill α × coverage × (1 − α)`. + +use super::*; +use photocraft_geom::Rect; + +/// The shrunk test document at `depth`, with "Top" active. +fn document(depth: u32) -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Top"})).unwrap(); + s.edit("red square", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(40, 10, 60, 30), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// Paints `color` into `rect` of the active layer, outside history. +fn paint(s: &mut Session, rect: Rect, color: [f32; 4]) { + s.edit("setup", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(rect, &color); + Ok(()) + }) + .unwrap(); +} + +fn pixels(s: &Session) -> Vec { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().read_region(d.doc.bounds()) +} + +fn rgba(s: &Session, x: i32, y: i32) -> [f32; 4] { + let d = s.active().unwrap(); + d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +/// The pixel as 8-bit levels. +fn levels(s: &Session, x: i32, y: i32) -> [i32; 4] { + rgba(s, x, y).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as i32) +} + +fn near(got: [i32; 4], want: [i32; 4]) -> bool { + got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 2) +} + +fn bucket(x: i32, y: i32, mode: &str) -> Value { + json!({"x": x, "y": y, "color": "#00ff00", "tolerance": 32, "antiAlias": true, "contiguous": true, "mode": mode}) +} + +#[test] +fn behind_on_the_opaque_square_changes_nothing() { + for depth in [8, 16, 32] { + let mut s = document(depth); + let before = pixels(&s); + s.execute("paint.bucket", bucket(50, 20, "behind")).unwrap_or_else(|e| panic!("depth {depth}: {e}")); + assert!(pixels(&s) == before, "depth {depth}: the opaque square takes nothing"); + } +} + +#[test] +fn behind_on_transparency_fills_exactly_like_normal_in_one_state() { + for depth in [8, 16, 32] { + let mut normal = document(depth); + normal.execute("paint.bucket", bucket(5, 5, "normal")).unwrap(); + let mut behind = document(depth); + let states = behind.active().unwrap().history.past_len(); + behind.execute("paint.bucket", bucket(5, 5, "behind")).unwrap_or_else(|e| panic!("depth {depth}: {e}")); + assert!(pixels(&behind) == pixels(&normal), "depth {depth}: Behind on transparency is Normal"); + assert_eq!(levels(&behind, 5, 5), [0, 255, 0, 255], "depth {depth}"); + assert_eq!(levels(&behind, 50, 20), [255, 0, 0, 255], "depth {depth}: the square stays"); + let h = &behind.active().unwrap().history; + assert_eq!(h.past_len(), states + 1, "depth {depth}: one state"); + assert_eq!(h.undo_label(), Some("Paint Bucket"), "depth {depth}"); + } +} + +/// Not measured: semi-transparent pixels take the fill underneath, as the Brush's Behind lays it. +/// Black at alpha 0.5, green behind at Opacity 100 → (0, 0.5, 0, 1); at Opacity 50 → the fill's +/// share 0.5 × 0.5 = 0.25 under alpha 0.5: alpha 0.75, green 0.25 / 0.75. +#[test] +fn behind_goes_under_semi_transparent_pixels_like_the_brush() { + for (opacity, want) in [(100, [0, 128, 0, 255]), (50, [0, 85, 0, 191])] { + let mut s = document(8); + paint(&mut s, Rect::new(10, 40, 20, 50), [0.0, 0.0, 0.0, 0.5]); + let mut p = bucket(15, 45, "behind"); + p["opacity"] = json!(opacity); + s.execute("paint.bucket", p).unwrap_or_else(|e| panic!("opacity {opacity}: {e}")); + let got = levels(&s, 15, 45); + assert!(near(got, want), "opacity {opacity}: {got:?}, want {want:?}"); + assert_eq!(levels(&s, 5, 5), [0, 0, 0, 0], "opacity {opacity}: the transparent area is not part of the region"); + } +} + +/// #12528's rim with Behind (rule decided on the issue's own terms): a black alpha-40 edge pixel +/// next to a filled transparent area keeps the rim's coverage `1 − α` and takes the fill under +/// it: about (0, 209, 0, 221), the alpha Normal gives (0, 248, 0, 221), with the black on top. +#[test] +fn behind_lays_the_rim_under_an_edge_pixel() { + for (mode, want) in [("behind", [0, 209, 0, 221]), ("normal", [0, 248, 0, 221])] { + let mut s = document(8); + paint(&mut s, Rect::new(10, 50, 11, 51), [0.0, 0.0, 0.0, 40.0 / 255.0]); + s.execute("paint.bucket", bucket(5, 5, mode)).unwrap_or_else(|e| panic!("{mode}: {e}")); + let got = levels(&s, 10, 50); + assert!(near(got, want), "{mode}: edge {got:?}, want {want:?}"); + } +} diff --git a/crates/ui-egui/src/brush_mode_menu.rs b/crates/ui-egui/src/brush_mode_menu.rs index 8064d1ba62..414144d122 100644 --- a/crates/ui-egui/src/brush_mode_menu.rs +++ b/crates/ui-egui/src/brush_mode_menu.rs @@ -181,6 +181,8 @@ pub(crate) fn current(app: &PhotocraftApp, tool: Tool) -> Option { } Tool::Gradient => Item::Blend(o.gradient_blend_mode), Tool::PaintBucket if o.bucket_clear => Item::Clear, + // This menu has no Behind row for the bucket yet, so no row is checked rather than Normal. + Tool::PaintBucket if o.bucket_behind => Item::Behind, Tool::PaintBucket => Item::Blend(o.bucket_blend_mode), _ => return items(tool).into_iter().find(|i| ui_value(app, *i).is_some_and(|v| v)), }; @@ -280,9 +282,13 @@ pub(crate) fn choose(app: &mut PhotocraftApp, item: Item) { Item::Blend(m) if tool == Tool::Gradient => crate::blend_keys::set_gradient_mode(app, m), Item::Blend(m) if tool == Tool::PaintBucket => { app.ui.tool_options.bucket_clear = false; + app.ui.tool_options.bucket_behind = false; app.ui.tool_options.bucket_blend_mode = m; } - Item::Clear if tool == Tool::PaintBucket => app.ui.tool_options.bucket_clear = true, + Item::Clear if tool == Tool::PaintBucket => { + app.ui.tool_options.bucket_clear = true; + app.ui.tool_options.bucket_behind = false; + } _ => {} } } diff --git a/crates/ui-egui/src/canvas/paint_tool.rs b/crates/ui-egui/src/canvas/paint_tool.rs index c3be4b4911..177a2cbe3a 100644 --- a/crates/ui-egui/src/canvas/paint_tool.rs +++ b/crates/ui-egui/src/canvas/paint_tool.rs @@ -162,6 +162,11 @@ fn clear_off_on_background(app: &mut PhotocraftApp, tool: Tool) { if tool == Tool::Brush && app.ui.tool_options.brush_clear && !app.held_erase && on_background && paint_target(app) == json!("pixels") { app.ui.tool_options.brush_clear = false; } + // The Paint Bucket's Behind is greyed on the Background (#12531), so a bucket click there + // turns it off the same way and the fill goes with the bucket's blend mode. + if tool == Tool::PaintBucket && app.ui.tool_options.bucket_behind && on_background && paint_target(app) == json!("pixels") { + app.ui.tool_options.bucket_behind = false; + } } /// Reports why a Mixer Brush press could not start: the two refusals every press would meet get @@ -191,9 +196,18 @@ fn with_resize(app: &mut PhotocraftApp, f: impl FnOnce(&mut crate::brush_resi fn click_tool(app: &mut PhotocraftApp, tool: Tool, at: [f64; 2]) -> bool { match tool { Tool::PaintBucket => { + // The press path returns before the stroke paths clear-off call, so the buckets + // own clear-off on the Background (#12531) happens here, before the options are read. + clear_off_on_background(app, Tool::PaintBucket); let o = app.ui.tool_options.clone(); let contents = if o.bucket_fill_pattern { "pattern" } else { "foreground" }; - let mode = if o.bucket_clear { "clear" } else { o.bucket_blend_mode.label() }; + let mode = if o.bucket_clear { + "clear" + } else if o.bucket_behind { + "behind" + } else { + o.bucket_blend_mode.label() + }; let params = json!({ "x": at[0].floor(), "y": at[1].floor(), diff --git a/crates/ui-egui/src/input/blend_keys.rs b/crates/ui-egui/src/input/blend_keys.rs index 7ece1ee5d5..caf9ed75ba 100644 --- a/crates/ui-egui/src/input/blend_keys.rs +++ b/crates/ui-egui/src/input/blend_keys.rs @@ -107,6 +107,8 @@ fn set_tool_mode(app: &mut PhotocraftApp, mode: Option) { return; } Tool::PaintBucket => { + // Like the Brush's, any other mode (Clear too) leaves Behind (#12531). + app.ui.tool_options.bucket_behind = false; app.ui.tool_options.bucket_clear = mode.is_none(); if let Some(m) = mode { app.ui.tool_options.bucket_blend_mode = m; diff --git a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs index 1a748c7799..d0129bb9dd 100644 --- a/crates/ui-egui/src/options_bar_mode_wheel_tests.rs +++ b/crates/ui-egui/src/options_bar_mode_wheel_tests.rs @@ -66,3 +66,64 @@ fn the_wheel_over_the_brush_mode_dropdown_steps_the_painting_mode() { wheel(&mut h, at, 4.0); assert_eq!(brush_mode(&h), BlendMode::Normal, "up steps back and stops at the first mode"); } + +/// The centre of a dropdown showing `value`. +fn combo(h: &Harness<'_, Box>, value: &str) -> Option { + h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some(value)).map(|n| n.rect().center()) +} + +/// The Paint Bucket's Mode dropdown has Behind and Clear after Dissolve, as the Brush's does; on +/// the Background both are greyed and the wheel steps past them (#12531). +#[test] +fn the_paint_bucket_mode_dropdown_has_behind_and_clear() { + let mut h = harness(Tool::PaintBucket); + let at = mode_dropdown(&h).center(); + // The new document's Background is active. + wheel(&mut h, at, -1.0); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Dissolve); + wheel(&mut h, at, -1.0); + assert!(!h.state().ui.tool_options.bucket_behind && !h.state().ui.tool_options.bucket_clear, "greyed on the Background"); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Darken); + + let mut h = harness(Tool::PaintBucket); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.run_steps(4); + let at = mode_dropdown(&h).center(); + wheel(&mut h, at, -1.0); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Dissolve); + wheel(&mut h, at, -1.0); + assert!(h.state().ui.tool_options.bucket_behind); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Normal); + wheel(&mut h, at, -1.0); + assert!(h.state().ui.tool_options.bucket_clear && !h.state().ui.tool_options.bucket_behind); + wheel(&mut h, at, -1.0); + assert!(!h.state().ui.tool_options.bucket_clear); + assert_eq!(h.state().ui.tool_options.bucket_blend_mode, BlendMode::Darken); +} + +/// Behind chosen on a pixel layer is the bucket's stored mode, so the Mode control keeps +/// reading Behind after a switch to the Background — greyed in its dropdown menu there +/// (#12531), as the Brush's Clear and the Pattern Stamp's Behind do with theirs — until a +/// bucket click on the Background turns it off (#11897's rule, pinned for the click in +/// `paint_bucket_behind_turns_off_on_the_background`). Switching layers alone clears +/// nothing, so returning to a pixel layer finds Behind still chosen. +#[test] +fn the_paint_bucket_mode_still_reads_behind_on_the_background_until_a_click() { + let mut h = harness(Tool::PaintBucket); + let background = h.state().session.active().unwrap().active_layer.unwrap(); + h.state_mut().run("layer.new.layer", json!({})).unwrap(); + h.run_steps(4); + let pixel = h.state().session.active().unwrap().active_layer.unwrap(); + assert_ne!(pixel, background, "the new pixel layer is active"); + h.state_mut().ui.tool_options.bucket_behind = true; + h.run_steps(4); + assert!(combo(&h, "Behind").is_some(), "Behind reads on a pixel layer"); + h.state_mut().session.active_mut().unwrap().set_active_layer(Some(background)); + h.run_steps(4); + assert!(h.state().ui.tool_options.bucket_behind, "switching to the Background alone does not clear Behind"); + assert!(combo(&h, "Behind").is_some(), "Mode still reads Behind on the Background"); + h.state_mut().session.active_mut().unwrap().set_active_layer(Some(pixel)); + h.run_steps(4); + assert!(h.state().ui.tool_options.bucket_behind, "Behind survives the round trip to the Background"); + assert!(combo(&h, "Behind").is_some(), "and still reads Behind back on a pixel layer"); +} diff --git a/crates/ui-egui/src/panels/options_bar/fill.rs b/crates/ui-egui/src/panels/options_bar/fill.rs index 4bae6f8d9e..000ae25cf6 100644 --- a/crates/ui-egui/src/panels/options_bar/fill.rs +++ b/crates/ui-egui/src/panels/options_bar/fill.rs @@ -48,12 +48,14 @@ pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> blend(BlendMode::Luminosity), ]; } - let keyed: Vec> = if tool == Tool::PatternStamp { - crate::brush_mode_menu::pattern_stamp_choices() + let keyed: Vec> = if tool == Tool::PatternStamp || tool == Tool::PaintBucket { + let choices = if tool == Tool::PatternStamp { crate::brush_mode_menu::pattern_stamp_choices() } else { crate::brush_mode_menu::choices() }; + choices .into_iter() .filter_map(|((mode, behind), _)| match (mode, behind) { (Some(blend), false) => Some(crate::panels::blend_entry(PaintMode::Blend(blend), blend)), (None, true) => Some(BlendKeyEntry::behind(PaintMode::Behind)), + (None, false) => Some(BlendKeyEntry::clear(PaintMode::Clear)), _ => None, }) .collect() @@ -72,7 +74,7 @@ pub(crate) fn mode_entries(tool: Tool, behind_enabled: bool, threshold: bool) -> key => label_of(key).into(), }) .into_iter() - .map(|entry| if entry.value() == Some(&PaintMode::Behind) { entry.enabled(behind_enabled) } else { entry }) + .map(|entry| if matches!(entry.value(), Some(&PaintMode::Behind) | Some(&PaintMode::Clear)) { entry.enabled(behind_enabled) } else { entry }) .collect() }) } @@ -98,25 +100,40 @@ pub(super) fn members(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if app.ui.tool != Tool::PaintBucket { return; } - let entries = mode_entries(Tool::PaintBucket, true, false); + let entries = mode_entries(Tool::PaintBucket, crate::brush_mode_menu::enabled(app, crate::brush_mode_menu::Item::Behind), false); let sources = [Entry::new(false, tl!("Foreground").to_owned()), Entry::new(true, tl!("Pattern").to_owned())]; // The Source dropdown stands alone, without a caption, as in the reference. Select::new(tl!("Source").to_owned(), bind_tracked!(app.ui.tool_options => bucket_fill_pattern), &sources) .tooltip(tl!("Set source for fill area").to_owned()) .show(ui); let o = &app.ui.tool_options; - let shown = if o.bucket_clear { PaintMode::Clear } else { PaintMode::Blend(o.bucket_blend_mode) }; + let shown = if o.bucket_clear { + PaintMode::Clear + } else if o.bucket_behind { + PaintMode::Behind + } else { + PaintMode::Blend(o.bucket_blend_mode) + }; let mut mode = shown; labelled(ui, tl!("Mode"), |ui| mode_select(Bind::bound(&mut mode), &entries).tooltip(tl!("Fill Mode").to_owned()).show(ui)); if mode != shown { let o = &mut app.ui.tool_options; match mode { - PaintMode::Clear => o.bucket_clear = true, + PaintMode::Clear => { + o.bucket_clear = true; + o.bucket_behind = false; + } PaintMode::Blend(blend) => { o.bucket_clear = false; + o.bucket_behind = false; o.bucket_blend_mode = blend; } - PaintMode::Behind => {} + PaintMode::Behind => { + o.bucket_clear = false; + o.bucket_behind = true; + // Behind names no blend: the stored mode reads Normal while it is chosen (#12531). + o.bucket_blend_mode = BlendMode::Normal; + } // Replace belongs to the Healing Brush's list, never the Paint Bucket's. PaintMode::HealingReplace => {} } diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 463ed44dbe..69931ee156 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -69,6 +69,10 @@ pub struct ToolOptions { pub bucket_blend_mode: photocraft_color::BlendMode, /// Paint Bucket › Mode: Clear, which erases the filled area (see `brush_clear`). pub bucket_clear: bool, + /// Paint Bucket › Mode: Behind, which fills only the pixels' transparency (#12531). Picking + /// it sets `bucket_blend_mode` to Normal, as the Brush's Behind does; picking any other mode + /// leaves it. + pub bucket_behind: bool, /// Type tool: family, style name, size (pt), anti-aliasing and paragraph alignment. pub type_font: String, pub type_style: String, @@ -484,6 +488,7 @@ impl Default for ToolOptions { bucket_fill_pattern: false, bucket_blend_mode: photocraft_color::BlendMode::Normal, bucket_clear: false, + bucket_behind: false, type_font: "Inter".into(), type_style: "Regular".into(), type_size: 50.0, diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index 6b8e32d9c8..cf362c814a 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -311,6 +311,55 @@ fn dab_tools_send_their_bar_values() { } } +/// The Paint Bucket's Mode reaches the fill: Multiply darkens, Clear erases. +#[test] +fn paint_bucket_mode_reaches_the_fill() { + let mut app = app(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app.session.tools.foreground = [0.5, 0.5, 0.5, 1.0]; + let click = |app: &mut PhotocraftApp| { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); + }; + click(&mut app); + app.session.tools.foreground = [1.0, 0.0, 0.0, 1.0]; + app.ui.tool_options.bucket_blend_mode = photocraft_color::BlendMode::Multiply; + click(&mut app); + let px = active(&app).surface().unwrap().rgba(20, 20); + assert!((px[0] - 0.5).abs() < 0.02 && px[1] < 0.02, "multiplied: {px:?}"); + app.ui.tool_options.bucket_clear = true; + click(&mut app); + assert_eq!(app.session.journal.last().unwrap().1["mode"], "clear"); + assert!(active(&app).surface().unwrap().rgba(20, 20)[3] < 0.01, "cleared"); + // Behind (#12531) fills the cleared transparency as Normal would. + app.ui.tool_options.bucket_clear = false; + app.ui.tool_options.bucket_behind = true; + click(&mut app); + assert_eq!(app.session.journal.last().unwrap().1["mode"], "behind"); + let px = active(&app).surface().unwrap().rgba(20, 20); + assert!(px[0] > 0.98 && px[3] > 0.98, "filled behind: {px:?}"); +} + +/// Behind is greyed on the Background (#12531): a bucket click there turns it off, as the +/// Brush's Clear is turned off (#11897), so the fill is sent with the blend mode and the +/// stored option no longer names a mode the Background cannot use. +#[test] +fn paint_bucket_behind_turns_off_on_the_background() { + let mut app = app(); + let background = app.session.active().unwrap().active_layer.unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.ui.tool = Tool::PaintBucket; + app.ui.tool_options.bucket_behind = true; + app.session.active_mut().unwrap().set_active_layer(Some(background)); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 20.0, y: 20.0 }, m); + assert!(!app.ui.tool_options.bucket_behind, "Behind turns off on the Background"); + assert_eq!(app.session.journal.last().unwrap().1["mode"], "Normal"); +} + #[test] fn retouch_strokes_paint_the_targeted_mask() { // #207: with the mask targeted, retouching changes the mask, never the pixels. diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index 9b2f5bb21f..3a052a56dd 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -227,7 +227,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), Tool::Gradient => reset!(gradient_style, gradient_reverse, gradient_dither, gradient_classic, gradient_blend_mode, fill_opacity), - Tool::PaintBucket => reset!(bucket_fill_pattern, bucket_blend_mode, bucket_clear, fill_opacity, tolerance, anti_alias, contiguous), + Tool::PaintBucket => reset!(bucket_fill_pattern, bucket_blend_mode, bucket_clear, bucket_behind, fill_opacity, tolerance, anti_alias, contiguous), Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { reset!(type_font, type_style, type_size, type_aa, type_align, type_direction, type_style_defaults) }