Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Select › Color Range: Photoshop's Sampled Colors model, Subtract from Sample and the eyedropper on the image (#1239)

Unemarsf08cffd4d1e9
diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs
index 20fbbd2c8..70468d0c0 100644
--- a/crates/algo/src/selection.rs
+++ b/crates/algo/src/selection.rs
@@ -479,6 +479,174 @@ pub fn color_range_samples(px: &[[f32; 4]], w: usize, samples: &[RangeSample], f
.collect()
}
+/// The colours of Color Range › Sampled Colors: the Lab box spanned by the eyedropper samples
+/// (Photoshop records it in actions as the Minimum and Maximum Lab colours; "Add to Sample"
+/// grows it). One sample is a box of size zero. CIE Lab (D50): L 0–100, a and b about −128–127.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct LabRange {
+ pub lo: [f32; 3],
+ pub hi: [f32; 3],
+}
+
+impl LabRange {
+ /// The box around one colour.
+ pub fn point(lab: [f32; 3]) -> Self {
+ Self { lo: lab, hi: lab }
+ }
+
+ /// The box spanning `colors`, `None` when there are none.
+ pub fn spanning(colors: &[[f32; 3]]) -> Option<Self> {
+ let first = *colors.first()?;
+ Some(colors.iter().fold(Self::point(first), |r, c| r.grow(c)))
+ }
+
+ /// "Add to Sample": the box grows to take `lab` in.
+ pub fn grow(self, lab: &[f32; 3]) -> Self {
+ Self { lo: [0, 1, 2].map(|k| self.lo[k].min(lab[k])), hi: [0, 1, 2].map(|k| self.hi[k].max(lab[k])) }
+ }
+
+ /// "Subtract from Sample" the way Photoshop does it (observed through its Color Range dialog):
+ /// it only reshapes the box, each Lab axis on its own, with `w` the axis's width at `fuzziness`
+ /// (L: fuzziness/2.55 units, a and b: a third of fuzziness·256/255) and q = w/5.
+ ///
+ /// - Inside the box, the nearer edge moves onto the subtracted value (the upper one on a tie),
+ /// so the subtracted colour stays selected, at the new edge.
+ /// - On an edge or outside it by less than w, that edge moves in to the first of
+ /// m + q, m + 2q, … m + 5q beyond it (m the subtracted value).
+ /// - Further out, nothing changes. An edge never crosses the other one.
+ pub fn subtract(self, lab: &[f32; 3], fuzziness: f32) -> Self {
+ let fz = if fuzziness.is_finite() { fuzziness.max(0.0) } else { 0.0 };
+ let mut r = self;
+ for (k, &m) in lab.iter().enumerate() {
+ // Measured: the lightness step has no 256/255 factor, the a/b steps do.
+ let w = if k == 0 { fz / 2.55 } else { fz * 256.0 / 255.0 / 3.0 };
+ let (lo, hi) = (r.lo[k], r.hi[k]);
+ if !m.is_finite() {
+ continue;
+ }
+ if m > lo && m < hi {
+ if m - lo < hi - m {
+ r.lo[k] = m;
+ } else {
+ r.hi[k] = m;
+ }
+ continue;
+ }
+ let q = w / 5.0;
+ if q <= 0.0 {
+ continue;
+ }
+ let d = if m <= lo { lo - m } else { m - hi };
+ let n = (d / q).floor() + 1.0;
+ if n > 5.0 {
+ continue;
+ }
+ if m <= lo {
+ r.lo[k] = (m + n * q).min(hi);
+ } else {
+ r.hi[k] = (m - n * q).max(lo);
+ }
+ }
+ r
+ }
+}
+
+/// How much a Lab colour belongs to `range` at `fuzziness` (0–200), the way Photoshop's
+/// Select › Color Range › Sampled Colors decides it. Reconstructed by observation only (Color
+/// Range run on synthetic Lab lattices and photos with Photoshop's own eyedropper, its masks
+/// compared value by value): on an 8-bit sRGB photo it matches Photoshop 2024 to about half a
+/// level of 255 on average.
+///
+/// - Per axis, the distance outside the box in 8-bit Lab units: L × 2.55, a and b as they are,
+/// with a and b weighted ×3 (hue counts three times as much as lightness).
+/// - Each axis falls off on its own and the coverage is their minimum: the falloff of the
+/// largest of the three distances.
+/// - The falloff is a quadratic B-spline of width fuzziness × 256/255: full at the box, half at
+/// half the width, nothing beyond it, quantised to 256 levels like Photoshop's 8-bit masks.
+///
+/// Fuzziness 0 keeps only colours equal to the samples. For 8-bit documents use
+/// [`lab_range_coverage_8bit`].
+pub fn lab_range_coverage(lab: [f32; 3], range: &LabRange, fuzziness: f32) -> f32 {
+ coverage(lab, range, fuzziness, false)
+}
+
+/// [`lab_range_coverage`] for 8-bit documents, which Photoshop compares on the 8-bit Lab grid
+/// (pixels and samples through [`quantize_lab8`] first). There, a and b steps are uneven: a step
+/// above the samples' range counts half a unit more, one below it half a unit less, while
+/// colours inside the range (the sampled colour itself) stay fully selected. Measured on
+/// Photoshop's eyedropper masks of a photo, this halves the error of the plain distance.
+pub fn lab_range_coverage_8bit(lab: [f32; 3], range: &LabRange, fuzziness: f32) -> f32 {
+ coverage(lab, range, fuzziness, true)
+}
+
+fn coverage(lab: [f32; 3], range: &LabRange, fuzziness: f32, grid8: bool) -> f32 {
+ let outside = |v: f32, lo: f32, hi: f32| (lo - v).max(v - hi).max(0.0);
+ if fuzziness.is_nan() || fuzziness <= 0.0 {
+ let d =
+ (outside(lab[0], range.lo[0], range.hi[0]) * 2.55).max(outside(lab[1], range.lo[1], range.hi[1])).max(outside(lab[2], range.lo[2], range.hi[2]));
+ return if d < 0.5 { 1.0 } else { 0.0 };
+ }
+ let ab = |v: f32, lo: f32, hi: f32| {
+ if !grid8 {
+ outside(v, lo, hi)
+ } else if v > hi {
+ v - hi + 0.5
+ } else if v < lo {
+ (lo - v - 0.5).max(0.0)
+ } else {
+ 0.0
+ }
+ };
+ let dl = outside(lab[0], range.lo[0], range.hi[0]) * 2.55;
+ let da = 3.0 * ab(lab[1], range.lo[1], range.hi[1]);
+ let db = 3.0 * ab(lab[2], range.lo[2], range.hi[2]);
+ let t = dl.max(da).max(db) / (fuzziness * 256.0 / 255.0);
+ let v = if t <= 0.5 {
+ 1.0 - 2.0 * t * t
+ } else if t < 1.0 {
+ 2.0 * (1.0 - t) * (1.0 - t)
+ } else {
+ 0.0
+ };
+ (v * 256.0).floor().clamp(0.0, 255.0) / 255.0
+}
+
+/// A Lab colour on Photoshop's 8-bit Lab grid (L in 1/2.55 steps, a and b whole units), the
+/// precision its Color Range compares 8-bit documents at (pixels and samples alike).
+pub fn quantize_lab8(lab: [f32; 3]) -> [f32; 3] {
+ [(lab[0] * 2.55).round() / 2.55, lab[1].round(), lab[2].round()]
+}
+
+/// Color Range › Sampled Colors over Lab pixels (`lab[i]` = L, a, b, alpha; `w` the row width):
+/// each pixel's [`lab_range_coverage`] ([`lab_range_coverage_8bit`] with `grid8`), 0 where
+/// transparent. With `localized` (Localized Color
+/// Clusters: a radius in pixels and the sample positions) coverage also fades with the distance
+/// to the nearest sample, reaching 0 at the radius, so only nearby matching colours are selected.
+pub fn color_range_lab(lab: &[[f32; 4]], w: usize, range: &LabRange, fuzziness: f32, grid8: bool, localized: Option<(f32, &[(f32, f32)])>) -> Vec<f32> {
+ let w = w.max(1);
+ let localized = localized.filter(|(_, at)| !at.is_empty());
+ let mut out = vec![0.0f32; lab.len()];
+ par_rows(&mut out, w, 1, |y, row| {
+ for (x, m) in row.iter_mut().enumerate() {
+ let Some(&[l, a, b, alpha]) = lab.get(y * w + x) else { continue };
+ if alpha.is_nan() || alpha <= 0.0 {
+ continue;
+ }
+ let mut k = coverage([l, a, b], range, fuzziness, grid8);
+ if let Some((radius, at)) = localized
+ && k > 0.0
+ {
+ let (px, py) = (x as f32, y as f32);
+ let near =
+ at.iter().map(|&(sx, sy)| (1.0 - ((px - sx).powi(2) + (py - sy).powi(2)).sqrt() / radius.max(1.0)).clamp(0.0, 1.0)).fold(0.0f32, f32::max);
+ k *= near;
+ }
+ *m = k;
+ }
+ });
+ out
+}
+
/// Hue (degrees, 0..360) and chroma (max − min) of an RGB colour.
fn hue_chroma([r, g, b]: [f32; 3]) -> (f32, f32) {
let mx = r.max(g).max(b);
@@ -741,6 +909,165 @@ mod tests {
assert!(color_range_samples(&px, 4, &[], 10.0, None).iter().all(|v| *v == 0.0));
}
+ /// Photoshop 2024's own Color Range coverage around the sample Lab (60, 25, 19.9961), read
+ /// from its selections on a 16-bit Lab document: (Lab in Photoshop's internal scale, where
+ /// a/b = (v16 − 32768)/256, fuzziness, coverage).
+ const PHOTOSHOP_COVERAGE: &[([f32; 3], f32, f32)] = &[
+ ([61.9989, 25.5977, 20.5742], 40.0, 0.9686),
+ ([64.9989, 25.5977, 20.5742], 40.0, 0.7961),
+ ([67.9988, 25.5977, 20.5742], 40.0, 0.4824),
+ ([71.9997, 25.5977, 20.5742], 40.0, 0.1098),
+ ([79.9985, 25.5977, 20.5742], 40.0, 0.0),
+ ([71.9997, 25.5977, 20.5742], 100.0, 0.8118),
+ ([79.9985, 25.5977, 20.5742], 100.0, 0.4824),
+ ([60.0, 13.5508, 20.5742], 40.0, 0.0432),
+ ([60.0, 19.5742, 20.5742], 40.0, 0.6706),
+ ([60.0, 22.582, 20.5742], 40.0, 0.9333),
+ ([60.0, 28.6055, 20.5742], 40.0, 0.8549),
+ ([60.0, 31.6211, 20.5742], 40.0, 0.5098),
+ ([60.0, 37.6445, 20.5742], 40.0, 0.0078),
+ ([60.0, 13.5508, 20.5742], 100.0, 0.7647),
+ ([60.0, 37.6445, 20.5742], 100.0, 0.7137),
+ ([60.0, 25.5977, 10.5352], 40.0, 0.1725),
+ ([60.0, 25.5977, 16.5586], 40.0, 0.8667),
+ ([60.0, 25.5977, 24.5898], 40.0, 0.7647),
+ ([60.0, 25.5977, 30.6133], 40.0, 0.0863),
+ ([60.0, 25.5977, 10.5352], 100.0, 0.8392),
+ ([60.0, 25.5977, 30.6133], 100.0, 0.8),
+ ];
+
+ #[test]
+ fn lab_range_matches_photoshop() {
+ let r = LabRange::point([60.0, 25.0, 19.9961]);
+ for &(lab, fz, ps) in PHOTOSHOP_COVERAGE {
+ let got = lab_range_coverage(lab, &r, fz);
+ assert!((got - ps).abs() <= 2.0 / 255.0, "{lab:?} at fuzziness {fz}: {got} vs Photoshop {ps}");
+ }
+ // Lightness is three times as forgiving as hue: the same 6-unit step along L and along a.
+ assert!(lab_range_coverage([66.0, 25.0, 20.0], &r, 40.0) > lab_range_coverage([60.0, 31.0, 20.0], &r, 40.0));
+ // The sampled colour itself is always fully selected.
+ for fz in [1.0, 10.0, 40.0] {
+ assert_eq!(lab_range_coverage([60.0, 25.0, 19.9961], &r, fz), 1.0);
+ }
+ assert_eq!(quantize_lab8([60.1, 25.4, -19.6]), [(153.0f32 / 2.55), 25.0, -20.0]);
+ }
+
+ #[test]
+ fn lab_range_box_and_edges() {
+ let r = LabRange::spanning(&[[50.0, 10.0, 0.0], [60.0, 20.0, 5.0]]).unwrap();
+ assert_eq!(r, LabRange { lo: [50.0, 10.0, 0.0], hi: [60.0, 20.0, 5.0] });
+ assert!(LabRange::spanning(&[]).is_none());
+ // Everything inside the box is fully selected, whatever the fuzziness.
+ for fz in [1.0, 40.0, 200.0] {
+ assert_eq!(lab_range_coverage([55.0, 15.0, 2.0], &r, fz), 1.0);
+ }
+ // Coverage falls off outside it and is gone a fuzziness away.
+ let near = lab_range_coverage([55.0, 22.0, 2.0], &r, 40.0);
+ assert!(near > 0.0 && near < 1.0, "{near}");
+ assert_eq!(lab_range_coverage([55.0, 40.0, 2.0], &r, 40.0), 0.0);
+ // Fuzziness 0: exact colours only.
+ let p = LabRange::point([50.0, 10.0, -5.0]);
+ assert_eq!(lab_range_coverage([50.0, 10.0, -5.0], &p, 0.0), 1.0);
+ assert_eq!(lab_range_coverage([50.0, 11.0, -5.0], &p, 0.0), 0.0);
+ // Hostile numbers never panic and never select.
+ for v in [f32::NAN, f32::INFINITY, -f32::INFINITY] {
+ for fz in [v, 40.0] {
+ let k = lab_range_coverage([v, 0.0, 0.0], &p, fz);
+ assert!((0.0..=1.0).contains(&k), "{k}");
+ }
+ }
+ }
+
+ /// Boxes Photoshop 2024's Color Range dialog returned after Subtract from Sample, at
+ /// fuzziness 40 unless noted: (lo, hi, subtracted value, fuzziness, new lo, new hi) on one axis.
+ const PHOTOSHOP_SUBTRACT_A: &[(f32, f32, f32, f32, f32, f32)] = &[
+ (0.0, 20.0, 5.0, 40.0, 5.0, 20.0),
+ (0.0, 20.0, 10.0, 40.0, 0.0, 10.0),
+ (0.0, 20.0, 15.0, 40.0, 0.0, 15.0),
+ (0.0, 20.0, 0.0, 40.0, 2.68, 20.0),
+ (0.0, 20.0, -2.0, 40.0, 0.68, 20.0),
+ (0.0, 20.0, -3.0, 40.0, 2.36, 20.0),
+ (0.0, 20.0, -8.0, 40.0, 0.04, 20.0),
+ (0.0, 20.0, -11.0, 40.0, 2.4, 20.0),
+ (0.0, 20.0, -13.0, 40.0, 0.4, 20.0),
+ (0.0, 20.0, -14.0, 40.0, 0.0, 20.0),
+ (0.0, 20.0, 20.0, 40.0, 0.0, 17.32),
+ (0.0, 20.0, 23.0, 40.0, 0.0, 17.64),
+ (0.0, 20.0, 33.0, 40.0, 0.0, 19.6),
+ (0.0, 20.0, 0.0, 80.0, 5.35, 20.0),
+ (0.0, 20.0, -12.0, 80.0, 4.05, 20.0),
+ (0.0, 20.0, -22.0, 80.0, 4.76, 20.0),
+ (0.0, 20.0, -30.0, 80.0, 0.0, 20.0),
+ (0.0, 6.0, 4.0, 40.0, 0.0, 4.0),
+ (0.0, 2.0, 0.0, 40.0, 2.0, 2.0),
+ (0.0, 2.0, 3.0, 40.0, 0.0, 0.32),
+ ];
+
+ #[test]
+ fn subtract_reshapes_the_box_like_photoshop() {
+ for &(lo, hi, m, fz, want_lo, want_hi) in PHOTOSHOP_SUBTRACT_A {
+ let r = LabRange { lo: [50.0, lo, 0.0], hi: [50.0, hi, 0.0] }.subtract(&[50.0, m, 0.0], fz);
+ assert!(
+ (r.lo[1] - want_lo).abs() < 0.03 && (r.hi[1] - want_hi).abs() < 0.03,
+ "a [{lo}, {hi}] − {m} at {fz}: [{}, {}] vs Photoshop [{want_lo}, {want_hi}]",
+ r.lo[1],
+ r.hi[1]
+ );
+ }
+ // Lightness (box 40–60, fuzziness 40): Photoshop gave 43.14, 41.17, 40.79 and 45.1.
+ for (m, want) in [(40.0, 43.14), (34.902, 41.17), (25.098, 40.79), (45.098, 45.1)] {
+ let r = LabRange { lo: [40.0, 0.0, 0.0], hi: [60.0, 0.0, 0.0] }.subtract(&[m, 0.0, 0.0], 40.0);
+ assert!((r.lo[0] - want).abs() < 0.05, "L − {m}: {} vs Photoshop {want}", r.lo[0]);
+ }
+ // All three axes at once (Photoshop: two samples, then one colour outside the box).
+ let r = LabRange { lo: [53.58, 0.0, 0.0], hi: [59.05, 30.56, 25.03] }.subtract(&[53.33, -28.71, 36.45], 40.0);
+ let want = LabRange { lo: [56.47, 0.0, 0.0], hi: [59.05, 30.56, 23.05] };
+ for k in 0..3 {
+ assert!((r.lo[k] - want.lo[k]).abs() < 0.05 && (r.hi[k] - want.hi[k]).abs() < 0.05, "{r:?} vs {want:?}");
+ }
+ // A single sample can't be subtracted from itself; hostile numbers change nothing.
+ let p = LabRange::point([50.0, 10.0, 10.0]);
+ assert_eq!(p.subtract(&[50.0, 10.0, 10.0], 40.0), p);
+ assert_eq!(p.subtract(&[f32::NAN, f32::INFINITY, -f32::INFINITY], f32::NAN), p);
+ assert_eq!(LabRange::spanning(&[[50.0, 0.0, 0.0]]).unwrap().grow(&[60.0, -5.0, 3.0]), LabRange { lo: [50.0, -5.0, 0.0], hi: [60.0, 0.0, 3.0] });
+ }
+
+ #[test]
+ fn eight_bit_grid_steps_are_uneven_like_photoshop() {
+ let r = LabRange::point([50.0, 10.0, -20.0]);
+ // The sampled colour itself is fully selected at any fuzziness.
+ for fz in [1.0, 5.0, 10.0, 40.0] {
+ assert_eq!(lab_range_coverage_8bit([50.0, 10.0, -20.0], &r, fz), 1.0);
+ }
+ // One step above on a counts as 1.5 units, one below as 0.5 (×3 weight): at fuzziness 40
+ // (width 40.16) that is t = 4.5/40.16 and 1.5/40.16.
+ let up = lab_range_coverage_8bit([50.0, 11.0, -20.0], &r, 40.0);
+ let down = lab_range_coverage_8bit([50.0, 9.0, -20.0], &r, 40.0);
+ let p = |d: f32| (((1.0 - 2.0 * (d / (40.0 * 256.0 / 255.0)).powi(2)) * 256.0).floor().min(255.0)) / 255.0;
+ assert_eq!((up, down), (p(4.5), p(1.5)));
+ assert!(down > up);
+ // Lightness has no such offset; the exact (non-8-bit) coverage is symmetric.
+ assert_eq!(lab_range_coverage_8bit([51.0, 10.0, -20.0], &r, 40.0), lab_range_coverage_8bit([49.0, 10.0, -20.0], &r, 40.0));
+ assert_eq!(lab_range_coverage([50.0, 11.0, -20.0], &r, 40.0), lab_range_coverage([50.0, 9.0, -20.0], &r, 40.0));
+ let px = [[50.0, 11.0, -20.0, 1.0], [50.0, 9.0, -20.0, 1.0]];
+ assert_eq!(color_range_lab(&px, 2, &r, 40.0, true, None), vec![up, down]);
+ }
+
+ #[test]
+ fn color_range_lab_alpha_and_localized() {
+ let r = LabRange::point([50.0, 0.0, 0.0]);
+ let px = img(10, 1, |x, _| [50.0, 0.0, 0.0, if x == 0 { 0.0 } else { 1.0 }]);
+ let m = color_range_lab(&px, 10, &r, 40.0, false, None);
+ assert_eq!(m[0], 0.0, "transparent pixels are never selected");
+ assert!(m[1..].iter().all(|v| *v > 0.9));
+ let at = [(1.0, 0.0)];
+ let l = color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &at)));
+ assert!(l[1] > l[3] && l[3] > 0.0 && l[6] == 0.0, "{l:?}");
+ // No positions: localized clusters have nothing to centre on and change nothing.
+ assert_eq!(color_range_lab(&px, 10, &r, 40.0, false, Some((4.0, &[]))), m);
+ assert!(color_range_lab(&[], 0, &r, 40.0, false, None).is_empty());
+ }
+
#[test]
fn hue_families() {
let px = vec![
diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs
index bcdce0d5e..c138306c4 100644
--- a/crates/engine/src/selection_cmds.rs
+++ b/crates/engine/src/selection_cmds.rs
@@ -119,6 +119,37 @@ fn eyedropper_samples(p: &Value, key: &str, area: Rect, px: &[[f32; 4]], bad: &i
Ok(out)
}
+/// Composite RGB (the compositor's output profile for the document) → CIE Lab D50.
+fn lab_transform(s: &Session) -> Result<std::sync::Arc<photocraft_cms::Transform>> {
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let src = crate::color_cmds::composite_profile(&d.doc);
+ photocraft_cms::cached(&src, photocraft_cms::Builtin::LabD50.profile(), photocraft_cms::TransformOptions::default())
+ .map_err(|e| EngineError::Other(format!("colour management: {e}")))
+}
+
+/// The Lab profile's normalised encoding (ICC v4) → L 0–100, a and b −128–127.
+fn decode_lab(v: [f32; 3]) -> [f32; 3] {
+ [v[0] * 100.0, v[1] * 255.0 - 128.0, v[2] * 255.0 - 128.0]
+}
+
+fn colour_to_lab(t: &photocraft_cms::Transform, rgb: [f32; 3]) -> [f32; 3] {
+ let mut out = [0.0f32; 3];
+ t.eval(&rgb.map(|v| v.clamp(0.0, 1.0)), &mut out);
+ decode_lab(out)
+}
+
+/// RGBA pixels → Lab + alpha (L, a, b, alpha).
+fn pixels_to_lab(t: &photocraft_cms::Transform, px: &[[f32; 4]]) -> Vec<[f32; 4]> {
+ let src: Vec<[f32; 4]> = px.iter().map(|p| [p[0].clamp(0.0, 1.0), p[1].clamp(0.0, 1.0), p[2].clamp(0.0, 1.0), p[3]]).collect();
+ let mut out = vec![[0.0f32; 4]; px.len()];
+ t.convert_f32(src.as_flattened(), 4, out.as_flattened_mut(), 4, true);
+ for p in &mut out {
+ let [l, a, b] = decode_lab([p[0], p[1], p[2]]);
+ *p = [l, a, b, p[3]];
+ }
+ out
+}
+
fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "select.colorRange";
let bad = |msg: String| EngineError::BadParams { cmd: CMD.into(), msg };
@@ -130,40 +161,80 @@ 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 mut samples = eyedropper_samples(p, "points", area, &px, &bad)?;
+ let plus = eyedropper_samples(p, "points", area, &px, &bad)?;
let minus = eyedropper_samples(p, "subtractPoints", area, &px, &bad)?;
+ // The order the eyedropper clicks came in ("+" a point, "-" a subtracted point):
+ // Photoshop applies them one after another. Without it, all additions come first.
+ let order: Vec<bool> = match p.get("order") {
+ None => std::iter::repeat_n(true, plus.len()).chain(std::iter::repeat_n(false, minus.len())).collect(),
+ Some(o) => {
+ let o = o.as_array().ok_or_else(|| bad("`order` must be a list of \"+\" and \"-\"".into()))?;
+ let order = o
+ .iter()
+ .map(|v| match v.as_str() {
+ Some("+") => Ok(true),
+ Some("-") => Ok(false),
+ _ => Err(bad(format!("bad entry {v} in `order` (want \"+\" or \"-\")"))),
+ })
+ .collect::<Result<Vec<bool>>>()?;
+ if order.iter().filter(|x| **x).count() != plus.len() || order.iter().filter(|x| !**x).count() != minus.len() {
+ return Err(bad("`order` must list each of `points` (\"+\") and `subtractPoints` (\"-\") once".into()));
+ }
+ order
+ }
+ };
+ let mut fixed: Vec<[f32; 3]> = Vec::new();
if let Some(cs) = p.get("colors") {
let cs = cs.as_array().ok_or_else(|| bad("`colors` must be a list of colours".into()))?;
- for c in cs {
- samples.push(sel::RangeSample { color: parse_color(&json!({ "color": c })), at: None });
- }
+ fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c }))));
}
- if p.get("color").is_some() || samples.is_empty() {
- let color = if p.get("color").is_some() {
- parse_color(p)
- } else {
- let [r, g, b, _] = s.tools.foreground;
- [r, g, b]
- };
- samples.push(sel::RangeSample { color, at: None });
+ if p.get("color").is_some() {
+ fixed.push(parse_color(p));
}
// Localized Color Clusters: Range is a percentage of the canvas's longer side.
+ let plus_at: Vec<(f32, f32)> = plus.iter().filter_map(|x| x.at).collect();
let localized = if b(p, "localized", false) {
- if !samples.iter().chain(&minus).any(|x| x.at.is_some()) {
+ if plus_at.is_empty() {
return Err(bad("localized clusters need eyedropper `points`".into()));
}
Some(f(p, "range", 100.0).clamp(0.0, 100.0) / 100.0 * area.width().max(area.height()) as f32)
} else {
None
};
- let mut mask = sel::color_range_samples(&px, w, &samples, fuzz(40.0), localized);
- // The minus eyedropper: colours matching a subtracted sample (same Fuzziness) drop out.
- if !minus.is_empty() {
- let cut = sel::color_range_samples(&px, w, &minus, fuzz(40.0), localized);
- for (m, c) in mask.iter_mut().zip(&cut) {
- *m *= 1.0 - c;
+ // Photoshop compares colours in Lab, through the document's profile
+ // (sel::lab_range_coverage). The samples span one Lab box; "Add to Sample" grows it,
+ // "Subtract from Sample" reshapes it (sel::LabRange::subtract).
+ let to_lab = lab_transform(s)?;
+ // 8-bit documents are compared on the 8-bit Lab grid, samples and pixels alike.
+ let grid = s.active().is_some_and(|d| d.doc.depth == photocraft_doc::SampleType::U8);
+ let q = |c: [f32; 3]| if grid { sel::quantize_lab8(c) } else { c };
+ let mut lab = pixels_to_lab(&to_lab, &px);
+ if grid {
+ for p in &mut lab {
+ let [l, a, b] = sel::quantize_lab8([p[0], p[1], p[2]]);
+ *p = [l, a, b, p[3]];
+ }
+ }
+ let colour_to_lab = |t: &photocraft_cms::Transform, c: [f32; 3]| q(colour_to_lab(t, c));
+ let foreground = || {
+ let [r, g, b, _] = s.tools.foreground;
+ sel::LabRange::point(colour_to_lab(&to_lab, [r, g, b]))
+ };
+ let fixed_lab: Vec<[f32; 3]> = fixed.iter().map(|c| colour_to_lab(&to_lab, *c)).collect();
+ let mut range = sel::LabRange::spanning(&fixed_lab);
+ let (mut pi, mut mi) = (plus.iter(), minus.iter());
+ for add in order {
+ if add {
+ if let Some(x) = pi.next() {
+ let c = colour_to_lab(&to_lab, x.color);
+ range = Some(range.map_or(sel::LabRange::point(c), |r| r.grow(&c)));
+ }
+ } else if let Some(x) = mi.next() {
+ range = Some(range.unwrap_or_else(foreground).subtract(&colour_to_lab(&to_lab, x.color), fuzz(40.0)));
}
}
+ let range = range.unwrap_or_else(foreground);
+ let mask = sel::color_range_lab(&lab, w, &range, fuzz(40.0), grid, localized.map(|r| (r, plus_at.as_slice())));
(area, mask)
}
"reds" | "yellows" | "greens" | "cyans" | "blues" | "magentas" => {
@@ -405,7 +476,7 @@ pub fn specs() -> Vec<CommandSpec> {
"select.colorRange",
"Color Range…",
["Select"],
- r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"fuzziness":0..200=40 (tones: 0..100 %=20),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##,
+ r##"{"select":"sampledColors|reds|yellows|greens|cyans|blues|magentas|highlights|midtones|shadows|outOfGamut"="sampledColors","color":"#rrggbb"=foreground,"colors":["#rrggbb",…]?,"points":[[x,y],…]? (eyedropper samples),"subtractPoints":[[x,y],…]? (minus eyedropper),"order":["+"|"-",…]? (click order of points and subtractPoints; default all points first),"fuzziness":0..200=40 (tones: 0..100 %=20),"localized":bool=false,"range":0..100=100 (% of the longer side),"tonalRange":level|[lo,hi] (shadows 65, highlights 190, midtones [105,150]),"invert":bool=false,"sampleAllLayers":bool=true,"mode":"replace|add|subtract|intersect"="replace"}"##,
has_doc,
color_range
),
@@ -485,9 +556,36 @@ mod tests {
#[test]
fn color_range_selects_by_colour() {
let mut s = session();
- s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 10})).unwrap();
+ s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 40})).unwrap();
+ // The sampled colour itself is fully selected (as with Photoshop's eyedropper).
assert_eq!(coverage(&s, 10, 10), 1.0);
assert_eq!(coverage(&s, 20, 20), 0.0);
+ s.execute("select.colorRange", json!({"color": "#ff0000", "fuzziness": 100})).unwrap();
+ assert_eq!(coverage(&s, 10, 10), 1.0);
+ assert_eq!(coverage(&s, 20, 20), 0.0);
+ }
+
+ #[test]
+ fn color_range_compares_in_lab_like_photoshop() {
+ // Photoshop weighs hue (Lab a/b) three times as much as lightness; a per-channel RGB
+ // distance can't tell a lighter shade from a redder one.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 30, "height": 10})).unwrap();
+ s.edit("paint", |doc, _| {
+ let bg = doc.layers[0].surface_mut().unwrap();
+ let v = |c: u8| f32::from(c) / 255.0;
+ bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]); // skin
+ bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(220), v(160), v(140), 1.0]); // lighter skin
+ bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(220), v(140), v(120), 1.0]); // redder skin
+ Ok(())
+ })
+ .unwrap();
+ s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 40})).unwrap();
+ assert!(coverage(&s, 5, 5) > 0.98);
+ // Both differ from the sample by 20 levels in one RGB channel, yet the lighter one is
+ // kept clearly more (about 0.55 vs 0.31).
+ let (lighter, redder) = (coverage(&s, 15, 5), coverage(&s, 25, 5));
+ assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}");
}
/// Red squares (from `session`), a blue square, a black and a mid-grey strip on white.
@@ -507,14 +605,16 @@ mod tests {
#[test]
fn color_range_several_samples_points_and_invert() {
let mut s = session_colours();
- s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 10})).unwrap();
+ // Several samples span one Lab box (Photoshop's Minimum/Maximum): red and blue take
+ // both squares, black, grey and white stay out.
+ s.execute("select.colorRange", json!({"colors": ["#ff0000", "#0000ff"], "fuzziness": 100})).unwrap();
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), 0.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.
- s.execute("select.colorRange", json!({"points": [[7, 22]], "fuzziness": 10, "invert": true})).unwrap();
+ 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.
- s.execute("select.colorRange", json!({"points": [[10, 10]], "fuzziness": 10, "localized": true, "range": 25})).unwrap();
+ 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);
@@ -523,6 +623,41 @@ mod tests {
assert_eq!(coverage(&s, 2, 2), 1.0);
}
+ #[test]
+ fn color_range_subtract_follows_photoshop_and_the_click_order() {
+ // Grey strips from dark to light; samples at both ends span the whole run.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 50, "height": 10})).unwrap();
+ s.edit("paint", |doc, _| {
+ let bg = doc.layers[0].surface_mut().unwrap();
+ for (i, v) in [0.30f32, 0.40, 0.50, 0.60, 0.70].iter().enumerate() {
+ bg.fill_rect(Rect::new(i as i32 * 10, 0, i as i32 * 10 + 10, 10), &[*v, *v, *v, 1.0]);
+ }
+ Ok(())
+ })
+ .unwrap();
+ let run = |s: &mut Session, extra: Value| {
+ 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();
+ (0..5).map(|i| coverage(s, i * 10 + 5, 5)).collect::<Vec<f32>>()
+ };
+ assert!(run(&mut s, json!({})).iter().all(|v| *v > 0.99), "both samples span every strip");
+ // Subtracting a colour inside the range moves the nearer edge onto it: the strips beyond
+ // it drop out, the subtracted grey itself stays selected (Photoshop does the same).
+ let cut = run(&mut s, json!({"subtractPoints": [[15, 5]]}));
+ assert!(cut[0] < 0.5 && cut[1] > 0.99 && cut[4] > 0.99, "{cut:?}");
+ // Order matters: adding the dark strip back after the subtraction restores it.
+ let readd = run(&mut s, json!({"points": [[5, 5], [45, 5], [5, 5]], "subtractPoints": [[15, 5]], "order": ["+", "+", "-", "+"]}));
+ assert!(readd[0] > 0.99, "{readd:?}");
+ 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.
+ 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}");
+ }
+ }
+
#[test]
fn color_range_presets() {
let mut s = session_colours();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index b4a801c4b..2a3774928 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1806,6 +1806,13 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let d = xf.to_doc(p);
crate::color_picker_ui::sample_at(app, d[0], d[1]);
}
+ } else if primary
+ && !middle
+ && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect)
+ {
+ // Color Range samples colours with its eyedropper on the image itself.
+ let press = crate::dialogs::free_press(&ctx, rect).map(|q| xf.to_doc(q));
+ crate::color_range_ui::canvas_eyedropper(app, &ctx, p, press);
}
}
if tool == Tool::Hand && response.dragged() {
diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rs
index 543868e65..0857e5500 100644
--- a/crates/ui-egui/src/color_range_ui.rs
+++ b/crates/ui-egui/src/color_range_ui.rs
@@ -98,6 +98,7 @@ pub fn open(app: &mut PhotocraftApp) -> u64 {
f.insert("invert".into(), json!(false));
f.insert("points".into(), json!([]));
f.insert("subtractPoints".into(), json!([]));
+ f.insert("__order".into(), json!([]));
f.insert("__tool".into(), json!("sample"));
f.insert("__view".into(), json!("selection"));
app.color_range = None;
@@ -124,6 +125,9 @@ pub fn params(f: &Map<String, Value>) -> Value {
}
if !sub.is_empty() {
p.insert("subtractPoints".into(), json!(sub));
+ if let Some(o) = order(f, add.len(), sub.len()) {
+ p.insert("order".into(), o);
+ }
}
// Localized clusters need a picked position; until then it is the plain colour range.
if c.range && picked {
@@ -434,6 +438,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
if add + sub > 0 && widgets::secondary_button(ui, tl!("Clear Samples"), 0.0).clicked() {
set_points(f, "points", &[]);
set_points(f, "subtractPoints", &[]);
+ f.insert("__order".into(), json!([]));
}
});
ui.add_space(8.0);
@@ -459,6 +464,65 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
}
}
+/// The top dialog's fields when it is Color Range in a mode that takes eyedropper samples.
+fn sampling_top(app: &PhotocraftApp) -> Option<Map<String, Value>> {
+ app.ui.dialogs.last().map(|d| &d.fields).filter(|f| owns(f) && controls(f).sampling).cloned()
+}
+
+/// The dialog's eyedropper on the canvas: with Color Range › Sampled Colors as the top dialog,
+/// picks the colour at document point `at` (Shift adds to the sample, Alt subtracts), as a click
+/// on the image does in Photoshop. Returns whether it picked.
+pub fn pick_top(app: &mut PhotocraftApp, at: [f64; 2], mods: egui::Modifiers) -> bool {
+ let Some(mut f) = sampling_top(app) else { return false };
+ pick(app, &mut f, at, mods);
+ match app.ui.dialogs.last_mut() {
+ Some(d) => {
+ d.fields = f;
+ true
+ }
+ None => false,
+ }
+}
+
+/// The canvas under an open Color Range dialog is its eyedropper (Photoshop): the pointer `over`
+/// shows the dialog's eyedropper (+ / − while Shift / Alt add or subtract), and a press at document
+/// point `press` takes a sample. False when Color Range isn't the top dialog.
+pub fn canvas_eyedropper(app: &mut PhotocraftApp, ctx: &egui::Context, over: egui::Pos2, press: Option<[f64; 2]>) -> bool {
+ let Some(f) = sampling_top(app) else { return false };
+ let mods = ctx.input(|i| i.modifiers);
+ let tool = if mods.shift {
+ "add"
+ } else if mods.alt {
+ "subtract"
+ } else {
+ s(&f, "__tool", "sample")
+ };
+ if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise {
+ ctx.set_cursor_icon(egui::CursorIcon::Crosshair);
+ } else {
+ // The tip of the icon's pipette is at (2, 22) of its 24-unit box (as the Color Picker's).
+ crate::icons::cursor(ctx, "pipette", over, vec2(2.0, 22.0) / 24.0, 20.0);
+ ctx.set_cursor_icon(egui::CursorIcon::None);
+ }
+ let badge = match tool {
+ "add" => "+",
+ "subtract" => "−",
+ _ => "",
+ };
+ if !badge.is_empty() {
+ let p = ctx.layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("pc-color-range-badge")));
+ let at = over + vec2(20.0, -4.0);
+ p.text(at + vec2(1.0, 1.0), egui::Align2::CENTER_CENTER, badge, crate::theme::semibold(13.0), Color32::from_black_alpha(200));
+ p.text(at, egui::Align2::CENTER_CENTER, badge, crate::theme::semibold(13.0), Color32::WHITE);
+ }
+ if let Some(at) = press
+ && pick_top(app, at, mods)
+ {
+ ctx.request_repaint();
+ }
+ true
+}
+
/// An eyedropper click at document pixel `at`: the plain eyedropper replaces the samples, the
/// + one (or Shift) adds one, the − one (or Alt) subtracts one.
pub fn pick(app: &PhotocraftApp, f: &mut Map<String, Value>, at: [f64; 2], mods: egui::Modifiers) {
@@ -473,22 +537,36 @@ pub fn pick(app: &PhotocraftApp, f: &mut Map<String, Value>, at: [f64; 2], mods:
} else {
s(f, "__tool", "sample")
};
+ // The click order matters: Photoshop applies additions and subtractions one after another.
+ let mut order: Vec<Value> = f.get("__order").and_then(Value::as_array).cloned().unwrap_or_default();
match tool {
"add" => {
let mut p = points(f, "points");
p.push(at);
set_points(f, "points", &p);
+ order.push(json!("+"));
}
"subtract" => {
let mut p = points(f, "subtractPoints");
p.push(at);
set_points(f, "subtractPoints", &p);
+ order.push(json!("-"));
}
_ => {
set_points(f, "points", &[at]);
set_points(f, "subtractPoints", &[]);
+ order = vec![json!("+")];
}
}
+ f.insert("__order".into(), Value::Array(order));
+}
+
+/// The click order for the command (`order`), when it is consistent with the point lists.
+fn order(f: &Map<String, Value>, add: usize, sub: usize) -> Option<Value> {
+ let o = f.get("__order").and_then(Value::as_array)?;
+ let plus = o.iter().filter(|v| v.as_str() == Some("+")).count();
+ let minus = o.iter().filter(|v| v.as_str() == Some("-")).count();
+ (plus == add && minus == sub && plus + minus == o.len()).then(|| Value::Array(o.clone()))
}
#[cfg(test)]
@@ -714,10 +792,18 @@ mod tests {
assert_eq!(points(&f(&h), "subtractPoints"), vec![[35.0, 10.0]]);
let p = params(&f(&h));
assert_eq!(p["select"], "sampledColors");
+ assert_eq!(p["order"], json!(["+", "+", "-"]));
ok(&mut h);
h.run_steps(2);
let app = h.state();
- assert_eq!((coverage(app, 5, 5), coverage(app, 30, 5), coverage(app, 5, 22)), (1.0, 0.0, 0.0));
+ // The sampled red stays fully selected.
+ assert_eq!(coverage(app, 5, 5), 1.0);
+ // Like Photoshop, subtracting a colour on the edge of the samples' range only trims that
+ // edge by a fifth of the falloff: the blue stays mostly selected (Photoshop: 232 of 255
+ // for the same case), black never was.
+ let blue = coverage(app, 30, 5);
+ assert!(blue > 0.85 && blue < 0.95, "{blue}");
+ assert_eq!(coverage(app, 5, 22), 0.0);
}
#[test]
@@ -734,7 +820,7 @@ mod tests {
pick(&app, &mut f, [1.0, 1.0], egui::Modifiers::ALT);
assert_eq!(
params(&f),
- json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0, "points": [[3.0, 4.0], [39.0, 0.0]], "subtractPoints": [[1.0, 1.0]], "localized": true, "range": 100.0})
+ json!({"select": "sampledColors", "invert": false, "fuzziness": 40.0, "points": [[3.0, 4.0], [39.0, 0.0]], "subtractPoints": [[1.0, 1.0]], "order": ["+", "+", "-"], "localized": true, "range": 100.0})
);
f.insert("select".into(), json!("midtones"));
f.insert("midtonesLow".into(), json!(160.0));
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 96e8693bf..64b90c14b 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -475,6 +475,10 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
if let Some(d) = app.drag.as_mut().filter(|d| crate::hold_keys::repositions(d.tool)) {
d.reposition = space;
}
+ // Color Range › Sampled Colors on top: a press is its eyedropper on the image.
+ if matches!(ev, ToolEvent::Down { .. }) && crate::color_range_ui::pick_top(app, [x, y], mods) {
+ continue;
+ }
tool_event(app, ev, mods);
}
app.stylus.feed.set(None);
diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs
index 98fdde7ca..881602776 100644
--- a/crates/ui-egui/src/input_tests.rs
+++ b/crates/ui-egui/src/input_tests.rs
@@ -90,6 +90,52 @@ fn keyboard_zoom_works_with_a_dialog_open() {
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), layers);
}
+/// Select › Color Range: the eyedropper picks on the image itself (Photoshop), not only in the
+/// dialog's preview. Shift adds a sample, and the dialog stays open.
+#[test]
+fn color_range_eyedropper_picks_on_the_canvas() {
+ let mut h = harness();
+ crate::color_range_ui::open(h.state_mut());
+ h.run_steps(4);
+ let points = |h: &Harness<'static, PhotocraftApp>| {
+ let f = &h.state().ui.dialogs.last().unwrap().fields;
+ (f["points"].as_array().unwrap().len(), f["points"].clone())
+ };
+ let click = |h: &mut Harness<'static, PhotocraftApp>, p: Pos2, modifiers: Modifiers| {
+ h.hover_at(p);
+ h.run_steps(1);
+ h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers }, modifiers);
+ h.run_steps(1);
+ h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers }, modifiers);
+ h.run_steps(2);
+ };
+ // Zoomed in, the document reaches out from under the centred dialog.
+ {
+ let v = &mut h.state_mut().ui.views[0];
+ v.zoom = 3.0;
+ v.center = [200.0, 150.0];
+ v.fit_pending = false;
+ }
+ h.run_steps(2);
+ let v = h.state().ui.views[0].clone();
+ let c = h.state().last_canvas_rect.center();
+ let screen = |d: [f32; 2]| pos2(c.x + (d[0] - v.center[0]) * v.zoom, c.y + (d[1] - v.center[1]) * v.zoom);
+ let p = screen([30.5, 40.5]);
+ assert!(h.state().last_canvas_rect.contains(p));
+ click(&mut h, p, Modifiers::NONE);
+ let (n, pts) = points(&h);
+ assert_eq!(n, 1, "{pts}");
+ let at = doc_at(&h, p);
+ assert_eq!(pts[0][0].as_f64().unwrap().floor(), f64::from(at[0]).floor(), "{pts} vs {at:?}");
+ assert_eq!(pts[0][1].as_f64().unwrap().floor(), f64::from(at[1]).floor(), "{pts} vs {at:?}");
+ // ⇧-click adds another sample; the dialog never closes.
+ click(&mut h, screen([60.5, 40.5]), Modifiers::SHIFT);
+ assert_eq!(points(&h).0, 2);
+ assert_eq!(h.state().ui.dialogs.len(), 1);
+ // The document is untouched until OK.
+ assert!(h.state().session.active().unwrap().doc.selection.is_none());
+}
+
#[test]
fn clicking_outside_a_dialog_keeps_it_open_and_the_canvas_pans_and_zooms() {
let mut h = harness();