Merge pull request #12201 from hectorviov/fix/eyedropper-zoom-box

Eyedropper: at 100 % zoom and below an N by N Average covers (N+1) x (N+1) screen pixels (#11751)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-11 00:51:27 +01:00
commit 5ba0bb0a3a
7 files changed
+249 -12

No files matched your search

+2
View File
@@ -138,6 +138,8 @@ pub mod redeye_cmds;
pub mod render_cmds;
pub mod retouch_cmds;
pub mod sample_cmds;
#[cfg(test)]
mod sample_zoom_box_tests;
pub mod sampler_cmds;
pub mod select_extra_cmds;
pub mod selection_cmds;
+50 -3
View File
@@ -76,6 +76,32 @@ pub fn sample_rect(x: f64, y: f64, size: u32, canvas: Rect) -> Option<Rect> {
Some(square.intersect(&canvas))
}
/// The widest box, in document pixels, a zoomed-out average reads (#11751): at 1 % zoom a
/// 101 by 101 Average would otherwise composite a 10 200-pixel square on every pointer move.
pub const MAX_ZOOM_BOX: u32 = 4096;
/// [`sample_rect`] for the Eyedropper at view `zoom` (screen pixels per document pixel, 1.0 is
/// 100 %), as in Photoshop (#11751). Above 100 % it is the centred `size` × `size` square. At 100 %
/// and below an N by N Average covers (N+1) × (N+1) *screen* pixels: at 100 % the document pixels
/// x−N/2 to x+N/2+1 (N/2 rounded down), at 50 % 3 by 3 covers 8 × 8 document pixels. Point
/// Sample is one pixel at every zoom; no zoom is today's centred square.
pub fn sample_rect_at(x: f64, y: f64, size: u32, zoom: Option<f64>, canvas: Rect) -> Option<Rect> {
let centred = sample_rect(x, y, size, canvas)?;
let Some(zoom) = zoom.filter(|z| z.is_finite() && *z > 0.0 && *z <= 1.0) else { return Some(centred) };
if size == 1 {
return Some(centred);
}
let (px, py) = (x.floor() as i32, y.floor() as i32);
// (N+1) screen pixels in document pixels, at least N+1.
let side = (f64::from(size + 1) / zoom).round().clamp(f64::from(size + 1), f64::from(MAX_ZOOM_BOX)) as i32;
// The pixel sits just left of the box's middle: x−N/2 … x+N/2+1 at 100 %.
let before = (side + 1) / 2 - 1;
let x0 = px.saturating_sub(before);
let y0 = py.saturating_sub(before);
let square = Rect::new(x0, y0, x0.saturating_add(side), y0.saturating_add(side));
Some(square.intersect(&canvas))
}
/// Round `v` to what a channel of `depth` can store (32 bit keeps the float).
fn quantize(v: f32, depth: SampleType) -> f32 {
let mut b = [0u8; 4];
@@ -166,7 +192,13 @@ fn sampled_document(doc: &Document, active: Option<LayerId>, which: SampleLayers
/// the canvas. Transparent black off the canvas, over transparency, or when `which` needs an
/// active layer and there is none.
pub fn sample_color(doc: &Document, active: Option<LayerId>, x: f64, y: f64, size: u32, which: SampleLayers) -> [f32; 4] {
let Some(rect) = sample_rect(x, y, size, doc.bounds()) else { return [0.0; 4] };
sample_color_at(doc, active, x, y, size, None, which)
}
/// [`sample_color`] over the box the Eyedropper reads at view `zoom` ([`sample_rect_at`]); `None`
/// is the centred square, as the Color Sampler always uses (#11751).
pub fn sample_color_at(doc: &Document, active: Option<LayerId>, x: f64, y: f64, size: u32, zoom: Option<f64>, which: SampleLayers) -> [f32; 4] {
let Some(rect) = sample_rect_at(x, y, size, zoom, doc.bounds()) else { return [0.0; 4] };
let Some(src) = sampled_document(doc, active, which) else { return [0.0; 4] };
let buf = photocraft_compose::render(&src, rect);
if size == 1 {
@@ -203,6 +235,20 @@ pub fn size_param(cmd: &str, p: &Value) -> Result<u32> {
}
}
/// The optional `zoom` param (#11751): the view zoom the Eyedropper samples at, screen pixels per
/// document pixel (1.0 = 100 %). Missing or null: the centred box. Anything but a finite positive
/// number is an error.
pub fn zoom_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
match p.get("zoom") {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_f64()
.filter(|z| z.is_finite() && *z > 0.0)
.map(Some)
.ok_or_else(|| bad(cmd, format!("`zoom` = {v} must be a positive number (screen pixels per document pixel, 1 = 100 %)"))),
}
}
/// The `sampleLayer` param (default `all`).
pub fn layers_param(cmd: &str, p: &Value) -> Result<SampleLayers> {
match p.get("sampleLayer") {
@@ -225,15 +271,16 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Sample Color",
menu: &[],
shortcut: None,
params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all"} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it, clipped to the canvas; transparent off the canvas)"##,
params: r##"{"x":f64,"y":f64,"size":"point"|1|3|5|11|31|51|101=1,"sampleLayer":"current"|"currentAndBelow"|"all"|"allNoAdjustments"|"currentAndBelowNoAdjustments"="all","zoom":f64? (the view zoom, 1 = 100 %: at 100 % and below an N by N Average covers (N+1)×(N+1) screen pixels, as in Photoshop; missing: the centred square)} → [r,g,b,a] (the Eyedropper's Sample Size and Sample: the composite pixel, or the average of the size×size square centred on it (without `zoom`; with it, the zoom-dependent box above), clipped to the canvas; transparent off the canvas)"##,
enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document open".into()),
run: |s: &mut Session, p: &Value| {
const CMD: &str = "document.sampleColor";
let (x, y) = (coord(CMD, p, "x")?, coord(CMD, p, "y")?);
let size = size_param(CMD, p)?;
let zoom = zoom_param(CMD, p)?;
let which = layers_param(CMD, p)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
Ok(json!(sample_color(&d.doc, d.active_layer, x, y, size, which)))
Ok(json!(sample_color_at(&d.doc, d.active_layer, x, y, size, zoom, which)))
},
journal: false,
}]
@@ -0,0 +1,162 @@
//! #11751: the Eyedropper's N by N Average box depends on the view zoom, as in Photoshop. Above
//! 100 % it is the centred N × N square of document pixels; at 100 % and below it covers
//! (N+1) × (N+1) screen pixels (at 100 % the document pixels x−N/2 … x+N/2+1). Without a zoom
//! `document.sampleColor` keeps the centred square.
use serde_json::{Value, json};
use crate::Session;
/// The issue's test document: 800 × 600 RGB/8 white; on a pixel layer a red (220,30,30) block at
/// 100,100–300,250, 2 px black / 2 px white stripes at 350,100–450,200 (black at x 350–351,
/// 354–355, …) and a grey ramp of ten 40 px blocks from x 100, values 100, 105, …, 145, at
/// y 350–450.
fn test_document() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap();
s.execute("layer.new.layer", json!({"name": "Pixels"})).unwrap();
let fill = |s: &mut Session, x: i32, y: i32, w: i32, h: i32, grey_or_hex: String| {
s.execute("select.rect", json!({"x": x, "y": y, "width": w, "height": h})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": grey_or_hex})).unwrap();
};
fill(&mut s, 100, 100, 200, 150, "#dc1e1e".into());
fill(&mut s, 350, 100, 100, 100, "#ffffff".into());
for x in (350..450).step_by(4) {
fill(&mut s, x, 100, 2, 100, "#000000".into());
}
for i in 0..10 {
let v = 100 + 5 * i;
fill(&mut s, 100 + 40 * i, 350, 40, 100, format!("#{v:02x}{v:02x}{v:02x}"));
}
s.execute("select.deselect", json!({})).unwrap();
s
}
/// A black 400 × 400 document with one white pixel at 200,200 (the issue's probe).
fn probe() -> Session {
let mut s = Session::new();
s.execute("file.new", json!({"width": 400, "height": 400, "background": "white"})).unwrap();
s.execute("select.all", json!({})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#000000"})).unwrap();
s.execute("select.rect", json!({"x": 200, "y": 200, "width": 1, "height": 1})).unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#ffffff"})).unwrap();
s.execute("select.deselect", json!({})).unwrap();
s
}
/// The 8-bit RGB read at document pixel (x, y).
fn read(s: &mut Session, x: i32, y: i32, size: u32, zoom: Option<f64>) -> [i64; 3] {
let mut p = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": size});
if let Some(z) = zoom {
p["zoom"] = json!(z);
}
let v = s.execute("document.sampleColor", p).unwrap();
let c = |i: usize| (v[i].as_f64().unwrap() * 255.0).round() as i64;
[c(0), c(1), c(2)]
}
fn grey(v: i64) -> [i64; 3] {
[v, v, v]
}
#[test]
fn at_100_percent_the_test_document_reads_the_measured_table() {
// Sample Size: stripes x 351, stripes x 352 (y 150), grey x 139 (y 400), red left edge x 100 (y 150).
// The reference application's table, except grey x 139 up to 51 by 51: that box is exactly
// half 100 and half 105, a mean of 102.5, which the reference reads 102 and PhotoCraft's shared
// `average` rounds to 103 (half up, as every Sample Size average does today). The box is right
// (101 by 101, whose mean is no tie, reads 122 in both).
const TIE: i64 = 103;
let measured: [(u32, [[i64; 3]; 4]); 6] = [
(3, [grey(128), grey(128), grey(TIE), [229, 86, 86]]),
(5, [grey(128), grey(85), grey(TIE), [232, 105, 105]]),
(11, [grey(170), grey(149), grey(TIE), [235, 124, 124]]),
(31, [grey(175), grey(175), grey(TIE), [236, 135, 135]]),
(51, [grey(186), grey(181), grey(TIE), [237, 138, 138]]),
(101, [grey(189), grey(186), grey(122), [237, 140, 140]]),
];
let mut s = test_document();
for (size, want) in measured {
let got = [
read(&mut s, 351, 150, size, Some(1.0)),
read(&mut s, 352, 150, size, Some(1.0)),
read(&mut s, 139, 400, size, Some(1.0)),
read(&mut s, 100, 150, size, Some(1.0)),
];
assert_eq!(got, want, "{size} by {size} at 100 %");
}
}
#[test]
fn without_a_zoom_the_box_stays_the_centred_square() {
// Today's values from the issue: 3 by 3 at stripes x 351 reads 85, red edge 232,105,105.
let mut s = test_document();
assert_eq!(read(&mut s, 351, 150, 3, None), grey(85));
assert_eq!(read(&mut s, 352, 150, 3, None), grey(170));
assert_eq!(read(&mut s, 100, 150, 3, None), [232, 105, 105]);
assert_eq!(read(&mut s, 351, 150, 11, None), grey(162));
}
#[test]
fn the_probe_at_100_percent_reads_16_for_3_by_3_and_7_for_5_by_5() {
let mut s = probe();
// 3 by 3 is 4 × 4 from x−1 to x+2: clicks at 198–201 (both axes) catch the white pixel.
for x in 197..=202 {
let want = if (198..=201).contains(&x) { 16 } else { 0 };
assert_eq!(read(&mut s, x, 200, 3, Some(1.0)), grey(want), "3 by 3, x {x}");
assert_eq!(read(&mut s, 200, x, 3, Some(1.0)), grey(want), "3 by 3, y {x}");
}
// 5 by 5 is 6 × 6 from x−2 to x+3.
for x in 196..=203 {
let want = if (197..=202).contains(&x) { 7 } else { 0 };
assert_eq!(read(&mut s, x, 200, 5, Some(1.0)), grey(want), "5 by 5, x {x}");
}
}
#[test]
fn at_50_percent_3_by_3_covers_8_by_8_document_pixels() {
let mut s = probe();
assert_eq!(read(&mut s, 200, 200, 3, Some(0.5)), grey(4), "255 / 64");
}
#[test]
fn above_100_percent_it_is_the_centred_square() {
let mut s = probe();
for zoom in [2.0, 3.125, 128.0] {
for x in 198..=202 {
let want = if (199..=201).contains(&x) { 28 } else { 0 };
assert_eq!(read(&mut s, x, 200, 3, Some(zoom)), grey(want), "{zoom}: x {x}");
}
}
}
#[test]
fn point_sample_is_one_pixel_at_every_zoom() {
let mut s = probe();
for zoom in [None, Some(0.05), Some(0.5), Some(1.0), Some(4.0)] {
assert_eq!(read(&mut s, 200, 200, 1, zoom), grey(255), "{zoom:?}");
assert_eq!(read(&mut s, 201, 200, 1, zoom), grey(0), "{zoom:?}");
}
}
#[test]
fn a_far_zoomed_out_box_is_capped_and_clipped_not_a_panic() {
let mut s = probe();
// At 1 % a 101 by 101 box would be 10 200 px wide: capped, and clipped to the canvas.
let v = read(&mut s, 0, 0, 101, Some(0.01));
assert!(v.iter().all(|c| (0..=1).contains(c)), "one white pixel in a canvas-wide average: {v:?}");
let rect = super::sample_cmds::sample_rect_at(200.5, 200.5, 101, Some(0.01), photocraft_geom::Rect::new(0, 0, 100_000, 100_000)).unwrap();
assert!(rect.width() <= super::sample_cmds::MAX_ZOOM_BOX && rect.height() <= super::sample_cmds::MAX_ZOOM_BOX, "{rect:?}");
}
#[test]
fn a_bad_zoom_is_an_error_not_a_panic() {
let mut s = probe();
for bad in [json!(0), json!(-1.0), json!("fast"), json!([1]), json!(-1e300)] {
let r = s.execute("document.sampleColor", json!({"x": 10, "y": 10, "size": 3, "zoom": bad}));
assert!(r.is_err(), "zoom {bad}: {r:?}");
}
// A huge zoom is above 100 %: the centred square.
let v: Value = s.execute("document.sampleColor", json!({"x": 200.5, "y": 200.5, "size": 3, "zoom": 1e300})).unwrap();
assert!((v[0].as_f64().unwrap() * 255.0 - 28.3).abs() < 1.0, "{v}");
}
+3 -1
View File
@@ -274,7 +274,9 @@ fn sample_color(app: &mut PhotocraftApp, x: f64, y: f64, sample_layer: &str) ->
return None;
}
let size = app.ui.tool_options.eyedropper_size;
let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer})).ok()?;
// The box depends on the view zoom at 100 % and below, as in Photoshop (#11751).
let zoom = f64::from(app.current_zoom());
let v = app.run("document.sampleColor", json!({"x": x, "y": y, "size": size, "sampleLayer": sample_layer, "zoom": zoom})).ok()?;
match serde_json::from_value::<Vec<f32>>(v).ok()?[..] {
[r, g, b, a] if a > 0.0 => Some([r, g, b]),
_ => None,
+2 -2
View File
@@ -346,8 +346,8 @@ use widgets::tab_strip;
pub use widgets::text_field_menu;
pub use widgets::tone;
/// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size.
type InfoSampleKey = (i32, i32, u64, u32);
/// The Info panel's cached sample: pixel x, y, document revision, Eyedropper Sample Size and the view zoom's bits.
type InfoSampleKey = (i32, i32, u64, u32, u32);
pub struct PhotocraftApp {
pub session: Session,
+8 -5
View File
@@ -7,19 +7,22 @@ pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> {
}
/// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over
/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision.
/// the Eyedropper's Sample Size over the box it reads at the view zoom, as in Photoshop (#1649,
/// #11751), and cached per pixel, revision, size and zoom.
pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> {
let rev = app.session.active()?.revision;
let sample_size = app.ui.tool_options.eyedropper_size;
if let Some(((cx, cy, cr, cs), v)) = app.info_sample
&& (cx, cy, cr, cs) == (x, y, rev, sample_size)
let zoom = app.current_zoom();
let key = (x, y, rev, sample_size, zoom.to_bits());
if let Some((k, v)) = app.info_sample
&& k == key
{
return Some(v);
}
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size});
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size, "zoom": f64::from(zoom)});
let v: Vec<f32> = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?;
let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?];
app.info_sample = Some(((x, y, rev, sample_size), v));
app.info_sample = Some((key, v));
Some(v)
}
+22 -1
View File
@@ -120,9 +120,26 @@ mod tests {
}
}
/// View the document at 200 %, where an N by N Average is the centred N × N square (#11751:
/// at 100 % and below it covers (N+1) × (N+1) screen pixels).
fn zoomed_in(app: &mut PhotocraftApp) {
app.sync_views();
for v in &mut app.ui.views {
v.zoom = 2.0;
}
}
#[test]
fn a_click_samples_the_average_of_the_sample_size() {
let mut app = app();
// At 100 % a 3 by 3 Average is the 4 × 4 box from (2, 2): one black pixel of sixteen (#11751).
app.sync_views();
app.ui.tool_options.eyedropper_size = 3;
click(&mut app, 3.5, 3.5, egui::Modifiers::NONE);
let want = (255.0f32 * 15.0 / 16.0).round() / 255.0;
assert_eq!(fg(&app), [want, want, want, 1.0], "3 by 3 at 100 %");
app.ui.tool_options.eyedropper_size = 1;
zoomed_in(&mut app);
// Point Sample at (3, 3): white.
click(&mut app, 3.5, 3.5, egui::Modifiers::NONE);
assert_eq!(fg(&app), [1.0; 4]);
@@ -200,7 +217,11 @@ mod tests {
}
crate::panels::options_bar(app, ui);
},
app(),
{
let mut a = app();
zoomed_in(&mut a);
a
},
);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio);
h.run_steps(4);