PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Color Range: sample colours outside the active selection (#5244) (#5296)
Gert Pellin - GPEfe8fa3b9bc16
diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rsindex eda55c7d7..d6fc50aee 100644--- a/crates/engine/src/selection_cmds.rs+++ b/crates/engine/src/selection_cmds.rs@@ -30,10 +30,6 @@ fn mode(p: &Value) -> SelectionMode {/// 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;@@ -153,14 +149,7 @@ 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]],- allowed: &impl Fn(i32, i32) -> bool,- bad: &impl Fn(String) -> EngineError,-) -> Result<Vec<sel::RangeSample>> {+fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &impl Fn(String) -> EngineError) -> Result<Vec<sel::RangeSample>> {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;@@ -178,9 +167,6 @@ fn eyedropper_samples(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)@@ -251,9 +237,6 @@ 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| {@@ -377,10 +360,10 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {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 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)?;+ // Like Photoshop's, they may sample anywhere on the canvas: an active selection only+ // limits the result (scope_color_range), not where colours are picked (#5244).+ let plus = eyedropper_samples(p, "points", area, &px, &bad)?;+ let minus = eyedropper_samples(p, "subtractPoints", area, &px, &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)@@ -868,15 +851,24 @@ mod tests {assert_eq!(coverage(&s, 30, 10), 0.0);}+ #[test]+ fn color_range_eyedropper_samples_anywhere_but_the_result_stays_in_the_selection() {+ // #5244: as in Photoshop, a colour picked outside the active selection is accepted; only+ // the result is limited to the selection.+ let mut s = session();+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 30})).unwrap();+ let outside = json!({"points": [[30, 10]], "fuzziness": 0});+ assert!(ColorRangeSamples::new(&s, &outside).is_ok());+ s.execute("select.colorRange", outside).unwrap();+ assert_eq!(coverage(&s, 10, 10), 1.0, "the red inside the selection is selected");+ assert_eq!(coverage(&s, 30, 10), 0.0, "the sampled red outside it stays out");+ assert_eq!(coverage(&s, 2, 2), 0.0, "white is not the sampled colour");+ }+#[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);diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rsindex 80417eeec..59b3bfeb2 100644--- a/crates/ui-egui/src/color_range_ui.rs+++ b/crates/ui-egui/src/color_range_ui.rs@@ -649,9 +649,6 @@ 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) => {@@ -708,9 +705,6 @@ pub fn pick(app: &PhotocraftApp, f: &mut Map<String, Value>, 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 {@@ -831,10 +825,12 @@ mod tests {assert_eq!(mask[5 * 40 + 25], 0.0, "even inverted previews stay within the selection");}+ // As in Photoshop, the eyedropper samples anywhere; only the result is scoped (#5244).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, [25.0, 5.0], egui::Modifiers::NONE));+ assert_eq!(points(&app.ui.dialogs.last().unwrap().fields, "points"), vec![[25.0, 5.0]], "a colour outside the selection is sampled");+ let mask = proxy_mask(&app, &doc, 1, &json!({"select": "sampledColors", "points": [[25, 5]], "fuzziness": 0})).unwrap();+ assert_eq!(mask[5 * 40 + 25], 0.0, "but the preview stays within the selection");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]]);}