Merge PR #14120: Tools: add the Adjustment Brush Tool (#12519)

This commit is contained in:
David Mann committed 2026-11-22 01:06:31 +01:00
commit a698d07214
26 files changed
+1054 -10

No files matched your search

+2 -2
View File
@@ -185,8 +185,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<table>
<tr>
<td width="33%" valign="top">
<h4>🧰 69 tools</h4>
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
<h4>🧰 70 tools</h4>
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
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
+3
View File
@@ -19,6 +19,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;
@@ -0,0 +1,262 @@
//! 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(kind: &str, mode: ColorMode, depth: SampleType) -> &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<Value> {
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<String>) -> 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<Adjustment> {
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<bool> {
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<Value> {
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<CommandSpec> {
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,
}]
}
@@ -0,0 +1,300 @@
//! 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<f32> = [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);
}
+6
View File
@@ -275,6 +275,12 @@ pub(crate) fn doc_cmyk_space(s: &Session) -> Option<std::sync::Arc<photocraft_co
photocraft_color::convert::CmykSpace::for_profile(s.active().and_then(|d| d.doc.icc_profile.as_ref()))
}
/// [`stroke_with`] for another tool's stroke (the Adjustment Brush painting a mask): `brush`
/// resolved, no Auto Erase, history state `label`.
pub(super) fn stroke_into(s: &mut Session, cmd: &str, p: &Value, label: &str, brush: BrushSettings, pts: Vec<StrokePoint>) -> Result<Value> {
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<StrokePoint>, auto_erase: bool) -> Result<Value> {
let raw_bg = s.tools.background;
+1 -1
View File
@@ -141,7 +141,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};
@@ -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() {
+1
View File
@@ -56,6 +56,7 @@ const TABLES: &[Table] = &[
("actions_edit_cmds", crate::actions_edit_cmds::specs),
("swatch_cmds", crate::swatch_cmds::specs),
("retouch_cmds", crate::retouch_cmds::specs),
("adjustment_brush_cmds", crate::adjustment_brush_cmds::specs),
("redeye_cmds", crate::redeye_cmds::specs),
("image_cmds", crate::image_cmds::specs),
("perspective_crop_cmds", crate::perspective_crop_cmds::specs),
@@ -407,6 +407,7 @@ paint.sharpen
paint.smudge
paint.historyBrush
paint.artHistoryBrush
paint.adjustmentBrush
paint.redEye
image.imageSize
image.canvasSize
+1
View File
@@ -70,6 +70,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;
+1
View File
@@ -1390,6 +1390,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"],
+1
View File
@@ -140,6 +140,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")),
@@ -0,0 +1,212 @@
//! #12519: the Adjustment Brush Tool in the shell: its toolbar slot between the Blur and Dodge
//! slots (no letter), 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::{Modifiers, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::{Adjustment, LayerContent};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::panels::toolbar::TOOL_SECTIONS;
use crate::state::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() -> Box<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)
}
/// The messages of the open framework alerts.
fn alerts(app: &PhotocraftApp) -> Vec<String> {
app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.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));
let command = crate::panels::tool_commands::command_of(Tool::AdjustmentBrush);
assert_eq!(crate::panels::tool_commands::tool_of(command), Tool::AdjustmentBrush);
assert_eq!(crate::icons::tool_icon(Tool::AdjustmentBrush), craft::behavior::IconId::new("adjustment_layer"));
}
#[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: Box<PhotocraftApp>) -> Harness<'static, Box<PhotocraftApp>> {
crate::theme::install_fonts(app.ctx());
crate::theme::apply(app.ctx(), &crate::theme::AppTheme::pro());
let mut h = Harness::builder().with_context(app.ctx().clone()).with_size(vec2(1800.0, 200.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|ui, app: &mut Box<PhotocraftApp>| {
crate::panels::options_bar(app, ui);
crate::dialogs::run(app, ui);
},
app,
);
h.run_steps(4);
h
}
/// The centre x of the control named `label` (not a caption's text node).
fn x_of(h: &Harness<'static, Box<PhotocraftApp>>, label: &str) -> f32 {
let named = h.query_all_by_label(label).find(|n| n.accesskit_node().role() != Role::Label);
let all = || h.query_all_by_role(Role::Button).filter_map(|n| n.accesskit_node().label()).collect::<Vec<_>>();
named.unwrap_or_else(|| panic!("no {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, "Adjustment:"),
x_of(&h, "Subtract from mask areas to remove adjustment from areas of the image"),
x_of(&h, "Add to mask areas to apply adjustment to more of the image"),
x_of(&h, "Always use pressure for size"),
x_of(&h, "Choose an object and have the adjustment applied to it"),
x_of(&h, "Overlay"),
x_of(&h, "Opacity:"),
x_of(&h, "Always use pressure for opacity"),
x_of(&h, "Flow:"),
x_of(&h, "Enable airbrush-style build-up effects"),
];
assert!(xs.windows(2).all(|w| w[0] < w[1]), "left to right: {xs:?}");
}
#[test]
fn subtract_and_add_swap_the_colours_and_the_paint() {
let mut h = bar(app());
h.get_by_label("Subtract from mask areas to remove adjustment from areas of the image").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 to mask areas to apply adjustment to more of the image").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!(app.framework.dialogs.open_dialogs().is_empty(), "{setup}: {:?}", alerts(&app));
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));
}
+6 -2
View File
@@ -47,14 +47,14 @@ pub fn sync_tool_brush(app: &mut PhotocraftApp) {
// first Pattern Stamp stroke multiply (or give Healing a mode its menu doesn't have).
// The Pattern Stamp also starts at full opacity and flow (#12616): those fields are its own.
// The Background Eraser, the Healing Brush, the Burn, Dodge and Sponge tools, the Clone
// Stamp, the Smudge tool and the Art History Brush start with their own measured tips
// Stamp, the Smudge tool, the Adjustment Brush and the Art History Brush start with their own measured tips
// instead, as the whole brush Reset Tool gives them (#11911, #12099, #12671, #12684,
// #13029, #12601, #12964, #12631); the Art History Brush's is at full opacity (#10263).
// The Art History Brush's Angle and pressure toggles are its own bar controls, so they
// start at 0° and off too, whatever the outgoing brush has (#12629).
None if matches!(
tool,
Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::ArtHistoryBrush
Tool::BackgroundEraser | Tool::Healing | Tool::Burn | Tool::Dodge | Tool::Sponge | Tool::CloneStamp | Tool::Smudge | Tool::AdjustmentBrush | Tool::ArtHistoryBrush
) =>
{
fresh_brush(tool, &current)
@@ -124,6 +124,9 @@ const ART_HISTORY_BRUSH_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
@@ -166,6 +169,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)
+2 -1
View File
@@ -704,7 +704,8 @@ pub(crate) fn finish(app: &mut PhotocraftApp, stroke: PaintStroke) {
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 {
+5
View File
@@ -460,6 +460,11 @@ impl Preflight<'_, '_> {
let pressure = pointer.sample.pressure;
let mods = pointer.mods;
self.scope.with_app(|app| {
// 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).
if tool == Tool::AdjustmentBrush {
return crate::adjustment_brush::press_refused(app);
}
// Auto-Select's press picks the layer to move, so the hidden active layer is not its target.
let picks = tool == Tool::Move && !crate::move_ui::moves_selected_pixels_with(app, tool) && app.ui.tool_options.move_auto_select != mods.cmd;
(!picks && press_refused(app, tool))
+1
View File
@@ -246,6 +246,7 @@ pub(crate) use services::{opaque_layer, saves_flat_in_place};
pub use text::cjk_fonts;
pub use text::direction;
pub use text::served_fonts;
pub use tools::adjustment_brush;
use tools::align_bar;
pub use tools::analysis;
pub use tools::artboard_tool;
+5 -2
View File
@@ -157,7 +157,9 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// The bar shows the active tool's brush: switch it in before drawing, so a tool change swaps the brush with it
// (Photoshop keeps one per tool).
crate::paint_mouse::sync_tool_brush(app);
if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser)) || tool == Tool::QuickSelection {
if (tool.is_brushlike() && !matches!(tool, Tool::Brush | Tool::Pencil | Tool::MixerBrush | Tool::Eraser | Tool::AdjustmentBrush))
|| tool == Tool::QuickSelection
{
crate::brush_picker::show_field(ui, app, true);
crate::brush_picker::settings_toggle(ui, app);
Divider::vertical().show(ui);
@@ -166,7 +168,8 @@ fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
stamp_members(app, ui, tool);
Divider::vertical().show(ui);
}
if crate::eraser_ui::options_bar(ui, app, tool)
if crate::adjustment_brush::options_bar(ui, app, tool)
|| crate::eraser_ui::options_bar(ui, app, tool)
|| crate::retouch_ui::bar::options_bar(ui, app, tool)
|| crate::vector_ui::options_bar(app, ui, tool)
|| crate::analysis::bars::options(app, ui, tool)
@@ -114,6 +114,8 @@ pub(crate) enum ToolCommand {
Sharpen,
#[command(label = "Smudge Tool", icon = "pointer", kind = "tool", group = "tools", alias = "tools.select.smudge")]
Smudge,
#[command(label = "Adjustment Brush Tool", icon = "adjustment_layer", kind = "tool", group = "tools", alias = "tools.select.adjustmentBrush")]
AdjustmentBrush,
#[command(label = "Dodge Tool", icon = "lollipop", kind = "tool", group = "O", default = "O", alias = "tools.select.dodge")]
Dodge,
#[command(label = "Burn Tool", icon = "flame", kind = "tool", group = "O", default = "O", alias = "tools.select.burn")]
@@ -218,6 +220,7 @@ pub(crate) fn command_of(tool: Tool) -> ToolCommand {
Tool::Blur => ToolCommand::Blur,
Tool::Sharpen => ToolCommand::Sharpen,
Tool::Smudge => ToolCommand::Smudge,
Tool::AdjustmentBrush => ToolCommand::AdjustmentBrush,
Tool::Dodge => ToolCommand::Dodge,
Tool::Burn => ToolCommand::Burn,
Tool::Sponge => ToolCommand::Sponge,
@@ -293,6 +296,7 @@ pub(crate) fn tool_of(command: ToolCommand) -> Tool {
ToolCommand::Blur => Tool::Blur,
ToolCommand::Sharpen => Tool::Sharpen,
ToolCommand::Smudge => Tool::Smudge,
ToolCommand::AdjustmentBrush => Tool::AdjustmentBrush,
ToolCommand::Dodge => Tool::Dodge,
ToolCommand::Burn => Tool::Burn,
ToolCommand::Sponge => Tool::Sponge,
+1
View File
@@ -48,6 +48,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],
],
&[
+1 -1
View File
@@ -625,7 +625,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() {
+9 -1
View File
@@ -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,
@@ -130,6 +132,7 @@ impl Tool {
Self::Blur => "blur",
Self::Sharpen => "sharpen",
Self::Smudge => "smudge",
Self::AdjustmentBrush => "adjustmentBrush",
Self::Dodge => "dodge",
Self::Burn => "burn",
Self::Sponge => "sponge",
@@ -164,7 +167,7 @@ impl Tool {
.copied()
}
pub const ALL: [Tool; 69] = [
pub const ALL: [Tool; 70] = [
Tool::Move,
Tool::Artboard,
Tool::RectMarquee,
@@ -211,6 +214,7 @@ impl Tool {
Tool::Blur,
Tool::Sharpen,
Tool::Smudge,
Tool::AdjustmentBrush,
Tool::Dodge,
Tool::Burn,
Tool::Sponge,
@@ -287,6 +291,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",
@@ -341,6 +346,7 @@ impl Tool {
| Tool::Blur
| Tool::Sharpen
| Tool::Smudge
| Tool::AdjustmentBrush
| Tool::Dodge
| Tool::Burn
| Tool::Sponge
@@ -367,6 +373,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',
+14
View File
@@ -39,6 +39,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<u64>,
pub feather: f32,
/// linear | radial | angle | reflected | diamond
pub gradient_style: String,
@@ -431,6 +441,10 @@ impl Default for ToolOptions {
object_hard_edge: 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,
+1
View File
@@ -1,3 +1,4 @@
pub mod adjustment_brush;
pub(super) mod align_bar;
pub mod analysis;
pub mod artboard_tool;
@@ -0,0 +1,208 @@
//! 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 craft::behavior::IconId;
use craft::ui::buttons::{IconButton, ToggleButton};
use craft::ui::choice::{Checkbox, Segmented};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _};
use craft::ui::display::Divider;
use craft::ui::pickers::Select;
use photocraft_engine::adjustment_brush_cmds::{self as ab, ENTRIES, INDEXED_ALERT};
use serde_json::json;
use super::option_cells;
use crate::PhotocraftApp;
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;
}
}
/// The reference application's alert for a press in an Indexed Color document, in the UI language.
fn indexed_alert() -> &'static str {
tl!(
"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."
)
}
/// 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 {
let _ = crate::dialogs::alerts::alert(app, 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) => {
let _ = crate::dialogs::alerts::alert(app, indexed_alert());
}
Err(e) => {
app.ui.status = e;
app.ui.status_error = true;
}
}
true
}
/// The Adjustment dropdown's rows: the entries in their groups, those the document can't take greyed.
fn kind_entries(mode: photocraft_doc::ColorMode, depth: photocraft_doc::SampleType) -> Vec<Entry<&'static str>> {
let mut rows = Vec::new();
for e in ENTRIES.iter() {
rows.push(Entry::new(e.kind, tl!(e.label).to_owned()).enabled(ab::enabled_in(e.kind, mode, depth)));
if e.separator_after {
rows.push(Entry::separator());
}
}
rows
}
/// 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(ui: &mut egui::Ui, app: &mut PhotocraftApp, 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));
let entries = kind_entries(mode, depth);
// Choosing an entry is no history state; a greyed entry can't be picked.
let picked = Select::new(tl!("Adjustment:").to_owned(), Bind::given(kind(app)), &entries).show(ui).events.committed().copied();
if let Some(k) = picked.filter(|k| ab::enabled_in(k, mode, depth)) {
app.ui.tool_options.adjustment_brush_kind = k.into();
}
let modes = [
Entry::new(true, tl!("Subtract from mask areas to remove adjustment from areas of the image").to_owned()).icon(IconId::new("minus")),
Entry::new(false, tl!("Add to mask areas to apply adjustment to more of the image").to_owned()).icon(IconId::new("plus")),
];
let subtract = app.ui.tool_options.adjustment_brush_subtract;
if let Some(next) = Segmented::new(tl!("Mask mode").to_owned(), Bind::given(subtract), &modes).show(ui).value().copied()
&& next != subtract
{
set_subtract(app, next);
}
Divider::vertical().show(ui);
crate::brush_picker::show_field(ui, app, true);
crate::brush_picker::settings_toggle(ui, app);
let before = app.session.tools.brush.clone();
let mut brush = before.clone();
let mut key = None;
let pressure =
ToggleButton::new(tl!("Always use pressure for size").to_owned(), Bind::given(brush.pressure_size)).icon(IconId::new("target")).icon_only().show(ui);
if let Some(on) = pressure.value().copied() {
brush.pressure_size = on;
key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e));
}
Divider::vertical().show(ui);
// Present but inert: what it does was not measured.
let choose = tl!("Choose an object and have the adjustment applied to it");
IconButton::new(IconId::new("square-dashed-mouse-pointer")).label(choose).tooltip(choose).enabled(false).show(ui);
// Its tint over the painted mask is its own item (#12520).
Checkbox::new(Bind::bound(&mut app.ui.tool_options.adjustment_brush_overlay)).label(tl!("Overlay").to_owned()).show(ui);
Divider::vertical().show(ui);
let mut alerts = Vec::new();
let mut opacity = (brush.opacity * 100.0).round();
let out = option_cells::number(tl!("Opacity:"), &mut opacity, 1.0..=100.0).whole().unit("%").show(ui);
key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key);
brush.opacity = opacity / 100.0;
alerts.extend(out.out_of_range);
let pressure = ToggleButton::new(tl!("Always use pressure for opacity").to_owned(), Bind::given(brush.pressure_opacity))
.icon(IconId::new("target"))
.icon_only()
.show(ui);
if let Some(on) = pressure.value().copied() {
brush.pressure_opacity = on;
key = pressure.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key);
}
let mut flow = brush.flow * 100.0;
let out = option_cells::number(tl!("Flow:"), &mut flow, 1.0..=100.0).unit("%").show(ui);
key = out.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key);
brush.flow = flow / 100.0;
alerts.extend(out.out_of_range);
let airbrush = ToggleButton::new(tl!("Enable airbrush-style build-up effects").to_owned(), Bind::given(brush.build_up))
.icon(IconId::new("sparkles"))
.icon_only()
.show(ui);
if let Some(on) = airbrush.value().copied() {
brush.build_up = on;
key = airbrush.events.iter().find_map(|e| crate::history_keys::coalesce("brush", e)).or(key);
}
// A field shown without an edit keeps the brush's exact value (no rounding by showing the bar).
if out_unchanged(&before, &brush) {
return true;
}
crate::brush_panel::commit_keyed(app, &before, &brush, key);
for alert in &alerts {
option_cells::range_alert(app, ui, alert);
}
true
}
/// Whether showing the bar left the brush as it was, up to the rounding of the percent fields.
fn out_unchanged(before: &photocraft_engine::BrushSettings, after: &photocraft_engine::BrushSettings) -> bool {
let near = |a: f32, b: f32| (a - b).abs() < 0.005;
near(before.opacity, after.opacity)
&& near(before.flow, after.flow)
&& before.pressure_size == after.pressure_size
&& before.pressure_opacity == after.pressure_opacity
&& before.build_up == after.build_up
}
#[cfg(test)]
#[path = "../adjustment_brush_tool_tests.rs"]
mod adjustment_brush_tool_tests;
+1
View File
@@ -213,6 +213,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),