From f0322f74e8a488c3a476c646ef3cfd00d67a39eb Mon Sep 17 00:00:00 2001 From: Nigel Ihza Firdausy <106657905+Ni-zav@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:52:08 +0700 Subject: [PATCH] fix(selection): scope Color Range to the active selection (#3313) (#3366) * fix(selection): keep Color Range inside active selection and reject out-of-bounds samples * fix(ui): scope Color Range dialog and canvas previews to the active selection * test(selection): cover Color Range scoping, sampling, invert, Add and undo * test(ui): ensure Color Range preview and pipette honor existing selection * test(selection): avoid Debug bound when asserting prepared-query error * test(selection): validate malformed Color Range sample orders without selection interference * Color Range: format, and scope the OK undo test's prior selection (#3313) The existing ok_applies_one_undo_step test picked a prior selection that excluded the red it then expected Color Range to select; with Color Range scoped to the active selection it now selects the red inside it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- crates/engine/src/selection_cmds.rs | 127 +++++++++++++++++++++++++-- crates/ui-egui/src/color_range_ui.rs | 63 +++++++++++-- 2 files changed, 176 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs index 9720041707..e92a8fd5c7 100644 --- a/crates/engine/src/selection_cmds.rs +++ b/crates/engine/src/selection_cmds.rs @@ -27,6 +27,24 @@ fn mode(p: &Value) -> SelectionMode { SelectionMode::parse(p.get("mode").and_then(Value::as_str).unwrap_or("replace")) } +/// A Color Range replacement is scoped to the selection that was active when it opened. +/// Explicit add/subtract/intersect operations retain their normal selection-combine semantics. +fn point_in_selection(doc: &Document, x: i32, y: i32) -> bool { + doc.selection.as_ref().is_none_or(|selection| selection.sample_channel(x, y, 0) > 0.0) +} + +fn scope_color_range(mask: &mut [f32], doc: &Document, area: Rect, m: SelectionMode) { + if m != SelectionMode::Replace { + return; + } + if let Some(selection) = doc.selection.as_ref() { + let previous = sel::mask_from_surface(Some(selection), area); + for (value, bound) in mask.iter_mut().zip(previous) { + *value = value.min(bound); + } + } +} + /// RGBA pixels the tools sample: the composite, or the active layer. fn sample_pixels(s: &Session, all_layers: bool) -> Result<(Rect, Vec<[f32; 4]>)> { let d = s.active().ok_or(EngineError::NoDocument)?; @@ -127,7 +145,14 @@ fn parse_color(p: &Value) -> [f32; 3] { /// Eyedropper samples from `key` (`[[x, y], …]` in document pixels): the colour under each point /// and where it was picked (area-local, for Localized Color Clusters). -fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &impl Fn(String) -> EngineError) -> Result> { +fn eyedropper_samples( + p: &Value, + key: &str, + area: Rect, + px: &[[f32; 4]], + allowed: &impl Fn(i32, i32) -> bool, + bad: &impl Fn(String) -> EngineError, +) -> Result> { let Some(pts) = p.get(key) else { return Ok(Vec::new()) }; let pts = pts.as_array().ok_or_else(|| bad(format!("`{key}` must be [[x, y], …]")))?; let w = area.width() as usize; @@ -145,6 +170,9 @@ fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &i let Some(&[r, g, b, _]) = q else { return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); }; + if !allowed(xi, yi) { + return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the active selection"))); + } out.push(sel::RangeSample { color: [r, g, b], at: Some(((xi - area.x0) as f32, (yi - area.y0) as f32)) }); } Ok(out) @@ -215,6 +243,9 @@ impl ColorRangeSamples { if !area.contains(x, y) { return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas"))); } + if mode(p) == SelectionMode::Replace && !point_in_selection(doc, x, y) { + return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the active selection"))); + } let r = Rect::from_xywh(x, y, 1, 1); let pixel = if !b(p, "sampleAllLayers", true) { s.active().and_then(|d| d.active_layer.and_then(|id| d.doc.layer(id))).and_then(|l| l.surface()).map(|surf| { @@ -327,14 +358,17 @@ fn color_range(s: &mut Session, p: &Value) -> Result { let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg }; let preset = p.get("select").map_or(Some("sampledColors"), Value::as_str).ok_or_else(|| bad("`select` must be a string".into()))?; let invert = b(p, "invert", false); + let selection_mode = mode(p); let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0); let (area, mut mask) = match preset { "sampledColors" => { let (area, px) = sample_pixels(s, b(p, "sampleAllLayers", true))?; let w = area.width() as usize; // The dialog's eyedroppers: colours picked on the image, at their positions. - let plus = eyedropper_samples(p, "points", area, &px, &bad)?; - let minus = eyedropper_samples(p, "subtractPoints", area, &px, &bad)?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let allowed = |x, y| selection_mode != SelectionMode::Replace || point_in_selection(doc, x, y); + let plus = eyedropper_samples(p, "points", area, &px, &allowed, &bad)?; + let minus = eyedropper_samples(p, "subtractPoints", area, &px, &allowed, &bad)?; let query = ColorRangeSamples::with_samples(s, p, area, &plus, &minus)?; let mask = query.coverage(&px, w, 1.0, [0.0, 0.0]); (area, mask) @@ -393,7 +427,10 @@ fn color_range(s: &mut Session, p: &Value) -> Result { *v = 1.0 - *v; } } - set_selection(s, "Color Range", area, mask, mode(p)) + // Invert the colour result first, then constrain it to the original selection. + // Add mode must still be able to extend an existing selection intentionally. + scope_color_range(&mut mask, &s.active().ok_or(EngineError::NoDocument)?.doc, area, selection_mode); + set_selection(s, "Color Range", area, mask, selection_mode) } fn modify(s: &mut Session, p: &Value, op: &str) -> Result { @@ -649,6 +686,72 @@ mod tests { s.active().unwrap().doc.selection.as_ref().map_or(0.0, |m| m.sample_channel(x, y, 0)) } + fn clear_selection(s: &mut Session) { + if s.active().unwrap().doc.selection.is_some() { + s.execute("select.deselect", json!({})).unwrap(); + } + } + + #[test] + fn color_range_replace_is_bounded_by_existing_selection() { + for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { + let mut s = session(); + // Both red squares match, but only the left is inside the original selection. + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", params).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + assert_eq!(coverage(&s, 2, 2), 0.0); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + } + } + + #[test] + fn color_range_invert_and_partial_masks_stay_within_prior_selection() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + s.execute("select.colorRange", json!({"select": "highlights", "invert": true})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0, "inverted white excludes the white background"); + assert_eq!(coverage(&s, 20, 20), 0.0, "invert must not select outside the old boundary"); + + let mut s = session(); + s.edit("soft selection", |doc, _| { + let mut mask = vec![0.0; 40 * 30]; + mask[10 * 40 + 10] = 128.0 / 255.0; + doc.selection = Some(sel::mask_to_surface(&mask, doc.bounds())); + Ok(()) + }) + .unwrap(); + s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); + assert!((coverage(&s, 10, 10) - 128.0 / 255.0).abs() < 0.001); + assert_eq!(coverage(&s, 30, 10), 0.0); + } + + #[test] + fn color_range_eyedropper_respects_selection_but_add_can_extend_it() { + let mut s = session(); + s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap(); + let before = current_mask(&s.active().unwrap().doc).1; + let outside = json!({"points": [[30, 10]], "fuzziness": 0}); + assert!(s.execute("select.colorRange", outside.clone()).unwrap_err().to_string().contains("outside the active selection")); + assert!(ColorRangeSamples::new(&s, &outside).err().unwrap().to_string().contains("outside the active selection")); + assert_eq!(current_mask(&s.active().unwrap().doc).1, before); + s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 0.0); + + // Explicitly adding a matching colour is still allowed to grow the selection. + s.execute("select.colorRange", json!({"points": [[30, 10]], "fuzziness": 0, "mode": "add"})).unwrap(); + assert_eq!(coverage(&s, 10, 10), 1.0); + assert_eq!(coverage(&s, 30, 10), 1.0); + + clear_selection(&mut s); + s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 0})).unwrap(); + assert_eq!(coverage(&s, 30, 10), 1.0, "an unbounded color range still searches the canvas"); + } + #[test] fn magic_wand_selects_the_visible_alpha_or_mask_not_the_rgb() { let mut s = session(); @@ -719,6 +822,7 @@ mod tests { json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}), json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}), ] { + clear_selection(&mut s); let q = ColorRangeSamples::new(&s, &p).unwrap(); let doc = s.active().unwrap().doc.clone(); let pixels = photocraft_compose::render(&doc, doc.bounds()); @@ -751,6 +855,7 @@ mod tests { }) .unwrap(); for all_layers in [false, true] { + clear_selection(&mut s); let p = json!({"points": [[7, 7]], "sampleAllLayers": all_layers, "fuzziness": 0}); let query = ColorRangeSamples::new(&s, &p).unwrap(); let (area, px) = sample_pixels(&s, all_layers).unwrap(); @@ -822,16 +927,18 @@ mod tests { assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10), coverage(&s, 10, 24)), (1.0, 1.0, 1.0)); assert_eq!((coverage(&s, 2, 2), coverage(&s, 22, 24), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); // Eyedropper point on the blue square; `invert` flips the result. + clear_selection(&mut s); s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 100, "invert": true})).unwrap(); assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10), coverage(&s, 2, 2)), (0.0, 1.0, 1.0)); // Localized clusters: picked on the left red square, a 25% range (10 px) leaves the right one. + clear_selection(&mut s); s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 100, "localized": true, "range": 25})).unwrap(); assert_eq!(coverage(&s, 10, 10), 1.0); assert!(coverage(&s, 13, 10) > 0.5); assert_eq!(coverage(&s, 30, 10), 0.0); - // One undo step per call. + // Undo restores the empty selection that preceded the most recent Color Range. s.execute("edit.undo", json!({})).unwrap(); - assert_eq!(coverage(&s, 2, 2), 1.0); + assert_eq!(coverage(&s, 2, 2), 0.0); } #[test] @@ -848,6 +955,7 @@ mod tests { }) .unwrap(); let run = |s: &mut Session, extra: Value| { + clear_selection(s); let mut p = json!({"points": [[5, 5], [45, 5]], "fuzziness": 10}); p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); s.execute("select.colorRange", p).unwrap(); @@ -864,6 +972,7 @@ mod tests { let sub_last = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "+", "-"]})); assert!(sub_last[0] < 0.5, "{sub_last:?}"); // A malformed or inconsistent order is an error, never a panic. + clear_selection(&mut s); for bad in [json!(["+"]), json!(["+", "+", "x"]), json!("+-"), json!(["-", "-", "+"])] { assert!(s.execute("select.colorRange", json!({"points": [[5, 5], [45, 5]], "subtractPoints": [[15, 5]], "order": bad})).is_err(), "{bad}"); } @@ -875,18 +984,24 @@ mod tests { s.execute("select.colorRange", json!({"select": "reds"})).unwrap(); assert_eq!((coverage(&s, 10, 10), coverage(&s, 30, 10)), (1.0, 1.0)); assert_eq!((coverage(&s, 10, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (0.0, 0.0, 0.0)); + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "blues"})).unwrap(); assert_eq!((coverage(&s, 10, 24), coverage(&s, 10, 10)), (1.0, 0.0)); + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "greens"})).unwrap(); assert!(s.active().unwrap().doc.selection.is_none() || coverage(&s, 10, 10) == 0.0); // Tones: black is a shadow, white a highlight, 50% grey (128) a midtone. + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "shadows"})).unwrap(); assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2), coverage(&s, 32, 24)), (1.0, 0.0, 0.0)); + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "highlights"})).unwrap(); assert_eq!((coverage(&s, 22, 24), coverage(&s, 2, 2)), (0.0, 1.0)); + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "midtones", "fuzziness": 0})).unwrap(); assert_eq!((coverage(&s, 32, 24), coverage(&s, 2, 2), coverage(&s, 22, 24)), (1.0, 0.0, 0.0)); // A wider shadow range takes the grey too. + clear_selection(&mut s); s.execute("select.colorRange", json!({"select": "shadows", "tonalRange": 140, "fuzziness": 0})).unwrap(); assert_eq!(coverage(&s, 32, 24), 1.0); // Modes combine as for the other selection commands. diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rs index be92f041ff..b0500437cd 100644 --- a/crates/ui-egui/src/color_range_ui.rs +++ b/crates/ui-egui/src/color_range_ui.rs @@ -202,6 +202,20 @@ fn query_key(app: &PhotocraftApp, params: &Value) -> u64 { key.finish().max(1) } +/// Keep the accelerated preview paths in sync with the engine's Color Range replacement. +/// The full-resolution engine handles other combine modes itself. +fn scope_preview(proxy: &Document, params: &Value, mask: &mut [f32]) { + if matches!(params.get("mode").and_then(Value::as_str), Some("add" | "subtract" | "intersect")) { + return; + } + if let Some(selection) = proxy.selection.as_ref() { + let prior = photocraft_algo::selection::mask_from_surface(Some(selection), proxy.bounds()); + for (value, bound) in mask.iter_mut().zip(prior) { + *value = value.min(bound); + } + } +} + /// The selection mask `params` would make, on the proxy: the engine command run on a scratch /// session (Out Of Gamut uses the document's own proof setup). fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> Result, String> { @@ -223,7 +237,7 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> _ => photocraft_compose::render(proxy, area).px, }; let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false); - return Ok(query + let mut mask: Vec = query .coverage(&px, area.width() as usize, k as f32, [0.0, 0.0]) .into_iter() .map(|v| { @@ -231,13 +245,17 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> // Match the command's GRAY8 mask rounding, before display interpolation. (v.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0 }) - .collect()); + .collect(); + scope_preview(proxy, params, &mut mask); + return Ok(mask); } if params.get("select").and_then(Value::as_str) == Some("outOfGamut") { let pv = app.session.color.proof(proxy.id); let (m, _) = photocraft_engine::color_cmds::gamut_mask(proxy, &pv.setup, pv.gamut_threshold).map_err(|e| e.to_string())?; let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false); - return Ok(m.iter().map(|v| f32::from(*v) / 255.0).map(|v| if invert { 1.0 - v } else { v }).collect()); + let mut mask: Vec = m.iter().map(|v| f32::from(*v) / 255.0).map(|v| if invert { 1.0 - v } else { v }).collect(); + scope_preview(proxy, params, &mut mask); + return Ok(mask); } let mut p = params.clone(); // Eyedropper points are in document pixels; the proxy is 1/k the size. @@ -258,9 +276,8 @@ fn proxy_mask(app: &PhotocraftApp, proxy: &Document, k: u32, params: &Value) -> } let mut s = photocraft_engine::Session::new(); s.tools = app.session.tools.clone(); - let mut doc = proxy.clone(); - doc.selection = None; - s.add_document(doc, None); + // Preserve the proxy's pre-existing selection so preview and OK use the same scope. + s.add_document(proxy.clone(), None); if let Some(id) = app.session.active().and_then(|d| d.active_layer) { let _ = s.select_layer(id); } @@ -627,6 +644,9 @@ pub fn pick_top(app: &mut PhotocraftApp, at: [f64; 2], mods: egui::Modifiers) -> if !at[0].is_finite() || !at[1].is_finite() || at[0] < 0.0 || at[1] < 0.0 || at[0] >= f64::from(doc.size.width) || at[1] >= f64::from(doc.size.height) { return false; } + if doc.selection.as_ref().is_some_and(|selection| selection.sample_channel(at[0].floor() as i32, at[1].floor() as i32, 0) <= 0.0) { + return false; + } pick(app, &mut f, at, mods); match app.ui.dialogs.last_mut() { Some(d) => { @@ -683,6 +703,9 @@ pub fn pick(app: &PhotocraftApp, f: &mut Map, at: [f64; 2], mods: let (w, h) = (f64::from(st.doc.size.width.max(1)), f64::from(st.doc.size.height.max(1))); let [x, y] = at; let at = [x.floor().clamp(0.0, w - 1.0), y.floor().clamp(0.0, h - 1.0)]; + if st.doc.selection.as_ref().is_some_and(|selection| selection.sample_channel(at[0] as i32, at[1] as i32, 0) <= 0.0) { + return; + } let tool = if mods.shift { "add" } else if mods.alt { @@ -788,6 +811,29 @@ mod tests { h.get_by_label(label).accesskit_node().is_disabled() } + #[test] + fn preview_and_eyedropper_keep_the_original_selection_boundary() { + let mut app = app_with_doc(); + app.session.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); + let doc = app.session.active().unwrap().doc.clone(); + for params in [json!({"select": "sampledColors", "color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] { + let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); + assert_eq!(mask[5 * 40 + 5], 1.0, "red inside the selection stays visible"); + assert_eq!(mask[5 * 40 + 25], 0.0, "the blue outside the selection stays excluded"); + } + for params in [json!({"select": "sampledColors", "color": "#ffffff", "invert": true}), json!({"select": "outOfGamut", "invert": true})] { + let mask = proxy_mask(&app, &doc, 1, ¶ms).unwrap(); + assert_eq!(mask[5 * 40 + 25], 0.0, "even inverted previews stay within the selection"); + } + + open(&mut app); + assert!(!pick_top(&mut app, [25.0, 5.0], egui::Modifiers::NONE)); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert!(points(fields, "points").is_empty(), "a click outside the selection is ignored"); + assert!(pick_top(&mut app, [5.0, 5.0], egui::Modifiers::NONE)); + assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[5.0, 5.0]]); + } + #[test] fn preview_cache_refreshes_after_foreground_and_proof_changes() { let mut app = app_with_doc(); @@ -921,7 +967,8 @@ mod tests { #[test] fn ok_applies_one_undo_step() { let mut h = harness(app_with_doc()); - h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap(); + // The prior selection covers the left red square: Color Range is scoped to it (#3313). + h.state_mut().run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap(); let past = h.state().session.active().unwrap().history.past_len(); open(h.state_mut()); h.run_steps(4); @@ -935,7 +982,7 @@ mod tests { assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Color Range")); h.state_mut().run("edit.undo", json!({})).unwrap(); let app = h.state(); - assert_eq!((coverage(app, 5, 5), coverage(app, 2, 22)), (0.0, 1.0), "undo restores the previous selection"); + assert_eq!((coverage(app, 5, 5), coverage(app, 2, 22), coverage(app, 30, 5)), (1.0, 1.0, 0.0), "undo restores the previous selection"); } #[test]