Skip to content

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

Color Range: improve previews, sampling and eyedropper responsiveness (#1377)

abc2cb02984af9696b
diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs
index 675bba2a3..de96f2ccf 100644
--- a/crates/engine/src/color_cmds.rs
+++ b/crates/engine/src/color_cmds.rs
@@ -288,8 +288,9 @@ impl ColorState {
self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: photocraft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
}
- /// The document's proofing state when it was ever changed (no default allocated).
- pub(crate) fn proof_ref(&self, doc: DocId) -> Option<&ProofView> {
+ /// Borrow the document's proofing state without cloning its profile or allocating defaults.
+ /// `None` means the unchanged defaults documented by [`Self::proof`].
+ pub fn proof_ref(&self, doc: DocId) -> Option<&ProofView> {
self.proofs.get(&doc)
}
diff --git a/crates/engine/src/selection_cmds.rs b/crates/engine/src/selection_cmds.rs
index 5fb515986..d9384ca3d 100644
--- a/crates/engine/src/selection_cmds.rs
+++ b/crates/engine/src/selection_cmds.rs
@@ -150,6 +150,147 @@ fn pixels_to_lab(t: &photocraft_cms::Transform, px: &[[f32; 4]]) -> Vec<[f32; 4]
out
}
+/// Prepared Sampled Colors query shared by the command and its interactive preview.
+/// Samples always come from the original document; reducing an image must not change them.
+pub struct ColorRangeSamples {
+ to_lab: std::sync::Arc<photocraft_cms::Transform>,
+ range: sel::LabRange,
+ grid: bool,
+ fuzziness: f32,
+ localized: Option<f32>,
+ plus_at: Vec<(f32, f32)>,
+}
+
+impl ColorRangeSamples {
+ /// Prepare the query without allocating a full-resolution composite. Point samples use
+ /// exactly the same compositor/profile as the final selection.
+ pub fn new(s: &Session, p: &Value) -> Result<Self> {
+ let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
+ let area = doc.bounds();
+ let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg };
+ let sample = |key: &str| -> 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 mut samples = Vec::new();
+ for point in pts {
+ let q = point.as_array().and_then(|v| match v.as_slice() {
+ [x, y] => Some((x.as_f64()?, y.as_f64()?)),
+ _ => None,
+ });
+ let Some((x, y)) = q.filter(|(x, y)| x.is_finite() && y.is_finite()) else {
+ return Err(bad(format!("bad point {point} in `{key}` (want [x, y])")));
+ };
+ let (x, y) = (x.floor() as i32, y.floor() as i32);
+ if !area.contains(x, y) {
+ return Err(bad(format!("point [{x}, {y}] in `{key}` is outside the canvas")));
+ }
+ 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| {
+ let mut px = [[0.0; 4]];
+ surf.read_rgba_into(r, &mut px);
+ px[0]
+ })
+ } else {
+ None
+ };
+ let px = match pixel {
+ Some(px) => px,
+ None => photocraft_compose::render(doc, r).px.first().copied().unwrap_or([0.0; 4]),
+ };
+ samples.push(sel::RangeSample { color: [px[0], px[1], px[2]], at: Some(((x - area.x0) as f32, (y - area.y0) as f32)) });
+ }
+ Ok(samples)
+ };
+ Self::with_samples(s, p, area, &sample("points")?, &sample("subtractPoints")?)
+ }
+
+ fn with_samples(s: &Session, p: &Value, area: Rect, plus: &[sel::RangeSample], minus: &[sel::RangeSample]) -> Result<Self> {
+ let bad = |msg: String| EngineError::BadParams { cmd: "select.colorRange".into(), msg };
+ let fuzz = |d: f32| f(p, "fuzziness", d).max(0.0);
+ // 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()))?;
+ fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c }))));
+ }
+ 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 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
+ };
+ // 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 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);
+ Ok(Self { to_lab, range, grid, fuzziness: fuzz(40.0), localized, plus_at })
+ }
+
+ /// Coverage of a composite rectangle. `scale` is the original document pixels represented
+ /// by one input pixel; `origin` is in original document pixels (for a visible canvas crop).
+ pub fn coverage(&self, px: &[[f32; 4]], width: usize, scale: f32, origin: [f32; 2]) -> Vec<f32> {
+ let mut lab = pixels_to_lab(&self.to_lab, px);
+ if self.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 scale = if scale.is_finite() && scale > 0.0 { scale } else { 1.0 };
+ let points: Vec<_> = self.plus_at.iter().map(|(x, y)| ((x - origin[0]) / scale, (y - origin[1]) / scale)).collect();
+ sel::color_range_lab(&lab, width, &self.range, self.fuzziness, self.grid, self.localized.map(|r| (r / scale, points.as_slice())))
+ }
+}
+
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 };
@@ -163,78 +304,8 @@ fn color_range(s: &mut Session, p: &Value) -> Result<Value> {
// 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)?;
- // 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()))?;
- fixed.extend(cs.iter().map(|c| parse_color(&json!({ "color": c }))));
- }
- 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 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
- };
- // 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())));
+ let query = ColorRangeSamples::with_samples(s, p, area, &plus, &minus)?;
+ let mask = query.coverage(&px, w, 1.0, [0.0, 0.0]);
(area, mask)
}
"reds" | "yellows" | "greens" | "cyans" | "blues" | "magentas" => {
@@ -555,6 +626,68 @@ mod tests {
assert_eq!(coverage(&s, 30, 10), 1.0);
}
+ #[test]
+ fn color_range_prepared_query_matches_the_command_at_all_depths() {
+ use photocraft_doc::{Color, ColorMode, SampleType, Size};
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for profile in [None, Some(photocraft_cms::Builtin::DisplayP3.profile().to_bytes())] {
+ let mut doc = Document::with_background("samples", Size::new(24, 12), ColorMode::Rgb, depth, Color::WHITE);
+ doc.icc_profile = profile;
+ let layer = doc.layers[0].surface_mut().unwrap();
+ layer.fill_rect(Rect::new(0, 0, 8, 12), &[0.65, 0.3, 0.2, 1.0]);
+ layer.fill_rect(Rect::new(8, 0, 16, 12), &[0.2, 0.3, 0.65, 1.0]);
+ let mut s = Session::new();
+ s.add_document(doc, None);
+ for p in [
+ json!({"points": [[2, 3]], "fuzziness": 0}),
+ json!({"points": [[2, 3], [10, 3]], "subtractPoints": [[10, 3]], "order": ["+", "+", "-"], "fuzziness": 40}),
+ json!({"points": [[2, 3]], "localized": true, "range": 50, "fuzziness": 80}),
+ ] {
+ let q = ColorRangeSamples::new(&s, &p).unwrap();
+ let doc = s.active().unwrap().doc.clone();
+ let pixels = photocraft_compose::render(&doc, doc.bounds());
+ let preview = q.coverage(&pixels.px, 24, 1.0, [0.0, 0.0]);
+ s.execute("select.colorRange", p).unwrap();
+ let actual = current_mask(&s.active().unwrap().doc).1;
+ for (shown, selected) in preview.iter().zip(actual) {
+ let rounded = (shown.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0;
+ assert_eq!(rounded, selected, "{depth:?}: original-pixel preview and OK differ");
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn color_range_prepared_query_samples_visible_layers_not_the_active_layer() {
+ use photocraft_doc::{Layer, LayerContent};
+ let mut s = session_colours();
+ let doc = s.active().unwrap().doc.clone();
+ let mut top = Layer::new("blue foreground", LayerContent::Raster(doc.layers[0].surface().unwrap().clone()));
+ top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]);
+ let mut hidden = Layer::new("hidden green", LayerContent::Raster(top.surface().unwrap().clone()));
+ hidden.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 40, 30), &[0.0, 1.0, 0.0, 1.0]);
+ hidden.visible = false;
+ s.edit("layers", |doc, _| {
+ doc.layers.push(top);
+ doc.layers.push(hidden);
+ Ok(())
+ })
+ .unwrap();
+ for all_layers in [false, true] {
+ 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();
+ let shown = query.coverage(&px, area.width() as usize, 1.0, [0.0, 0.0]);
+ s.execute("select.colorRange", p).unwrap();
+ assert_eq!(shown[7 * 40 + 7], coverage(&s, 7, 7));
+ assert_eq!(shown[24 * 40 + 10], coverage(&s, 10, 24));
+ }
+ for p in [json!({"points": [[-1, 0]]}), json!({"points": [[40, 1]]}), json!({"points": "wrong"}), json!({"points": [[null, 0]]})] {
+ assert!(ColorRangeSamples::new(&s, &p).is_err(), "{p}");
+ }
+ }
+
#[test]
fn color_range_selects_by_colour() {
let mut s = session();
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 6ce162b29..508aef84f 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1895,6 +1895,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) };
painter.image(tex, img_rect, uv, Color32::WHITE);
}
+ crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip);
// Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
if doc.has_artboards() {
let t = crate::theme::Tokens::get(&ctx);
@@ -2051,7 +2052,9 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
// Color Picker, never the reduced adjustment preview.
let curves_picking = crate::adjust_dialog::picker_armed(app);
let picking = primary && (crate::color_picker_ui::top(app).is_some() || curves_picking);
- let hand = app.ui.tool == Tool::Hand && !picking;
+ let range_picking =
+ primary && app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields) && crate::color_range_ui::controls(&d.fields).sampling);
+ let hand = app.ui.tool == Tool::Hand && !picking && !range_picking;
if let Some(d) = crate::dialogs::pan_delta(&ctx, rect, hand) {
view.center[0] -= d.x / view.zoom * if flip { -1.0 } else { 1.0 };
view.center[1] -= d.y / view.zoom;
@@ -2074,10 +2077,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
}
} else if primary
&& !middle
- && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect)
+ && let Some(p) = crate::dialogs::free_pointer_over(&ctx, rect).filter(|p| img_rect.contains(*p))
{
// 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));
+ let press = crate::dialogs::free_press(&ctx, rect)
+ .filter(|p| img_rect.contains(*p) && ctx.input(|i| i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO))
+ .map(|q| xf.to_doc(q));
crate::color_range_ui::canvas_eyedropper(app, &ctx, p, press);
}
}
diff --git a/crates/ui-egui/src/color_range_ui.rs b/crates/ui-egui/src/color_range_ui.rs
index 0857e5500..be92f041f 100644
--- a/crates/ui-egui/src/color_range_ui.rs
+++ b/crates/ui-egui/src/color_range_ui.rs
@@ -2,13 +2,15 @@
//! families, Highlights / Midtones / Shadows, Out Of Gamut), Fuzziness, Localized Color Clusters
//! with Range, the tonal range of Highlights / Midtones / Shadows, the three eyedroppers (sample,
//! add, subtract; they pick on the preview, Shift adds and Alt subtracts), a Selection / Image
-//! preview and Invert. Controls a mode doesn't use are disabled, like Photoshop's.
+//! preview, canvas Selection Preview modes and Invert. Controls a mode doesn't use are disabled, like Photoshop's.
//!
//! Everything lives in the dialog fields (`ui.dialog.set` drives it). The preview and OK run the
//! same engine command, `select.colorRange`, so the GUI, MCP and scripts select identically; the
-//! preview runs it on a small proxy of the document, OK on the document itself (one history step).
+//! preview compares a small proxy against samples from the original document; OK selects at
+//! full resolution (one history step). Reduced previews approximate fine detail and effects.
//! Cancel never touches the document, so the previous selection stays as it was.
+use std::hash::{Hash, Hasher};
use std::sync::Arc;
use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
@@ -41,6 +43,10 @@ pub const SELECTS: &[(&str, &str)] = &[
/// Longest side of the preview thumbnail, in points.
const PREVIEW: u32 = 200;
+/// Canvas overlays are view state; keep their allocation bounded on very large documents.
+const CANVAS_PREVIEW: u32 = 1024;
+const PREVIEWS: &[(&str, &str)] =
+ &[("none", "None"), ("grayscale", "Grayscale"), ("blackMatte", "Black Matte"), ("whiteMatte", "White Matte"), ("quickMask", "Quick Mask")];
/// Which controls the current Select mode uses (the rest are disabled or hidden).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -101,6 +107,7 @@ pub fn open(app: &mut PhotocraftApp) -> u64 {
f.insert("__order".into(), json!([]));
f.insert("__tool".into(), json!("sample"));
f.insert("__view".into(), json!("selection"));
+ f.insert("__selectionPreview".into(), json!("none"));
app.color_range = None;
app.ui.open_dialog(DialogKind::Command, f)
}
@@ -168,16 +175,64 @@ pub struct Preview {
mask: Option<egui::TextureHandle>,
/// Why the preview couldn't be drawn (shown in the dialog and logged, never silent: #145).
error: Option<String>,
+ canvas_proxy: Option<(u32, Arc<Document>)>,
+ overlay: Option<egui::TextureHandle>,
+ overlay_key: u64,
}
fn hash(text: &str) -> u64 {
text.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3))
}
+fn query_key(app: &PhotocraftApp, params: &Value) -> u64 {
+ let mut key = std::collections::hash_map::DefaultHasher::new();
+ params.to_string().hash(&mut key);
+ let foreground = app.session.tools.foreground;
+ foreground.map(f32::to_bits).hash(&mut key);
+ // This runs several times per frame, including mere pointer motion. Debug-formatting a
+ // ProofView serializes the whole ICC profile/LUT; proof() also clones the default profile.
+ // Borrow the state and use the profile's memoized content hash instead.
+ let proof = app.session.active().and_then(|st| app.session.color.proof_ref(st.doc.id));
+ proof.is_some().hash(&mut key);
+ if let Some(proof) = proof {
+ let setup = &proof.setup;
+ (setup.profile.content_hash(), setup.intent, setup.bpc, setup.simulate_paper, setup.kind).hash(&mut key);
+ (proof.enabled, proof.gamut_warning, proof.gamut_threshold.to_bits()).hash(&mut key);
+ }
+ key.finish().max(1)
+}
+
/// 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<Vec<f32>, String> {
let area = proxy.bounds();
+ if params.get("select").and_then(Value::as_str).unwrap_or("sampledColors") == "sampledColors" {
+ // Pick on the original document, not the thumbnail's nearest retained pixel. The
+ // prepared Lab query is the same one the command uses at full resolution.
+ let query = photocraft_engine::selection_cmds::ColorRangeSamples::new(&app.session, params).map_err(|e| e.to_string())?;
+ // Like the command (and OK): `sampleAllLayers: false` judges the active layer's own
+ // pixels, otherwise the composite.
+ let all_layers = params.get("sampleAllLayers").and_then(Value::as_bool).unwrap_or(true);
+ let layer = app.session.active().and_then(|d| d.active_layer).and_then(|id| proxy.layer(id)).and_then(|l| l.surface());
+ let px = match (all_layers, layer) {
+ (false, Some(surf)) => {
+ let mut px = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];
+ surf.read_rgba_into(area, &mut px);
+ px
+ }
+ _ => photocraft_compose::render(proxy, area).px,
+ };
+ let invert = params.get("invert").and_then(Value::as_bool).unwrap_or(false);
+ return Ok(query
+ .coverage(&px, area.width() as usize, k as f32, [0.0, 0.0])
+ .into_iter()
+ .map(|v| {
+ let v = if invert { 1.0 - v } else { v };
+ // Match the command's GRAY8 mask rounding, before display interpolation.
+ (v.clamp(0.0, 1.0) * 255.0 + 0.5).floor() / 255.0
+ })
+ .collect());
+ }
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())?;
@@ -236,11 +291,23 @@ fn preview(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map<String, Value>)
let side = doc.size.width.max(doc.size.height).max(1);
let k = side.div_ceil(PREVIEW).max(1);
let proxy = Arc::new(crate::proxy::proxy_document(&doc, k));
- app.color_range = Some(Preview { doc: doc_id, revision, k, proxy, image: None, mask_key: 0, mask: None, error: None });
+ app.color_range = Some(Preview {
+ doc: doc_id,
+ revision,
+ k,
+ proxy,
+ image: None,
+ mask_key: 0,
+ mask: None,
+ error: None,
+ canvas_proxy: None,
+ overlay: None,
+ overlay_key: 0,
+ });
}
- let image_view = s(f, "__view", "selection") == "image";
+ let image_view = (s(f, "__view", "selection") == "image") ^ ctx.input(|i| i.modifiers.command || (!cfg!(target_os = "macos") && i.modifiers.ctrl));
let params = params(f);
- let key = hash(&params.to_string()).max(1);
+ let key = query_key(app, &params);
let (proxy, k) = {
let p = app.color_range.as_ref()?;
(p.proxy.clone(), p.k)
@@ -248,7 +315,14 @@ fn preview(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Map<String, Value>)
let (w, h) = (proxy.size.width as usize, proxy.size.height as usize);
if image_view {
if app.color_range.as_ref().is_some_and(|p| p.image.is_none()) {
- let thumb = photocraft_compose::thumbnail(&proxy, proxy.size.width.max(proxy.size.height));
+ let buf = photocraft_compose::thumbnail_buffer(&proxy, proxy.size.width.max(proxy.size.height));
+ let thumb = match app.session.color.canvas_display(&proxy) {
+ Ok(display) => display.to_rgba8(&buf),
+ Err(e) => {
+ report(app, Some(e.to_string()));
+ return None;
+ }
+ };
let size = [thumb.width as usize, thumb.height as usize];
if size != [w, h] || thumb.pixels.len() != w * h * 4 {
report(app, Some(format!("the image thumbnail is {}×{}, expected {w}×{h}", thumb.width, thumb.height)));
@@ -380,7 +454,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
ui.horizontal_top(|ui| {
// Preview: the selection as a grayscale mask, or the image to pick colours from.
let box_size = vec2(PREVIEW as f32, PREVIEW as f32);
- let (frame, resp) = ui.allocate_exact_size(box_size, Sense::click());
+ let (frame, resp) = ui.allocate_exact_size(box_size, Sense::click_and_drag());
ui.painter().rect_filled(frame, 0.0, t.canvas);
let shown = preview(app, ui.ctx(), f);
if let Some((tex, [w, h], k)) = shown {
@@ -388,7 +462,13 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
let img_rect = Rect::from_center_size(frame.center(), vec2(w as f32 * scale, h as f32 * scale));
ui.painter().image(tex, img_rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
// Eyedropper on the preview (Photoshop also samples in the preview area).
- if let Some(p) = resp.interact_pointer_pos().filter(|p| resp.clicked() && c.sampling && img_rect.contains(*p)) {
+ // Response::clicked may consume accessibility input (a write lock): query it
+ // before reading PointerState, never from inside Ui::input's read lock.
+ let clicked = resp.clicked();
+ let held = resp.is_pointer_button_down_on();
+ let sample =
+ ui.input(|i| (clicked && i.pointer.primary_pressed()) || (held && (i.pointer.primary_pressed() || i.pointer.delta() != egui::Vec2::ZERO)));
+ if let Some(p) = resp.interact_pointer_pos().filter(|p| c.sampling && sample && img_rect.contains(*p)) {
let at = [
((p.x - img_rect.left()) / scale).floor().max(0.0) as f64 * f64::from(k) + f64::from(k / 2),
((p.y - img_rect.top()) / scale).floor().max(0.0) as f64 * f64::from(k) + f64::from(k / 2),
@@ -459,11 +539,80 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Valu
f.insert("__view".into(), json!("image"));
}
});
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ ui.label(egui::RichText::new(tl!("Selection Preview:")).color(t.text_dim));
+ let mode = s(f, "__selectionPreview", "none").to_string();
+ let mut chosen = mode.as_str();
+ if widgets::dropdown(ui, "color-range-selection-preview", &mut chosen, PREVIEWS, 170.0) {
+ f.insert("__selectionPreview".into(), json!(chosen));
+ }
+ });
if app.session.active().is_none() {
ui.label(egui::RichText::new(tl!("Open a document to select a colour range.")).color(t.text_faint));
}
}
+/// A selection view is an overlay only: eyedroppers always sample the original image below it.
+/// White = selected, black = unselected, gray = partial; matte/Quick Mask cover unselected pixels.
+fn overlay_pixel(mode: &str, coverage: f32) -> Color32 {
+ let coverage = coverage.clamp(0.0, 1.0);
+ let q = |v: f32| (v * 255.0 + 0.5) as u8;
+ match mode {
+ "grayscale" => Color32::from_gray(q(coverage)),
+ "blackMatte" => Color32::from_black_alpha(q(1.0 - coverage)),
+ "whiteMatte" => Color32::from_rgba_unmultiplied(255, 255, 255, q(1.0 - coverage)),
+ "quickMask" => Color32::from_rgba_unmultiplied(255, 0, 0, q(0.5 * (1.0 - coverage))),
+ _ => Color32::TRANSPARENT,
+ }
+}
+
+/// Photoshop's Selection Preview on the image, shared by CPU/GPU canvases and all platforms.
+/// This never edits the real selection, image, channels or history; closing the dialog removes it.
+pub(crate) fn paint_selection_preview(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, doc: DocId, image: Rect, flip: bool) {
+ let Some(fields) = app.ui.dialogs.last().filter(|d| owns(&d.fields)).map(|d| d.fields.clone()) else { return };
+ let mode = s(&fields, "__selectionPreview", "none");
+ if mode == "none" || !app.session.active().is_some_and(|st| st.doc.id == doc) {
+ return;
+ }
+ // Refresh the document/revision cache before borrowing its canvas proxy.
+ let _ = preview(app, ctx, &fields);
+ if app.color_range.as_ref().is_some_and(|p| p.canvas_proxy.is_none()) {
+ let Some(original) = app.session.active().map(|st| st.doc.clone()) else { return };
+ let k = original.size.width.max(original.size.height).max(1).div_ceil(CANVAS_PREVIEW);
+ let proxy = Arc::new(crate::proxy::proxy_document(&original, k));
+ if let Some(p) = app.color_range.as_mut() {
+ p.canvas_proxy = Some((k, proxy));
+ }
+ }
+ let params = params(&fields);
+ let key = (query_key(app, &params) ^ hash(mode)).max(1);
+ if app.color_range.as_ref().is_some_and(|p| p.overlay_key != key || p.overlay.is_none()) {
+ let Some((k, proxy)) = app.color_range.as_ref().and_then(|p| p.canvas_proxy.clone()) else { return };
+ let mask = match proxy_mask(app, &proxy, k, &params) {
+ Ok(mask) => mask,
+ Err(e) => {
+ report(app, Some(e));
+ return;
+ }
+ };
+ let size = [proxy.size.width as usize, proxy.size.height as usize];
+ let pixels = mask.into_iter().map(|v| overlay_pixel(mode, v)).collect();
+ let img = egui::ColorImage::new(size, pixels);
+ if let Some(p) = app.color_range.as_mut() {
+ match &mut p.overlay {
+ Some(t) => t.set(img, egui::TextureOptions::LINEAR),
+ None => p.overlay = Some(ctx.load_texture("color-range-canvas-preview", img, egui::TextureOptions::LINEAR)),
+ }
+ p.overlay_key = key;
+ }
+ }
+ if let Some(tex) = app.color_range.as_ref().and_then(|p| p.overlay.as_ref()) {
+ let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)) };
+ painter.image(tex.id(), image, uv, Color32::WHITE);
+ }
+}
+
/// 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()
@@ -474,6 +623,10 @@ fn sampling_top(app: &PhotocraftApp) -> Option<Map<String, Value>> {
/// 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 };
+ let Some(doc) = app.session.active().map(|st| &st.doc) else { return false };
+ 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;
+ }
pick(app, &mut f, at, mods);
match app.ui.dialogs.last_mut() {
Some(d) => {
@@ -529,7 +682,7 @@ pub fn pick(app: &PhotocraftApp, f: &mut Map<String, Value>, at: [f64; 2], mods:
let Some(st) = app.session.active() else { return };
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.clamp(0.0, w - 1.0), y.clamp(0.0, h - 1.0)];
+ let at = [x.floor().clamp(0.0, w - 1.0), y.floor().clamp(0.0, h - 1.0)];
let tool = if mods.shift {
"add"
} else if mods.alt {
@@ -635,6 +788,67 @@ mod tests {
h.get_by_label(label).accesskit_node().is_disabled()
}
+ #[test]
+ fn preview_cache_refreshes_after_foreground_and_proof_changes() {
+ let mut app = app_with_doc();
+ let p = json!({"select": "outOfGamut"});
+ let mut previous = query_key(&app, &p);
+ app.session.tools.foreground = [0.2, 0.3, 0.4, 1.0];
+ let key = query_key(&app, &p);
+ assert_ne!(key, previous);
+ previous = key;
+ for setup in [
+ json!({"profile": "srgb"}),
+ json!({"profile": "linear-srgb"}),
+ json!({"profile": "linear-srgb", "intent": "perceptual"}),
+ json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false}),
+ json!({"profile": "linear-srgb", "intent": "perceptual", "bpc": false, "simulatePaper": true}),
+ ] {
+ app.run("view.proofSetup", setup).unwrap();
+ let key = query_key(&app, &p);
+ assert_ne!(key, previous, "changed proof settings must invalidate the preview");
+ assert_eq!(key, query_key(&app, &p), "an unchanged ICC profile must keep its cache key");
+ previous = key;
+ }
+ app.run("view.gamutWarning", json!({"on": true, "threshold": 8})).unwrap();
+ assert_ne!(previous, query_key(&app, &p));
+ previous = query_key(&app, &p);
+ app.run("view.gamutWarning", json!({"on": true, "threshold": 16})).unwrap();
+ assert_ne!(previous, query_key(&app, &p));
+ assert_ne!(query_key(&app, &p), query_key(&app, &json!({"select": "outOfGamut", "invert": true})));
+ }
+
+ #[test]
+ fn eyedropper_hover_reuses_preview_textures_without_sampling() {
+ let mut h = Harness::builder().with_size(vec2(1200.0, 900.0)).build_eframe(|cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ app_with_doc()
+ });
+ h.state_mut().ui.views[0].zoom = 20.0;
+ h.state_mut().ui.views[0].center = [20.0, 15.0];
+ h.state_mut().ui.views[0].fit_pending = false;
+ h.run_steps(3);
+ let id = open(h.state_mut());
+ set(&mut h, "__selectionPreview", json!("quickMask"));
+ let fields = h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields.clone();
+ let cached = |app: &PhotocraftApp| {
+ let p = app.color_range.as_ref().unwrap();
+ (p.mask_key, p.overlay_key, p.mask.as_ref().unwrap().id(), p.overlay.as_ref().unwrap().id(), Arc::as_ptr(&p.proxy))
+ };
+ let before = cached(h.state());
+ let st = h.state().session.active().unwrap();
+ let document = (st.revision, st.history.past_len());
+ for i in 0..12 {
+ let at = crate::canvas::ViewXform::active(h.state()).unwrap().to_screen(4.0 + i as f32 * 0.5, 15.0);
+ h.hover_at(at);
+ h.run_steps(1);
+ assert_eq!(cached(h.state()), before, "hover must reuse the mask, overlay and proxy");
+ }
+ assert_eq!(h.state_mut().ui.dialog_mut(id).unwrap().fields, fields, "hover must not pick a colour");
+ let st = h.state().session.active().unwrap();
+ assert_eq!((st.revision, st.history.past_len()), document);
+ }
+
#[test]
fn opens_from_the_select_menu_without_touching_the_document() {
let mut h = harness(app_with_doc());
@@ -806,6 +1020,159 @@ mod tests {
assert_eq!(coverage(app, 5, 22), 0.0);
}
+ #[test]
+ fn selection_preview_modes_cover_only_unselected_pixels() {
+ assert_eq!(overlay_pixel("grayscale", 1.0), Color32::WHITE);
+ assert_eq!(overlay_pixel("grayscale", 0.0), Color32::BLACK);
+ assert_eq!(overlay_pixel("grayscale", 0.5), Color32::from_gray(128));
+ for mode in ["blackMatte", "whiteMatte", "quickMask"] {
+ assert_eq!(overlay_pixel(mode, 1.0).a(), 0, "{mode}: selected pixels stay visible");
+ }
+ assert_eq!(overlay_pixel("blackMatte", 0.0), Color32::BLACK);
+ assert_eq!(overlay_pixel("whiteMatte", 0.0), Color32::WHITE);
+ assert_eq!(overlay_pixel("quickMask", 0.0).a(), 128);
+ assert_eq!(overlay_pixel("quickMask", 0.5).a(), 64);
+ assert_eq!(overlay_pixel("none", 0.0), Color32::TRANSPARENT);
+ }
+
+ #[test]
+ fn preview_mode_is_view_state_and_cancel_preserves_selection() {
+ let mut h = harness(app_with_doc());
+ h.state_mut().run("select.rect", json!({"x": 0, "y": 20, "width": 5, "height": 5})).unwrap();
+ let original = h.state().session.active().unwrap();
+ let past = original.history.past_len();
+ let revision = original.revision;
+ let id = open(h.state_mut());
+ h.run_steps(3);
+ for (mode, _) in PREVIEWS {
+ set(&mut h, "__selectionPreview", json!(mode));
+ let f = &h.state().ui.dialogs.last().unwrap().fields;
+ assert!(params(f).get("__selectionPreview").is_none());
+ let painter = h.ctx.layer_painter(egui::LayerId::background());
+ let doc = h.state().session.active().unwrap().doc.id;
+ let ctx = h.ctx.clone();
+ paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0)), false);
+ let st = h.state().session.active().unwrap();
+ assert_eq!((st.revision, st.history.past_len()), (revision, past));
+ assert_eq!(coverage(h.state(), 2, 22), 1.0);
+ }
+ h.state_mut().ui.close_dialog(id);
+ let painter = h.ctx.layer_painter(egui::LayerId::background());
+ let ctx = h.ctx.clone();
+ let doc = h.state().session.active().unwrap().doc.id;
+ paint_selection_preview(h.state_mut(), &ctx, &painter, doc, Rect::EVERYTHING, false);
+ assert_eq!(coverage(h.state(), 2, 22), 1.0);
+ }
+
+ #[test]
+ fn repeated_subtraction_clicks_are_not_discarded() {
+ let mut app = app_with_doc();
+ let id = open(&mut app);
+ let mut f = app.ui.dialog_mut(id).unwrap().fields.clone();
+ pick(&app, &mut f, [2.0, 2.0], egui::Modifiers::NONE);
+ pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::SHIFT);
+ pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT);
+ pick(&app, &mut f, [30.0, 2.0], egui::Modifiers::ALT);
+ assert_eq!(params(&f)["order"], json!(["+", "+", "-", "-"]));
+ }
+
+ #[test]
+ fn control_pointer_drag_samples_and_never_paints_under_the_dialog() {
+ let mut h = harness(app_with_doc());
+ let app = h.state_mut();
+ open(app);
+ let doc = app.session.active().unwrap();
+ let before = doc.revision;
+ let history = doc.history.past_len();
+ let ctx = h.ctx.clone();
+ for (events, shift) in [
+ (json!([{"kind":"down","x":2,"y":2},{"kind":"move","x":3,"y":2},{"kind":"up","x":3,"y":2}]), false),
+ (json!([{"kind":"down","x":30,"y":2},{"kind":"move","x":31,"y":2},{"kind":"up","x":31,"y":2}]), true),
+ ] {
+ let (req, _) = crate::control::ControlRequest::new("ui.pointer", json!({"events":events,"shift":shift}));
+ let _ = crate::control::handle(h.state_mut(), &ctx, &req);
+ }
+ let fields = &h.state().ui.dialogs.last().unwrap().fields;
+ assert_eq!(points(fields, "points"), [[3.0, 2.0], [30.0, 2.0], [31.0, 2.0]]);
+ let doc = h.state().session.active().unwrap();
+ assert_eq!((doc.revision, doc.history.past_len()), (before, history));
+ assert!(h.state().drag.is_none());
+ assert!(!pick_top(h.state_mut(), [-1.0, 0.0], egui::Modifiers::NONE));
+ }
+
+ #[test]
+ fn modifier_temporarily_swaps_image_and_selection_thumbnail() {
+ let mut h = harness(app_with_doc());
+ let id = open(h.state_mut());
+ h.run_steps(3);
+ let f = h.state().ui.dialogs.last().unwrap().fields.clone();
+ let ctx = h.ctx.clone();
+ let selection = preview(h.state_mut(), &ctx, &f).unwrap().0;
+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::COMMAND));
+ h.run_steps(2);
+ let image = preview(h.state_mut(), &ctx, &f).unwrap().0;
+ assert_ne!(image, selection);
+ assert_eq!(h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields["__view"], "selection");
+ h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
+ h.run_steps(2);
+ assert_eq!(preview(h.state_mut(), &ctx, &f).unwrap().0, selection);
+ }
+
+ /// A sample between thumbnail pixels must use the original pixel, not its neighbour.
+ #[test]
+ fn reduced_preview_matches_the_original_eyedropper_sample() {
+ let mut doc = Document::with_background("fine detail", Size::new(400, 4), ColorMode::Rgb, SampleType::U8, Color::rgb(1.0, 0.0, 0.0));
+ let surface = doc.layers[0].surface_mut().unwrap();
+ surface.fill_rect(GRect::new(200, 0, 400, 4), &[0.0, 0.0, 1.0, 1.0]);
+ surface.fill_rect(GRect::new(101, 0, 102, 4), &[0.0, 0.0, 1.0, 1.0]);
+ let mut session = photocraft_engine::Session::new();
+ session.add_document(doc, None);
+ let mut app = PhotocraftApp::new(session, crate::Services::default());
+ let id = open(&mut app);
+ let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone();
+ pick(&app, &mut fields, [101.0, 1.0], egui::Modifiers::NONE);
+ fields.insert("fuzziness".into(), json!(0.0));
+ let original = app.session.active().unwrap().doc.clone();
+ let proxy = crate::proxy::proxy_document(&original, 2);
+ let mut old = photocraft_engine::Session::new();
+ old.add_document(proxy.clone(), None);
+ old.execute(COMMAND, json!({"points": [[50, 0]], "fuzziness": 0})).unwrap();
+ assert_eq!(
+ old.active().unwrap().doc.selection.as_ref().unwrap().sample_channel(150, 0, 0),
+ 0.0,
+ "sampling the thumbnail instead selects the red neighbour"
+ );
+ let shown = proxy_mask(&app, &proxy, 2, &params(&fields)).unwrap();
+ confirm(&mut app, &fields).unwrap();
+ assert_eq!(coverage(&app, 300, 0), 1.0);
+ assert_eq!(shown[150], coverage(&app, 300, 0), "preview must show the same blue pixels as OK");
+ assert_eq!(shown[0], coverage(&app, 0, 0), "preview must leave the red background unselected");
+ }
+
+ /// `sampleAllLayers: false` judges the active layer in the preview, as OK does.
+ #[test]
+ fn preview_honours_sample_all_layers_like_ok() {
+ let mut app = app_with_doc();
+ let doc = app.session.active().unwrap().doc.clone();
+ let mut top = photocraft_doc::Layer::new("blue cover", photocraft_doc::LayerContent::Raster(doc.layers[0].surface().unwrap().clone()));
+ top.surface_mut().unwrap().fill_rect(GRect::new(0, 0, 40, 30), &[0.0, 0.0, 1.0, 1.0]);
+ app.session
+ .edit("layers", |doc, _| {
+ doc.layers.push(top);
+ Ok(())
+ })
+ .unwrap();
+ for all_layers in [false, true] {
+ let p = json!({"select": "sampledColors", "points": [[5, 5]], "fuzziness": 0, "sampleAllLayers": all_layers});
+ let proxy = crate::proxy::proxy_document(&app.session.active().unwrap().doc, 1);
+ let shown = proxy_mask(&app, &proxy, 1, &p).unwrap();
+ app.run(COMMAND, p).unwrap();
+ for (x, y) in [(5, 5), (30, 5), (5, 20), (30, 20)] {
+ assert_eq!(shown[y * 40 + x], coverage(&app, x as i32, y as i32), "all_layers={all_layers} at ({x}, {y})");
+ }
+ }
+ }
+
#[test]
fn params_send_only_what_the_mode_uses() {
let mut app = app_with_doc();
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index bf877ebaa..800f05a11 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -567,6 +567,20 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
}
continue;
}
+ // The dialog owns all pointer events, including Up: no underlying brush stroke
+ // or context menu may leak through while inspecting a Color Range preview.
+ if app.ui.dialogs.last().is_some_and(|d| crate::color_range_ui::owns(&d.fields)) {
+ let down = matches!(ev, ToolEvent::Down { .. });
+ let up = matches!(ev, ToolEvent::Up { .. });
+ let held = app.ui.dialogs.last().and_then(|d| d.fields.get("__pointerDown")).and_then(Value::as_bool).unwrap_or(false);
+ if let Some(d) = app.ui.dialogs.last_mut() {
+ d.fields.insert("__pointerDown".into(), json!(!up && (down || held)));
+ }
+ if !up && (down || held) && !space && !matches!(s("button"), Some("secondary" | "right" | "middle")) {
+ crate::color_range_ui::pick_top(app, [x, y], mods);
+ }
+ continue;
+ }
if matches!(s("button"), Some("secondary" | "right")) {
let down = matches!(ev, ToolEvent::Down { .. });
// Right-click with the Move tool, or ⌘/Ctrl+right-click: list the layers there.
@@ -597,10 +611,6 @@ 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/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index b79e56c2f..44a95cd54 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2189,6 +2189,9 @@ cameraRaw Color Barvy
Set Neutral Gray Point Nastavit neutrální šedý bod
Set White Point Nastavit bílý bod
Unavailable in this color mode V tomto barevném režimu není k dispozici
+ Selection Preview: Náhled výběru:
+ Black Matte Černý podklad
+ White Matte Bílý podklad
# Layer colour labels.
Seafoam Mořská pěna
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 62a32495b..eb6081ae3 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2228,6 +2228,9 @@
Set Neutral Gray Point Neutralen Graupunkt festlegen
Set White Point Weißpunkt festlegen
Unavailable in this color mode In diesem Farbmodus nicht verfügbar
+ Selection Preview: Auswahlvorschau:
+ Black Matte Schwarzer Hintergrund
+ White Matte Weißer Hintergrund
# Layer colour labels.
layerLabel No Color Keine Farbe
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 178b06ff9..380aaa765 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2259,6 +2259,9 @@ cameraRaw Amount Cantidad
Set Neutral Gray Point Definir punto gris neutro
Set White Point Definir punto blanco
Unavailable in this color mode No disponible en este modo de color
+ Selection Preview: Previsualización de selección:
+ Black Matte Fondo negro
+ White Matte Fondo blanco
# Layer colour labels.
Seafoam Espuma de mar
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index cafccef5d..485e0f552 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2618,6 +2618,9 @@ cameraRaw Blending Fusion
Set Neutral Gray Point Définir le point gris neutre
Set White Point Définir le point blanc
Unavailable in this color mode Indisponible dans ce mode colorimétrique
+ Selection Preview: Aperçu de la sélection :
+ Black Matte Fond noir
+ White Matte Fond blanc
# Layer colour labels.
Seafoam Écume de mer
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index d83a67a09..3796811ba 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2605,6 +2605,9 @@ cameraRaw Blending Pembauran
Set Neutral Gray Point Atur Titik Abu-abu Netral
Set White Point Atur Titik Putih
Unavailable in this color mode Tidak tersedia dalam mode warna ini
+ Selection Preview: Pratinjau Seleksi:
+ Black Matte Latar Hitam
+ White Matte Latar Putih
# Layer colour labels.
Seafoam Busa Laut
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index e5c245baf..18fe61bac 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2261,6 +2261,9 @@ cameraRaw Amount Quantità
Set Neutral Gray Point Imposta il punto grigio neutro
Set White Point Imposta punto bianco
Unavailable in this color mode Non disponibile in questa modalità colore
+ Selection Preview: Anteprima selezione:
+ Black Matte Sfondo nero
+ White Matte Sfondo bianco
# Layer colour labels.
Seafoam Schiuma marina
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 9879cd084..d8af1f816 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2172,6 +2172,9 @@ cameraRaw Color カラー
Set Neutral Gray Point 中間調のグレーポイントを設定
Set White Point 白色点を設定
Unavailable in this color mode このカラーモードでは使用できません
+ Selection Preview: 選択範囲のプレビュー:
+ Black Matte 黒の背景
+ White Matte 白の背景
# Layer colour labels.
Seafoam シーフォーム
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 64ae82d61..194416762 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2774,6 +2774,9 @@ cameraRaw Color 색상
Click a red pupil to neutralize it 빨간 동공을 클릭하여 보정합니다
open source 오픈 소스
…and {n} more …외 {n}개
+ Selection Preview: 선택 영역 미리 보기:
+ Black Matte 검정 배경
+ White Matte 흰색 배경
# Layer colour labels.
Seafoam 바다 거품색
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 43fe84590..7f1942ac4 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3233,6 +3233,9 @@ cameraRaw Roughness Chropowatość
Set Neutral Gray Point Ustaw punkt neutralnej szarości
Set White Point Ustaw punkt bieli
Unavailable in this color mode Niedostępne w tym trybie koloru
+ Selection Preview: Podgląd zaznaczenia:
+ Black Matte Czarne tło
+ White Matte Białe tło
# Layer colour labels.
Seafoam Morski
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 8fd7f7ed6..884156e9a 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2625,6 +2625,9 @@ cameraRaw Whites Brancos
Set Neutral Gray Point Definir ponto cinza neutro
Set White Point Definir ponto branco
Unavailable in this color mode Indisponível neste modo de cor
+ Selection Preview: Visualização da seleção:
+ Black Matte Fundo preto
+ White Matte Fundo branco
# Layer colour labels.
Seafoam Espuma do mar
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 2b56d93ab..e4fa04d3a 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2465,6 +2465,10 @@ cameraRaw Roughness Неровность
Set Neutral Gray Point Задать нейтральную серую точку
Set White Point Задать точку белого
Unavailable in this color mode Недоступно в этом цветовом режиме
+ Selection Preview: Просмотр выделения:
+ Black Matte На чёрном фоне
+ White Matte На белом фоне
+ Quick Mask Быстрая маска
# Layer colour labels.
Seafoam Морская пена
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index dd0360e1a..722d9b525 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2197,6 +2197,9 @@ cameraRaw Blending 混合
Set Neutral Gray Point 设置中性灰场
Set White Point 设置白场
Unavailable in this color mode 此颜色模式下不可用
+ Selection Preview: 选区预览:
+ Black Matte 黑色背景
+ White Matte 白色背景
# Layer colour labels.
Seafoam 海沫色
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index fb01a3266..9649e3c1a 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2166,6 +2166,9 @@ cameraRaw Blending 混合
Set Neutral Gray Point 設定中性灰點
Set White Point 設定白點
Unavailable in this color mode 此色彩模式無法使用
+ Selection Preview: 選取範圍預視:
+ Black Matte 黑色背景
+ White Matte 白色背景
# Layer colour labels.
Seafoam 海沫色
diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs
index 4f3292b2d..b2df7b1bd 100644
--- a/crates/ui-egui/src/input_tests.rs
+++ b/crates/ui-egui/src/input_tests.rs
@@ -131,6 +131,21 @@ fn color_range_eyedropper_picks_on_the_canvas() {
// ⇧-click adds another sample; the dialog never closes.
click(&mut h, screen([60.5, 40.5]), Modifiers::SHIFT);
assert_eq!(points(&h).0, 2);
+ click(&mut h, screen([60.5, 40.5]), Modifiers::ALT);
+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["subtractPoints"].as_array().unwrap().len(), 1);
+ // A stationary held button must not subtract again on every redraw.
+ let p = screen([60.5, 40.5]);
+ h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::ALT }, Modifiers::ALT);
+ h.run_steps(4);
+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["subtractPoints"].as_array().unwrap().len(), 2);
+ h.event_modifiers(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::ALT }, Modifiers::ALT);
+ h.run_steps(2);
+ // The modal eyedropper overrides a previously selected Hand tool.
+ h.state_mut().ui.tool = crate::state::Tool::Hand;
+ let center = h.state().ui.views[0].center;
+ click(&mut h, screen([30.5, 40.5]), Modifiers::NONE);
+ assert_eq!(points(&h).0, 1);
+ assert_eq!(h.state().ui.views[0].center, center);
assert_eq!(h.state().ui.dialogs.len(), 1);
// The document is untouched until OK.
assert!(h.state().session.active().unwrap().doc.selection.is_none());