Skip to content

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

Object Selection: hover preview of the object it would select (Object Finder) (#4087) (#4095)

FredApps858fbcf1ad19
diff --git a/crates/algo/src/segment/grabcut.rs b/crates/algo/src/segment/grabcut.rs
index 5e80791ff..ae1a586c1 100644
--- a/crates/algo/src/segment/grabcut.rs
+++ b/crates/algo/src/segment/grabcut.rs
@@ -116,3 +116,147 @@ pub fn object_select(sampler: &dyn Sampler, canvas: Rect, rect: Rect, work_px: u
let low = super::clean_mask(&low, lw, lh, 0.1, 0.002);
super::finish_region(sampler, window, step, &low, lw, lh, Some((&fg, &bg)))
}
+
+/// Working-resolution budget (pixels) for [`object_at`]: small enough to run while the pointer
+/// hovers.
+pub const OBJECT_AT_WORK_PX: usize = 60_000;
+
+/// Object Selection's Object Finder (hover / click): the object under document point `(x, y)`.
+///
+/// A heuristic, not a semantic segmenter (that is #2788): on a working-resolution copy of the
+/// canvas the area around the point is grown over pixels of similar colour (CIELAB, bounded both
+/// by the distance to the seed's running mean and by the local edge step), so it stops at the
+/// object's outline. A region that grows over most of the canvas is the background: nothing is
+/// found. Otherwise GrabCut refines it inside its padded bounding box (the grown area probable
+/// foreground, the cursor definite foreground, outside the box definite background), the part
+/// connected to the cursor is kept and the boundary is re-cut at full resolution, as the
+/// rectangle mode does.
+pub fn object_at(sampler: &dyn Sampler, canvas: Rect, x: f32, y: f32, work_px: usize) -> Option<Region> {
+ if canvas.width() < 4 || canvas.height() < 4 || !x.is_finite() || !y.is_finite() {
+ return None;
+ }
+ let (px, py) = (x.floor() as i32, y.floor() as i32);
+ if !canvas.contains(px, py) {
+ return None;
+ }
+ let step = super::scale_for(canvas, work_px.max(1024));
+ let img = sampler.rgb_scaled(canvas, step);
+ let (w, h) = (img.w, img.h);
+ if w < 2 || h < 2 {
+ return None;
+ }
+ // Lightly smoothed, so noise and texture don't stop the growth; edges survive.
+ let lab: Vec<[f32; 3]> = box3(&box3(&img.px, w, h), w, h).iter().map(|c| super::slic::rgb_to_lab(*c)).collect();
+ let sx = (((px - canvas.x0) as usize) / step).min(w - 1);
+ let sy = (((py - canvas.y0) as usize) / step).min(h - 1);
+ let grown = grow_similar(&lab, w, h, sx, sy);
+ let count = grown.iter().filter(|g| **g).count();
+ // Background (or a flat image): no single object under the cursor.
+ if count * 10 > w * h * 6 || count < 4 {
+ return None;
+ }
+ let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0usize, 0usize);
+ for (i, g) in grown.iter().enumerate() {
+ if *g {
+ let (gx, gy) = (i % w, i / w);
+ (x0, y0, x1, y1) = (x0.min(gx), y0.min(gy), x1.max(gx + 1), y1.max(gy + 1));
+ }
+ }
+ let pad = ((x1 - x0).max(y1 - y0) / 6).max(2);
+ let (bx0, by0, bx1, by1) = (x0.saturating_sub(pad), y0.saturating_sub(pad), (x1 + pad).min(w), (y1 + pad).min(h));
+ let mut trimap = vec![BG; w * h];
+ let mut any_bg = false;
+ for yy in 0..h {
+ for xx in 0..w {
+ let i = yy * w + xx;
+ let inside = xx >= bx0 && xx < bx1 && yy >= by0 && yy < by1;
+ trimap[i] = if grown[i] {
+ PR_FG
+ } else if inside {
+ PR_BG
+ } else {
+ any_bg = true;
+ BG
+ };
+ }
+ }
+ if !any_bg {
+ // The box is the whole canvas: the frame is background.
+ for yy in 0..h {
+ for xx in 0..w {
+ if (xx == 0 || yy == 0 || xx + 1 == w || yy + 1 == h) && !(xx == sx && yy == sy) {
+ trimap[yy * w + xx] = BG;
+ }
+ }
+ }
+ }
+ trimap[sy * w + sx] = FG;
+ let (fg, bg) = grabcut(&img, &mut trimap, 5)?;
+ let low: Vec<bool> = trimap.iter().map(|t| is_fg(*t)).collect();
+ let mut seeds = vec![false; w * h];
+ seeds[sy * w + sx] = true;
+ let low = super::keep_seeded(&low, &seeds, w, h);
+ let low = super::clean_mask(&low, w, h, 0.1, 0.01);
+ if !low.iter().any(|v| *v) {
+ return None;
+ }
+ super::finish_region(sampler, canvas, step, &low, w, h, Some((&fg, &bg)))
+}
+
+/// Region growing (4-connected) from `(sx, sy)` over pixels whose CIELAB colour is within a
+/// distance of the seed area's running mean and whose step from the neighbour it was reached
+/// from is small, so it stops at edges.
+fn grow_similar(lab: &[[f32; 3]], w: usize, h: usize, sx: usize, sy: usize) -> Vec<bool> {
+ const MEAN_DIST: f32 = 32.0;
+ const EDGE_STEP: f32 = 10.0;
+ let d = |a: [f32; 3], b: [f32; 3]| ((a[0] - b[0]).powi(2) + (a[1] - b[1]).powi(2) + (a[2] - b[2]).powi(2)).sqrt();
+ let mut out = vec![false; w * h];
+ let Some(&seed) = lab.get(sy * w + sx) else { return out };
+ let (mut sum, mut n) = ([seed[0] as f64, seed[1] as f64, seed[2] as f64], 1.0f64);
+ let mut stack = vec![(sx, sy)];
+ out[sy * w + sx] = true;
+ while let Some((x, y)) = stack.pop() {
+ let c = lab[y * w + x];
+ let mean = [(sum[0] / n) as f32, (sum[1] / n) as f32, (sum[2] / n) as f32];
+ let nbrs = [(x.wrapping_sub(1), y), (x + 1, y), (x, y.wrapping_sub(1)), (x, y + 1)];
+ for (nx, ny) in nbrs {
+ if nx >= w || ny >= h {
+ continue;
+ }
+ let i = ny * w + nx;
+ if out[i] {
+ continue;
+ }
+ let q = lab[i];
+ if d(q, c) <= EDGE_STEP && d(q, mean) <= MEAN_DIST {
+ out[i] = true;
+ sum = [sum[0] + q[0] as f64, sum[1] + q[1] as f64, sum[2] + q[2] as f64];
+ n += 1.0;
+ stack.push((nx, ny));
+ }
+ }
+ }
+ out
+}
+
+/// 3×3 box blur (clamped at the edges).
+fn box3(px: &[[f32; 3]], w: usize, h: usize) -> Vec<[f32; 3]> {
+ let mut out = vec![[0.0f32; 3]; px.len()];
+ for y in 0..h {
+ for x in 0..w {
+ let (mut acc, mut n) = ([0.0f32; 3], 0.0f32);
+ for yy in y.saturating_sub(1)..(y + 2).min(h) {
+ for xx in x.saturating_sub(1)..(x + 2).min(w) {
+ if let Some(p) = px.get(yy * w + xx) {
+ acc = [acc[0] + p[0], acc[1] + p[1], acc[2] + p[2]];
+ n += 1.0;
+ }
+ }
+ }
+ if let Some(o) = out.get_mut(y * w + x) {
+ *o = acc.map(|v| v / n.max(1.0));
+ }
+ }
+ }
+ out
+}
diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rs
index 4f741eb22..869f3c671 100644
--- a/crates/algo/src/segment/tests.rs
+++ b/crates/algo/src/segment/tests.rs
@@ -659,3 +659,24 @@ fn dump_quick_scenes() {
save("thin_line", &line);
save("disc_scene", &disc_scene(600, 500, 300.0, 250.0, 180.0, 4).0);
}
+
+#[test]
+fn object_at_finds_the_disc_under_the_cursor() {
+ let (img, truth) = disc_scene(320, 240, 160.0, 120.0, 70.0, 7);
+ let s = ImageSampler { img: &img, origin: (0, 0) };
+ let canvas = Rect::new(0, 0, 320, 240);
+ let reg = grabcut::object_at(&s, canvas, 165.0, 118.0, 20_000).unwrap();
+ let v = iou(&reg, &truth, 320, 240);
+ assert!(v > 0.9, "IoU {v}");
+}
+
+#[test]
+fn object_at_on_the_background_or_off_canvas_finds_nothing() {
+ let (img, _) = disc_scene(320, 240, 160.0, 120.0, 70.0, 7);
+ let s = ImageSampler { img: &img, origin: (0, 0) };
+ let canvas = Rect::new(0, 0, 320, 240);
+ assert!(grabcut::object_at(&s, canvas, 10.0, 10.0, 20_000).is_none());
+ assert!(grabcut::object_at(&s, canvas, -5.0, 10.0, 20_000).is_none());
+ assert!(grabcut::object_at(&s, canvas, f32::NAN, 10.0, 20_000).is_none());
+ assert!(grabcut::object_at(&s, canvas, 400.0, 10.0, 0).is_none());
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 45cf3418f..1cc8eb692 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -432,6 +432,9 @@ pub struct Session {
pub link_scan: Option<link_watch::LinkScan>,
/// Select Subject's last result, reused while the pixels are unchanged (#2865).
subject_cache: smartselect_cmds::SubjectCache,
+ /// Object Selection's Object Finder results (#4087), shared by the hover preview and the
+ /// click that commits it; valid while the pixels are unchanged.
+ pub object_finder: smartselect_cmds::ObjectFinderCache,
/// A finished live stroke offered to the `paint.stroke` / `paint.pencil` that commits it
/// ([`Session::offer_live_stroke`]).
pub(crate) live_commit: Option<brush_cmds::LiveCommit>,
@@ -528,6 +531,7 @@ impl Session {
if let Some(id) = self.docs.get(index).map(|d| d.doc.id) {
self.cancel_jobs_on(id);
self.subject_cache.forget_doc(id);
+ self.object_finder.forget_doc(id);
}
let d = self.docs.remove(index);
self.active = if self.docs.is_empty() {
@@ -701,6 +705,7 @@ impl Session {
if damage.is_none_or(|d| !d.is_empty()) {
// Free the mask early; a stale entry would only miss (it is keyed by pixels).
self.subject_cache = Default::default();
+ self.object_finder = Default::default();
}
Ok(r)
}
diff --git a/crates/engine/src/smartselect_cmds.rs b/crates/engine/src/smartselect_cmds.rs
index 6c15c6be5..b04aae7a8 100644
--- a/crates/engine/src/smartselect_cmds.rs
+++ b/crates/engine/src/smartselect_cmds.rs
@@ -130,8 +130,124 @@ fn rect_param(p: &Value) -> Option<Rect> {
Some(Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32))
}
+fn point_param(p: &Value) -> Option<(f32, f32)> {
+ let a = p.get("point")?.as_array()?;
+ let (x, y) = (a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32);
+ (x.is_finite() && y.is_finite()).then_some((x, y))
+}
+
+/// The layer [`with_doc_sampler`] samples for `layer` / `all_layers`: `None` = the composite.
+pub fn sampled_target(doc: &Document, layer: Option<LayerId>, all_layers: bool) -> Option<LayerId> {
+ layer.filter(|id| !all_layers && doc.layer(*id).and_then(Layer::surface).is_some())
+}
+
+/// Object Finder (#4087): the object Object Selection would select at document point `(x, y)`,
+/// sampling `layer` (or the composite). Pure, so the UI can run it on a worker thread while the
+/// pointer hovers; `select.object` with `"point"` commits the same result.
+pub fn find_object(doc: &Document, layer: Option<LayerId>, all_layers: bool, x: f32, y: f32) -> Option<Region> {
+ with_doc_sampler(doc, layer, all_layers, |smp, doc| grabcut::object_at(smp, doc.bounds(), x, y, grabcut::OBJECT_AT_WORK_PX))
+}
+
+/// Most objects remembered by [`ObjectFinderCache`].
+pub const OBJECT_FINDER_ENTRIES: usize = 12;
+
+/// Object Finder results for one document's pixels (#4087): hovering over an object already
+/// found, or clicking it, answers at once. Keyed like [`SubjectCache`] (valid while the pixels
+/// are the same, the document held weakly) plus the sampled layer; a lookup hits any cached
+/// object that covers the point, so one computation serves the whole object.
+#[derive(Debug, Default)]
+pub struct ObjectFinderCache {
+ doc: std::sync::Weak<Document>,
+ doc_id: Option<photocraft_doc::DocId>,
+ target: Option<LayerId>,
+ regions: Vec<std::sync::Arc<Region>>,
+}
+
+impl ObjectFinderCache {
+ fn valid(&self, doc: &Document, target: Option<LayerId>) -> bool {
+ self.doc_id == Some(doc.id) && self.target == target && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc))
+ }
+
+ /// A cached object of `doc` (sampling `target`) covering `(x, y)`.
+ pub fn lookup(&self, doc: &Document, target: Option<LayerId>, x: f32, y: f32) -> Option<std::sync::Arc<Region>> {
+ if !x.is_finite() || !y.is_finite() || !self.valid(doc, target) {
+ return None;
+ }
+ let (px, py) = (x.floor() as i32, y.floor() as i32);
+ self.regions.iter().find(|r| r.at(px, py) >= 0.5).cloned()
+ }
+
+ /// Remembers `region`, found in `doc` sampling `target`. A different document or pixels
+ /// start over; the oldest object is dropped beyond [`OBJECT_FINDER_ENTRIES`].
+ pub fn insert(&mut self, doc: &std::sync::Arc<Document>, target: Option<LayerId>, region: std::sync::Arc<Region>) {
+ if !self.valid(doc, target) {
+ self.regions.clear();
+ }
+ self.doc = std::sync::Arc::downgrade(doc);
+ self.doc_id = Some(doc.id);
+ self.target = target;
+ if self.regions.len() >= OBJECT_FINDER_ENTRIES {
+ self.regions.remove(0);
+ }
+ self.regions.push(region);
+ }
+
+ /// Number of remembered objects.
+ pub fn len(&self) -> usize {
+ self.regions.len()
+ }
+
+ /// Whether nothing is remembered.
+ pub fn is_empty(&self) -> bool {
+ self.regions.is_empty()
+ }
+
+ /// Forget the results if they were computed from the document `id` (it is closing).
+ pub(crate) fn forget_doc(&mut self, id: photocraft_doc::DocId) {
+ if self.doc_id == Some(id) {
+ *self = Self::default();
+ }
+ }
+
+ /// Follows `doc` past a selection-only edit (same pixels), so the next lookup still hits.
+ fn follow(&mut self, doc: &std::sync::Arc<Document>) {
+ if self.doc_id == Some(doc.id) && self.doc.upgrade().is_some_and(|old| crate::layer_multi_cmds::same_pixels(&old, doc)) {
+ self.doc = std::sync::Arc::downgrade(doc);
+ }
+ }
+}
+
+/// `select.object` with `"point"`: the Object Finder's object under the point (cached).
+fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result<Value> {
+ let all_layers = b(p, "sampleAllLayers", false);
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let target = sampled_target(&d.doc, d.active_layer, all_layers);
+ let region = match s.object_finder.lookup(&d.doc, target, x, y) {
+ Some(r) => Some(r),
+ None => {
+ let doc = std::sync::Arc::clone(&d.doc);
+ let found = find_object(&doc, d.active_layer, all_layers, x, y).map(std::sync::Arc::new);
+ if let Some(r) = &found {
+ s.object_finder.insert(&doc, target, std::sync::Arc::clone(r));
+ }
+ found
+ }
+ };
+ let out = apply(s, "Object Selection", region.as_deref(), mode(p, "replace"))?;
+ if let Some(d) = s.active() {
+ let doc = std::sync::Arc::clone(&d.doc);
+ s.object_finder.follow(&doc);
+ }
+ Ok(out)
+}
+
fn object_selection(s: &mut Session, p: &Value) -> Result<Value> {
- let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h]"))?;
+ if p.get("rect").is_none()
+ && let Some(pt) = point_param(p)
+ {
+ return object_at_point(s, p, pt);
+ }
+ let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h] or \"point\": [x, y]"))?;
let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?;
apply(s, "Object Selection", region.as_ref(), mode(p, "replace"))
}
@@ -373,7 +489,7 @@ pub fn specs() -> Vec<CommandSpec> {
"select.object",
"Object Selection",
[],
- r##"{"rect":[x,y,w,h],"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=false}"##,
+ r##"{"rect":[x,y,w,h] | "point":[x,y],"mode":"replace|add|subtract|intersect"="replace","sampleAllLayers":bool=false} (point: the Object Finder's object under the point, as hovering previews it)"##,
has_doc,
object_selection
),
@@ -544,6 +660,59 @@ mod tests {
assert!(cov(&s, 10, 10) >= 0.99);
}
+ #[test]
+ fn object_selection_point_selects_the_object_under_it() {
+ for depth in [8, 16, 32] {
+ let (mut s, inside) = disc(depth);
+ let r = s.execute("select.object", json!({"point": [100, 80]})).unwrap();
+ assert_eq!(r["changed"], true, "depth {depth}");
+ let v = sel_iou(&s, 200, 160, &inside);
+ assert!(v > 0.9, "depth {depth}: IoU {v}");
+ }
+ // The background is no object: nothing changes.
+ let (mut s, _) = disc(8);
+ let r = s.execute("select.object", json!({"point": [3, 3]})).unwrap();
+ assert_eq!(r["changed"], false);
+ assert!(s.active().unwrap().doc.selection.is_none());
+ assert!(s.execute("select.object", json!({"point": ["a", 1]})).is_err());
+ }
+
+ #[test]
+ fn object_selection_point_honours_the_modes() {
+ let (mut s, _) = disc(8);
+ s.execute("select.all", json!({})).unwrap();
+ s.execute("select.object", json!({"point": [100, 80], "mode": "subtract"})).unwrap();
+ assert!(cov(&s, 100, 80) < 0.5 && cov(&s, 3, 3) >= 0.5);
+ s.execute("select.object", json!({"point": [100, 80], "mode": "add"})).unwrap();
+ assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) >= 0.5);
+ s.execute("select.object", json!({"point": [100, 80], "mode": "intersect"})).unwrap();
+ assert!(cov(&s, 100, 80) >= 0.5 && cov(&s, 3, 3) < 0.5);
+ }
+
+ #[test]
+ fn object_finder_cache_serves_the_whole_object_until_pixels_change() {
+ let (mut s, _) = disc(8);
+ let d = s.active().unwrap();
+ let doc = std::sync::Arc::clone(&d.doc);
+ let target = sampled_target(&doc, d.active_layer, false);
+ assert!(s.object_finder.lookup(&doc, target, 100.0, 80.0).is_none());
+ let r = std::sync::Arc::new(find_object(&doc, d.active_layer, false, 100.0, 80.0).unwrap());
+ s.object_finder.insert(&doc, target, std::sync::Arc::clone(&r));
+ // Any point on the object hits; the background and another target miss.
+ assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r));
+ assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none());
+ assert!(s.object_finder.lookup(&doc, Some(LayerId(9999)), 100.0, 80.0).is_none());
+ // The click reuses it, and a selection-only edit keeps it.
+ s.execute("select.object", json!({"point": [110, 70]})).unwrap();
+ assert_eq!(s.object_finder.len(), 1);
+ s.execute("select.deselect", json!({})).unwrap();
+ let d = s.active().unwrap();
+ assert!(s.object_finder.lookup(&std::sync::Arc::clone(&d.doc), target, 100.0, 80.0).is_some());
+ // A pixel edit drops it.
+ s.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap();
+ assert!(s.object_finder.is_empty());
+ }
+
#[test]
fn object_selection_disc() {
for depth in [8, 16, 32] {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 362eef2a3..bfcb0d1a7 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -3438,6 +3438,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
let resizing = crate::brush_resize::draw(app, &painter, &xf);
draw_transform_controls(app, &painter, &xf);
crate::move_hover::draw(app, &painter, &xf, idx, response.hover_pos());
+ crate::object_finder::draw(app, &painter, &xf, idx, response.hover_pos());
crate::layer_pick_ui::show(app, &ctx);
let shown = app.ui.views.get(idx).cloned();
crate::canvas_tool_menu::show(app, &ctx);
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 89fa3da9f..8c2bac34c 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -3658,6 +3658,8 @@ navigator Zoom Zvětšení
Light Blue Světle modrá
Light Red Světle červená
Medium Blue Středně modrá
+ Object Finder Hledání objektů
+ No object found there — drag a rectangle around it Nebyl tam nalezen žádný objekt — přetáhněte kolem něj obdélník
Remove after each stroke Odstranit po každém tahu
Apply the removal ({key}) Použít odstranění ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Tahy k odstranění: {n} (Enter použije, Esc zruší)
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index fde840b1e..3e5c38703 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2690,6 +2690,8 @@ curves Smooth Glätten
Light Red Hellrot
Medium Blue Mittelblau
Light Gray Hellgrau
+ Object Finder Objektsucher
+ No object found there — drag a rectangle around it Dort wurde kein Objekt gefunden — ziehen Sie ein Rechteck darum
Remove after each stroke Nach jedem Strich entfernen
Apply the removal ({key}) Entfernen anwenden ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Striche zum Entfernen: {n} (Eingabe wendet an, Esc bricht ab)
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index a3da64e9d..01582d5d7 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3748,6 +3748,8 @@ curves Smooth Εξομάλυνση
Light Red Ανοιχτό κόκκινο
Medium Blue Μεσαίο μπλε
Light Gray Ανοιχτό γκρι
+ Object Finder Εύρεση αντικειμένων
+ No object found there — drag a rectangle around it Δεν βρέθηκε αντικείμενο εκεί — σύρετε ένα ορθογώνιο γύρω του
Remove after each stroke Αφαίρεση μετά από κάθε πινελιά
Apply the removal ({key}) Εφαρμογή της αφαίρεσης ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Πινελιές προς αφαίρεση: {n} (Enter εφαρμόζει, Esc ακυρώνει)
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 96ecc18d3..d3a61f70b 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2731,6 +2731,8 @@ curves Smooth Suavizar
Light Red Rojo claro
Medium Blue Azul medio
Light Gray Gris claro
+ Object Finder Buscador de objetos
+ No object found there — drag a rectangle around it No se encontró ningún objeto ahí; arrastra un rectángulo a su alrededor
Remove after each stroke Eliminar después de cada trazo
Apply the removal ({key}) Aplicar la eliminación ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Trazos por eliminar: {n} (Intro aplica, Esc cancela)
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 3f9ec9fb3..b1eb9c5e0 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -3051,6 +3051,8 @@ curves Smooth Lisser
Light Red Rouge clair
Medium Blue Bleu moyen
Light Gray Gris clair
+ Object Finder Outil de recherche d’objets
+ No object found there — drag a rectangle around it Aucun objet trouvé ici — tracez un rectangle autour
Remove after each stroke Supprimer après chaque trait
Apply the removal ({key}) Appliquer la suppression ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Traits à supprimer : {n} (Entrée applique, Échap annule)
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index f37ef4d33..626b84cd1 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -3993,4 +3993,6 @@ cameraRaw Yellow Sárga
Action playback stopped A művelet lejátszása leállt
Step {step} is waiting for its dialog A(z) {step}. lépés a párbeszédablakára vár
@plural {n} action|{n} actions {n} művelet
+ Object Finder Objektumkereső
+ No object found there — drag a rectangle around it Ott nem található objektum – húzz köré egy téglalapot
Drag to pan · Scroll to zoom · Double-click to fit Húzás: mozgatás · Görgetés: nagyítás · Dupla kattintás: igazítás
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 18d2c776f..e29822449 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -3038,6 +3038,8 @@ curves Smooth Haluskan
Light Red Merah Terang
Medium Blue Biru Sedang
Light Gray Abu-abu Muda
+ Object Finder Pencari Objek
+ No object found there — drag a rectangle around it Tidak ada objek ditemukan di sana — seret persegi panjang di sekelilingnya
Remove after each stroke Hapus setelah setiap goresan
Apply the removal ({key}) Terapkan penghapusan ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Goresan untuk dihapus: {n} (Enter menerapkan, Esc membatalkan)
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index de47f7bca..1c6ba0ec7 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -4014,6 +4014,8 @@ navigator Zoom Zoom
{index} of {total} {index} di {total}
{shortcut} assigned. {shortcut} assegnata.
{shortcut} is already in use by {commands} and will be removed from it when you click OK. {shortcut} è già usata da {commands} e verrà rimossa quando fai clic su OK.
+ Object Finder Ricerca oggetti
+ No object found there — drag a rectangle around it Nessun oggetto trovato lì: trascina un rettangolo intorno
Remove after each stroke Rimuovi dopo ogni tratto
Apply the removal ({key}) Applica la rimozione ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Tratti da rimuovere: {n} (Invio applica, Esc annulla)
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index f2d3bd669..761501e85 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -3660,6 +3660,8 @@ curves Smooth スムーズ
Light Red ライトレッド
Medium Blue ミディアムブルー
Light Gray ライトグレー
+ Object Finder オブジェクトファインダー
+ No object found there — drag a rectangle around it そこにオブジェクトが見つかりません — 周囲に矩形をドラッグしてください
Remove after each stroke ストロークごとに削除
Apply the removal ({key}) 削除を適用 ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) 削除するストローク: {n}(Enter で適用、Esc で取り消し)
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 84f30fc19..b28041689 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -3220,6 +3220,8 @@ curves Smooth 매끄럽게
Light Red 연한 빨강
Medium Blue 중간 파랑
Light Gray 연한 회색
+ Object Finder 개체 찾기
+ No object found there — drag a rectangle around it 그곳에서 개체를 찾지 못했습니다 — 주위에 사각형을 드래그하세요
Remove after each stroke 획마다 제거
Apply the removal ({key}) 제거 적용 ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) 제거할 획: {n} (Enter 적용, Esc 취소)
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index fde9f9974..cf570d402 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -3810,6 +3810,8 @@ curves Smooth Vloeiend maken
Light Red Lichtrood
Medium Blue Middelblauw
Light Gray Lichtgrijs
+ Object Finder Objectzoeker
+ No object found there — drag a rectangle around it Daar is geen object gevonden — sleep er een rechthoek omheen
Remove after each stroke Verwijderen na elke streek
Apply the removal ({key}) Verwijdering toepassen ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Streken om te verwijderen: {n} (Enter past toe, Esc annuleert)
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 29dfcef28..cc0b77df7 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3647,6 +3647,8 @@ curves Smooth Wygładź
Light Red Jasnoczerwony
Medium Blue Średnioniebieski
Light Gray Jasnoszary
+ Object Finder Wyszukiwanie obiektów
+ No object found there — drag a rectangle around it Nie znaleziono tam obiektu — przeciągnij wokół niego prostokąt
Remove after each stroke Usuwaj po każdym pociągnięciu
Apply the removal ({key}) Zastosuj usuwanie ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Pociągnięcia do usunięcia: {n} (Enter stosuje, Esc anuluje)
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index a68ba566f..bbe1fd8e7 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -3840,6 +3840,8 @@ layerLabel No Color Sem cor
Light Red Vermelho-claro
Medium Blue Azul médio
Light Gray Cinza-claro
+ Object Finder Localizador de objetos
+ No object found there — drag a rectangle around it Nenhum objeto encontrado ali — arraste um retângulo ao redor dele
Remove after each stroke Remover após cada traço
Apply the removal ({key}) Aplicar a remoção ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Traços a remover: {n} (Enter aplica, Esc cancela)
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index e6caf04cb..3e4e0b009 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2995,6 +2995,8 @@ curves Smooth Сгладить
Light Red Светло-красный
Medium Blue Средне-синий
Light Gray Светло-серый
+ Object Finder Поиск объектов
+ No object found there — drag a rectangle around it Там не найден объект — обведите его прямоугольником
Remove after each stroke Удалять после каждого штриха
Apply the removal ({key}) Применить удаление ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Штрихов к удалению: {n} (Enter применяет, Esc отменяет)
diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv
index d944622ec..419c54c8a 100644
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@ -3805,4 +3805,6 @@ cameraData Lens Lens
Action playback stopped Eylem oynatma durduruldu
Step {step} is waiting for its dialog {step}. adım iletişim kutusunu bekliyor
@plural {n} action|{n} actions {n} eylem
+ Object Finder Nesne Bulucu
+ No object found there — drag a rectangle around it Orada nesne bulunamadı — çevresine bir dikdörtgen sürükleyin
Drag to pan · Scroll to zoom · Double-click to fit Kaydırmak için sürükleyin · Yakınlaştırmak için kaydırın · Sığdırmak için çift tıklayın
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index bd93075fa..c5c724c92 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -3748,6 +3748,8 @@ curves Smooth Згладити
Light Red Світло-червоний
Medium Blue Середньо-синій
Light Gray Світло-сірий
+ Object Finder Пошук об’єктів
+ No object found there — drag a rectangle around it Там не знайдено об’єкта — обведіть його прямокутником
Remove after each stroke Видаляти після кожного штриха
Apply the removal ({key}) Застосувати видалення ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Штрихів для видалення: {n} (Enter застосовує, Esc скасовує)
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index ea93bc326..6872d8cf6 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -3534,6 +3534,8 @@ curves Smooth Làm mượt
Stroke Path… Đi nét đường dẫn…
Apply mask to layer before removing? Áp dụng mặt nạ vào lớp trước khi xóa?
Delete the vector mask? Xóa mặt nạ vectơ?
+ Object Finder Trình tìm đối tượng
+ No object found there — drag a rectangle around it Không tìm thấy đối tượng ở đó — hãy kéo một hình chữ nhật quanh nó
Remove after each stroke Xóa sau mỗi nét vẽ
Apply the removal ({key}) Áp dụng việc xóa ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy)
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 9e66946f4..beb1b0a5c 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2655,6 +2655,8 @@ curves Smooth 平滑
Light Red 浅红色
Medium Blue 中蓝色
Light Gray 浅灰色
+ Object Finder 对象查找程序
+ No object found there — drag a rectangle around it 那里未找到对象 — 请在其周围拖动矩形
Remove after each stroke 每次描边后移除
Apply the removal ({key}) 应用移除 ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描边:{n}(Enter 应用,Esc 取消)
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index b7685958e..c3772fc1c 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2640,6 +2640,8 @@ curves Smooth 平滑
Light Red 淺紅色
Medium Blue 中藍色
Light Gray 淺灰色
+ Object Finder 物件尋找器
+ No object found there — drag a rectangle around it 那裡找不到物件 — 請在其周圍拖曳矩形
Remove after each stroke 每次描邊後移除
Apply the removal ({key}) 套用移除 ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) 待移除的描邊:{n}(Enter 套用,Esc 取消)
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index bc219f5ff..cef61293f 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -132,6 +132,7 @@ pub mod new_guide_ui;
pub mod new_layer_ui;
pub mod notices;
mod numeric_expression;
+pub mod object_finder;
mod opacity_keys;
pub mod outline;
pub mod paint_mouse;
@@ -511,6 +512,8 @@ pub struct PhotocraftApp {
pub(crate) move_preview: Option<move_ui::MovePreview>,
/// Move tool › Show Highlight on Rollover: the last hover answer (`move_hover`).
pub(crate) move_hover: Option<move_hover::Hover>,
+ /// Object Selection › Object Finder: the hover preview (`object_finder`).
+ pub(crate) object_finder: Option<object_finder::Finder>,
/// A blend mode hovered in the Layers panel, shown live (`blend_preview`).
pub(crate) blend_preview: Option<blend_preview::BlendPreview>,
/// Patch Tool drag: the healed document at the pointer (`patch_preview`).
@@ -739,6 +742,7 @@ impl PhotocraftApp {
menu_cache: None,
move_preview: None,
move_hover: None,
+ object_finder: None,
blend_preview: None,
patch_preview: None,
magnetic: Default::default(),
diff --git a/crates/ui-egui/src/object_finder.rs b/crates/ui-egui/src/object_finder.rs
new file mode 100644
index 000000000..e219b0ddf
--- /dev/null
+++ b/crates/ui-egui/src/object_finder.rs
@@ -0,0 +1,331 @@
+//! Object Selection › Object Finder (#4087): with the Object Selection tool active, resting the
+//! pointer on the canvas highlights the object a click there would select, as Photoshop's Object
+//! Finder does. A click (without dragging) commits that object (`select.object` with `"point"`;
+//! ⇧ adds, ⌥ subtracts, ⇧⌥ intersects); dragging keeps the rectangle mode.
+//!
+//! The lookup is `photocraft_engine::smartselect_cmds::find_object`, run after the pointer has
+//! been still for [`DEBOUNCE`] seconds on a worker thread (inline on the web), so the UI never
+//! waits for it. Results go into the session's `object_finder` cache, which the click reuses and
+//! which serves every point of an object already found; it is keyed by the document's pixels,
+//! so an edit drops it. The preview itself is keyed by document revision, sampled layer and
+//! Sample All Layers, and clears when the pointer leaves the canvas, the tool changes, a button
+//! goes down or the option is off. Quality of the object found is out of scope here (#2788).
+
+use std::sync::Arc;
+
+use egui::{Color32, TextureOptions, pos2};
+use photocraft_algo::selection::Region;
+use photocraft_doc::{DocId, Document, LayerId};
+use photocraft_engine::smartselect_cmds::{find_object, sampled_target};
+
+use crate::PhotocraftApp;
+use crate::canvas::ViewXform;
+use crate::state::Tool;
+
+/// Seconds the pointer must rest before an object is looked up.
+pub const DEBOUNCE: f64 = 0.12;
+/// Longest side of the overlay texture (the overlay is a preview, not the selection).
+const TEX_MAX: usize = 768;
+
+/// A lookup running off the UI thread.
+struct Job {
+ at: [i32; 2],
+ doc: Arc<Document>,
+ rx: std::sync::mpsc::Receiver<Option<Region>>,
+}
+
+/// The hover state of the active document (`PhotocraftApp::object_finder`).
+pub(crate) struct Finder {
+ doc: DocId,
+ revision: u64,
+ target: Option<LayerId>,
+ all_layers: bool,
+ /// The pointer pixel and when it got there.
+ at: [i32; 2],
+ since: f64,
+ job: Option<Job>,
+ /// Points already looked up that found nothing (the background).
+ misses: Vec<[i32; 2]>,
+ shown: Option<Arc<Region>>,
+ texture: Option<(usize, egui::TextureHandle)>,
+}
+
+/// What [`update`] decided.
+#[derive(Clone, Debug, Default)]
+pub(crate) struct Update {
+ /// The object to highlight.
+ pub shown: Option<Arc<Region>>,
+ /// A lookup is pending or running: repaint soon to pick it up.
+ pub busy: bool,
+}
+
+/// Whether the preview applies now (`pressed`: a pointer button is down).
+fn active(app: &PhotocraftApp, pressed: bool) -> bool {
+ app.ui.tool == Tool::ObjectSelection
+ && app.ui.tool_options.object_finder
+ && !pressed
+ && app.drag.is_none()
+ && app.ui.transform.is_none()
+ && app.session.active().is_some()
+}
+
+/// Advances the hover preview with the pointer at `at` (document px; `None` = off the canvas)
+/// at time `now` (seconds).
+pub(crate) fn update(app: &mut PhotocraftApp, at: Option<[f64; 2]>, pressed: bool, now: f64) -> Update {
+ let at = at.filter(|p| p[0].is_finite() && p[1].is_finite());
+ let (Some(at), true) = (at, active(app, pressed)) else {
+ app.object_finder = None;
+ return Update::default();
+ };
+ let Some(st) = app.session.active() else { return Update::default() };
+ let all_layers = app.ui.tool_options.sample_all_layers;
+ let target = sampled_target(&st.doc, st.active_layer, all_layers);
+ let (doc, revision, layer) = (st.doc.id, st.revision, st.active_layer);
+ let px = [at[0].floor() as i32, at[1].floor() as i32];
+ let fresh = app.object_finder.as_ref().is_some_and(|f| f.doc == doc && f.revision == revision && f.target == target && f.all_layers == all_layers);
+ if !fresh {
+ app.object_finder = Some(Finder { doc, revision, target, all_layers, at: px, since: now, job: None, misses: Vec::new(), shown: None, texture: None });
+ }
+ let doc_arc = Arc::clone(&st.doc);
+ let Some(f) = app.object_finder.as_mut() else { return Update::default() };
+ if f.at != px {
+ f.at = px;
+ f.since = now;
+ }
+ // A finished lookup: remember it (only for the pixels it was computed from).
+ if let Some(job) = &f.job {
+ match job.rx.try_recv() {
+ Ok(found) => {
+ if let Some(r) = found {
+ if photocraft_engine::layer_multi_cmds::same_pixels(&job.doc, &doc_arc) {
+ app.session.object_finder.insert(&doc_arc, target, Arc::new(r));
+ }
+ } else {
+ f.misses.push(job.at);
+ if f.misses.len() > 64 {
+ f.misses.remove(0);
+ }
+ }
+ f.job = None;
+ }
+ Err(std::sync::mpsc::TryRecvError::Empty) => {}
+ Err(std::sync::mpsc::TryRecvError::Disconnected) => f.job = None,
+ }
+ }
+ let inside = |r: &Region| r.at(px[0], px[1]) >= 0.5;
+ if !f.shown.as_deref().is_some_and(inside) {
+ f.shown = app.session.object_finder.lookup(&doc_arc, target, at[0] as f32, at[1] as f32);
+ }
+ let missed = f.misses.iter().any(|m| (m[0] - px[0]).abs() <= 2 && (m[1] - px[1]).abs() <= 2);
+ if f.shown.is_none() && f.job.is_none() && !missed && now - f.since >= DEBOUNCE && doc_arc.bounds().contains(px[0], px[1]) {
+ f.job = Some(spawn(Arc::clone(&doc_arc), layer, all_layers, px, at));
+ }
+ let busy = f.job.is_some() || (f.shown.is_none() && !missed && now - f.since < DEBOUNCE);
+ Update { shown: f.shown.clone(), busy }
+}
+
+fn spawn(doc: Arc<Document>, layer: Option<LayerId>, all_layers: bool, px: [i32; 2], at: [f64; 2]) -> Job {
+ let (tx, rx) = std::sync::mpsc::channel();
+ let work = {
+ let doc = Arc::clone(&doc);
+ move || {
+ let _ = tx.send(find_object(&doc, layer, all_layers, at[0] as f32, at[1] as f32));
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ let spawned = std::thread::Builder::new().name("object-finder".into()).spawn(work);
+ if spawned.is_err() {
+ // No thread: the receiver reports Disconnected and the next rest retries.
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ work();
+ Job { at: px, doc, rx }
+}
+
+/// Clears the preview (a tool switch or an edit made elsewhere is caught by [`update`] too).
+pub(crate) fn clear(app: &mut PhotocraftApp) {
+ app.object_finder = None;
+}
+
+/// The overlay colour: the theme accent, translucent (Photoshop tints the object it finds).
+fn overlay(accent: Color32, cov: f32, edge: bool) -> Color32 {
+ let a = if edge { 0.95 } else { 0.42 * cov.clamp(0.0, 1.0) };
+ Color32::from_rgba_unmultiplied(accent.r(), accent.g(), accent.b(), (a * 255.0).round() as u8)
+}
+
+/// The overlay image of `r`: translucent fill with an opaque one-texel outline, at most
+/// [`TEX_MAX`] texels on its longest side.
+pub(crate) fn overlay_image(r: &Region, accent: Color32) -> egui::ColorImage {
+ let (w, h) = (r.bbox.width().max(1) as usize, r.bbox.height().max(1) as usize);
+ let step = w.max(h).div_ceil(TEX_MAX).max(1);
+ let (tw, th) = (w.div_ceil(step), h.div_ceil(step));
+ let cov = |tx: usize, ty: usize| r.at(r.bbox.x0 + (tx * step) as i32, r.bbox.y0 + (ty * step) as i32);
+ let mut px = Vec::with_capacity(tw * th);
+ for ty in 0..th {
+ for tx in 0..tw {
+ let c = cov(tx, ty);
+ let on = c >= 0.5;
+ let edge = on
+ && (tx == 0
+ || ty == 0
+ || tx + 1 == tw
+ || ty + 1 == th
+ || cov(tx - 1, ty) < 0.5
+ || cov(tx + 1, ty) < 0.5
+ || cov(tx, ty - 1) < 0.5
+ || cov(tx, ty + 1) < 0.5);
+ px.push(if c <= 0.0 { Color32::TRANSPARENT } else { overlay(accent, c, edge) });
+ }
+ }
+ egui::ColorImage::new([tw, th], px)
+}
+
+/// Updates the preview for this frame and draws the highlight on the active document's canvas.
+pub(crate) fn draw(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &ViewXform, idx: usize, hover: Option<egui::Pos2>) {
+ if app.session.active_index() != Some(idx) {
+ return;
+ }
+ let ctx = painter.ctx().clone();
+ let (pressed, now) = ctx.input(|i| (i.pointer.any_down(), i.time));
+ let up = update(app, hover.map(|p| xf.to_doc(p)), pressed, now);
+ if up.busy {
+ ctx.request_repaint_after(std::time::Duration::from_millis(40));
+ }
+ let Some(r) = up.shown else { return };
+ let Some(f) = app.object_finder.as_mut() else { return };
+ let key = Arc::as_ptr(&r) as usize;
+ if f.texture.as_ref().is_none_or(|(k, _)| *k != key) {
+ let accent = crate::theme::Tokens::get(&ctx).accent;
+ let tex = ctx.load_texture("object-finder", overlay_image(&r, accent), TextureOptions::LINEAR);
+ f.texture = Some((key, tex));
+ }
+ let Some((_, tex)) = &f.texture else { return };
+ let b = r.bbox;
+ let mut mesh = egui::Mesh::with_texture(tex.id());
+ let corners = [(b.x0, b.y0, 0.0, 0.0), (b.x1, b.y0, 1.0, 0.0), (b.x1, b.y1, 1.0, 1.0), (b.x0, b.y1, 0.0, 1.0)];
+ for (x, y, u, v) in corners {
+ mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(x as f32, y as f32), uv: pos2(u, v), color: Color32::WHITE });
+ }
+ mesh.indices.extend_from_slice(&[0, 1, 2, 0, 2, 3]);
+ painter.add(egui::Shape::mesh(mesh));
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ /// A 200 × 160 document: a red disc (centre 100, 80, radius 45) on blue.
+ pub(crate) fn disc_app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 160})).unwrap();
+ app.session
+ .edit("paint", |doc, a| {
+ let s = doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap();
+ s.fill_rect(photocraft_geom::Rect::new(0, 0, 200, 160), &[0.2, 0.4, 0.8, 1.0]);
+ for y in 0..160 {
+ for x in 0..200 {
+ let (dx, dy) = (x as f32 + 0.5 - 100.0, y as f32 + 0.5 - 80.0);
+ if dx * dx + dy * dy <= 45.0 * 45.0 {
+ s.fill_rect(photocraft_geom::Rect::new(x, y, x + 1, y + 1), &[0.9, 0.2, 0.1, 1.0]);
+ }
+ }
+ }
+ Ok(())
+ })
+ .unwrap();
+ app.ui.tool = Tool::ObjectSelection;
+ app
+ }
+
+ /// Hovers at `at` until the lookup settles (time advances past the debounce).
+ pub(crate) fn hover(app: &mut PhotocraftApp, at: [f64; 2]) -> Update {
+ let mut t = 100.0;
+ loop {
+ let u = update(app, Some(at), false, t);
+ if !u.busy || t > 130.0 {
+ return u;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ t += 0.05;
+ }
+ }
+
+ #[test]
+ fn hovering_an_object_highlights_it_after_a_rest() {
+ let mut app = disc_app();
+ // Not before the pointer has rested.
+ let u = update(&mut app, Some([100.0, 80.0]), false, 50.0);
+ assert!(u.shown.is_none() && u.busy);
+ let u = hover(&mut app, [100.0, 80.0]);
+ let r = u.shown.expect("the disc is highlighted");
+ assert!(r.at(100, 80) >= 0.5 && r.at(60, 80) >= 0.5 && r.at(5, 5) < 0.5);
+ // Elsewhere on the same object: served from the cache, no new lookup.
+ let u = update(&mut app, Some([120.0, 90.0]), false, 200.0);
+ assert!(u.shown.is_some_and(|s| Arc::ptr_eq(&s, &r)) && !u.busy);
+ assert_eq!(app.session.object_finder.len(), 1);
+ // The background highlights nothing.
+ assert!(hover(&mut app, [4.0, 4.0]).shown.is_none());
+ }
+
+ #[test]
+ fn preview_clears_on_leave_tool_switch_button_option_and_edits() {
+ let mut app = disc_app();
+ assert!(hover(&mut app, [100.0, 80.0]).shown.is_some());
+ assert!(update(&mut app, None, false, 300.0).shown.is_none());
+ assert!(app.object_finder.is_none());
+ assert!(hover(&mut app, [100.0, 80.0]).shown.is_some());
+ assert!(update(&mut app, Some([100.0, 80.0]), true, 300.0).shown.is_none());
+ app.ui.tool = Tool::Lasso;
+ assert!(update(&mut app, Some([100.0, 80.0]), false, 300.0).shown.is_none());
+ app.ui.tool = Tool::ObjectSelection;
+ app.ui.tool_options.object_finder = false;
+ assert!(update(&mut app, Some([100.0, 80.0]), false, 300.0).shown.is_none());
+ app.ui.tool_options.object_finder = true;
+ assert!(hover(&mut app, [100.0, 80.0]).shown.is_some());
+ // A pixel edit: the cached object is dropped and the preview starts over.
+ app.session.execute("paint.pencil", json!({"points": [[5, 5], [30, 5]], "size": 4, "color": "#000000"})).unwrap();
+ let u = update(&mut app, Some([100.0, 80.0]), false, 400.0);
+ assert!(u.shown.is_none() && u.busy);
+ }
+
+ #[test]
+ fn click_commits_the_highlighted_object_with_the_modifiers() {
+ use crate::canvas::{ToolEvent, tool_event};
+ let mut app = disc_app();
+ assert!(hover(&mut app, [100.0, 80.0]).shown.is_some());
+ let click = |app: &mut PhotocraftApp, m: egui::Modifiers| {
+ tool_event(app, ToolEvent::Down { x: 100.0, y: 80.0, pressure: 1.0 }, m);
+ tool_event(app, ToolEvent::Up { x: 100.0, y: 80.0 }, m);
+ };
+ let cov = |app: &PhotocraftApp, x: i32, y: i32| app.session.active().unwrap().doc.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0));
+ click(&mut app, egui::Modifiers::NONE);
+ assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.object"));
+ assert!(cov(&app, 100, 80) >= 0.5 && cov(&app, 60, 80) >= 0.5 && cov(&app, 5, 5) < 0.5);
+ app.run("select.all", json!({})).unwrap();
+ click(&mut app, egui::Modifiers::ALT);
+ assert!(cov(&app, 100, 80) < 0.5 && cov(&app, 5, 5) >= 0.5);
+ click(&mut app, egui::Modifiers::SHIFT);
+ assert!(cov(&app, 100, 80) >= 0.5 && cov(&app, 5, 5) >= 0.5);
+ click(&mut app, egui::Modifiers { alt: true, shift: true, ..Default::default() });
+ assert!(cov(&app, 100, 80) >= 0.5 && cov(&app, 5, 5) < 0.5);
+ // Off: a click keeps the Quick Selection fallback.
+ app.ui.tool_options.object_finder = false;
+ click(&mut app, egui::Modifiers::NONE);
+ assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("select.quick"));
+ }
+
+ #[test]
+ fn overlay_image_tints_the_object_and_outlines_it() {
+ let r = Region { bbox: photocraft_geom::Rect::new(0, 0, 4, 4), mask: vec![255; 16] };
+ let img = overlay_image(&r, Color32::from_rgb(0, 120, 255));
+ assert_eq!(img.size, [4, 4]);
+ assert!(img.pixels[0].a() > 200, "edge");
+ assert!(img.pixels[5].a() > 0 && img.pixels[5].a() < 200, "fill");
+ let big = Region { bbox: photocraft_geom::Rect::new(0, 0, 3000, 10), mask: vec![255; 30_000] };
+ assert!(overlay_image(&big, Color32::WHITE).size[0] <= TEX_MAX);
+ }
+}
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index a9e1241e0..48beefbaa 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -342,13 +342,28 @@ pub fn content_aware_move_params(app: &PhotocraftApp, offset: [i64; 2]) -> Value
}
/// Object Selection: the dragged rectangle. A click (or a sub-2 px nudge) cannot be a
-/// rectangle: like Photoshop's click-to-select, it falls back to a Quick Selection dab at
+/// rectangle: with Object Finder on it selects the object under the pointer, the one hovering
+/// highlighted (#4087; ⇧ adds, ⌥ subtracts, ⇧⌥ intersects, otherwise replaces). With it off it
+/// falls back to a Quick Selection dab at
/// the brush size instead of looking dead (⌥ subtracts, otherwise it adds). Larger drags
/// run the rectangle GrabCut (⌥ subtracts, ⇧ adds, otherwise replaces).
pub fn finish_object_selection(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], mods: egui::Modifiers) {
let (x, y) = (start[0].min(end[0]), start[1].min(end[1]));
let (w, h) = ((end[0] - start[0]).abs(), (end[1] - start[1]).abs());
let sample_all = app.ui.tool_options.sample_all_layers;
+ if (w < 2.0 || h < 2.0) && app.ui.tool_options.object_finder {
+ // Object Finder (#4087): the object under the click, as hovering highlighted it.
+ let mode = match (mods.shift, mods.alt) {
+ (true, true) => "intersect",
+ (true, false) => "add",
+ (false, true) => "subtract",
+ (false, false) => "replace",
+ };
+ let r = app.run("select.object", json!({"point": [end[0], end[1]], "mode": mode, "sampleAllLayers": sample_all}));
+ crate::object_finder::clear(app);
+ report_smart_result(app, r, tl!("No object found there — drag a rectangle around it"));
+ return;
+ }
if w < 2.0 || h < 2.0 {
let size = app.session.tools.brush.size;
let mode = if mods.alt { "subtract" } else { "add" };
@@ -600,6 +615,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
}
}
Tool::ObjectSelection => {
+ crate::widgets::checkbox(ui, &mut o.object_finder, tl!("Object Finder"));
crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers"));
opt(ui, tl!("Drag a rectangle around the object"));
crate::widgets::vline(ui, 22.0);
@@ -776,6 +792,7 @@ mod tests {
// A click cannot be a rectangle: it selects at the cursor instead of looking dead.
let mut app = app();
app.ui.tool = Tool::ObjectSelection;
+ app.ui.tool_options.object_finder = false;
let m = egui::Modifiers::NONE;
tool_event(&mut app, ToolEvent::Down { x: 50.0, y: 30.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 30.0 }, m);
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index ff76da78c..620adf8d2 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -508,6 +508,8 @@ pub struct ToolOptions {
pub contiguous: bool,
pub anti_alias: bool,
pub sample_all_layers: bool,
+ /// Object Selection › Object Finder: hovering highlights the object a click selects (#4087).
+ pub object_finder: bool,
/// Remove tool: the fill goes to a new layer above the target (Photoshop's Create a new layer).
pub remove_new_layer: bool,
/// Remove tool: each stroke is filled when released (Photoshop's default). Off, the strokes
@@ -750,6 +752,7 @@ impl Default for ToolOptions {
contiguous: true,
anti_alias: true,
sample_all_layers: false,
+ object_finder: true,
remove_new_layer: false,
remove_after_each_stroke: true,
feather: 0.0,
diff --git a/crates/ui-egui/src/tool_reset.rs b/crates/ui-egui/src/tool_reset.rs
index 646af4f7a..8743fc105 100644
--- a/crates/ui-egui/src/tool_reset.rs
+++ b/crates/ui-egui/src/tool_reset.rs
@@ -124,7 +124,8 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) {
Tool::Lasso | Tool::PolygonLasso => reset!(feather, anti_alias),
Tool::MagneticLasso => reset!(feather, anti_alias, magnetic_width, magnetic_contrast, magnetic_frequency, magnetic_pressure),
Tool::MagicWand => reset!(tolerance, anti_alias, contiguous, sample_all_layers),
- Tool::QuickSelection | Tool::ObjectSelection => reset!(sample_all_layers, enhance_edge),
+ Tool::QuickSelection => reset!(sample_all_layers, enhance_edge),
+ Tool::ObjectSelection => reset!(sample_all_layers, enhance_edge, object_finder),
Tool::Crop => reset!(
crop_ratio,
crop_delete,
diff --git a/docs/ui-parity.md b/docs/ui-parity.md
index 70b503d0c..a48db144a 100644
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@ -29,7 +29,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| Move, artboard | Move, Artboard | |
| Marquee | Rectangular, Elliptical, Single Row, Single Column | |
| Lasso | Lasso, Polygonal, Magnetic | |
-| Selection | Object Selection, Quick Selection, Magic Wand | |
+| Selection | Object Selection, Quick Selection, Magic Wand | Object Selection's Object Finder (on by default in its options bar): resting the pointer highlights the object a click selects (`select.object` with `point`; ⇧ adds, ⌥ subtracts, ⇧⌥ intersects); dragging keeps the rectangle mode (#4087). Heuristic, not a learned segmenter (#2788). |
| Crop and slice | Crop, Perspective Crop, Slice, Slice Select | |
| Frame | Frame (frames are groups clipped by a rectangular or elliptical mask) | |
| Eyedropper | Eyedropper, Color Sampler, Ruler, Note, Count | |