From e0194f143e8de8a383d86fee6d1045f9402f559f Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 00:49:22 +0100 Subject: [PATCH 1/4] WIP: Tools: add the Adjustment Brush Tool (#12519) From 8e54fc2df3af8c3e816939874730d216f8b657a1 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:04:59 +0100 Subject: [PATCH 2/4] Engine: paint.adjustmentBrush, the Adjustment Brush Tool's stroke (#12519) --- crates/engine/src/cmd.rs | 4 + .../engine/src/cmd/adjustment_brush_cmds.rs | 263 +++++++++++++++ .../src/cmd/adjustment_brush_cmds_tests.rs | 302 ++++++++++++++++++ crates/engine/src/cmd/brush_cmds.rs | 6 + crates/engine/src/cmd/channel_cmds.rs | 2 +- .../engine/src/cmd/channel_cmds/targeting.rs | 5 + crates/engine/src/lib.rs | 1 + 7 files changed, 582 insertions(+), 1 deletion(-) create mode 100644 crates/engine/src/cmd/adjustment_brush_cmds.rs create mode 100644 crates/engine/src/cmd/adjustment_brush_cmds_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index d44758cd52..b6ed6ed878 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -58,6 +58,9 @@ pub mod actions_cmds; pub mod actions_edit_cmds; pub mod adjust_cmds; mod adjust_params; +pub mod adjustment_brush_cmds; +#[cfg(test)] +mod adjustment_brush_cmds_tests; pub mod align_cmds; pub mod analysis_cmds; pub mod artboard_cmds; @@ -1375,6 +1378,7 @@ fn build() -> Vec { v.extend(crate::actions_edit_cmds::specs()); v.extend(crate::swatch_cmds::specs()); v.extend(crate::retouch_cmds::specs()); + v.extend(crate::adjustment_brush_cmds::specs()); v.extend(crate::redeye_cmds::specs()); v.extend(crate::image_cmds::specs()); v.extend(crate::perspective_crop_cmds::specs()); diff --git a/crates/engine/src/cmd/adjustment_brush_cmds.rs b/crates/engine/src/cmd/adjustment_brush_cmds.rs new file mode 100644 index 0000000000..73c228f46e --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds.rs @@ -0,0 +1,263 @@ +//! The Adjustment Brush Tool (#12519): painting on the image makes an adjustment layer whose mask +//! is what was painted, or paints into the mask of the active adjustment layer of the chosen kind. +//! The kinds it offers, which of them a document's colour mode and bit depth grey out, and the +//! starting values a new layer gets, as measured in the reference application. + +use photocraft_doc::{Adjustment, ColorMode, Layer, LayerContent, LayerMask, SampleType}; +use serde_json::{Value, json}; + +use super::adjust_params::adjustment_kind; +use super::layer_params::{mask_at_depth, selection_mask}; +use crate::commands::CommandSpec; +use crate::{EngineError, Result, Session}; + +const CMD: &str = "paint.adjustmentBrush"; + +/// The history state of a stroke that makes the layer. +pub const NEW_LAYER_LABEL: &str = "New Adjustment Layer"; +/// The history state of a stroke into an existing adjustment layer's mask. +pub const STROKE_LABEL: &str = "Adjustment Brush"; + +/// The alert a stroke on an Indexed Color document shows; nothing changes. +pub const INDEXED_ALERT: &str = + "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; + +/// One entry of the options bar's Adjustment dropdown: the kind id (the `layer.newAdjustmentLayer` +/// suffix for the kinds that exist), its label, and whether a separator follows it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Entry { + pub kind: &'static str, + pub label: &'static str, + pub separator_after: bool, +} + +const fn entry(kind: &'static str, label: &'static str, separator_after: bool) -> Entry { + Entry { kind, label, separator_after } +} + +/// The dropdown in the reference application's order, separators after Grain, Exposure and +/// Selective Color. +pub const ENTRIES: [Entry; 18] = [ + entry("light", "Light", false), + entry("colorVibrance", "Color and vibrance", false), + entry("clarityDehaze", "Clarity and dehaze", false), + entry("grain", "Grain", true), + entry("levels", "Levels", false), + entry("curves", "Curves", false), + entry("exposure", "Exposure", true), + entry("hueSaturation", "Hue/Saturation", false), + entry("colorBalance", "Color Balance", false), + entry("blackWhite", "Black & White", false), + entry("photoFilter", "Photo Filter", false), + entry("channelMixer", "Channel Mixer", false), + entry("colorLookup", "Color Lookup", false), + entry("selectiveColor", "Selective Color", true), + entry("invert", "Invert", false), + entry("posterize", "Posterize", false), + entry("threshold", "Threshold", false), + entry("gradientMap", "Gradient Map", false), +]; + +/// Entries whose adjustment doesn't exist yet: always greyed. +const MISSING: [&str; 4] = ["light", "colorVibrance", "clarityDehaze", "grain"]; + +/// The entry the tool starts on: the reference application's default (Light) while it is +/// available, else the first enabled entry. +pub const DEFAULT_KIND: &str = "levels"; + +/// The entry with id `kind`. +pub fn entry_of(kind: &str) -> Option<&'static Entry> { + ENTRIES.iter().find(|e| e.kind == kind) +} + +/// Is `kind` offered (not greyed) in a document of `mode` and `depth`? Indexed Color refuses +/// the stroke as a whole ([`INDEXED_ALERT`]), so its entries stay as RGB's. Bitmap, Duotone and +/// Multichannel were not measured and grey nothing extra. +pub fn enabled_in(kind: &str, mode: ColorMode, depth: SampleType) -> bool { + if entry_of(kind).is_none() || MISSING.contains(&kind) { + return false; + } + let greyed: &[&str] = match mode { + ColorMode::Grayscale => &["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"], + ColorMode::Cmyk => &["exposure", "blackWhite"], + ColorMode::Lab => &["exposure", "blackWhite", "channelMixer", "selectiveColor"], + _ => &[], + }; + let float: &[&str] = if depth == SampleType::F32 { &["invert", "posterize", "threshold", "gradientMap"] } else { &[] }; + !greyed.contains(&kind) && !float.contains(&kind) +} + +/// The kind the dropdown shows when `kind` is greyed in this document: `kind` itself when it is +/// offered, else the first offered entry. +pub fn offered_kind<'a>(kind: &'a str, mode: ColorMode, depth: SampleType) -> &'a str { + if enabled_in(kind, mode, depth) { + return kind; + } + ENTRIES.iter().map(|e| e.kind).find(|k| enabled_in(k, mode, depth)).unwrap_or(kind) +} + +/// The params of the starting values a layer of `kind` gets (the layer already changes the +/// image; these are not Layer › New Adjustment Layer's identity values). Color Lookup starts on a +/// built-in film look: the reference application ships its own film-stock table, which is not +/// ours to copy. +pub fn starting_params(kind: &str) -> Option { + Some(match kind { + "levels" => json!({"inBlack": 20, "gamma": 1.0, "inWhite": 220, "outBlack": 0, "outWhite": 255}), + "curves" => json!({"points": [[0, 0], [127, 191], [255, 255]]}), + "exposure" => json!({"exposure": 1.0, "offset": 0.0, "gamma": 1.0}), + "hueSaturation" => json!({"hue": 0, "saturation": 30, "lightness": 0, "colorize": false}), + "colorBalance" => json!({"shadows": [0, 0, 0], "midtones": [20, -15, 15], "highlights": [0, 0, 0], "preserveLuminosity": true}), + "blackWhite" => json!({"reds": 40, "yellows": 60, "greens": 40, "cyans": 60, "blues": 20, "magentas": 80, "tint": false}), + // Warming Filter (85), the reference application's Lab (67.06, 32, 120) shown in sRGB. + "photoFilter" => json!({"filter": "warming85", "density": 25, "preserveLuminosity": true}), + "channelMixer" => json!({"red": [80, 10, 10, 5], "green": [0, 100, 0, 0], "blue": [0, 0, 100, 0], "monochrome": false}), + "colorLookup" => json!({"lut": "fadedFilm"}), + "selectiveColor" => json!({"method": "relative", "reds": [-20, 100, -60, 40]}), + "invert" => json!({}), + "posterize" => json!({"levels": 4}), + "threshold" => json!({"level": 128}), + "gradientMap" => json!({"stops": [[0, "#000000"], [1, "#ffffff"]], "reverse": false, "dither": false}), + _ => return None, + }) +} + +fn bad(msg: impl Into) -> EngineError { + EngineError::BadParams { cmd: CMD.into(), msg: msg.into() } +} + +/// The adjustment a new layer of `kind` starts with in a document of `mode`. +pub fn starting_adjustment(kind: &str, mode: ColorMode) -> Result { + let p = starting_params(kind).ok_or_else(|| bad(format!("`{kind}` is not available yet")))?; + crate::adjust_params::from_params(kind, &p, None, mode) +} + +/// The mask colours of the stroke: white adds the adjustment, black (Subtract) takes it away. +fn paint_colors(subtract: bool) -> ([f32; 4], [f32; 4]) { + let (white, black) = ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]); + if subtract { (black, white) } else { (white, black) } +} + +/// The kind of the active layer when it is an adjustment layer (the dropdown follows it). +pub fn active_kind(s: &Session) -> Option<&'static str> { + let st = s.active()?; + let layer = st.doc.layer(st.active_layer?)?; + match &layer.content { + LayerContent::Adjustment(adj) => Some(adjustment_kind(adj)).filter(|k| entry_of(k).is_some()), + _ => None, + } +} + +fn kind_param(p: &Value) -> Result<&str> { + match p.get("kind") { + None | Some(Value::Null) => Ok(DEFAULT_KIND), + Some(Value::String(k)) => entry_of(k).map(|e| e.kind).ok_or_else(|| bad(format!("unknown adjustment `{k}`"))), + Some(other) => Err(bad(format!("`kind` must be an adjustment id, not {other}"))), + } +} + +fn subtract_param(p: &Value) -> Result { + match p.get("subtract") { + None | Some(Value::Null) => Ok(false), + Some(v) => v.as_bool().ok_or_else(|| bad("`subtract` must be true or false")), + } +} + +/// `paint.adjustmentBrush`. +fn run(s: &mut Session, p: &Value) -> Result { + if !p.is_object() { + return Err(bad("params must be an object")); + } + let (mode, depth) = { + let st = s.active().ok_or(EngineError::NoDocument)?; + (st.doc.mode, st.doc.depth) + }; + if mode == ColorMode::Indexed { + return Err(EngineError::Other(INDEXED_ALERT.into())); + } + let kind = kind_param(p)?; + if MISSING.contains(&kind) { + return Err(bad(format!("`{kind}` is not available yet"))); + } + if !enabled_in(kind, mode, depth) { + return Err(bad(format!("`{kind}` is not available in this document's color mode or bit depth"))); + } + let subtract = subtract_param(p)?; + let (fg, bg) = paint_colors(subtract); + // The stroke params without the tool's own keys, painting the mask in its colour. + let mut q = p.clone(); + if let Some(o) = q.as_object_mut() { + o.remove("kind"); + o.remove("subtract"); + o.remove("erase"); + o.remove("mode"); + o.remove("fill"); + o.insert("color".into(), json!([fg[0], fg[1], fg[2]])); + o.insert("target".into(), json!("mask")); + } + let pts = super::brush_cmds::parse_points(&q, CMD)?; + let mut brush = super::brush_cmds::resolve_brush(s, &q, CMD)?; + brush.color = fg; + brush.color_cmyk = None; + brush.erase = false; + brush.mode = photocraft_color::BlendMode::Normal; + brush.behind = false; + let zoom = q.get("zoom").and_then(Value::as_f64).filter(|z| z.is_finite() && *z > 0.0).unwrap_or(1.0) as f32; + + // An adjustment layer of this kind with a mask is active: paint into its mask. + let paints_active = active_kind(s) == Some(kind) + && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); + let result = if paints_active { + let mut r = super::brush_cmds::stroke_into(s, CMD, &q, STROKE_LABEL, brush, pts)?; + r["created"] = json!(false); + r + } else { + let adj = starting_adjustment(kind, mode)?; + let label = entry_of(kind).map_or(kind, |e| e.label); + let (id, damage) = s.edit(NEW_LAYER_LABEL, |doc, active| { + let mut l = Layer::new(doc.next_layer_name(label), LayerContent::Adjustment(adj)); + // The selection becomes the mask and goes away; the stroke adds to it unclipped. + let (mut mask, revealed) = match selection_mask(doc)? { + Some(mask) => { + let revealed = doc.selection.take().map_or(photocraft_geom::Rect::EMPTY, |sel| sel.content_bounds()); + (mask, revealed) + } + None => (mask_at_depth(LayerMask::hide_all(), doc.depth)?, photocraft_geom::Rect::EMPTY), + }; + let clip = doc.bounds().union(&mask.surface.tile_bounds()); + let painted = photocraft_paint::render_stroke_clipped(&mut mask.surface, &brush, &pts, None, false, zoom, Some(clip)); + l.mask = Some(mask); + let id = crate::layer_place::insert_new(doc, *active, l, crate::layer_place::Place::Auto); + *active = Some(id); + // The image changes where the mask reveals the adjustment: the selection and the stroke. + Ok((id, painted.union(&revealed).intersect(&doc.bounds()))) + })?; + s.hint_damage(damage); + json!({"layer": id.0, "created": true, "damage": [damage.x0, damage.y0, damage.width(), damage.height()]}) + }; + // The new layer's mask is the target, and the colours are the stroke's. + super::channel_cmds::target_layer_mask(s); + s.tools.foreground = fg; + s.tools.background = bg; + Ok(result) +} + +/// Enabled with a document open. +fn enabled(s: &Session) -> std::result::Result<(), String> { + if s.active().is_none() { + return Err("no document".into()); + } + Ok(()) +} + +pub fn specs() -> Vec { + vec![CommandSpec { + id: CMD, + label: "Adjustment Brush", + menu: &[], + shortcut: None, + params: r#"{"kind":"levels|curves|exposure|hueSaturation|colorBalance|blackWhite|photoFilter|channelMixer|colorLookup|selectiveColor|invert|posterize|threshold|gradientMap"="levels","subtract":bool=false (paint black: remove the adjustment),"points":[[x,y,pressure?],…],"size":px=tool size,"hardness":0..1,"opacity":0..1,"flow":0..1,"smoothing":0..1,"seed":u64?,"zoom":number=1} → {"layer"?,"created":bool,"damage"?} (with an adjustment layer of this kind active, the stroke paints its mask; else it makes the layer above the active one, its mask black or the selection, and paints the stroke white)"#, + enabled, + run, + journal: true, + }] +} diff --git a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs new file mode 100644 index 0000000000..c88936af84 --- /dev/null +++ b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs @@ -0,0 +1,302 @@ +//! Tests of `paint.adjustmentBrush`, the Adjustment Brush Tool's stroke (#12519). Reference +//! values measured in the reference application: a 100 px soft dab centred at (600, 450) on an +//! 1200 x 900 document. + +use photocraft_doc::{Adjustment, ColorMode, LayerContent, SampleType}; +use serde_json::{Value, json}; + +use super::adjustment_brush_cmds::{ENTRIES, INDEXED_ALERT, NEW_LAYER_LABEL, STROKE_LABEL, enabled_in, starting_adjustment}; +use crate::Session; + +const CMD: &str = "paint.adjustmentBrush"; + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1200, "height": 900, "background": "white"})).unwrap(); + s +} + +fn dab(kind: &str) -> Value { + json!({"kind": kind, "points": [[600, 450, 1.0]], "size": 100, "hardness": 0.0, "opacity": 1.0, "flow": 1.0}) +} + +fn active(s: &Session) -> &photocraft_doc::Layer { + let st = s.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn mask_at(s: &Session, x: i32, y: i32) -> f32 { + active(s).mask.as_ref().expect("a layer mask").surface.sample_channel(x, y, 0) * 255.0 +} + +fn layer_count(s: &Session) -> usize { + s.active().unwrap().doc.walk().len() +} + +fn past(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +#[test] +fn first_stroke_makes_a_masked_adjustment_layer_in_one_history_state() { + let mut s = doc(); + let before = (layer_count(&s), past(&s)); + let bg = s.active().unwrap().active_layer.unwrap(); + let r = s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(r["created"], json!(true)); + assert_eq!(layer_count(&s), before.0 + 1); + assert_eq!(past(&s), before.1 + 1, "one history state"); + let st = s.active().unwrap(); + assert_eq!(st.history.undo_label(), Some(NEW_LAYER_LABEL)); + let l = active(&s); + assert_eq!(l.name, "Levels 1"); + assert!(matches!(l.content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert_eq!((l.blend, l.opacity, l.clipped), (photocraft_doc::BlendMode::Normal, 1.0, false)); + // Directly above the Background. + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order, vec![bg, l.id]); + // Black outside the dab, white at its centre. + assert_eq!(mask_at(&s, 10, 10), 0.0); + assert_eq!(mask_at(&s, 680, 450), 0.0); + assert!(mask_at(&s, 600, 450) >= 250.0, "centre {}", mask_at(&s, 600, 450)); + // The mask is the target, white over black. + assert!(st.channel_view.target == crate::channel_cmds::ChannelTarget::LayerMask); + assert_eq!((s.tools.foreground, s.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn a_soft_dab_falls_off_like_the_reference() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + // The reference row: 550: 22, 570: 119, 590: 237, 600: 254, 620: 172, 640: 52, 660: 2, 670: 0. + let row: Vec = [550, 570, 590, 600, 620, 640, 660, 670].iter().map(|&x| mask_at(&s, x, 450)).collect(); + for w in row[..4].windows(2) { + assert!(w[0] <= w[1], "rises to the centre: {row:?}"); + } + for w in row[3..].windows(2) { + assert!(w[0] >= w[1], "falls off past it: {row:?}"); + } + assert!(row[7] <= 3.0 && row[0] < 128.0 && row[3] > 240.0, "{row:?}"); +} + +#[test] +fn layer_names_count_per_label() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + s.execute(CMD, dab("blackWhite")).unwrap(); + assert_eq!(active(&s).name, "Black & White 1"); + s.execute("layer.select", json!({"layer": {"background": true}})).unwrap(); + s.execute(CMD, dab("levels")).unwrap(); + assert_eq!(active(&s).name, "Levels 2"); +} + +#[test] +fn the_selection_becomes_the_mask_and_the_dab_is_not_clipped_to_it() { + let mut s = doc(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 400, "height": 900})).unwrap(); + let before = past(&s); + s.execute(CMD, json!({"kind": "curves", "points": [[400, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(past(&s), before + 1, "still one history state"); + assert!(s.active().unwrap().doc.selection.is_none(), "the selection is gone"); + assert_eq!(mask_at(&s, 100, 100), 255.0, "inside the selection"); + assert_eq!(mask_at(&s, 900, 100), 0.0, "outside it"); + // The dab reaches past the selection edge at x 400. + assert!(mask_at(&s, 420, 450) > 100.0, "{}", mask_at(&s, 420, 450)); +} + +#[test] +fn inside_an_active_group_the_layer_goes_into_the_group() { + let mut s = doc(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.execute("layer.groupLayers", json!({})).unwrap(); + let group = s.active().unwrap().active_layer.unwrap(); + // An open group takes new layers, as Layer › New Adjustment Layer puts them. + s.execute("layer.setExpanded", json!({"expanded": true})).unwrap(); + s.execute(CMD, dab("invert")).unwrap(); + let id = active(&s).id; + let st = s.active().unwrap(); + let children = st.doc.layer(group).and_then(|g| g.children()).unwrap(); + assert!(children.iter().any(|l| l.id == id), "the new layer is inside the group"); +} + +#[test] +fn starting_values_are_read_back_from_the_new_layer() { + for e in ENTRIES.iter().filter(|e| enabled_in(e.kind, ColorMode::Rgb, SampleType::U8)) { + let mut s = doc(); + s.execute(CMD, dab(e.kind)).unwrap(); + let LayerContent::Adjustment(adj) = &active(&s).content else { panic!("{}: an adjustment layer", e.kind) }; + assert_eq!(adj.label(), e.label, "{}", e.kind); + assert_eq!(*adj, starting_adjustment(e.kind, ColorMode::Rgb).unwrap(), "{}", e.kind); + } +} + +#[test] +fn starting_values_match_the_reference() { + let close = |a: f32, b: f32| (a - b).abs() < 1e-3; + let adj = |kind: &str| starting_adjustment(kind, ColorMode::Rgb).unwrap(); + let Adjustment::Levels { master, .. } = adj("levels") else { panic!() }; + assert!(close(master.in_black * 255.0, 20.0) && close(master.in_white * 255.0, 220.0) && close(master.gamma, 1.0)); + assert!(close(master.out_black, 0.0) && close(master.out_white, 1.0)); + let Adjustment::Curves { master, .. } = adj("curves") else { panic!() }; + let pts: Vec<(f32, f32)> = master.iter().map(|p| (p.input * 255.0, p.output * 255.0)).collect(); + assert_eq!(pts.len(), 3); + assert!(close(pts[1].0, 127.0) && close(pts[1].1, 191.0), "{pts:?}"); + assert_eq!(adj("exposure"), Adjustment::Exposure { exposure: 1.0, offset: 0.0, gamma: 1.0 }); + let Adjustment::HueSaturation { hue, saturation, lightness, colorize, .. } = adj("hueSaturation") else { panic!() }; + assert_eq!((hue, saturation, lightness, colorize), (0.0, 30.0, 0.0, false)); + let Adjustment::ColorBalance { shadows, midtones, highlights, preserve_luminosity } = adj("colorBalance") else { panic!() }; + assert_eq!((shadows, midtones, highlights, preserve_luminosity), ([0.0; 3], [20.0, -15.0, 15.0], [0.0; 3], true)); + assert_eq!(adj("blackWhite"), Adjustment::BlackWhite { weights: [40.0, 60.0, 40.0, 60.0, 20.0, 80.0], tint: None }); + let Adjustment::PhotoFilter { density, preserve_luminosity, .. } = adj("photoFilter") else { panic!() }; + assert!(close(density, 0.25) && preserve_luminosity); + let Adjustment::ChannelMixer { matrix, monochrome } = adj("channelMixer") else { panic!() }; + assert!(!monochrome); + let want = [[0.8, 0.1, 0.1, 0.05], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + assert!(matrix.iter().flatten().zip(want.iter().flatten()).all(|(a, b)| close(*a, *b)), "{matrix:?}"); + assert!(matches!(adj("colorLookup"), Adjustment::ColorLookup { lut: Some(_), .. })); + let Adjustment::SelectiveColor { relative, adjustments } = adj("selectiveColor") else { panic!() }; + assert!(relative); + assert_eq!(adjustments[0], [-20.0, 100.0, -60.0, 40.0]); + assert_eq!(adj("invert"), Adjustment::Invert); + assert_eq!(adj("posterize"), Adjustment::Posterize { levels: 4 }); + assert!(matches!(adj("threshold"), Adjustment::Threshold { level } if close(level * 255.0, 128.0))); + let Adjustment::GradientMap { stops, reverse, dither, .. } = adj("gradientMap") else { panic!() }; + assert_eq!((stops.first().map(|s| s.1), stops.last().map(|s| s.1), reverse, dither), (Some([0.0; 3]), Some([1.0; 3]), false, false)); +} + +#[test] +fn a_later_stroke_paints_the_active_layers_mask() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let (id, n, depth) = (active(&s).id, layer_count(&s), past(&s)); + assert_eq!(mask_at(&s, 900, 450), 0.0); + let r = s.execute(CMD, json!({"kind": "levels", "points": [[900, 450, 1.0]], "size": 100, "hardness": 0.0})).unwrap(); + assert_eq!(r["created"], json!(false)); + assert_eq!((active(&s).id, layer_count(&s), past(&s)), (id, n, depth + 1), "no new layer, one more state"); + assert_eq!(s.active().unwrap().history.undo_label(), Some(STROKE_LABEL)); + assert!(mask_at(&s, 900, 450) >= 250.0); +} + +#[test] +fn a_layer_made_by_new_adjustment_layer_takes_the_stroke_too() { + let mut s = doc(); + s.execute("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + let (id, n) = (active(&s).id, layer_count(&s)); + s.execute(CMD, dab("curves")).unwrap(); + assert_eq!((active(&s).id, layer_count(&s)), (id, n)); +} + +#[test] +fn another_kind_makes_a_new_layer_above_the_active_one() { + let mut s = doc(); + s.execute(CMD, dab("levels")).unwrap(); + let first = active(&s).id; + s.execute(CMD, dab("exposure")).unwrap(); + let st = s.active().unwrap(); + let order: Vec<_> = st.doc.layers.iter().map(|l| l.id).collect(); + assert_eq!(order.len(), 3); + assert_eq!(order[1], first); + assert_eq!(active(&s).name, "Exposure 1"); +} + +#[test] +fn subtract_paints_black_and_swaps_the_colours() { + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[600, 450], [800, 450]], "size": 100, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0); + s.execute(CMD, json!({"kind": "levels", "subtract": true, "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert_eq!(mask_at(&s, 700, 450), 0.0); + assert!(mask_at(&s, 610, 450) >= 250.0, "the rest stays"); + assert_eq!((s.tools.foreground, s.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + s.execute(CMD, json!({"kind": "levels", "points": [[700, 450]], "size": 40, "hardness": 1.0})).unwrap(); + assert!(mask_at(&s, 700, 450) >= 250.0, "Add paints white again"); + assert_eq!(s.tools.foreground, [1.0, 1.0, 1.0, 1.0]); +} + +#[test] +fn entries_grey_out_per_mode_and_depth() { + let off = |mode, depth| -> Vec<&str> { ENTRIES.iter().map(|e| e.kind).filter(|k| !enabled_in(k, mode, depth)).collect() }; + let missing = ["light", "colorVibrance", "clarityDehaze", "grain"]; + let with = |more: &[&'static str]| -> Vec<&'static str> { + ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() + }; + assert_eq!(off(ColorMode::Rgb, SampleType::U8), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::U16), with(&[])); + assert_eq!(off(ColorMode::Rgb, SampleType::F32), with(&["invert", "posterize", "threshold", "gradientMap"])); + assert_eq!( + off(ColorMode::Grayscale, SampleType::U8), + with(&["hueSaturation", "colorBalance", "blackWhite", "photoFilter", "channelMixer", "colorLookup", "selectiveColor"]) + ); + assert_eq!(off(ColorMode::Cmyk, SampleType::U8), with(&["exposure", "blackWhite"])); + assert_eq!(off(ColorMode::Lab, SampleType::U8), with(&["exposure", "blackWhite", "channelMixer", "selectiveColor"])); +} + +#[test] +fn a_greyed_entry_is_refused_and_an_offered_one_works_in_other_modes() { + for (mode, refused, works) in [ + ("image.mode.grayscale", "hueSaturation", "levels"), + ("image.mode.cmyk", "exposure", "curves"), + ("image.mode.lab", "channelMixer", "invert"), + ("image.mode.bits32", "posterize", "exposure"), + ("image.mode.bits16", "", "gradientMap"), + ] { + let mut s = doc(); + s.execute(mode, json!({})).unwrap(); + if !refused.is_empty() { + let before = layer_count(&s); + assert!(s.execute(CMD, dab(refused)).is_err(), "{mode}: {refused}"); + assert_eq!(layer_count(&s), before); + } + s.execute(CMD, dab(works)).unwrap_or_else(|e| panic!("{mode}: {works}: {e}")); + assert!(matches!(active(&s).content, LayerContent::Adjustment(_))); + } +} + +#[test] +fn indexed_color_refuses_the_stroke_with_the_alert() { + let mut s = doc(); + s.execute("image.mode.indexedColor", json!({})).unwrap(); + let (n, depth) = (layer_count(&s), past(&s)); + let e = s.execute(CMD, dab("levels")).unwrap_err().to_string(); + assert!(e.contains(INDEXED_ALERT), "{e}"); + assert_eq!((layer_count(&s), past(&s)), (n, depth), "nothing changes"); +} + +#[test] +fn bad_params_are_errors_not_panics() { + let mut s = Session::new(); + assert!(s.execute(CMD, dab("levels")).is_err(), "no document"); + let mut s = doc(); + for p in [ + json!(null), + json!([]), + json!("levels"), + json!({}), + json!({"kind": "levels"}), + json!({"kind": "levels", "points": []}), + json!({"kind": "levels", "points": "x"}), + json!({"kind": "levels", "points": [[f64::MAX, 1.0]]}), + json!({"kind": "levels", "points": [[1e30, -1e30]]}), + json!({"kind": "light", "points": [[10, 10]]}), + json!({"kind": "grain", "points": [[10, 10]]}), + json!({"kind": "nope", "points": [[10, 10]]}), + json!({"kind": 7, "points": [[10, 10]]}), + json!({"kind": "levels", "subtract": "yes", "points": [[10, 10]]}), + json!({"kind": "levels", "points": [[10, 10]], "size": -5}), + json!({"kind": "levels", "points": [[10, 10]], "size": 1e12}), + json!({"kind": "levels", "points": [[10, 10]], "zoom": -1}), + json!({"kind": "levels", "points": [[10, 10]], "preset": "no such preset"}), + json!({"kind": "levels", "points": [[10, 10]], "brush": {"size": "big"}}), + ] { + let _ = s.execute(CMD, p.clone()); + } + for p in [json!({"kind": "light", "points": [[10, 10]]}), json!({"kind": "nope", "points": [[10, 10]]}), json!({"kind": "levels", "subtract": 1})] { + let n = layer_count(&s); + assert!(s.execute(CMD, p).is_err()); + assert_eq!(layer_count(&s), n, "a refused stroke leaves no layer behind"); + } + // Painting off the canvas still makes the layer, with nothing painted. + let mut s = doc(); + s.execute(CMD, json!({"kind": "levels", "points": [[-5000, -5000]]})).unwrap(); + assert_eq!(mask_at(&s, 0, 0), 0.0); +} diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 82abc3d436..22d8e04c92 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -276,6 +276,12 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option) -> Result { + stroke_with(s, cmd, p, label, brush, pts, false) +} + /// Stroke with a resolved brush onto the target layer (pixels or mask). fn stroke_with(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushSettings, pts: Vec, auto_erase: bool) -> Result { let raw_bg = s.tools.background; diff --git a/crates/engine/src/cmd/channel_cmds.rs b/crates/engine/src/cmd/channel_cmds.rs index 5fe3b4fd19..07256328a6 100644 --- a/crates/engine/src/cmd/channel_cmds.rs +++ b/crates/engine/src/cmd/channel_cmds.rs @@ -134,7 +134,7 @@ use spot::{is_flat, merge, merge_spot, mergeable, split}; use targeting::{SLOT_KEY, target_cmd, target_slot}; pub(crate) use targeting::{ Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region, - is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_of, target_surface, targeted_channel, + is_channel_target, is_spot_target, mask_target_enabled, restrict_to_color, routed, target_layer_mask, target_of, target_surface, targeted_channel, }; pub use targeting::{follows_filter_mask, follows_target, follows_vector_mask_target, gray_target, read_target_surface}; pub use tone_target::{ToneTarget, resolve_tone_target}; diff --git a/crates/engine/src/cmd/channel_cmds/targeting.rs b/crates/engine/src/cmd/channel_cmds/targeting.rs index 80215708f7..b4e7880c5e 100644 --- a/crates/engine/src/cmd/channel_cmds/targeting.rs +++ b/crates/engine/src/cmd/channel_cmds/targeting.rs @@ -399,6 +399,11 @@ pub(crate) fn edits_channel(s: &Session) -> bool { }) } +/// Target the active layer's mask, as clicking its thumbnail does. +pub(crate) fn target_layer_mask(s: &mut Session) { + target(s, ChannelTarget::LayerMask); +} + /// Make `t` the edit target and show it the way Photoshop does when its row is clicked. pub(super) fn target(s: &mut Session, t: ChannelTarget) { if let Some(st) = s.active_mut() { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ef4eae9be2..a88eb800a8 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -68,6 +68,7 @@ pub use cmd as commands; pub use cmd::actions_cmds; pub use cmd::actions_edit_cmds; pub use cmd::adjust_cmds; +pub use cmd::adjustment_brush_cmds; pub use cmd::align_cmds; pub use cmd::analysis_cmds; pub use cmd::artboard_cmds; From 1cd68c3538764b48a9b69eecd24538c80a24dc25 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 01:23:09 +0100 Subject: [PATCH 3/4] UI: the Adjustment Brush Tool's toolbar slot, options bar and strokes (#12519) --- .../engine/src/cmd/adjustment_brush_cmds.rs | 7 +- .../src/cmd/adjustment_brush_cmds_tests.rs | 4 +- .../src/adjustment_brush_tool_tests.rs | 253 ++++++++++++++++++ crates/ui-egui/src/canvas/gesture.rs | 3 +- crates/ui-egui/src/canvas/paint_mouse.rs | 10 +- crates/ui-egui/src/canvas/strokes.rs | 1 + crates/ui-egui/src/canvas/tool_input.rs | 9 +- crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/panels/brush_controls.rs | 2 +- crates/ui-egui/src/panels/options_bar.rs | 11 +- crates/ui-egui/src/panels/toolbar.rs | 5 + crates/ui-egui/src/state/tool.rs | 16 +- crates/ui-egui/src/state/tool_options.rs | 14 + crates/ui-egui/src/tools.rs | 1 + crates/ui-egui/src/tools/adjustment_brush.rs | 159 +++++++++++ crates/ui-egui/src/tools/tool_reset.rs | 1 + 18 files changed, 482 insertions(+), 17 deletions(-) create mode 100644 crates/ui-egui/src/adjustment_brush_tool_tests.rs create mode 100644 crates/ui-egui/src/tools/adjustment_brush.rs diff --git a/crates/engine/src/cmd/adjustment_brush_cmds.rs b/crates/engine/src/cmd/adjustment_brush_cmds.rs index 73c228f46e..90dc8b915c 100644 --- a/crates/engine/src/cmd/adjustment_brush_cmds.rs +++ b/crates/engine/src/cmd/adjustment_brush_cmds.rs @@ -19,8 +19,7 @@ pub const NEW_LAYER_LABEL: &str = "New Adjustment Layer"; pub const STROKE_LABEL: &str = "Adjustment Brush"; /// The alert a stroke on an Indexed Color document shows; nothing changes. -pub const INDEXED_ALERT: &str = - "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; +pub const INDEXED_ALERT: &str = "Could not complete your request because the tool does not work with Indexed Color images. Please convert the image to RGB or another supported mode before using."; /// One entry of the options bar's Adjustment dropdown: the kind id (the `layer.newAdjustmentLayer` /// suffix for the kinds that exist), its label, and whether a separator follows it. @@ -204,8 +203,8 @@ fn run(s: &mut Session, p: &Value) -> Result { let zoom = q.get("zoom").and_then(Value::as_f64).filter(|z| z.is_finite() && *z > 0.0).unwrap_or(1.0) as f32; // An adjustment layer of this kind with a mask is active: paint into its mask. - let paints_active = active_kind(s) == Some(kind) - && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); + let paints_active = + active_kind(s) == Some(kind) && s.active().and_then(|st| st.active_layer.and_then(|id| st.doc.layer(id))).is_some_and(|l| l.mask.is_some()); let result = if paints_active { let mut r = super::brush_cmds::stroke_into(s, CMD, &q, STROKE_LABEL, brush, pts)?; r["created"] = json!(false); diff --git a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs index c88936af84..bc927059b9 100644 --- a/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs +++ b/crates/engine/src/cmd/adjustment_brush_cmds_tests.rs @@ -217,9 +217,7 @@ fn subtract_paints_black_and_swaps_the_colours() { fn entries_grey_out_per_mode_and_depth() { let off = |mode, depth| -> Vec<&str> { ENTRIES.iter().map(|e| e.kind).filter(|k| !enabled_in(k, mode, depth)).collect() }; let missing = ["light", "colorVibrance", "clarityDehaze", "grain"]; - let with = |more: &[&'static str]| -> Vec<&'static str> { - ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() - }; + let with = |more: &[&'static str]| -> Vec<&'static str> { ENTRIES.iter().map(|e| e.kind).filter(|k| missing.contains(k) || more.contains(k)).collect() }; assert_eq!(off(ColorMode::Rgb, SampleType::U8), with(&[])); assert_eq!(off(ColorMode::Rgb, SampleType::U16), with(&[])); assert_eq!(off(ColorMode::Rgb, SampleType::F32), with(&["invert", "posterize", "threshold", "gradientMap"])); diff --git a/crates/ui-egui/src/adjustment_brush_tool_tests.rs b/crates/ui-egui/src/adjustment_brush_tool_tests.rs new file mode 100644 index 0000000000..2d42777d0c --- /dev/null +++ b/crates/ui-egui/src/adjustment_brush_tool_tests.rs @@ -0,0 +1,253 @@ +//! #12519: the Adjustment Brush Tool in the shell: its toolbar slot between the Blur and Dodge +//! slots (no letter, its own tooltip), its options bar, and strokes through the real pointer +//! path that make an adjustment layer whose mask is the stroke, or paint into it. + +use egui::accesskit::Role; +use egui::{Key, Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{Adjustment, LayerContent}; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::panels::toolbar::TOOL_SECTIONS; +use crate::state::{DialogKind, Tool}; + +/// A 200 x 200 document with a painted layer active and the Adjustment Brush picked, its brush +/// swapped in as a frame does. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + app.run("layer.new.layer", json!({})).unwrap(); + app.run("edit.fill", json!({"color": "#808080"})).unwrap(); + pick(&mut app); + app +} + +fn pick(app: &mut PhotocraftApp) { + app.ui.tool = Tool::AdjustmentBrush; + crate::paint_mouse::sync_tool_brush(app); + app.sync_views(); +} + +fn stroke(app: &mut PhotocraftApp, y: f64) { + tool_event(app, ToolEvent::Down { x: 40.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Move { x: 160.0, y, pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: 160.0, y }, Modifiers::NONE); + app.sync_views(); +} + +fn active(app: &PhotocraftApp) -> &photocraft_doc::Layer { + let st = app.session.active().unwrap(); + st.doc.layer(st.active_layer.unwrap()).unwrap() +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.walk().len() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn mask_at(app: &PhotocraftApp, x: i32, y: i32) -> f32 { + active(app).mask.as_ref().expect("a mask").surface.sample_channel(x, y, 0) +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message").and_then(Value::as_str).map(str::to_string)).collect() +} + +#[test] +fn its_own_slot_sits_between_the_blur_and_dodge_slots() { + let slots: Vec<&[Tool]> = TOOL_SECTIONS.iter().flat_map(|s| s.iter().copied()).collect(); + let i = slots.iter().position(|s| *s == [Tool::AdjustmentBrush]).expect("an own slot"); + assert_eq!(slots[i - 1], [Tool::Blur, Tool::Sharpen, Tool::Smudge]); + assert_eq!(slots[i + 1], [Tool::Dodge, Tool::Burn, Tool::Sponge]); + assert_eq!(Tool::AdjustmentBrush.key(), '\0', "no letter"); + assert_eq!(Tool::from_name("adjustmentBrush"), Some(Tool::AdjustmentBrush)); +} + +#[test] +fn the_toolbar_tooltip_names_it_and_says_what_it_does() { + let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let mut h = Harness::builder().with_size(vec2(400.0, 1600.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + crate::panels::toolbar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ProMedium); + h.run_steps(2); + let tip = "Adjustment Brush Tool\nCreate local adjustment layers."; + let button = h.get_by_label(tip); + button.click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool, Tool::AdjustmentBrush); +} + +/// Shift+letter and plain letters, pressed from every tool, never pick the Adjustment Brush. +#[test] +fn no_letter_or_shift_letter_cycle_reaches_it() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 50, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + let press = |app: &mut PhotocraftApp, key: Key, modifiers: Modifiers| { + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::ModifiersChanged(modifiers), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); + }; + for key in [Key::O, Key::B, Key::J, Key::S, Key::Y, Key::E] { + for _ in 0..8 { + press(&mut app, key, Modifiers::SHIFT); + assert_ne!(app.ui.tool, Tool::AdjustmentBrush, "{key:?}"); + press(&mut app, key, Modifiers::NONE); + assert_ne!(app.ui.tool, Tool::AdjustmentBrush, "{key:?}"); + } + } +} + +#[test] +fn it_starts_with_a_100_px_soft_round() { + let app = app(); + let b = &app.session.tools.brush; + assert_eq!((b.size, b.hardness), (100.0, 0.0)); +} + +fn bar(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder() + .with_size(vec2(1800.0, 200.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ProMedium)) + .build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app); + h.run_steps(4); + h +} + +fn x_of(h: &Harness<'static, PhotocraftApp>, role: Role, label: &str) -> f32 { + let all = || h.query_all_by_role(role).map(|n| n.accesskit_node().label()).collect::>(); + h.query_all_by_role(role) + .find(|n| n.accesskit_node().label().as_deref() == Some(label)) + .unwrap_or_else(|| panic!("no {role:?} {label:?} in {:?}", all())) + .rect() + .center() + .x +} + +#[test] +fn the_options_bar_shows_its_controls_in_order() { + let h = bar(app()); + let xs = [ + x_of(&h, Role::ComboBox, "Adjustment:"), + x_of(&h, Role::Button, "Subtract"), + x_of(&h, Role::Button, "Add"), + x_of(&h, Role::Button, "Always use pressure for size"), + x_of(&h, Role::Button, "Choose an object and have the adjustment applied to it"), + x_of(&h, Role::CheckBox, "Overlay"), + x_of(&h, Role::SpinButton, "Opacity:"), + x_of(&h, Role::Button, "Always use pressure for opacity"), + x_of(&h, Role::SpinButton, "Flow:"), + x_of(&h, Role::Button, "Enable airbrush-style build-up effects"), + ]; + assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right: {xs:?}"); + // Light is the reference default; it isn't available yet, so the first enabled entry shows. + let kind = h.query_all_by_role(Role::ComboBox).find(|n| n.accesskit_node().label().as_deref() == Some("Adjustment:")).unwrap(); + assert_eq!(kind.accesskit_node().value().as_deref(), Some("Levels")); +} + +#[test] +fn subtract_and_add_swap_the_colours_and_the_paint() { + let mut h = bar(app()); + h.get_by_label("Subtract").click(); + h.run_steps(2); + let app = h.state(); + assert!(app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0])); + h.get_by_label("Add").click(); + h.run_steps(2); + let app = h.state(); + assert!(!app.ui.tool_options.adjustment_brush_subtract); + assert_eq!((app.session.tools.foreground, app.session.tools.background), ([1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0])); +} + +#[test] +fn the_first_stroke_makes_the_layer_in_one_history_state() { + let mut app = app(); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 1), "{}", app.ui.status); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("New Adjustment Layer")); + assert_eq!(active(&app).name, "Levels 1"); + assert!(matches!(active(&app).content, LayerContent::Adjustment(Adjustment::Levels { .. }))); + assert!(mask_at(&app, 100, 100) > 0.98 && mask_at(&app, 100, 10) == 0.0); + assert!(app.ui.mask_target, "the new mask is targeted"); + // A second stroke paints the same mask. + stroke(&mut app, 30.0); + assert_eq!((layers(&app), steps(&app)), (n + 1, past + 2)); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Adjustment Brush")); + assert!(mask_at(&app, 100, 30) > 0.98); +} + +#[test] +fn a_hidden_locked_or_group_layer_does_not_refuse_the_stroke() { + for setup in ["hidden", "locked", "group", "type"] { + let mut app = app(); + let id = active(&app).id.0; + match setup { + "hidden" => app.run("layer.setProps", json!({"layer": id, "visible": false})).map(|_| ()), + "locked" => app.run("layer.lockLayers", json!({"all": true})).map(|_| ()), + "group" => app.run("layer.new.group", json!({})).map(|_| ()), + _ => app.run("type.create", json!({"text": "Hi", "x": 20, "y": 40})).map(|_| ()), + } + .unwrap_or_else(|e| panic!("{setup}: {e}")); + pick(&mut app); + let n = layers(&app); + stroke(&mut app, 100.0); + assert!(alerts(&app).is_empty() && app.ui.dialogs.is_empty(), "{setup}: {:?}", app.ui.dialogs); + assert_eq!(layers(&app), n + 1, "{setup}: {}", app.ui.status); + assert!(matches!(active(&app).content, LayerContent::Adjustment(_)), "{setup}"); + } +} + +#[test] +fn selecting_an_adjustment_layer_sets_the_dropdown() { + let mut app = app(); + app.run("layer.newAdjustmentLayer.curves", json!({})).unwrap(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "curves"); + // A pick after that sticks while the layer stays active. + app.ui.tool_options.adjustment_brush_kind = "exposure".into(); + crate::adjustment_brush::follow_active_layer(&mut app); + assert_eq!(crate::adjustment_brush::kind(&app), "exposure"); + // And a stroke with it makes an Exposure layer above the Curves one. + let n = layers(&app); + stroke(&mut app, 100.0); + assert_eq!((layers(&app), active(&app).name.as_str()), (n + 1, "Exposure 1")); +} + +#[test] +fn greyed_entries_fall_back_to_the_first_offered_one() { + let mut app = app(); + app.run("image.mode.bits32", json!({})).unwrap(); + app.ui.tool_options.adjustment_brush_kind = "posterize".into(); + assert_eq!(crate::adjustment_brush::kind(&app), "levels"); + stroke(&mut app, 100.0); + assert_eq!(active(&app).name, "Levels 1", "{}", app.ui.status); +} + +#[test] +fn indexed_color_alerts_at_the_press_and_changes_nothing() { + let mut app = app(); + app.run("layer.flatten", json!({})).ok(); + app.run("image.mode.indexedColor", json!({})).unwrap(); + pick(&mut app); + let (n, past) = (layers(&app), steps(&app)); + stroke(&mut app, 100.0); + assert_eq!(alerts(&app), [photocraft_engine::adjustment_brush_cmds::INDEXED_ALERT]); + assert_eq!((layers(&app), steps(&app)), (n, past)); +} diff --git a/crates/ui-egui/src/canvas/gesture.rs b/crates/ui-egui/src/canvas/gesture.rs index 155ae25ac8..27951d8be5 100644 --- a/crates/ui-egui/src/canvas/gesture.rs +++ b/crates/ui-egui/src/canvas/gesture.rs @@ -97,7 +97,8 @@ fn finish(app: &mut PhotocraftApp, mut d: Drag, click: Option) { if live_retouch_command(d.tool).is_some() || crate::retouch_ui::dab_params(app, d.tool).is_some() || d.tool == Tool::ColorReplacement { app.live_stroke = None; } - let finished = crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) + let finished = crate::adjustment_brush::finish_stroke(app, d.tool, &d.points, d.line) + || crate::eraser_ui::finish_stroke(app, d.tool, &d.points, d.line) || crate::retouch_ui::finish_stroke_with(app, d.tool, &d.points, d.modifiers, d.line, d.history_params.clone()); app.session.clear_live_stroke(); if finished { diff --git a/crates/ui-egui/src/canvas/paint_mouse.rs b/crates/ui-egui/src/canvas/paint_mouse.rs index c611df6f40..0322494301 100644 --- a/crates/ui-egui/src/canvas/paint_mouse.rs +++ b/crates/ui-egui/src/canvas/paint_mouse.rs @@ -45,7 +45,11 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) { // The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone // Stamp and the Smudge tool start with their own measured tips instead, as the whole brush // Reset Tool gives them (#11911, #12099, #12671, #12684, #13029, #12601, #12964). - None if matches!(tool, Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge) => { + None if matches!( + tool, + Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::AdjustmentBrush + ) => + { fresh_brush(tool, ¤t) } // The Pencil starts with its own 1 px hard round (#12200) regardless of the Brush, keeping @@ -104,6 +108,9 @@ const CLONE_STAMP_TIP: (f32, f32, f32) = (21.0, 0.0, 0.25); const REMOVE_TOOL_SIZE: f32 = 19.0; /// The Smudge tool's tip after Reset Tool (#12964): a 13 px soft round at 25 % spacing. const SMUDGE_TOOL_TIP: (f32, f32, f32) = (13.0, 0.0, 0.25); +/// The Adjustment Brush's starting tip (#12519): a 100 px soft round (hardness 0 %). Its spacing +/// was not measured, so it stays the default brush's. +const ADJUSTMENT_BRUSH_TIP: (f32, f32) = (100.0, 0.0); /// `tool`'s brush as it starts out (Reset Tool, #2825): the default brush at Photoshop's /// smoothing, with the session's own fields of `current`. The Brush tool's tip is @@ -126,6 +133,7 @@ pub(crate) fn fresh_brush(tool: Tool, current: &BrushSettings) -> BrushSettings brush.smoothing.amount = 0.0; } Tool::Remove => brush.size = REMOVE_TOOL_SIZE, + Tool::AdjustmentBrush => (brush.size, brush.hardness) = ADJUSTMENT_BRUSH_TIP, _ => {} } session_fields(current, &brush) diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 678cb9892f..5d4686bb09 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -676,6 +676,7 @@ pub(crate) fn freehand_tool(tool: Tool) -> bool { | Tool::Blur | Tool::Sharpen | Tool::Smudge + | Tool::AdjustmentBrush | Tool::Dodge | Tool::Burn | Tool::Sponge diff --git a/crates/ui-egui/src/canvas/tool_input.rs b/crates/ui-egui/src/canvas/tool_input.rs index 4f4325cbb0..d1a95a21a1 100644 --- a/crates/ui-egui/src/canvas/tool_input.rs +++ b/crates/ui-egui/src/canvas/tool_input.rs @@ -540,12 +540,19 @@ pub(super) fn tool_event_with_view(app: &mut PhotocraftApp, ev: ToolEvent, mods: // Painting a type, shape, Smart Object or fill layer asks to rasterize it first // (⌥-click with the Clone Stamp or Healing Brush only sets the source). let sets_source = matches!(tool, Tool::CloneStamp | Tool::Healing) && mods.alt; + // The Adjustment Brush paints a new layer's mask whatever the active layer is (hidden, + // locked, a group or type): only Indexed Color refuses it (#12519). + let own_layer = tool == Tool::AdjustmentBrush; + if own_layer && crate::adjustment_brush::press_refused(app) { + return; + } // Painting on or moving a hidden layer is refused at the press, as in Photoshop (#571). - if !sets_source && press_refused(app, tool) { + if !sets_source && !own_layer && press_refused(app, tool) { return; } // The Clone Stamp's no-source alert opens at the press, after any rasterize prompt. if !sets_source + && !own_layer && (crate::rasterize_prompt::intercept(app, tool, x, y, pressure) || refuse_group(app, tool) || crate::retouch_ui::clone_stamp_without_source(app, tool)) diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index c8594a61cd..635155cca4 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -188,6 +188,7 @@ pub fn tool_icon(t: Tool) -> &'static str { Tool::Sharpen => "triangle", Tool::Smudge => "pointer", Tool::Dodge => "lollipop", + Tool::AdjustmentBrush => "adjustment-layer", Tool::Burn => "flame", Tool::Sponge => "cloud", Tool::QuickSelection => "quick-selection", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7928bf442c..7eaa1185a6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -276,6 +276,7 @@ pub use text::egui_fonts; use text::font_filters; use text::font_preview; pub use text::served_fonts; +pub use tools::adjustment_brush; use tools::align_bar; pub use tools::analysis_ui; pub use tools::anchor_tools; diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 1f660fb4cd..f3c799b3a7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -65,6 +65,7 @@ pub(crate) mod toolbar; pub mod type_panels_ui; pub(super) mod variables_ui; +pub(crate) use brush_controls::brush_preset_chip; #[cfg(test)] use color::color_field_height; pub(crate) use color::{color_field, color_field_fill_id, field_chips, field_hsva, offer_color_field_fill, srgb_hsva}; diff --git a/crates/ui-egui/src/panels/brush_controls.rs b/crates/ui-egui/src/panels/brush_controls.rs index 7f2aa4996b..79c9a67a90 100644 --- a/crates/ui-egui/src/panels/brush_controls.rs +++ b/crates/ui-egui/src/panels/brush_controls.rs @@ -223,7 +223,7 @@ pub(super) fn mixer_load_swatch(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Options-bar brush chip: a click shows or hides Photoshop's Brush Preset picker below it (size, /// hardness, the preset library), the one a right-click on the canvas opens. -pub(super) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { +pub(crate) fn brush_preset_chip(ui: &mut egui::Ui, b: &photocraft_engine::BrushSettings, state: &mut crate::state::UiState) { let t = Tokens::get(ui.ctx()); let (r, _) = ui.allocate_exact_size(vec2(44.0, 30.0), Sense::hover()); let resp = ui.interact(r, crate::brush_picker::chip_id(), Sense::click()); diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 005bf4793e..eeb7a129c3 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -133,7 +133,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { // chip, so a tool change swaps the brush with it (Photoshop keeps one per tool). crate::paint_mouse::sync_tool_brush(app); // Brush edits here go through `tools.setBrush`, one journal entry per gesture (Rule 1). - if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) + if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser | Tool::AdjustmentBrush)) || tool == Tool::QuickSelection { brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); @@ -181,7 +181,8 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &brush); widgets::vline(ui, 22.0); } - if crate::eraser_ui::options_bar(app, ui, tool) + if crate::adjustment_brush::options_bar(app, ui, tool) + || crate::eraser_ui::options_bar(app, ui, tool) || crate::retouch_ui::options_bar(app, ui, tool) || crate::vector_ui::options_bar(app, ui, tool) || crate::analysis_ui::options_bar(app, ui, tool) @@ -993,7 +994,7 @@ fn fixed_size_field(ui: &mut egui::Ui, px: &mut f32, units: widgets::FieldUnits, picked } -fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { +pub(crate) fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { opt_label(ui, label); let mut percent = *value * 100.0; let r = widgets::value_field_named(ui, label, &mut percent, range, "%", width); @@ -1005,7 +1006,7 @@ fn percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::op /// A pressure toggle named `name` (for screen readers and tests); its tooltip is `name`, unless /// `own_tip` leaves the tooltip to the caller (the Brush's own texts, #11813). -fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> egui::Response { +pub(crate) fn pressure_button(ui: &mut egui::Ui, on: bool, name: &str, own_tip: bool) -> egui::Response { icons::button_with_icon_size_tip(ui, "circle-dot", 24.0, (24.0f32 * 0.52).round(), on, name, !own_tip) } @@ -1036,7 +1037,7 @@ pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { /// [`percent_field`] that keeps whole percents (`33.7` becomes 34 %). A value set elsewhere (a /// `tools.setBrush` fraction, an older saved 0) shows as the whole percent in range. -fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { +pub(crate) fn whole_percent_field(ui: &mut egui::Ui, label: &str, value: &mut f32, range: std::ops::RangeInclusive, width: f32) -> egui::Response { opt_label(ui, label); let mut percent = (*value * 100.0).round().max(*range.start()).min(*range.end()); let r = widgets::value_field_named(ui, label, &mut percent, range.clone(), "%", width); diff --git a/crates/ui-egui/src/panels/toolbar.rs b/crates/ui-egui/src/panels/toolbar.rs index a8ed212b72..ebb495933b 100644 --- a/crates/ui-egui/src/panels/toolbar.rs +++ b/crates/ui-egui/src/panels/toolbar.rs @@ -36,6 +36,7 @@ pub(crate) const TOOL_SECTIONS: &[&[&[Tool]]] = &[ &[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser], &[Tool::Gradient, Tool::PaintBucket], &[Tool::Blur, Tool::Sharpen, Tool::Smudge], + &[Tool::AdjustmentBrush], &[Tool::Dodge, Tool::Burn, Tool::Sponge], ], &[ @@ -262,6 +263,10 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { Some(sc) => format!("{} ({})", tl!(tool.label()), crate::shortcuts::pretty(&sc)), None => tl!(tool.label()).to_string(), }; + let tip = match tool.description() { + Some(d) => format!("{tip}\n{}", tl!(d)), + None => tip, + }; let resp = icons::button_with_icon_size_tip(ui, icons::tool_icon(tool), bx, toolbar_icon_size(bx, t.pro), sel, &tip, tool_tips); if slot.len() > 1 { paint_toolbar_flyout_indicator(ui, &t, &resp, side); diff --git a/crates/ui-egui/src/state/tool.rs b/crates/ui-egui/src/state/tool.rs index 66aa7d53f6..b1d4624bda 100644 --- a/crates/ui-egui/src/state/tool.rs +++ b/crates/ui-egui/src/state/tool.rs @@ -52,6 +52,8 @@ pub enum Tool { Blur, Sharpen, Smudge, + /// Paints an adjustment layer's mask, making the layer on the first stroke (#12519). + AdjustmentBrush, Dodge, Burn, Sponge, @@ -81,7 +83,7 @@ pub enum Tool { } impl Tool { - pub const ALL: [Tool; 69] = [ + pub const ALL: [Tool; 70] = [ Tool::Move, Tool::Artboard, Tool::RectMarquee, @@ -128,6 +130,7 @@ impl Tool { Tool::Blur, Tool::Sharpen, Tool::Smudge, + Tool::AdjustmentBrush, Tool::Dodge, Tool::Burn, Tool::Sponge, @@ -204,6 +207,7 @@ impl Tool { Tool::Blur => "Blur Tool", Tool::Sharpen => "Sharpen Tool", Tool::Smudge => "Smudge Tool", + Tool::AdjustmentBrush => "Adjustment Brush Tool", Tool::Dodge => "Dodge Tool", Tool::Burn => "Burn Tool", Tool::Sponge => "Sponge Tool", @@ -226,6 +230,13 @@ impl Tool { Tool::CustomShape => "Custom Shape Tool", } } + /// The second line of the toolbar tooltip, for the tools whose description was measured. + pub fn description(self) -> Option<&'static str> { + match self { + Tool::AdjustmentBrush => Some("Create local adjustment layers."), + _ => None, + } + } pub fn is_type(self) -> bool { matches!(self, Self::Type | Self::VerticalType | Self::HorizontalTypeMask | Self::VerticalTypeMask) } @@ -258,6 +269,7 @@ impl Tool { | Tool::Blur | Tool::Sharpen | Tool::Smudge + | Tool::AdjustmentBrush | Tool::Dodge | Tool::Burn | Tool::Sponge @@ -284,6 +296,8 @@ impl Tool { Tool::CloneStamp | Tool::PatternStamp => 'S', Tool::HistoryBrush | Tool::ArtHistoryBrush => 'Y', Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0', + // Its own slot without a letter: no Shift+letter cycle reaches it. + Tool::AdjustmentBrush => '\0', // In the Marquee flyout, but M cycles only the Rectangular and Elliptical Marquee. Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0', Tool::Dodge | Tool::Burn | Tool::Sponge => 'O', diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 874c444d19..55eb02c485 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -18,6 +18,16 @@ pub struct ToolOptions { /// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes /// collect as a tint on the canvas and ↩ applies them together (Esc drops them). pub remove_after_each_stroke: bool, + /// Adjustment Brush: the Adjustment dropdown's entry (`photocraft_engine::adjustment_brush_cmds::ENTRIES`). + pub adjustment_brush_kind: String, + /// Adjustment Brush: Subtract (paints black into the mask) instead of Add. + pub adjustment_brush_subtract: bool, + /// Adjustment Brush: the Overlay checkbox (its tint over the mask is #12520). + pub adjustment_brush_overlay: bool, + /// Adjustment Brush: the active layer the dropdown last followed, so selecting another + /// adjustment layer sets it once and a pick in the dropdown sticks. + #[serde(skip)] + pub adjustment_brush_followed: Option, pub feather: f32, /// linear | radial | angle | reflected | diamond pub gradient_style: String, @@ -469,6 +479,10 @@ impl Default for ToolOptions { object_finder: true, remove_new_layer: false, remove_after_each_stroke: true, + adjustment_brush_kind: photocraft_engine::adjustment_brush_cmds::DEFAULT_KIND.into(), + adjustment_brush_subtract: false, + adjustment_brush_overlay: false, + adjustment_brush_followed: None, feather: 0.0, gradient_style: "linear".into(), gradient_reverse: false, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index 503bbe0a7d..452a5002fd 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -1,3 +1,4 @@ +pub mod adjustment_brush; pub(super) mod align_bar; pub mod analysis_ui; pub mod anchor_tools; diff --git a/crates/ui-egui/src/tools/adjustment_brush.rs b/crates/ui-egui/src/tools/adjustment_brush.rs new file mode 100644 index 0000000000..7ef98338d7 --- /dev/null +++ b/crates/ui-egui/src/tools/adjustment_brush.rs @@ -0,0 +1,159 @@ +//! The Adjustment Brush Tool (#12519): its options bar and its stroke. Painting runs +//! `paint.adjustmentBrush`, which makes an adjustment layer of the dropdown's kind whose mask is +//! the stroke, or paints into the mask of the active adjustment layer of that kind. The stroke +//! shows as the painting tools' trail while it is drawn and is applied on release. + +use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::panels::options_bar::{opt_label, percent_field, pressure_button, whole_percent_field}; +use crate::state::Tool; + +/// The kind a stroke paints: the dropdown's entry, or the first offered one when the document's +/// colour mode or bit depth greys it. +pub fn kind(app: &PhotocraftApp) -> &'static str { + let stored = ab::entry_of(&app.ui.tool_options.adjustment_brush_kind).map_or(ab::DEFAULT_KIND, |e| e.kind); + match app.session.active() { + Some(st) => ab::offered_kind(stored, st.doc.mode, st.doc.depth), + None => stored, + } +} + +/// Selecting an adjustment layer sets the dropdown to its kind, once per selection, so a later +/// pick in the dropdown sticks. +pub fn follow_active_layer(app: &mut PhotocraftApp) { + let active = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + if app.ui.tool_options.adjustment_brush_followed == active { + return; + } + app.ui.tool_options.adjustment_brush_followed = active; + if let Some(k) = ab::active_kind(&app.session) { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } +} + +/// Subtract (black over white) or Add (white over black): the mode and the colours the stroke +/// paints the mask with. +pub fn set_subtract(app: &mut PhotocraftApp, subtract: bool) { + app.ui.tool_options.adjustment_brush_subtract = subtract; + let (fg, bg) = if subtract { ("#000000", "#ffffff") } else { ("#ffffff", "#000000") }; + if let Err(e) = app.run("tools.setColors", json!({"foreground": fg, "background": bg})) { + app.ui.status = e; + app.ui.status_error = true; + } +} + +/// A press in an Indexed Color document: the reference application's alert, and no stroke. +pub fn press_refused(app: &mut PhotocraftApp) -> bool { + let indexed = app.session.active().is_some_and(|st| st.doc.mode == photocraft_doc::ColorMode::Indexed); + if indexed { + crate::brush_refusal::prompt(app, tl!(INDEXED_ALERT)); + } + indexed +} + +/// Applies a finished drag. Returns false for another tool. +pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], line: bool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let mut p = json!({ + "kind": kind(app), + "subtract": app.ui.tool_options.adjustment_brush_subtract, + "points": points, + "zoom": app.point_zoom(), + }); + crate::canvas::unsmoothed_line(&mut p, line); + match app.run("paint.adjustmentBrush", p) { + Ok(_) => { + // The layer painted is active with its mask targeted, as after a New Adjustment Layer. + app.ui.mask_target = true; + app.ui.vector_mask_target = false; + app.ui.tool_options.adjustment_brush_followed = app.session.active().and_then(|st| st.active_layer).map(|l| l.0); + } + Err(e) if e.contains(INDEXED_ALERT) => crate::brush_refusal::prompt(app, tl!(INDEXED_ALERT)), + Err(e) => { + app.ui.status = e; + app.ui.status_error = true; + } + } + true +} + +/// Does a separator line go above `kind` in the dropdown? +fn starts_group(kind: &str) -> bool { + let i = ENTRIES.iter().position(|e| e.kind == kind); + i.and_then(|i| i.checked_sub(1)).and_then(|i| ENTRIES.get(i)).is_some_and(|e| e.separator_after) +} + +/// The options bar, left to right as in the reference application: (the tool preset picker) · +/// Adjustment · Subtract / Add · Brush Preset · Pressure for Size · Choose an object · Overlay · +/// Opacity · Pressure for Opacity · Flow · Airbrush. Returns false for another tool. +pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool { + if tool != Tool::AdjustmentBrush { + return false; + } + follow_active_layer(app); + let (mode, depth) = app.session.active().map_or((photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), |st| (st.doc.mode, st.doc.depth)); + opt_label(ui, tl!("Adjustment:")); + let options: Vec<(&'static str, &str)> = ENTRIES.iter().map(|e| (e.kind, e.label)).collect(); + let mut current = kind(app); + let chosen = crate::widgets::dropdown_wheel_grouped_enabled( + ui, + "adjustment-brush-kind", + tl!("Adjustment"), + &mut current, + &options, + 150.0, + |k| starts_group(k), + |k| ab::enabled_in(k, mode, depth), + ) + .0; + // Choosing an entry is no history state; the keys may land on a greyed one, which keeps the choice. + if let Some(&k) = chosen.last() + && ab::enabled_in(k, mode, depth) + { + app.ui.tool_options.adjustment_brush_kind = k.into(); + } + let subtract = app.ui.tool_options.adjustment_brush_subtract; + let sub = crate::icons::button(ui, "minus", 24.0, subtract, tl!("Subtract from mask areas to remove adjustment from areas of the image")); + let add = crate::icons::button(ui, "plus", 24.0, !subtract, tl!("Add to mask areas to apply adjustment to more of the image")); + if crate::brush_picker::named(sub, "Subtract").clicked() && !subtract { + set_subtract(app, true); + } else if crate::brush_picker::named(add, "Add").clicked() && subtract { + set_subtract(app, false); + } + crate::widgets::vline(ui, 22.0); + crate::panels::brush_preset_chip(ui, &app.session.tools.brush, &mut app.ui); + crate::brush_picker::settings_toggle(app, ui); + let before = app.session.tools.brush.clone(); + let mut b = before.clone(); + if pressure_button(ui, b.pressure_size, tl!("Always use pressure for size"), false).clicked() { + b.pressure_size = !b.pressure_size; + } + crate::widgets::vline(ui, 22.0); + // Present but inert: what it does was not measured. + ui.add_enabled_ui(false, |ui| { + crate::icons::button(ui, "square-dashed-mouse-pointer", 24.0, false, tl!("Choose an object and have the adjustment applied to it")); + }); + // Its tint over the painted mask is its own item (#12520). + crate::widgets::checkbox(ui, &mut app.ui.tool_options.adjustment_brush_overlay, tl!("Overlay")); + crate::widgets::vline(ui, 22.0); + whole_percent_field(ui, tl!("Opacity"), &mut b.opacity, 1.0..=100.0, 62.0); + if pressure_button(ui, b.pressure_opacity, tl!("Always use pressure for opacity"), false).clicked() { + b.pressure_opacity = !b.pressure_opacity; + } + percent_field(ui, tl!("Flow"), &mut b.flow, 1.0..=100.0, 62.0); + let airbrush = crate::icons::button(ui, "sparkles", 24.0, b.build_up, tl!("Enable airbrush-style build-up effects")); + if crate::brush_picker::named(airbrush, "Enable airbrush-style build-up effects").clicked() { + b.build_up = !b.build_up; + } + crate::brush_panel::commit_gesture(app, ui.ctx(), &before, &b); + true +} + +#[cfg(test)] +#[path = "../adjustment_brush_tool_tests.rs"] +mod adjustment_brush_tool_tests; diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index ba62a52b9d..d24b277659 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -233,6 +233,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Pencil => reset!(pencil_auto_erase, pencil_clear), Tool::Eraser => reset!(eraser_mode, erase_to_history), Tool::Remove => reset!(remove_new_layer, remove_after_each_stroke), + Tool::AdjustmentBrush => reset!(adjustment_brush_kind, adjustment_brush_subtract, adjustment_brush_overlay), Tool::BackgroundEraser => reset!(bg_sampling, bg_limits, bg_tolerance, bg_protect_fg, bg_tolerance_control), Tool::ColorReplacement => reset!(cr_mode, cr_sampling, cr_limits, cr_tolerance, cr_anti_alias), Tool::MagicEraser => reset!(tolerance, anti_alias, contiguous, magic_eraser_opacity), From 8cca993d49a856bfd55feaa4992013ea573339ef Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 23:47:19 +0100 Subject: [PATCH 4/4] Adjustment Brush: add its slot to main's stored toolbar layout and tool list Main now builds the toolbar from DEFAULT_TOOLBAR and resolves tool names through shell_commands::TOOLS, so the new slot needs an entry in both. Main also gained a tool meanwhile: 70 tools in Tool::ALL and the README. The Free Transform switch test's window grows to 1000 px so the longer tool column keeps the Hand Tool on screen. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- crates/engine/src/prefs.rs | 1 + crates/engine/src/shell_commands.rs | 1 + crates/ui-egui/src/state.rs | 2 +- crates/ui-egui/src/transform_switch_tests.rs | 6 +++--- 5 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 04508f9637..2e9ed0502a 100644 --- a/README.md +++ b/README.md @@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
-

🧰 69 tools

- Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom +

🧰 70 tools

+ Move · Artboard · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Perspective Crop · Slice · Slice Select · Frame · Eyedropper · Color Sampler · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Art History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Adjustment Brush · Dodge · Burn · Sponge · Pen · Freeform Pen · Curvature Pen · Add Anchor Point · Delete Anchor Point · Convert Point · Horizontal and Vertical Type · Horizontal and Vertical Type Mask · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Star · Line · Custom Shape · Hand · Rotate View · Zoom

🖌️ A real brush engine

diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index d9b6fb7144..2f079c87ef 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1361,6 +1361,7 @@ pub const DEFAULT_TOOLBAR: &[&[&str]] = &[ &["Eraser", "BackgroundEraser", "MagicEraser"], &["Gradient", "PaintBucket"], &["Blur", "Sharpen", "Smudge"], + &["AdjustmentBrush"], &["Dodge", "Burn", "Sponge"], &["Pen", "FreeformPen", "CurvaturePen", "AddAnchorPoint", "DeleteAnchorPoint", "ConvertPoint"], &["Type", "VerticalType", "VerticalTypeMask", "HorizontalTypeMask"], diff --git a/crates/engine/src/shell_commands.rs b/crates/engine/src/shell_commands.rs index cec9e757be..05b2b7f940 100644 --- a/crates/engine/src/shell_commands.rs +++ b/crates/engine/src/shell_commands.rs @@ -154,6 +154,7 @@ pub const TOOLS: &[(&str, &str, Option<&str>)] = &[ ("tools.select.blur", "Blur Tool", None), ("tools.select.sharpen", "Sharpen Tool", None), ("tools.select.smudge", "Smudge Tool", None), + ("tools.select.adjustmentBrush", "Adjustment Brush Tool", None), ("tools.select.dodge", "Dodge Tool", Some("O")), ("tools.select.burn", "Burn Tool", Some("O")), ("tools.select.sponge", "Sponge Tool", Some("O")), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 138d995469..91211c5545 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -865,7 +865,7 @@ mod tests { assert!(!Tool::RedEye.is_brushlike()); assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp)); assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp)); - assert_eq!(Tool::ALL.len(), 69); + assert_eq!(Tool::ALL.len(), 70); } fn vector_tool_names_parse() { diff --git a/crates/ui-egui/src/transform_switch_tests.rs b/crates/ui-egui/src/transform_switch_tests.rs index f5be113d2a..857669010e 100644 --- a/crates/ui-egui/src/transform_switch_tests.rs +++ b/crates/ui-egui/src/transform_switch_tests.rs @@ -8,9 +8,9 @@ use serde_json::json; use crate::PhotocraftApp; /// The app with a 400 × 300 document: a red 100 × 60 rectangle at (100, 100) on its own layer -/// above the Background. +/// above the Background. Tall enough that the whole tool column, Hand Tool included, is on screen. fn app() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); @@ -58,7 +58,7 @@ fn picking_another_tool_in_the_toolbar_applies_the_transform() { /// the same step), as Place Embedded leaves it for the box `begin_placed` opens: cancelling the /// place takes that step back. fn placed_app() -> Harness<'static, PhotocraftApp> { - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(64).build_eframe(|cc| { + let mut h = Harness::builder().with_size(egui::vec2(1400.0, 1000.0)).with_max_steps(64).build_eframe(|cc| { PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();