diff --git a/crates/engine/src/cmd/adjust_cmds.rs b/crates/engine/src/cmd/adjust_cmds.rs index 7f31b8d2268..ea3e3278321 100644 --- a/crates/engine/src/cmd/adjust_cmds.rs +++ b/crates/engine/src/cmd/adjust_cmds.rs @@ -434,6 +434,33 @@ fn replace_color(s: &mut Session, p: &Value) -> Result { // Localized Color Clusters, as in Select › Color Range: the colour only matches within Range // (a percentage of the canvas's longer side) of where it was picked. let points = sample_points(p).map_err(|m| bad(CMD, m))?; + // Several samples (Add to Sample / Subtract from Sample, #6280): the colours match as + // Select › Color Range's do for the same clicks, through its own matcher. + // A malformed `subtractPoints` is refused here, as malformed `points` are, rather than read as + // no subtraction by the single-colour path. + let subtracted = match p.get("subtractPoints") { + None => false, + Some(v) => !v.as_array().ok_or_else(|| bad(CMD, "`subtractPoints` must be [[x, y], …]"))?.is_empty(), + }; + if subtracted || points.len() > 1 { + let mut q = json!({"points": p.get("points").cloned().unwrap_or(Value::Array(Vec::new())), "fuzziness": fuzz}); + // With no Add samples, the subtraction starts from the dialog's From colour, not the + // foreground; with them, the samples alone span the range, as in Color Range. + // Forwarded as resolved (a `null` or missing colour is the foreground), as RGB 0..1. + if points.is_empty() { + q["color"] = json!([c[0], c[1], c[2]]); + } + for key in ["subtractPoints", "order", "localized", "range"] { + if let Some(v) = p.get(key) { + q[key] = v.clone(); + } + } + let samples = crate::selection_cmds::ColorRangeSamples::new(s, &q).map_err(|e| bad(CMD, e.to_string()))?; + return rgba_edit(s, "Replace Color", p, |px, r| { + let mask = samples.coverage(px, r.width() as usize, 1.0, [r.x0 as f32, r.y0 as f32]); + tone::replace_color_masked(px, &mask, h, sat, l); + }); + } let localized = if p.get("localized").and_then(Value::as_bool).unwrap_or(false) { if points.is_empty() { return Err(bad(CMD, "localized clusters need eyedropper `points` (where the colour was picked)")); @@ -587,7 +614,7 @@ pub fn specs() -> Vec { "image.adjustments.replaceColor", "Replace Color…", ["Image", "Adjustments"], - r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/localized/range; composite pixel-layer target only. Otherwise color defaults to the foreground; localized points use range % of the longer side.)"##, + r##"{"localized":bool=false,"color":color,"fuzziness":0..200=40,"range":0..100=100,"hue":-180..180=0,"saturation":-100..100=0,"lightness":-100..100=0,"points":[[x,y],…]?,"subtractPoints":[[x,y],…]?,"order":["+"|"-",…]?,"labMinimum":[L,a,b]?,"labMaximum":[L,a,b]?} (Lab bounds: a finite ordered D50 box, mutually exclusive with color/points/subtractPoints/order/localized/range; composite pixel-layer target only. Otherwise color ("#rrggbb") defaults to the foreground; localized points use range % of the longer side; several "points" (Add to Sample) or any "subtractPoints" (Subtract from Sample) match as select.colorRange does for the same samples, "order" the click order.)"##, has_pixels, replace_color ), diff --git a/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs b/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs index 574610523cf..9ee5371ac06 100644 --- a/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs +++ b/crates/engine/src/cmd/adjust_cmds/replace_color_range.rs @@ -242,4 +242,20 @@ mod tests { assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.past_len(), history); } + + /// Add to Sample / Subtract from Sample (#6280) are RGB samples: with Lab bounds they are + /// refused, as `points` are, and the document is left as it was. + #[test] + fn lab_bounds_refuse_subtracted_samples_and_click_order() { + for extra in [serde_json::json!({"subtractPoints": [[1, 1]]}), serde_json::json!({"order": ["+", "-"]}), serde_json::json!({"subtractPoints": []})] { + let mut s = Session::new(); + s.execute("file.new", serde_json::json!({"width": 4, "height": 2})).unwrap(); + let before = s.active().unwrap().doc.clone(); + let mut p = serde_json::json!({"labMinimum": [0, -10, -10], "labMaximum": [100, 10, 10], "lightness": 50}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + let err = s.execute(CMD, p).unwrap_err().to_string(); + assert!(err.contains("Lab bounds cannot be combined"), "{extra}: {err}"); + assert_eq!(s.active().unwrap().doc, before, "{extra}"); + } + } } diff --git a/crates/engine/src/cmd/adjust_cmds/tests.rs b/crates/engine/src/cmd/adjust_cmds/tests.rs index 51843ae0226..162524367d7 100644 --- a/crates/engine/src/cmd/adjust_cmds/tests.rs +++ b/crates/engine/src/cmd/adjust_cmds/tests.rs @@ -36,6 +36,12 @@ fn changed(a: [f32; 4], b: [f32; 4]) -> f32 { (0..3).map(|c| (a[c] - b[c]).abs()).fold(0.0, f32::max) } +/// Every pixel of the active layer, row by row. +fn pixels(s: &Session) -> Vec<[f32; 4]> { + let b = doc(s).bounds(); + (b.y0..b.y1).flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))).map(|(x, y)| rgba(s, x, y)).collect() +} + fn doc(s: &Session) -> &Document { &s.active().unwrap().doc } @@ -754,6 +760,239 @@ fn replace_color_localized_clusters_only_change_the_colour_near_the_sample() { assert!(err.to_string().contains("bad point"), "{err}"); } +/// #6280: Add to Sample and Subtract from Sample, as in Photoshop: several picked colours are +/// all replaced, and a subtracted one is left alone, matching as Select › Color Range does for +/// the same samples. +#[test] +fn replace_color_adds_and_subtracts_samples_as_color_range_does() { + // Red on the left (x < 16), blue in the middle, green on the right (32 ≤ x < 44), and a + // lighter red at the edge that the samples only partly cover. + let (red, blue, green, pink) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0], [0.1, 0.8, 0.15, 1.0], [0.95, 0.25, 0.25, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| { + if x < 16 { + red + } else if x < 32 { + blue + } else if x < 44 { + green + } else { + pink + } + }); + let before = (rgba(&s, 4, 16), rgba(&s, 24, 16), rgba(&s, 40, 16), rgba(&s, 46, 16)); + let original = pixels(&s); + let shift = |extra: Value| { + let mut p = json!({"fuzziness": 40, "hue": 120, "saturation": 20}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + // Red and blue sampled (one added): both change, green doesn't. + s.execute("image.adjustments.replaceColor", shift(json!({"color": "#d91a1a", "points": [[4, 16], [24, 16]]}))).unwrap(); + assert!(changed(rgba(&s, 4, 16), before.0) > 0.1, "red is replaced"); + assert!(changed(rgba(&s, 24, 16), before.1) > 0.1, "the added blue is replaced"); + assert_eq!(rgba(&s, 40, 16), before.2, "green wasn't sampled"); + let partial = rgba(&s, 46, 16); + // One undo step brings every pixel back exactly. + s.execute("edit.undo", json!({})).unwrap(); + assert!(pixels(&s) == original, "undo restores the pixels"); + // The same coverage as Select › Color Range for the same clicks. + s.execute("select.colorRange", json!({"points": [[4, 16], [24, 16]], "fuzziness": 40})).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + for x in [4, 24, 40] { + let want = sel.read_region(Rect::from_xywh(x, 16, 1, 1))[0]; + assert!((want > 0.5) == (x < 32), "Color Range at {x}: {want}"); + } + // The lighter red is partly covered, and replaced in proportion: the blend of its colour and + // its fully replaced colour at that coverage, not either one (as a 0.5 threshold would give). + let k = sel.read_region(Rect::from_xywh(46, 16, 1, 1))[0]; + assert!(k > 0.1 && k < 0.9, "partial coverage: {k}"); + let mut full = [before.3]; + tone::replace_color_masked(&mut full, &[1.0], 120.0, 20.0, 0.0); + let blend: [f32; 4] = std::array::from_fn(|c| before.3[c] + (full[0][c] - before.3[c]) * k); + assert!(changed(partial, blend) < 1.5 / 255.0, "{partial:?} vs the blend {blend:?} at coverage {k}"); + assert!(changed(blend, before.3).min(changed(blend, full[0])) > 0.1, "the blend is far from both ends a threshold gives"); + s.execute("select.deselect", json!({})).unwrap(); + // A subtraction undoes exactly too. (Blue is far from the red sample here, so subtracting + // it changes nothing; `replace_color_subtracting_inside_the_added_range_takes_a_colour_out` + // has a subtraction that does.) + let selected = pixels(&s); + s.execute("image.adjustments.replaceColor", shift(json!({"points": [[4, 16]], "subtractPoints": [[24, 16]], "order": ["+", "-"]}))).unwrap(); + assert!(changed(rgba(&s, 4, 16), before.0) > 0.1); + assert_eq!(rgba(&s, 40, 16), before.2); + s.execute("edit.undo", json!({})).unwrap(); + assert!(pixels(&s) == selected, "undo restores the pixels"); + // Bad samples are refused, naming this command. + let err = s.execute("image.adjustments.replaceColor", shift(json!({"points": [[4, 16]], "subtractPoints": [[999, 16]]}))).unwrap_err(); + assert!(err.to_string().contains("replaceColor") && err.to_string().contains("outside"), "{err}"); +} + +/// FredApps review on #10443: a subtracted sample inside the added range. Photoshop's Subtract +/// from Sample reshapes the samples' Lab box (`LabRange::subtract`): a subtracted colour inside +/// it pulls the nearer edge onto itself, so it stays matched and the added colour beyond that +/// edge drops out. Two added greys span dark to light; subtracting a grey near the light end +/// leaves the light one unreplaced. +#[test] +fn replace_color_subtracting_inside_the_added_range_takes_a_colour_out() { + let grey = |v: f32| [v, v, v, 1.0]; + // Dark grey (x < 12), mid grey (subtracted), light grey, black (never sampled). + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..12 => grey(0.25), + 12..24 => grey(0.65), + 24..36 => grey(0.75), + _ => grey(0.0), + }); + let at = [(4, 16), (16, 16), (28, 16), (40, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let added = json!({"fuzziness": 20, "lightness": -50, "points": [[4, 16], [28, 16]]}); + // Added only: the box spans dark to light, so all three greys are replaced. + s.execute("image.adjustments.replaceColor", added.clone()).unwrap(); + for (i, &(x, y)) in at[..3].iter().enumerate() { + assert!(changed(rgba(&s, x, y), before[i]) > 0.1, "grey {i} is in the added range"); + } + assert_eq!(rgba(&s, 40, 16), before[3]); + s.execute("edit.undo", json!({})).unwrap(); + // Mid grey subtracted: the light end moves onto it, so the light grey is left alone. + let mut subtracted = added.clone(); + subtracted["subtractPoints"] = json!([[16, 16]]); + subtracted["order"] = json!(["+", "+", "-"]); + s.execute("image.adjustments.replaceColor", subtracted.clone()).unwrap(); + assert!(changed(rgba(&s, 4, 16), before[0]) > 0.1, "the dark grey is still replaced"); + assert!(changed(rgba(&s, 16, 16), before[1]) > 0.1, "the subtracted grey stays matched, at the new edge"); + assert_eq!(rgba(&s, 28, 16), before[2], "the light grey beyond it is taken out"); + assert_eq!(rgba(&s, 40, 16), before[3]); + // Select › Color Range agrees for the same clicks. + s.execute("edit.undo", json!({})).unwrap(); + let mut range = subtracted; + range.as_object_mut().unwrap().remove("lightness"); + s.execute("select.colorRange", range).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, false, false]); +} + +/// CodeRabbit review on #10443: the click order (`"order"`) reaches the matcher, as in Select › +/// Color Range. Added dark grey, subtracted mid grey, added light grey (`+ - +`): the subtraction +/// comes while the box is the dark grey alone, far from the mid grey, so it changes nothing and the +/// light grey is replaced; all additions first (`+ + -`) would leave it out. +#[test] +fn replace_color_follows_the_click_order_as_color_range_does() { + let grey = |v: f32| [v, v, v, 1.0]; + // Dark grey (x < 12), mid grey (subtracted), light grey, black (never sampled). + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..12 => grey(0.25), + 12..24 => grey(0.65), + 24..36 => grey(0.75), + _ => grey(0.0), + }); + let at = [(4, 16), (16, 16), (28, 16), (40, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let clicks = json!({"fuzziness": 20, "points": [[4, 16], [28, 16]], "subtractPoints": [[16, 16]], "order": ["+", "-", "+"]}); + let mut p = clicks.clone(); + p["lightness"] = json!(-50); + s.execute("image.adjustments.replaceColor", p).unwrap(); + let replaced: Vec = at.iter().enumerate().map(|(i, &(x, y))| changed(rgba(&s, x, y), before[i]) > 0.1).collect(); + s.execute("edit.undo", json!({})).unwrap(); + // Darkening leaves black black whether or not it's matched: lighten to see whether it is. + p = clicks.clone(); + p["lightness"] = json!(50); + s.execute("image.adjustments.replaceColor", p).unwrap(); + let lifted = changed(rgba(&s, 40, 16), before[3]) > 0.1; + s.execute("edit.undo", json!({})).unwrap(); + s.execute("select.colorRange", clicks).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, true, false], "Color Range: the light grey is added back after the subtraction"); + assert_eq!(replaced, covered, "Replace Color matches what Color Range covers for the same clicks"); + assert_eq!(lifted, covered[3], "Replace Color matches black as Color Range does"); +} + +/// FredApps review on #10443: Localized Color Clusters with several samples. A matching colour +/// is replaced only near one of the samples, as in Select › Color Range. +#[test] +fn replace_color_localized_clusters_with_several_samples() { + // Two creams, sampled at x = 2 and x = 24; the first cream again far right (x ≥ 40). + let (cream, cream2, grey) = ([0.9, 0.88, 0.79, 1.0], [0.88, 0.86, 0.76, 1.0], [0.5, 0.5, 0.5, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| match x { + ..8 => cream, + 20..28 => cream2, + 40.. => cream, + _ => grey, + }); + let at = [(3, 16), (24, 16), (44, 16), (14, 16)]; + let before: Vec<_> = at.iter().map(|&(x, y)| rgba(&s, x, y)).collect(); + let mut p = json!({"fuzziness": 20, "hue": 180, "saturation": 60, "points": [[2, 16], [24, 16]]}); + // Without clusters both creams change everywhere, the far one too. + s.execute("image.adjustments.replaceColor", p.clone()).unwrap(); + assert!(changed(rgba(&s, 44, 16), before[2]) > 0.05, "far cream without clusters"); + s.execute("edit.undo", json!({})).unwrap(); + // Range 20 % of 48 px: within about 10 px of either sample. + p["localized"] = json!(true); + p["range"] = json!(20); + s.execute("image.adjustments.replaceColor", p.clone()).unwrap(); + assert!(changed(rgba(&s, 3, 16), before[0]) > 0.05, "near the first sample"); + assert!(changed(rgba(&s, 24, 16), before[1]) > 0.05, "near the second sample"); + assert_eq!(rgba(&s, 44, 16), before[2], "the same cream far from both samples"); + assert_eq!(rgba(&s, 14, 16), before[3], "grey isn't sampled"); + // Select › Color Range agrees for the same clicks. + s.execute("edit.undo", json!({})).unwrap(); + for k in ["hue", "saturation"] { + p.as_object_mut().unwrap().remove(k); + } + s.execute("select.colorRange", p).unwrap(); + let sel = doc(&s).selection.clone().unwrap(); + let covered: Vec = at.iter().map(|&(x, y)| sel.read_region(Rect::from_xywh(x, y, 1, 1))[0] > 0.5).collect(); + assert_eq!(covered, [true, true, false, false]); +} + +/// #10443 review: with only Subtract from Sample clicks, the dialog's From colour is what the +/// subtraction starts from, not the foreground (black here), so the red is still replaced. +#[test] +fn replace_color_subtract_only_starts_from_the_from_colour() { + let (red, blue) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| if x < 16 { red } else { blue }); + let (r0, b0) = (rgba(&s, 4, 16), rgba(&s, 24, 16)); + let p = json!({"color": "#d91a1a", "hue": 120, "fuzziness": 40, "points": [], "subtractPoints": [[24, 16]]}); + s.execute("image.adjustments.replaceColor", p).unwrap(); + assert_ne!(rgba(&s, 4, 16), r0, "the From colour (red) is replaced"); + // Blue is outside the From colour's range anyway: subtracting from a single colour doesn't + // reshape its range, as in Photoshop (see + // `replace_color_subtracting_inside_the_added_range_takes_a_colour_out`). + assert_eq!(rgba(&s, 24, 16), b0, "blue isn't matched"); +} + +/// #10443 review: a `null` From colour means the foreground, for the subtract-only matcher too. +#[test] +fn replace_color_subtract_only_reads_a_null_colour_as_the_foreground() { + let (red, blue) = ([0.85, 0.1, 0.1, 1.0], [0.1, 0.15, 0.85, 1.0]); + let mut s = session(8, "rgb"); + paint(&mut s, |x, _| if x < 16 { red } else { blue }); + s.tools.foreground = red; + let r0 = rgba(&s, 4, 16); + let p = json!({"color": null, "hue": 120, "fuzziness": 40, "points": [], "subtractPoints": [[24, 16]]}); + s.execute("image.adjustments.replaceColor", p).unwrap(); + assert_ne!(rgba(&s, 4, 16), r0, "the foreground (red) is replaced"); +} + +/// A malformed `subtractPoints` is refused even with one sample, where the single-colour path +/// would otherwise ignore it (CodeRabbit review on #10443). +#[test] +fn replace_color_refuses_malformed_subtract_points() { + let mut s = session(8, "rgb"); + paint(&mut s, |_, _| [0.85, 0.1, 0.1, 1.0]); + for points in [json!([]), json!([[4, 16]])] { + let p = json!({"color": "#d91a1a", "hue": 120, "points": points, "subtractPoints": "invalid"}); + let err = s.execute("image.adjustments.replaceColor", p).unwrap_err(); + assert!(err.to_string().contains("replaceColor") && err.to_string().contains("subtractPoints"), "{err}"); + } + // An empty list is no subtraction: the single-colour path. + s.execute("image.adjustments.replaceColor", json!({"color": "#d91a1a", "hue": 120, "points": [[4, 16]], "subtractPoints": []})).unwrap(); +} + /// #6095: ⌘I in Quick Mask inverts the whole mask, not only where it was white, so leaving Quick /// Mask selects everything but the original rectangle, whichever way the colour reads. With /// Color Indicates Selected Areas and nothing selected, it selects everything. A black alpha diff --git a/crates/engine/tests/panic_hunt.rs b/crates/engine/tests/panic_hunt.rs index c4d8359e183..81f893ee68e 100644 --- a/crates/engine/tests/panic_hunt.rs +++ b/crates/engine/tests/panic_hunt.rs @@ -89,6 +89,11 @@ fn no_command_panics_or_hangs_on_adversarial_params() { json!({"x": -9, "y": -9, "radius": 0, "amount": 0, "angle": 0, "opacity": 0, "scale": 0, "levels": 0, "tolerance": 0, "gamma": 0, "layer": 999999, "channel": 999, "index": 999999, "count": 0}), json!({"x": 1e5, "y": -1e5, "radius": 300, "amount": 300, "angle": 1e5, "opacity": -100, "scale": -5, "gamma": -1}), json!({"points": [], "from": [0, 0], "to": [0, 0], "stops": [], "matrix": [0, 0, 0, 0, 0, 0], "colors": [], "name": "", "mode": "", "style": ""}), + // Color Range and Replace Color samples (#6280): far off the canvas, malformed, and a + // click order that doesn't match them. + json!({"points": [[1e9, -1e9], [0.5, 0.5]], "subtractPoints": [[-1e9, 1e9], [2, 2]], "order": ["+", "-", "x", 5], "localized": true, "range": 0}), + json!({"points": [[3, 3]], "subtractPoints": [[3]], "order": {}, "fuzziness": -1}), + json!({"subtractPoints": "none", "order": ["-"], "labMinimum": [0, 0, 0], "labMaximum": [100, 0, 0]}), ]; let mut bad: Vec = Vec::new(); for spec in command_specs() { diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1397f9fa9e1..a75309bf854 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -770,7 +770,7 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< if curves_picking { crate::adjust_dialog::sample_at(app, d[0], d[1]); } else if replace_picking { - crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1]); + crate::filter_dialog::color_eyedropper_sample(app, d[0], d[1], input.ctx.input(|i| i.modifiers)); } else { crate::color_picker_ui::sample_at(app, d[0], d[1]); } diff --git a/crates/ui-egui/src/dialogs/color_range_ui.rs b/crates/ui-egui/src/dialogs/color_range_ui.rs index 3b02806d3a5..e914204315b 100644 --- a/crates/ui-egui/src/dialogs/color_range_ui.rs +++ b/crates/ui-egui/src/dialogs/color_range_ui.rs @@ -401,7 +401,7 @@ fn radio(ui: &mut egui::Ui, on: bool, label: &str) -> egui::Response { } /// Eyedropper button: the pipette icon with a +/− badge; labelled for accessibility. -fn eyedropper(ui: &mut egui::Ui, badge: &str, selected: bool, label: &str) -> egui::Response { +pub(crate) fn eyedropper(ui: &mut egui::Ui, badge: &str, selected: bool, label: &str) -> egui::Response { let t = Tokens::get(ui.ctx()); let r = crate::icons::button(ui, "pipette", 26.0, selected, label); if !badge.is_empty() { diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index be530341837..540c1bb3b97 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -508,6 +508,8 @@ pub fn reset_fields(app: &PhotocraftApp, fields: &mut Map) { // Drop user params; keep private `__` chrome (and fixed keys outside the schema for `__spec`). let schema_keys: std::collections::HashSet = parse_spec(&spec).into_iter().map(|p| p.key).collect(); fields.retain(|k, _| k.starts_with("__") || !schema_keys.contains(k)); + // The eyedroppers' click order goes with the samples just dropped (Replace Color, #6280). + fields.remove("__order"); for p in parse_spec(&spec) { if let Some(v) = default_value(app, &command, &p) { fields.insert(p.key, v); @@ -783,16 +785,31 @@ pub(crate) fn color_eyedropper_armed(app: &PhotocraftApp) -> bool { /// Sample the merged image at document point (x, y) into the armed dialog's "From" colour. /// Returns true when the click was consumed, even off-image or over transparency, where nothing /// changes and the eyedropper stays armed (like the Curves picker). -pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64) -> bool { +/// With the Add to Sample eyedropper (or Shift) the click adds a sample, with Subtract from +/// Sample (or Alt) it subtracts one, as in Photoshop and Select › Color Range (#6280). +pub(crate) fn color_eyedropper_sample(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) -> bool { let Some(id) = app.ui.dialogs.last().filter(|d| color_eyedropper_owns(&d.fields)).map(|d| d.id) else { return false; }; - if let Some(rgb) = crate::canvas::composite_color(app, x, y) - && let Some(d) = app.ui.dialog_mut(id) - { - d.fields.insert("color".into(), json!(crate::color_picker_ui::hex(rgb))); - // Where it was picked: Localized Color Clusters match the colour near this point (#4457). - d.fields.insert("points".into(), json!([[x.floor(), y.floor()]])); + let Some(rgb) = crate::canvas::composite_color(app, x, y) else { return true }; + let Some(mut f) = app.ui.dialogs.last().map(|d| d.fields.clone()) else { return true }; + let tool = f.get("__tool").and_then(Value::as_str); + let sample = !mods.shift && !mods.alt && tool.is_none_or(|t| t == "sample"); + // A first Add to Sample, before any sample, starts from the clicked colour too: one point + // matches through `color`, and Color Range's matcher starts its range there as well. + let add = mods.shift || (!mods.alt && tool == Some("add")); + let first_add = add && f.get("points").and_then(Value::as_array).is_none_or(Vec::is_empty); + if sample || first_add { + f.insert("color".into(), json!(crate::color_picker_ui::hex(rgb))); + } + // Where it was picked: Localized Color Clusters match the colour near this point (#4457); + // added and subtracted samples go to `points` / `subtractPoints` in click order. + crate::color_range_ui::pick(app, &mut f, [x, y], mods); + if let Some(order) = f.get("__order").cloned() { + f.insert("order".into(), order); + } + if let Some(d) = app.ui.dialog_mut(id) { + d.fields = f; } true } @@ -1034,9 +1051,21 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map) { // PhotoCraft's Color Picker, as everywhere else (#2144). clicked = crate::widgets::color_swatch_button(ui, egui::Color32::from_rgb(bytes[0], bytes[1], bytes[2]), &name).clicked(); if eyedropper { + // Photoshop's three eyedroppers (#6280), right to left here: Subtract + // from Sample, Add to Sample, Eyedropper. Clicking the chosen one again + // puts it away. let armed = f.get(COLOR_EYEDROPPER).and_then(Value::as_bool).unwrap_or(false); - if crate::icons::button(ui, "pipette", 24.0, armed, "Pick Color From Image").clicked() { - f.insert(COLOR_EYEDROPPER.into(), json!(!armed)); + let tool = f.get("__tool").and_then(Value::as_str).unwrap_or("sample").to_string(); + for (id, badge, label) in [ + ("subtract", "−", tl!("Subtract from Sample")), + ("add", "+", tl!("Add to Sample")), + ("sample", "", tl!("Pick Color From Image")), + ] { + let on = armed && tool == id; + if crate::color_range_ui::eyedropper(ui, badge, on, label).clicked() { + f.insert(COLOR_EYEDROPPER.into(), json!(!on)); + f.insert("__tool".into(), json!(id)); + } } } ui.label(egui::RichText::new(crate::color_picker_ui::hex(rgb)).color(t.text_dim).monospace()); diff --git a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs index 036b0858820..de9f389e234 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog/tests.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog/tests.rs @@ -1535,18 +1535,92 @@ fn replace_color_eyedropper_samples_the_image() { assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#ff0000"), "the dialog starts from the foreground colour"); // #6279: armed as it opens, so the first click on the image samples. assert!(color_eyedropper_armed(&app)); - assert!(color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0, egui::Modifiers::NONE)); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); // #4457: where it was picked, for Localized Color Clusters. assert_eq!(app.ui.dialogs.last().unwrap().fields["points"], json!([[4.0, 4.0]])); // Off-image: the click is consumed, nothing changes and the eyedropper stays armed. - assert!(color_eyedropper_sample(&mut app, -1.0, 4.0)); + assert!(color_eyedropper_sample(&mut app, -1.0, 4.0, egui::Modifiers::NONE)); assert_eq!(app.ui.dialogs.last().unwrap().fields["color"], json!("#00ff00")); assert!(color_eyedropper_armed(&app)); // Disarmed, the dialog never claims the click. app.ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(false)); assert!(!color_eyedropper_armed(&app)); - assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0)); + assert!(!color_eyedropper_sample(&mut app, 4.0, 4.0, egui::Modifiers::NONE)); +} + +/// #6280: Shift-click adds a sample and Alt-click subtracts one (as do the + and − eyedroppers), +/// in click order, as in Photoshop; a plain click starts over from the clicked colour. +#[test] +fn replace_color_shift_and_alt_clicks_add_and_subtract_samples() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + open(&mut app, REPLACE_COLOR).unwrap(); + let field = |app: &PhotocraftApp, k: &str| app.ui.dialogs.last().unwrap().fields.get(k).cloned().unwrap_or(Value::Null); + assert!(color_eyedropper_sample(&mut app, 2.0, 2.0, egui::Modifiers::NONE)); + assert!(color_eyedropper_sample(&mut app, 5.0, 5.0, egui::Modifiers::SHIFT)); + assert!(color_eyedropper_sample(&mut app, 9.0, 9.0, egui::Modifiers::ALT)); + assert_eq!(field(&app, "points"), json!([[2.0, 2.0], [5.0, 5.0]])); + assert_eq!(field(&app, "subtractPoints"), json!([[9.0, 9.0]])); + assert_eq!(field(&app, "order"), json!(["+", "+", "-"])); + assert_eq!(field(&app, "color"), json!("#00ff00"), "the From colour is the plain sample's"); + // The − eyedropper subtracts without a modifier; a plain click with the plain one starts over. + let id = app.ui.dialogs.last().unwrap().id; + app.ui.dialog_mut(id).unwrap().fields.insert("__tool".into(), json!("subtract")); + assert!(color_eyedropper_sample(&mut app, 3.0, 3.0, egui::Modifiers::NONE)); + assert_eq!(field(&app, "subtractPoints"), json!([[9.0, 9.0], [3.0, 3.0]])); + app.ui.dialog_mut(id).unwrap().fields.insert("__tool".into(), json!("sample")); + assert!(color_eyedropper_sample(&mut app, 7.0, 7.0, egui::Modifiers::NONE)); + assert_eq!((field(&app, "points"), field(&app, "subtractPoints")), (json!([[7.0, 7.0]]), json!([]))); +} + +/// A first click with Add to Sample, before any plain sample, takes the clicked colour as the +/// From colour, so the single-sample command replaces it, not the foreground colour (CodeRabbit +/// review on #10443). Color Range's matcher, used from the second sample on, also starts its +/// range at the first added colour. +#[test] +fn replace_color_first_add_to_sample_click_sets_the_from_colour() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + let field = |app: &PhotocraftApp, k: &str| app.ui.dialogs.last().unwrap().fields.get(k).cloned().unwrap_or(Value::Null); + assert_ne!(field(&app, "color"), json!("#00ff00"), "the dialog starts from the foreground colour"); + for (tool, mods) in [("sample", egui::Modifiers::SHIFT), ("add", egui::Modifiers::NONE)] { + let mut fields = app.ui.dialogs.last().unwrap().fields.clone(); + reset_fields(&app, &mut fields); + fields.insert("__tool".into(), json!(tool)); + app.ui.dialog_mut(id).unwrap().fields = fields; + assert!(color_eyedropper_sample(&mut app, 4.0, 4.0, mods)); + assert_eq!(field(&app, "points"), json!([[4.0, 4.0]])); + assert_eq!(field(&app, "color"), json!("#00ff00"), "{tool}"); + } + // A later added sample leaves the From colour alone. + app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("#123456")); + assert!(color_eyedropper_sample(&mut app, 6.0, 6.0, egui::Modifiers::SHIFT)); + assert_eq!(field(&app, "color"), json!("#123456")); +} + +/// Reset (Alt+Cancel) forgets the click order with the samples, so samples added afterwards +/// carry an order that fits them and the command takes it (CodeRabbit review on #10443). +#[test] +fn replace_color_reset_forgets_the_click_order() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 16, "height": 16, "background": "#00ff00"})).unwrap(); + let mut app = PhotocraftApp::new(s, crate::Services::default()); + let id = open(&mut app, REPLACE_COLOR).unwrap(); + assert!(color_eyedropper_sample(&mut app, 2.0, 2.0, egui::Modifiers::NONE)); + assert!(color_eyedropper_sample(&mut app, 9.0, 9.0, egui::Modifiers::ALT)); + let mut fields = app.ui.dialogs.last().unwrap().fields.clone(); + reset_fields(&app, &mut fields); + app.ui.dialog_mut(id).unwrap().fields = fields; + assert!(color_eyedropper_sample(&mut app, 5.0, 5.0, egui::Modifiers::SHIFT)); + assert!(color_eyedropper_sample(&mut app, 7.0, 7.0, egui::Modifiers::SHIFT)); + let f = app.ui.dialogs.last().unwrap().fields.clone(); + assert_eq!(f["order"], json!(["+", "+"]), "{f:?}"); + let p = json!({"color": f["color"], "points": f["points"], "order": f["order"], "hue": 30}); + app.session.execute(REPLACE_COLOR, p).unwrap(); } /// #4143: the eyedropper button disarms and re-arms the canvas picker (#6279: it opens armed). @@ -1627,7 +1701,7 @@ fn replace_color_localized_color_clusters() { h.run_steps(3); let _ = h.get_by_label("Localized Color Clusters"); h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(COLOR_EYEDROPPER.into(), json!(true)); - assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0)); + assert!(color_eyedropper_sample(h.state_mut(), 2.0, 5.0, egui::Modifiers::NONE)); h.get_by_label("Localized Color Clusters").click(); h.run_steps(2); let f = h.state().ui.dialogs.last().unwrap().fields.clone();