From b3268a6621a95787c3919b13a42c66a828e211fb Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:42:22 +0100 Subject: [PATCH 1/7] Select and Mask: draw the Marching Ants view with the canvas's ants (#10506) The workspace kept an early copy of the marching ants: one unit edge per pixel pair of the refined preview, each drawn as a 1-point antialiased line coloured black or white per 4 document px, with the colour flipping 8 times a second. The whole outline blinked instead of marching, came out grey and uneven off the pixel grid, turned into specks when zoomed out, and was dropped past 4 MP or 200k edges. Trace the refined proxy selection with the canvas tracer (merged runs at the view's step, over the visible region within the selection's bounds) and draw it with canvas::marching_ants_mapped, so the ants look and march as on the canvas. The preview job traces for the view it was asked for; the UI traces again only when a pan or zoom changes the key. The preview keeps its own k, so a pending High Quality toggle doesn't misplace them. view_step and view_region are pure helpers in canvas/outline.rs. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/outline.rs | 45 +++ crates/ui-egui/src/dialogs/select_mask_ui.rs | 215 ++++++------ .../src/dialogs/select_mask_ui/tests.rs | 306 +++++++++++++++++- 3 files changed, 455 insertions(+), 111 deletions(-) diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 9e06a1ae68..d35a973f77 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -25,6 +25,31 @@ pub(crate) fn bounded_step(bounds: Rect, mut step: u32) -> u32 { step } +/// The trace step for a view of `device_zoom` device px per document px, of a mask reduced by `k`: +/// about one sample per device pixel, a power of two in 1..=64. +pub(crate) fn view_step(device_zoom: f32, k: u32) -> u32 { + (1.0 / (device_zoom * k.max(1) as f32).max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32 +} + +/// The part of a mask reduced by `k` to trace for the document rectangle `[x0, y0, x1, y1]` in +/// view: quantised to 256 cells of `step` so small pans keep it, and padded by that so the cut +/// edges of a trace fall outside the view. +pub(crate) fn view_region(view: [f64; 4], k: u32, step: u32) -> Rect { + let k = f64::from(k.max(1)); + let q = 256 * step.clamp(1, 64) as i32; + // The view centre can be any finite number. Past ±2³⁰ there is no document to outline, and + // the padding (at most 2 · 256 · 64) can't overflow i32 from there. + let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; + let (x0, x1) = (view[0].min(view[2]) / k, view[0].max(view[2]) / k); + let (y0, y1) = (view[1].min(view[3]) / k, view[1].max(view[3]) / k); + Rect::new( + px(x0.floor()).div_euclid(q) * q - q, + px(y0.floor()).div_euclid(q) * q - q, + (px(x1.ceil()).div_euclid(q) + 2) * q, + (px(y1.ceil()).div_euclid(q) + 2) * q, + ) +} + /// Extract the boundary of `mask` (> 0.5 = selected) as merged horizontal and vertical segments. pub fn outline(mask: &Surface, bounds: Rect) -> Vec { outline_scaled(mask, bounds, 1) @@ -210,6 +235,26 @@ mod tests { } } + #[test] + fn view_step_and_region_follow_the_canvas_and_survive_hostile_views() { + assert_eq!(view_step(1.0, 1), 1); + assert_eq!(view_step(0.25, 1), 4); + assert_eq!(view_step(0.5, 2), 1, "a copy reduced by 2 seen at 50 % is at its own size"); + assert_eq!(view_region([10.0, 20.0, 300.0, 200.0], 1, 1), Rect::new(-256, -256, 768, 512)); + assert_eq!(view_region([0.0, 0.0, 1024.0, 512.0], 2, 1), Rect::new(-256, -256, 1024, 768)); + for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1e9, 1e-30] { + for k in [0, 1, 3, u32::MAX] { + assert!((1..=64).contains(&view_step(zoom, k)), "zoom {zoom}, k {k}"); + } + } + for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e30, -1e30] { + for step in [0, 1, 64, u32::MAX] { + let r = view_region([v, -v, v, 1e30], 1, step); + assert!(r.x0 <= r.x1 && r.y0 <= r.y1, "{v}, {step}: {r:?}"); + } + } + } + #[test] fn empty_mask_has_no_outline() { let m = Surface::new(PixelFormat::GRAY8); diff --git a/crates/ui-egui/src/dialogs/select_mask_ui.rs b/crates/ui-egui/src/dialogs/select_mask_ui.rs index 3430569775..4ce7e2478e 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui.rs @@ -35,6 +35,7 @@ use serde_json::{Map, Value, json}; use crate::PhotocraftApp; use crate::canvas::ToolEvent; +use crate::outline::Segment; use crate::select_mask_view::Mode; use crate::theme::Tokens; use crate::widgets; @@ -46,10 +47,6 @@ const BAR_H: f32 = 36.0; const TAB_H: f32 = 28.0; const PANEL_W: f32 = 350.0; const UNDO_LIMIT: usize = 100; -/// Marching ants with more edges than this are not drawn. -const MAX_ANT_EDGES: usize = 200_000; -/// Bound the temporary dense mask used for marching ants. -const MAX_ANT_PIXELS: usize = 4_000_000; /// The `prefs.dialogs` key under which Remember Settings keeps the settings. const REMEMBERED: &str = "select.refineEdge.workspace"; const CMD: &str = crate::select_mask_view::COMMAND; @@ -354,11 +351,26 @@ struct BaseCache { base: Option, } +/// Which part of the refined selection the Marching Ants view traced, and how coarsely. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct OutlineKey { + step: u32, + /// Reduced-copy px. + region: Rect, + k: u32, +} + /// A computed preview, ready to upload. struct Shown { image: egui::ColorImage, - /// Marching ants (document px) in the Marching Ants view. - ants: Option>, + /// The refined selection on the reduced copy, for the Marching Ants view. + selection: Option, + /// Where its outline can be (reduced-copy px): its content within the copy. + trace_bounds: Rect, + /// Document px per reduced-copy px of this preview. + k: u32, + /// The outline traced for the view the preview was asked for (reduced-copy px). + outline: Option<(OutlineKey, Vec)>, /// Reduced-copy pixels at least half selected. selected: usize, /// How many points of the stroke being drawn it includes ([`usize::MAX`]: every stroke is in). @@ -380,7 +392,12 @@ struct Preview { shown: u64, pending: Option, tex: Option, - ants: Option>, + /// [`Shown::selection`], [`Shown::trace_bounds`] and [`Shown::k`] of the preview shown. + selection: Option, + trace_bounds: Rect, + k: u32, + /// The outline of `selection` for the view, traced again when the view moves past its key. + outline: Option<(OutlineKey, Vec)>, covers: [f32; 2], selected: usize, /// [`Shown::trail`] of the preview shown. @@ -431,6 +448,8 @@ pub struct SelectMaskWorkspace { image_tex: Option, zoom: f32, center: [f64; 2], + /// The document's area on screen and the device px per point, as last drawn. + view_area: Option<(ERect, f32)>, hover: Option<[f64; 2]>, preview: Preview, pub error: Option, @@ -765,6 +784,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result<(), String> { image_tex: None, zoom: 0.0, center: [f64::from(canvas.x0 + canvas.x1) / 2.0, f64::from(canvas.y0 + canvas.y1) / 2.0], + view_area: None, hover: None, preview: Preview::default(), error: None, @@ -1028,6 +1048,9 @@ struct Job { texture_limit: usize, /// [`Shown::trail`] of this preview. trail: usize, + /// In the Marching Ants view: the device px per document px and the document rectangle in + /// view, to trace the outline for. + ants: Option<(f32, [f64; 4])>, } fn job(app: &PhotocraftApp) -> Option { @@ -1073,38 +1096,10 @@ fn job(app: &PhotocraftApp) -> Option { Some(_) => 0, None => usize::MAX, }, + ants: w.view_area.filter(|_| w.opts.view == Mode::MarchingAnts).map(|(area, ppp)| ant_view(View { area, zoom: w.zoom, center: w.center }, ppp)), }) } -/// Unit edges between selected (≥ ½) and unselected pixels of `m` (`w × h`, reduced by `k`), in -/// document px; `None` past [`MAX_ANT_EDGES`]. -fn ant_edges(m: &[f32], w: usize, h: usize, k: f32) -> Option> { - let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && m.get(y as usize * w + x as usize).is_some_and(|v| *v >= 0.5); - let mut out = Vec::new(); - for y in 0..h as i64 { - for x in 0..w as i64 { - if !at(x, y) { - continue; - } - let (fx, fy) = (x as f32, y as f32); - for (n, a, b) in [ - (at(x - 1, y), [fx, fy], [fx, fy + 1.0]), - (at(x + 1, y), [fx + 1.0, fy], [fx + 1.0, fy + 1.0]), - (at(x, y - 1), [fx, fy], [fx + 1.0, fy]), - (at(x, y + 1), [fx, fy + 1.0], [fx + 1.0, fy + 1.0]), - ] { - if !n { - out.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]); - } - } - if out.len() > MAX_ANT_EDGES { - return None; - } - } - } - Some(out) -} - /// Count selected pixels without allocating a canvas-sized mask. Missing tiles use the surface's /// default value, including an inverted selection whose default is selected. fn selected_pixels(selection: Option<&Surface>, area: Rect) -> usize { @@ -1127,65 +1122,46 @@ fn selected_pixels(selection: Option<&Surface>, area: Rect) -> usize { count } -/// Generate ants only when the dense temporary mask fits the preview budget. -fn preview_ants(selection: Option<&Surface>, area: Rect, k: f32) -> Option> { - let (w, h) = (area.width() as usize, area.height() as usize); - if w.checked_mul(h).is_none_or(|n| n > MAX_ANT_PIXELS) { - return sparse_preview_ants(selection?, area, k); - } - let coverage = photocraft_algo::selection::mask_from_surface(selection, area); - ant_edges(&coverage, w, h, k) +/// The device px per document px and the document rectangle `[x0, y0, x1, y1]` the view shows. +fn ant_view(v: View, ppp: f32) -> (f32, [f64; 4]) { + let (a, b) = (v.to_doc(v.area.min), v.to_doc(v.area.max)); + (v.zoom * ppp, [a[0], a[1], b[0], b[1]]) } -/// Follow sparse selections on large canvases without scanning the empty canvas. A selected -/// default or too many stored pixels falls back to omitting ants, as for too many edges. -fn sparse_preview_ants(surface: &Surface, area: Rect, k: f32) -> Option> { - if surface.default_pixel().first().is_some_and(|v| *v >= 0.5) { - return None; +/// Where the outline of `selection` can be within the reduced copy `area`: all of it when the +/// default pixel is selected (an inverted selection is outlined along the canvas border). +fn trace_bounds(selection: Option<&Surface>, area: Rect) -> Rect { + match selection { + Some(s) if s.default_pixel().first().is_some_and(|v| *v > 0.5) => area, + Some(s) => s.content_bounds().intersect(&area), + None => Rect::EMPTY, } - let mut work = 0usize; - let mut edges = Vec::new(); - let mut sample = vec![0.0; surface.channels()]; - for (coord, _) in surface.tiles() { - let tile = coord.rect().intersect(&area); - if tile.is_empty() { - continue; - } - work = work.checked_add((tile.width() as usize).checked_mul(tile.height() as usize)?)?; - if work > MAX_ANT_PIXELS { - return None; - } - let coverage = photocraft_algo::selection::mask_from_surface(Some(surface), tile); - for y in tile.y0..tile.y1 { - for x in tile.x0..tile.x1 { - let index = (y - tile.y0) as usize * tile.width() as usize + (x - tile.x0) as usize; - if !coverage.get(index).is_some_and(|v| *v >= 0.5) { - continue; - } - let (fx, fy) = ((x - area.x0) as f32, (y - area.y0) as f32); - for (nx, ny, a, b) in [ - (x - 1, y, [fx, fy], [fx, fy + 1.0]), - (x + 1, y, [fx + 1.0, fy], [fx + 1.0, fy + 1.0]), - (x, y - 1, [fx, fy], [fx + 1.0, fy]), - (x, y + 1, [fx, fy + 1.0], [fx + 1.0, fy + 1.0]), - ] { - let selected = if nx < area.x0 || nx >= area.x1 || ny < area.y0 || ny >= area.y1 { - false - } else { - surface.read_pixel(nx, ny, &mut sample); - sample.first().is_some_and(|v| *v >= 0.5) - }; - if !selected { - edges.push([[a[0] * k, a[1] * k], [b[0] * k, b[1] * k]]); - if edges.len() > MAX_ANT_EDGES { - return None; - } - } - } - } - } +} + +/// The trace of a preview reduced by `k` within `bounds`, for a view (see [`ant_view`]). +fn outline_key(k: u32, bounds: Rect, (zoom, view): (f32, [f64; 4])) -> OutlineKey { + let k = k.max(1); + let step = crate::outline::view_step(zoom, k); + OutlineKey { step, region: crate::outline::view_region(view, k, step).intersect(&bounds), k } +} + +fn trace(selection: &Surface, key: OutlineKey, parallel: bool) -> Vec { + if parallel { + crate::outline::outline_scaled(selection, key.region, key.step) + } else { + // A preview job may hold Rayon's workers; the UI thread must not wait for them (#1554). + crate::outline::outline_scaled_serial(selection, key.region, key.step) } - Some(edges) +} + +/// The outline of the preview shown for a view, traced again only when the view's key changes. +fn ant_outline(pv: &mut Preview, view: (f32, [f64; 4]), parallel: bool) -> Option<&[Segment]> { + let selection = pv.selection.as_ref()?; + let key = outline_key(pv.k, pv.trace_bounds, view); + if pv.outline.as_ref().is_none_or(|(k, _)| *k != key) { + pv.outline = Some((key, trace(selection, key, parallel))); + } + pv.outline.as_ref().map(|(_, segs)| segs.as_slice()) } /// The preview of `job`: the edits applied (from where the cache left off), the edge refined and @@ -1236,10 +1212,15 @@ fn compute(job: Job, cancel: Option<&photocraft_engine::jobs::JobCtx>) -> Result let buf = photocraft_compose::render_reduced(&shown, u32::try_from(tw).unwrap_or(1), u32::try_from(th).unwrap_or(1)); let image = crate::canvas::display_image(job.display.as_deref(), &buf); let selected = selected_pixels(shown.selection.as_ref(), shown.bounds()); - let mode = params.get("__view").and_then(|v| v.get("mode")).and_then(Value::as_str); - let ants = if mode == Some(Mode::MarchingAnts.id()) { preview_ants(shown.selection.as_ref(), shown.bounds(), k as f32) } else { None }; + let bounds = trace_bounds(shown.selection.as_ref(), shown.bounds()); + // Traced here, off the UI thread, for the view as it was: the UI traces again only after a + // pan or zoom. + let outline = shown.selection.as_ref().zip(job.ants).map(|(sel, view)| { + let key = outline_key(k, bounds, view); + (key, trace(sel, key, true)) + }); let covers = [(pw as f32) * k as f32, (ph as f32) * k as f32]; - Ok((Shown { image, ants, selected, trail: job.trail, covers }, cache, proxy)) + Ok((Shown { image, selection: shown.selection, trace_bounds: bounds, k, outline, selected, trail: job.trail, covers }, cache, proxy)) } /// Takes the preview of state `generation` (made from document `revision`): the image when it is @@ -1483,7 +1464,10 @@ fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { Some(t) => t.set(s.image, egui::TextureOptions::LINEAR), None => w.preview.tex = Some(ctx.load_texture("select-mask-preview", s.image, egui::TextureOptions::LINEAR)), } - w.preview.ants = s.ants; + w.preview.selection = s.selection; + w.preview.trace_bounds = s.trace_bounds; + w.preview.k = s.k; + w.preview.outline = s.outline; w.preview.covers = s.covers; } } @@ -1650,13 +1634,27 @@ fn follow_revision(app: &mut PhotocraftApp) { w.preview.tex = None; w.preview.pending = None; w.preview.cache = None; + w.preview.selection = None; + w.preview.outline = None; w.stale(); } } /// Draws the document, the refined edge, the stroke being drawn and the polygon in progress. -fn paint_canvas(ui: &mut egui::Ui, ctx: &egui::Context, w: &mut SelectMaskWorkspace, t: &Tokens, painter: &egui::Painter, resp: &egui::Response, area: ERect) { +#[allow(clippy::too_many_arguments)] +fn paint_canvas( + ui: &mut egui::Ui, + ctx: &egui::Context, + w: &mut SelectMaskWorkspace, + t: &Tokens, + painter: &egui::Painter, + resp: &egui::Response, + area: ERect, + parallel: bool, +) { let v = View { area, zoom: w.zoom, center: w.center }; + let ppp = ctx.pixels_per_point(); + w.view_area = Some((area, ppp)); let clip = painter.with_clip_rect(area); let img = v.rect(w.canvas); let uv = ERect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); @@ -1673,18 +1671,14 @@ fn paint_canvas(ui: &mut egui::Ui, ctx: &egui::Context, w: &mut SelectMaskWorksp } (None, None) => {} } - // Marching Ants: the refined selection's edge, black dashes on white. - if !w.hide_view - && w.opts.view == Mode::MarchingAnts - && let Some(edges) = &w.preview.ants - { - let phase = (ui.input(|i| i.time) * 8.0) as usize; - for e in edges { - let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); - let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); - clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); + // Marching Ants: the refined selection's edge, drawn as the canvas draws its ants. + if !w.hide_view && w.opts.view == Mode::MarchingAnts { + let k = f64::from(w.preview.k.max(1)); + if let Some(segs) = ant_outline(&mut w.preview, ant_view(v, ppp), parallel).filter(|s| !s.is_empty()) { + let time = ui.input(|i| i.time); + crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen([f64::from(p[0]) * k, f64::from(p[1]) * k])); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); } - ctx.request_repaint_after(std::time::Duration::from_millis(120)); } if w.preview.shown != w.preview.want && !w.pressed { let sp = ERect::from_min_size(area.right_bottom() - vec2(26.0, 26.0), vec2(18.0, 18.0)); @@ -1826,6 +1820,11 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let mut mods = egui::Modifiers::NONE; let mut edit: Option = None; let mut do_reset = false; + // As on the canvas: trace in parallel unless a job may hold Rayon's workers (#1554). + #[cfg(not(target_arch = "wasm32"))] + let parallel = !app.session.has_jobs() && app.distort.select_mask.as_ref().is_some_and(|w| w.preview.running.is_none()); + #[cfg(target_arch = "wasm32")] + let parallel = false; egui::Area::new(egui::Id::unique("select-mask-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { let Some(w) = app.distort.select_mask.as_mut() else { return }; let before = (w.opts.clone(), w.sample_all); @@ -1936,7 +1935,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } let v = View { area, zoom: w.zoom, center: w.center }; - paint_canvas(ui, ctx, w, &t, &painter, &resp, area); + paint_canvas(ui, ctx, w, &t, &painter, &resp, area, parallel); // Space, the middle button or the Hand pan. The Polygonal Lasso takes clicks: each adds a // vertex, a double-click closes. let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == SmTool::Hand; diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index faa4021ab1..e1c67e532c 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -770,18 +770,28 @@ fn the_reason_a_stale_workspace_closed_is_reported() { } } +/// A preview of `selection` over the reduced copy `area`, `k` document px per copy px. +fn shown_preview(selection: Surface, area: Rect, k: u32) -> Preview { + let trace_bounds = trace_bounds(Some(&selection), area); + Preview { selection: Some(selection), trace_bounds, k, ..Default::default() } +} + #[test] -fn sparse_large_preview_counts_coverage_without_a_dense_canvas_mask() { +fn sparse_large_preview_keeps_its_ants() { let area = Rect::new(0, 0, 100_000, 100_000); let mut selection = Surface::new(photocraft_color::PixelFormat::GRAY8); selection.write_pixel(99_999, 99_999, &[1.0]); selection.write_pixel(2, 3, &[0.5]); selection.write_pixel(-1, -1, &[1.0]); assert_eq!(selected_pixels(Some(&selection), area), 2); - assert_eq!(preview_ants(Some(&selection), area, 1.0).unwrap().len(), 8); let small = Rect::new(0, 0, 10, 10); assert_eq!(selected_pixels(Some(&selection), small), 1); - assert_eq!(preview_ants(Some(&selection), small, 1.0).unwrap().len(), 4); + // At 100 % around the far corner: the one pixel there, outlined by four lines. The old ants + // were unit edges of a canvas-sized mask, dropped past 4 MP. + let mut pv = shown_preview(selection, area, 1); + let segs = ant_outline(&mut pv, (1.0, [99_500.0, 99_500.0, 100_500.0, 100_500.0]), false).unwrap(); + assert_eq!(segs.len(), 4, "{segs:?}"); + assert!(segs.iter().all(|(a, b)| [a, b].iter().all(|p| (99_999..=100_000).contains(&p[0]) && (99_999..=100_000).contains(&p[1])))); let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]); inverted.write_pixel(2, 3, &[0.0]); @@ -789,3 +799,293 @@ fn sparse_large_preview_counts_coverage_without_a_dense_canvas_mask() { assert_eq!(selected_pixels(Some(&inverted), smaller), 999_999); assert_eq!(selected_pixels(None, area), 0); } + +/// A selection of the rectangle `r` (reduced-copy px). +fn rect_selection(r: Rect) -> Surface { + let mut s = Surface::new(photocraft_color::PixelFormat::GRAY8); + s.fill_rect(r, &[1.0]); + s +} + +/// The Marching Ants view outlines the refined selection as the canvas does: merged runs (4 lines +/// for a rectangle, not one per pixel edge), on the document's pixel edges at the copy's scale. +#[test] +fn marching_ants_trace_merged_runs_like_the_canvas() { + let area = Rect::new(0, 0, 100, 60); + let sel = rect_selection(Rect::new(5, 5, 25, 15)); + let whole = crate::outline::outline(&sel, sel.content_bounds()); + let mut pv = shown_preview(sel, area, 2); + let segs = ant_outline(&mut pv, (1.0, [0.0, 0.0, 200.0, 120.0]), false).unwrap().to_vec(); + assert_eq!(segs, whole); + assert_eq!(segs.len(), 4, "{segs:?}"); + for (a, b) in segs { + for p in [a, b].map(|p| [p[0] * 2, p[1] * 2]) { + let on_x = (p[0] == 10 || p[0] == 50) && (10..=30).contains(&p[1]); + let on_y = (p[1] == 10 || p[1] == 30) && (10..=50).contains(&p[0]); + assert!(on_x || on_y, "{p:?} lies on the document rectangle (10, 10)–(50, 30)"); + } + } +} + +/// Frames reuse the trace while the view stays within its quantised region; a zoom traces again. +#[test] +fn ant_outline_is_cached_per_view() { + let mut pv = shown_preview(rect_selection(Rect::new(10, 10, 90, 50)), Rect::new(0, 0, 100, 60), 1); + let first = ant_outline(&mut pv, (1.0, [0.0, 0.0, 100.0, 60.0]), false).unwrap().as_ptr(); + let key = pv.outline.as_ref().unwrap().0; + let panned = ant_outline(&mut pv, (1.0, [3.0, 2.0, 103.0, 62.0]), false).unwrap().as_ptr(); + assert_eq!(first, panned, "a small pan keeps the trace"); + assert_eq!(pv.outline.as_ref().unwrap().0, key); + let zoomed = ant_outline(&mut pv, (0.25, [0.0, 0.0, 400.0, 240.0]), false).unwrap().len(); + assert_eq!(pv.outline.as_ref().unwrap().0.step, 4, "zoomed out to 25 %: one sample per 4 px"); + assert_eq!(zoomed, 4); +} + +/// The preview job traces the outline for the view it was asked for, so a new preview (one per +/// move with Real-Time Refinement) costs the UI thread no trace. +#[test] +fn the_preview_job_traces_the_outline_for_the_view() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + let area = ERect::from_min_size(pos2(50.0, 60.0), vec2(800.0, 500.0)); + let w = ws_mut(&mut app); + (w.view_area, w.zoom, w.center) = (Some((area, 1.5)), 2.0, [80.0, 50.0]); + ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); + upload(&mut app, &egui::Context::default()); + let w = ws_mut(&mut app); + let view = ant_view(View { area, zoom: w.zoom, center: w.center }, 1.5); + let traced = w.preview.outline.as_ref().map(|(key, segs)| (*key, segs.as_ptr())).expect("traced in the job"); + assert_eq!(traced.0, outline_key(w.preview.k, w.preview.trace_bounds, view)); + assert_eq!(ant_outline(&mut w.preview, view, false).unwrap().as_ptr(), traced.1, "drawn without tracing again"); + assert_eq!(w.preview.outline.as_ref().unwrap().1.len(), 4, "the 20 × 20 selection"); +} + +/// Until the preview at the new scale arrives, the ants keep the scale of the preview they outline. +#[test] +fn the_outline_keeps_its_previews_scale_while_high_quality_is_toggled() { + let mut app = app_sized(3300, 60); + app.session.execute("select.rect", json!({"x": 30, "y": 15, "width": 30, "height": 30})).unwrap(); + open(&mut app).unwrap(); + ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); + upload(&mut app, &egui::Context::default()); + ui(&mut app, json!({"highQualityPreview": true})); + let w = ws_mut(&mut app); + assert_eq!((w.proxy_k(), w.preview.k), (1, 3)); + let k = w.preview.k as i32; + let segs = ant_outline(&mut w.preview, (1.0, [0.0, 0.0, 3300.0, 60.0]), false).unwrap(); + let mut doc: Vec<_> = segs.iter().map(|(a, b)| ([a[0] * k, a[1] * k], [b[0] * k, b[1] * k])).collect(); + doc.sort(); + assert_eq!(doc, vec![([30, 15], [30, 45]), ([30, 15], [60, 15]), ([30, 45], [60, 45]), ([60, 15], [60, 45])]); +} + +/// An inverted selection (selected by default) is outlined along the canvas border too, as +/// Photoshop does, on a canvas past the old ants' 4 MP limit. +#[test] +fn an_inverted_selection_outlines_the_canvas_border() { + let area = Rect::new(0, 0, 3000, 2000); + let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]); + inverted.fill_rect(Rect::new(1000, 800, 1400, 1200), &[0.0]); + let mut pv = shown_preview(inverted, area, 1); + assert_eq!(pv.trace_bounds, area); + let segs = ant_outline(&mut pv, (0.25, [0.0, 0.0, 3000.0, 2000.0]), false).unwrap(); + assert_eq!(segs.len(), 8, "{segs:?}"); + for border in [([0, 0], [3000, 0]), ([0, 2000], [3000, 2000]), ([0, 0], [0, 2000]), ([3000, 0], [3000, 2000])] { + assert!(segs.contains(&border), "{border:?} in {segs:?}"); + } +} + +/// A document edit while the workspace is open drops the old preview's ants with its image. +#[test] +fn a_document_edit_clears_the_old_ants() { + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); + upload(&mut app, &egui::Context::default()); + assert!(ant_outline(&mut ws_mut(&mut app).preview, (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_some_and(|s| !s.is_empty())); + app.session + .edit("paint", |doc, _| { + doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + follow_revision(&mut app); + let pv = &mut ws_mut(&mut app).preview; + assert!(pv.selection.is_none() && pv.outline.is_none()); + assert!(ant_outline(pv, (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_none()); +} + +/// With nothing selected the Marching Ants view draws no ants, and drawing it doesn't panic. +#[test] +fn marching_ants_without_a_selection_draw_nothing() { + assert!(ant_outline(&mut Preview::default(), (1.0, [0.0, 0.0, 100.0, 100.0]), true).is_none()); + let mut app = app_with_selection(); + open(&mut app).unwrap(); + ui(&mut app, json!({"clearSelection": true, "view": "marchingAnts", "waitPreview": true})); + assert_eq!(ws(&app).describe()["selectedProxyPixels"].as_u64(), Some(0)); + let mut h = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + show(app, &ctx); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let w = h.state().distort.select_mask.as_ref().unwrap(); + assert!(w.preview.outline.as_ref().is_some_and(|(_, segs)| segs.is_empty()), "traced, and nothing to outline"); +} + +type GpuHarness = egui_kittest::Harness<'static, PhotocraftApp>; + +/// A rendered frame: RGBA8, device pixels. +struct Frame { + w: u32, + h: u32, + px: Vec, +} + +impl Frame { + fn luma(&self, x: i64, y: i64) -> Option { + if x < 0 || y < 0 || x >= i64::from(self.w) || y >= i64::from(self.h) { + return None; + } + let i = (y as usize * self.w as usize + x as usize) * 4; + let p = self.px.get(i..i + 3)?; + Some(((u16::from(p[0]) * 3 + u16::from(p[1]) * 6 + u16::from(p[2])) / 10) as u8) + } +} + +/// The workspace open on a white 400 × 300 document with (100, 80)–(300, 220) selected, in the +/// Marching Ants view at 100 %, on an offscreen wgpu harness; `None` without a GPU adapter. +fn ants_harness(ppp: f32, step_dt: f32) -> Option { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); + app.run("select.rect", json!({"x": 100, "y": 80, "width": 200, "height": 140})).unwrap(); + app.sync_views(); + open(&mut app).unwrap(); + ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); + // `wgpu()` creates the render state and panics when no adapter is found. + let builder = std::panic::catch_unwind(|| { + egui_kittest::Harness::::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(ppp).with_step_dt(step_dt).wgpu() + }) + .ok()?; + let mut h = builder.build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + show(app, &ctx); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let w = h.state_mut().distort.select_mask.as_mut().unwrap(); + (w.zoom, w.center) = (1.0, [200.0, 150.0]); + h.run_steps(2); + Some(h) +} + +fn frame(h: &mut GpuHarness) -> Frame { + let img = h.render().unwrap(); + Frame { w: img.width(), h: img.height(), px: img.into_raw() } +} + +/// Device pixel of document point `p`. +fn device(h: &GpuHarness, ppp: f32, p: [f64; 2]) -> (i64, i64) { + let w = h.state().distort.select_mask.as_ref().unwrap(); + let (area, _) = w.view_area.unwrap(); + let s = View { area, zoom: w.zoom, center: w.center }.to_screen(p) * ppp; + (s.x.round() as i64, s.y.round() as i64) +} + +/// Along the edge from device pixel `a` to `b` (12 px in from each end): the offsets across it +/// (±6) of the dark pixels at each step, and how many pixels of the band are grey. +fn scan(img: &Frame, a: (i64, i64), b: (i64, i64)) -> (Vec>, usize) { + let vertical = a.0 == b.0; + let (lo, hi) = if vertical { (a.1.min(b.1), a.1.max(b.1)) } else { (a.0.min(b.0), a.0.max(b.0)) }; + let mut across = Vec::new(); + let mut greys = 0; + for t in lo + 12..hi - 12 { + let mut dark = Vec::new(); + for o in -6..=6 { + let (x, y) = if vertical { (a.0 + o, t) } else { (t, a.1 + o) }; + let l = img.luma(x, y).unwrap_or(255); + if l < 64 { + dark.push(o); + } + if (24..232).contains(&l) { + greys += 1; + } + } + across.push(dark); + } + (across, greys) +} + +/// #10506: the Marching Ants view draws the canvas's ants: every edge `w` device px thick, crisp +/// black and white, dashes of 4·w px. They were 1-point antialiased lines, grey and uneven. +#[test] +fn select_and_mask_ants_match_the_canvas() { + let _gpu = photocraft_testkit::gpu_lock(); + for ppp in [1.0f32, 1.25] { + let Some(mut h) = ants_harness(ppp, 1.0 / 60.0) else { return }; + let img = frame(&mut h); + let w = ppp.ceil() as usize; + let [tl, tr, br, bl] = [[100.0, 80.0], [300.0, 80.0], [300.0, 220.0], [100.0, 220.0]].map(|p| device(&h, ppp, p)); + for (name, (a, b)) in [("top", (tl, tr)), ("right", (tr, br)), ("bottom", (bl, br)), ("left", (tl, bl))] { + let (across, greys) = scan(&img, a, b); + assert_eq!(greys, 0, "@{ppp}x {name}: crisp black and white"); + let max = across.iter().map(Vec::len).max().unwrap_or(0); + assert_eq!(max, w, "@{ppp}x {name}: {w} px thick"); + let dark: usize = across.iter().map(Vec::len).sum(); + let frac = dark as f32 / (across.len() * w) as f32; + assert!((0.45..=0.55).contains(&frac), "@{ppp}x {name}: {frac:.2} of the line is black"); + let rows: std::collections::BTreeSet = across.iter().flatten().copied().collect(); + for row in rows { + let mut runs = vec![0usize]; + for d in &across { + match (d.contains(&row), runs.last_mut()) { + (true, Some(n)) => *n += 1, + (false, Some(0)) => {} + _ => runs.push(0), + } + } + let inner = runs.get(1..runs.len().saturating_sub(1)).unwrap_or(&[]); + assert!(inner.iter().all(|&n| n == 4 * w), "@{ppp}x {name} row {row}: dashes {runs:?}, want {} px", 4 * w); + } + } + } +} + +/// #10506: the ants march along the edge. They used to swap black and white 8 times a second. +#[test] +fn select_and_mask_ants_march_rather_than_blink() { + let _gpu = photocraft_testkit::gpu_lock(); + let Some(mut h) = ants_harness(1.0, 0.125) else { return }; + let row = |h: &mut GpuHarness| { + let img = frame(h); + let ((x0, y), (x1, _)) = (device(h, 1.0, [100.0, 80.0]), device(h, 1.0, [300.0, 80.0])); + // The darkest row of the band along the top edge (grey counts as dark here, so an + // antialiased line is still read). + let line = |dy: i64| (x0 + 12..x1 - 12).map(|x| img.luma(x, y + dy).is_some_and(|l| l < 160)).collect::>(); + let best = (-2..=2).max_by_key(|dy| line(*dy).iter().filter(|b| **b).count()).unwrap(); + (line(best), h.ctx.input(|i| i.time)) + }; + let (a, ta) = row(&mut h); + h.step(); + let (b, tb) = row(&mut h); + assert!((tb - ta - 0.125).abs() < 1e-6, "frames {ta} and {tb}"); + let phase = |t: f64| ((t * 10.0) % 8.0) as usize; + let shift = (phase(tb) + 8 - phase(ta)) % 8; + assert!(shift > 0, "the pattern moves"); + let dark = a.iter().filter(|d| **d).count(); + assert!((a.len() * 2..=a.len() * 8).contains(&(dark * 10)), "the edge has dashes: {dark} of {} px dark", a.len()); + let n = b.len() - shift; + let shifted = (0..n).filter(|&i| b[i] != a[i + shift]).count(); + let inverted = (0..n).filter(|&i| b[i] != a[i]).count(); + assert!(shifted * 10 < n, "the dashes shift by {shift} px: {shifted} of {n} pixels don't"); + assert!(inverted * 10 < n * 9, "black and white don't swap: {inverted} of {n} pixels changed"); +} From 236331d2ac83b88893083907974fdadacec03a79 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 16:56:00 +0100 Subject: [PATCH 2/7] Content-Aware Fill: outline the fill area with the canvas's ants (#10506) The fill area had the same early marching ants as Select and Mask: one 1-point line per pixel edge, black or white per 4 document px, the whole outline flipping 8 times a second. Merge the fill area's edges into runs straight from the plan's hole (over its bounds, at full resolution) and draw them with canvas::marching_ants_mapped. Past 200k runs the bounding box is drawn instead, as before. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/caf_ui.rs | 8 +-- crates/ui-egui/src/dialogs/caf_ui/preview.rs | 57 ++++++++++---------- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 38 +++++++++++++ crates/ui-egui/src/dialogs/caf_ui/view.rs | 14 ++--- 4 files changed, 76 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/dialogs/caf_ui.rs b/crates/ui-egui/src/dialogs/caf_ui.rs index 1b5e9a97eb..f81ab2e864 100644 --- a/crates/ui-egui/src/dialogs/caf_ui.rs +++ b/crates/ui-egui/src/dialogs/caf_ui.rs @@ -56,8 +56,8 @@ const BAR_H: f32 = 36.0; const PANEL_W: f32 = 300.0; const PREVIEW_W: f32 = 380.0; const UNDO_LIMIT: usize = 100; -/// Outlines with more edges than this are drawn at the proxy's resolution. -const MAX_OUTLINE_EDGES: usize = 200_000; +/// Outlines with more runs than this are drawn as the fill area's bounding box. +const MAX_OUTLINE_SEGMENTS: usize = 200_000; /// Photoshop's overlay colour as it shows (a 50 % tint of grey 200 reads 171, 204, 153). const OVERLAY_COLOR: [u8; 3] = [142, 208, 106]; /// The `prefs.dialogs` key under which the settings are remembered. @@ -237,8 +237,8 @@ pub struct CafWorkspace { /// The lasso polygon being drawn and its selection mode. lasso: Option<(usize, Vec<[f64; 2]>)>, base: Base, - /// Fill-area outline edges (document px), or `None` when there are too many. - outline: Option>, + /// The fill area's outline (document px), or `None` when there are too many runs. + outline: Option>, /// Document px per proxy px, and the proxy size. k: usize, pw: usize, diff --git a/crates/ui-egui/src/dialogs/caf_ui/preview.rs b/crates/ui-egui/src/dialogs/caf_ui/preview.rs index cf17506e3d..fd20949064 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/preview.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/preview.rs @@ -1,4 +1,5 @@ -use super::{CMD, CafWorkspace, Color32, LayerId, MAX_CAF_POINTS, MAX_OUTLINE_EDGES, PhotocraftApp, Rect, TextureHandle, Value, json, stroke_json}; +use super::{CMD, CafWorkspace, Color32, LayerId, MAX_CAF_POINTS, MAX_OUTLINE_SEGMENTS, PhotocraftApp, Rect, TextureHandle, Value, json, stroke_json}; +use crate::outline::Segment; /// What the plan (without the brush strokes) says: the window, the fill area and the sampling /// option's area, over `rect`. @@ -99,36 +100,36 @@ pub(super) fn compute_base(app: &PhotocraftApp, w: &CafWorkspace) -> Result Option> { - let (w, h) = (b.rect.width() as usize, b.rect.height() as usize); - let (ox, oy) = (b.rect.x0 as f32, b.rect.y0 as f32); - let at = |x: i64, y: i64| x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h && b.hole.get(y as usize * w + x as usize).copied().unwrap_or(false); - let mut out = Vec::new(); - for y in 0..h as i64 { - for x in 0..w as i64 { - if !at(x, y) { - continue; - } - let (fx, fy) = (ox + x as f32, oy + y as f32); - if !at(x - 1, y) { - out.push([[fx, fy], [fx, fy + 1.0]]); - } - if !at(x + 1, y) { - out.push([[fx + 1.0, fy], [fx + 1.0, fy + 1.0]]); - } - if !at(x, y - 1) { - out.push([[fx, fy], [fx + 1.0, fy]]); - } - if !at(x, y + 1) { - out.push([[fx, fy + 1.0], [fx + 1.0, fy + 1.0]]); - } - if out.len() > MAX_OUTLINE_EDGES { - return None; +/// The fill area's edges merged into runs, as the canvas traces a selection, in document px; +/// `None` past [`MAX_OUTLINE_SEGMENTS`]. +pub(super) fn outline(b: &Base) -> Option> { + let area = super::lifecycle::bounds(b); + let w = b.rect.width() as usize; + let at = |x: i32, y: i32| b.rect.contains(x, y) && b.hole.get((y - b.rect.y0) as usize * w + (x - b.rect.x0) as usize).copied().unwrap_or(false); + let mut segs = Vec::new(); + // Between rows y - 1 and y along x, then between columns x - 1 and x along y. + for horizontal in [true, false] { + let (l0, l1, t0, t1) = if horizontal { (area.y0, area.y1, area.x0, area.x1) } else { (area.x0, area.x1, area.y0, area.y1) }; + for l in l0..=l1 { + let mut run = None; + for t in t0..=t1 { + let (p, q) = if horizontal { ((t, l), (t, l.saturating_sub(1))) } else { ((l, t), (l.saturating_sub(1), t)) }; + let edge = t < t1 && at(p.0, p.1) != at(q.0, q.1); + match (edge, run) { + (true, None) => run = Some(t), + (false, Some(s)) => { + segs.push(if horizontal { ([s, l], [t, l]) } else { ([l, s], [l, t]) }); + if segs.len() > MAX_OUTLINE_SEGMENTS { + return None; + } + run = None; + } + _ => {} + } } } } - Some(out) + Some(segs) } /// Recompute the base after a change of the fill area, the sampling option or the document. diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 84071e3856..4c1632b9ba 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -472,3 +472,41 @@ fn strokes_past_the_engines_limits_are_refused_at_the_brush() { assert_eq!(d["fillEdits"], json!(0)); assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}"); } + +/// A plan over `rect` whose fill area is the union of `parts`. +fn base_with_hole(rect: Rect, parts: &[Rect]) -> Base { + let (w, h) = (rect.width() as usize, rect.height() as usize); + let mut hole = vec![false; w * h]; + for (i, cell) in hole.iter_mut().enumerate() { + let (x, y) = (rect.x0 + (i % w) as i32, rect.y0 + (i / w) as i32); + *cell = parts.iter().any(|p| p.contains(x, y)); + } + Base { window: rect, rect, hole, base: vec![false; w * h] } +} + +/// #10506: the fill area is outlined by merged runs, as the canvas outlines a selection, so it +/// is drawn with the canvas's ants (it was one 1-point line per pixel edge, blinking). +#[test] +fn fill_area_outline_is_merged_runs() { + let rect = Rect::new(10, 20, 210, 180); + let mut square = outline(&base_with_hole(rect, &[Rect::new(50, 60, 90, 100)])).unwrap(); + square.sort(); + assert_eq!(square, vec![([50, 60], [50, 100]), ([50, 60], [90, 60]), ([50, 100], [90, 100]), ([90, 60], [90, 100])]); + let mut l = outline(&base_with_hole(rect, &[Rect::new(20, 30, 40, 90), Rect::new(20, 70, 100, 90)])).unwrap(); + l.sort(); + assert_eq!(l, vec![([20, 30], [20, 90]), ([20, 30], [40, 30]), ([20, 90], [100, 90]), ([40, 30], [40, 70]), ([40, 70], [100, 70]), ([100, 70], [100, 90])]); + // At the plan's edge too, and nothing for no fill area. + assert_eq!(outline(&base_with_hole(rect, &[rect])).map(|s| s.len()), Some(4)); + assert_eq!(outline(&base_with_hole(rect, &[])), Some(Vec::new())); +} + +/// A speckled fill area past the cap falls back to its bounding box. +#[test] +fn a_speckled_fill_area_falls_back_to_its_bounds() { + let rect = Rect::new(0, 0, 1000, 1000); + let mut b = base_with_hole(rect, &[]); + for (i, cell) in b.hole.iter_mut().enumerate() { + *cell = (i % 1000).is_multiple_of(2) && (i / 1000).is_multiple_of(2); + } + assert!(outline(&b).is_none()); +} diff --git a/crates/ui-egui/src/dialogs/caf_ui/view.rs b/crates/ui-egui/src/dialogs/caf_ui/view.rs index a2124c9ef5..0c8ef922dd 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/view.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/view.rs @@ -380,22 +380,18 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let pr = ERect::from_min_size(img.min, vec2((w.pw * w.k) as f32 * v.zoom, (w.ph * w.k) as f32 * v.zoom)); clip.with_clip_rect(img.intersect(area)).image(tex.id(), pr, uv, Color32::WHITE); } - // The fill area's outline (marching ants: black dashes on white). - let phase = (ui.input(|i| i.time) * 8.0) as usize; + // The fill area's outline: marching ants, as the canvas draws them. match &w.outline { - Some(edges) => { - for e in edges { - let (a, b) = (v.to_screen([f64::from(e[0][0]), f64::from(e[0][1])]), v.to_screen([f64::from(e[1][0]), f64::from(e[1][1])])); - let dark = ((e[0][0] + e[0][1]) as usize / 4 + phase).is_multiple_of(2); - clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE })); - } + Some(segs) => { + let time = ui.input(|i| i.time); + crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen([f64::from(p[0]), f64::from(p[1])])); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); } None => { let b = v.rect(bounds(&w.base)); clip.rect_stroke(b, 0.0, Stroke::new(1.0, Color32::WHITE), egui::StrokeKind::Outside); } } - ctx.request_repaint_after(std::time::Duration::from_millis(120)); if let Some((_, pts)) = &w.lasso && pts.len() > 1 { From b42cd8bb2fed87aa08cf5200a3d15e75585c2683 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:16:44 +0100 Subject: [PATCH 3/7] Select and Mask: keep the ants on the canvas, group their state (#10506) The reduced copy covers whole blocks of k px, so on a canvas whose size isn't a multiple of k its border ants were drawn up to k-1 px past the right and bottom edges (an inverted selection, Select All). Clamp the mapped points to the canvas. The refined selection, its trace bounds, k and outline now travel as one Option, kept only for previews made in the Marching Ants view (switching views runs a new preview anyway). paint_canvas takes its context from the Ui instead of an extra argument. The web build traces in parallel when no jobs run, as the canvas does. The march test reads the phase and period from ants::Style. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/ants.rs | 6 + crates/ui-egui/src/canvas/outline.rs | 2 +- crates/ui-egui/src/dialogs/select_mask_ui.rs | 106 +++++++++--------- .../src/dialogs/select_mask_ui/tests.rs | 97 ++++++++++------ 4 files changed, 126 insertions(+), 85 deletions(-) diff --git a/crates/ui-egui/src/canvas/ants.rs b/crates/ui-egui/src/canvas/ants.rs index 2af2e7bd08..9a4a633023 100644 --- a/crates/ui-egui/src/canvas/ants.rs +++ b/crates/ui-egui/src/canvas/ants.rs @@ -48,6 +48,12 @@ impl Style { Self { ppp, width, dash, phase } } + /// How far the pattern has marched and its period, in device pixels. + #[cfg(test)] + pub(crate) fn march(&self) -> (i64, i64) { + (self.phase, 2 * self.dash) + } + /// The black runs of `[lo, hi)` along one pixel row (or column) of a band. A pixel is black /// where `(s + phase) mod 2·dash < dash`, `s` being its position along the edge plus `off`, /// `width` times its position across it: `x + w·y` on a horizontal edge, `y + w·x` on a diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index d35a973f77..74440e4ad8 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -236,7 +236,7 @@ mod tests { } #[test] - fn view_step_and_region_follow_the_canvas_and_survive_hostile_views() { + fn view_step_and_region_quantise_and_survive_hostile_views() { assert_eq!(view_step(1.0, 1), 1); assert_eq!(view_step(0.25, 1), 4); assert_eq!(view_step(0.5, 2), 1, "a copy reduced by 2 seen at 50 % is at its own size"); diff --git a/crates/ui-egui/src/dialogs/select_mask_ui.rs b/crates/ui-egui/src/dialogs/select_mask_ui.rs index 4ce7e2478e..9745566c8c 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui.rs @@ -360,17 +360,23 @@ struct OutlineKey { k: u32, } +/// What the Marching Ants view outlines: the refined selection of one preview. +struct Ants { + /// The refined selection on the reduced copy. + selection: Surface, + /// Where its outline can be (reduced-copy px): its content within the copy. + bounds: Rect, + /// Document px per reduced-copy px of the preview. + k: u32, + /// The outline for a view (reduced-copy px), traced again when the view moves past its key. + outline: Option<(OutlineKey, Vec)>, +} + /// A computed preview, ready to upload. struct Shown { image: egui::ColorImage, - /// The refined selection on the reduced copy, for the Marching Ants view. - selection: Option, - /// Where its outline can be (reduced-copy px): its content within the copy. - trace_bounds: Rect, - /// Document px per reduced-copy px of this preview. - k: u32, - /// The outline traced for the view the preview was asked for (reduced-copy px). - outline: Option<(OutlineKey, Vec)>, + /// In the Marching Ants view, with the outline traced for the view the preview was asked for. + ants: Option, /// Reduced-copy pixels at least half selected. selected: usize, /// How many points of the stroke being drawn it includes ([`usize::MAX`]: every stroke is in). @@ -392,12 +398,8 @@ struct Preview { shown: u64, pending: Option, tex: Option, - /// [`Shown::selection`], [`Shown::trace_bounds`] and [`Shown::k`] of the preview shown. - selection: Option, - trace_bounds: Rect, - k: u32, - /// The outline of `selection` for the view, traced again when the view moves past its key. - outline: Option<(OutlineKey, Vec)>, + /// [`Shown::ants`] of the preview shown. + ants: Option, covers: [f32; 2], selected: usize, /// [`Shown::trail`] of the preview shown. @@ -1154,14 +1156,21 @@ fn trace(selection: &Surface, key: OutlineKey, parallel: bool) -> Vec { } } -/// The outline of the preview shown for a view, traced again only when the view's key changes. -fn ant_outline(pv: &mut Preview, view: (f32, [f64; 4]), parallel: bool) -> Option<&[Segment]> { - let selection = pv.selection.as_ref()?; - let key = outline_key(pv.k, pv.trace_bounds, view); - if pv.outline.as_ref().is_none_or(|(k, _)| *k != key) { - pv.outline = Some((key, trace(selection, key, parallel))); +/// The outline for a view, traced again only when the view's key changes. +fn ant_outline(ants: &mut Ants, view: (f32, [f64; 4]), parallel: bool) -> &[Segment] { + let key = outline_key(ants.k, ants.bounds, view); + if ants.outline.as_ref().is_none_or(|(k, _)| *k != key) { + ants.outline = Some((key, trace(&ants.selection, key, parallel))); } - pv.outline.as_ref().map(|(_, segs)| segs.as_slice()) + ants.outline.as_ref().map_or(&[], |(_, segs)| segs.as_slice()) +} + +/// Document point of outline point `p` (reduced by `k`), within `canvas`: the reduced copy's +/// last row and column may reach past it. +fn ant_point(p: [i32; 2], k: u32, canvas: Rect) -> [f64; 2] { + let k = f64::from(k.max(1)); + let at = |v: i32, lo: i32, hi: i32| (f64::from(v) * k).clamp(f64::from(lo), f64::from(hi.max(lo))); + [at(p[0], canvas.x0, canvas.x1), at(p[1], canvas.y0, canvas.y1)] } /// The preview of `job`: the edits applied (from where the cache left off), the edge refined and @@ -1212,15 +1221,21 @@ fn compute(job: Job, cancel: Option<&photocraft_engine::jobs::JobCtx>) -> Result let buf = photocraft_compose::render_reduced(&shown, u32::try_from(tw).unwrap_or(1), u32::try_from(th).unwrap_or(1)); let image = crate::canvas::display_image(job.display.as_deref(), &buf); let selected = selected_pixels(shown.selection.as_ref(), shown.bounds()); - let bounds = trace_bounds(shown.selection.as_ref(), shown.bounds()); - // Traced here, off the UI thread, for the view as it was: the UI traces again only after a - // pan or zoom. - let outline = shown.selection.as_ref().zip(job.ants).map(|(sel, view)| { - let key = outline_key(k, bounds, view); - (key, trace(sel, key, true)) + // Only the Marching Ants view keeps the refined selection; switching to it runs a new preview. + let mode = params.get("__view").and_then(|v| v.get("mode")).and_then(Value::as_str); + let area = shown.bounds(); + let ants = shown.selection.filter(|_| mode == Some(Mode::MarchingAnts.id())).map(|selection| { + let bounds = trace_bounds(Some(&selection), area); + // Traced here, off the UI thread, for the view as it was: the UI traces again only after + // a pan or zoom. On the web this runs on the UI thread, where Rayon has no workers. + let outline = job.ants.map(|view| { + let key = outline_key(k, bounds, view); + (key, trace(&selection, key, true)) + }); + Ants { selection, bounds, k, outline } }); let covers = [(pw as f32) * k as f32, (ph as f32) * k as f32]; - Ok((Shown { image, selection: shown.selection, trace_bounds: bounds, k, outline, selected, trail: job.trail, covers }, cache, proxy)) + Ok((Shown { image, ants, selected, trail: job.trail, covers }, cache, proxy)) } /// Takes the preview of state `generation` (made from document `revision`): the image when it is @@ -1464,10 +1479,7 @@ fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) { Some(t) => t.set(s.image, egui::TextureOptions::LINEAR), None => w.preview.tex = Some(ctx.load_texture("select-mask-preview", s.image, egui::TextureOptions::LINEAR)), } - w.preview.selection = s.selection; - w.preview.trace_bounds = s.trace_bounds; - w.preview.k = s.k; - w.preview.outline = s.outline; + w.preview.ants = s.ants; w.preview.covers = s.covers; } } @@ -1634,24 +1646,14 @@ fn follow_revision(app: &mut PhotocraftApp) { w.preview.tex = None; w.preview.pending = None; w.preview.cache = None; - w.preview.selection = None; - w.preview.outline = None; + w.preview.ants = None; w.stale(); } } /// Draws the document, the refined edge, the stroke being drawn and the polygon in progress. -#[allow(clippy::too_many_arguments)] -fn paint_canvas( - ui: &mut egui::Ui, - ctx: &egui::Context, - w: &mut SelectMaskWorkspace, - t: &Tokens, - painter: &egui::Painter, - resp: &egui::Response, - area: ERect, - parallel: bool, -) { +fn paint_canvas(ui: &mut egui::Ui, w: &mut SelectMaskWorkspace, t: &Tokens, painter: &egui::Painter, resp: &egui::Response, area: ERect, parallel: bool) { + let ctx = &ui.ctx().clone(); let v = View { area, zoom: w.zoom, center: w.center }; let ppp = ctx.pixels_per_point(); w.view_area = Some((area, ppp)); @@ -1673,10 +1675,14 @@ fn paint_canvas( } // Marching Ants: the refined selection's edge, drawn as the canvas draws its ants. if !w.hide_view && w.opts.view == Mode::MarchingAnts { - let k = f64::from(w.preview.k.max(1)); - if let Some(segs) = ant_outline(&mut w.preview, ant_view(v, ppp), parallel).filter(|s| !s.is_empty()) { + let canvas = w.canvas; + if let Some(ants) = w.preview.ants.as_mut() + && let k = ants.k + && let segs = ant_outline(ants, ant_view(v, ppp), parallel) + && !segs.is_empty() + { let time = ui.input(|i| i.time); - crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen([f64::from(p[0]) * k, f64::from(p[1]) * k])); + crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen(ant_point(p, k, canvas))); ctx.request_repaint_after(std::time::Duration::from_millis(100)); } } @@ -1824,7 +1830,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] let parallel = !app.session.has_jobs() && app.distort.select_mask.as_ref().is_some_and(|w| w.preview.running.is_none()); #[cfg(target_arch = "wasm32")] - let parallel = false; + let parallel = !app.session.has_jobs(); egui::Area::new(egui::Id::unique("select-mask-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| { let Some(w) = app.distort.select_mask.as_mut() else { return }; let before = (w.opts.clone(), w.sample_all); @@ -1935,7 +1941,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } } let v = View { area, zoom: w.zoom, center: w.center }; - paint_canvas(ui, ctx, w, &t, &painter, &resp, area, parallel); + paint_canvas(ui, w, &t, &painter, &resp, area, parallel); // Space, the middle button or the Hand pan. The Polygonal Lasso takes clicks: each adds a // vertex, a double-click closes. let pan = ui.input(|i| i.key_down(egui::Key::Space) || i.pointer.middle_down()) || w.tool == SmTool::Hand; diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index e1c67e532c..c45b2f524e 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -770,10 +770,14 @@ fn the_reason_a_stale_workspace_closed_is_reported() { } } -/// A preview of `selection` over the reduced copy `area`, `k` document px per copy px. -fn shown_preview(selection: Surface, area: Rect, k: u32) -> Preview { - let trace_bounds = trace_bounds(Some(&selection), area); - Preview { selection: Some(selection), trace_bounds, k, ..Default::default() } +/// The ants of `selection` over the reduced copy `area`, `k` document px per copy px. +fn shown_ants(selection: Surface, area: Rect, k: u32) -> Ants { + let bounds = trace_bounds(Some(&selection), area); + Ants { selection, bounds, k, outline: None } +} + +fn ants_mut(app: &mut PhotocraftApp) -> &mut Ants { + ws_mut(app).preview.ants.as_mut().unwrap() } #[test] @@ -788,8 +792,8 @@ fn sparse_large_preview_keeps_its_ants() { assert_eq!(selected_pixels(Some(&selection), small), 1); // At 100 % around the far corner: the one pixel there, outlined by four lines. The old ants // were unit edges of a canvas-sized mask, dropped past 4 MP. - let mut pv = shown_preview(selection, area, 1); - let segs = ant_outline(&mut pv, (1.0, [99_500.0, 99_500.0, 100_500.0, 100_500.0]), false).unwrap(); + let mut ants = shown_ants(selection, area, 1); + let segs = ant_outline(&mut ants, (1.0, [99_500.0, 99_500.0, 100_500.0, 100_500.0]), false); assert_eq!(segs.len(), 4, "{segs:?}"); assert!(segs.iter().all(|(a, b)| [a, b].iter().all(|p| (99_999..=100_000).contains(&p[0]) && (99_999..=100_000).contains(&p[1])))); @@ -814,8 +818,8 @@ fn marching_ants_trace_merged_runs_like_the_canvas() { let area = Rect::new(0, 0, 100, 60); let sel = rect_selection(Rect::new(5, 5, 25, 15)); let whole = crate::outline::outline(&sel, sel.content_bounds()); - let mut pv = shown_preview(sel, area, 2); - let segs = ant_outline(&mut pv, (1.0, [0.0, 0.0, 200.0, 120.0]), false).unwrap().to_vec(); + let mut ants = shown_ants(sel, area, 2); + let segs = ant_outline(&mut ants, (1.0, [0.0, 0.0, 200.0, 120.0]), false).to_vec(); assert_eq!(segs, whole); assert_eq!(segs.len(), 4, "{segs:?}"); for (a, b) in segs { @@ -830,14 +834,14 @@ fn marching_ants_trace_merged_runs_like_the_canvas() { /// Frames reuse the trace while the view stays within its quantised region; a zoom traces again. #[test] fn ant_outline_is_cached_per_view() { - let mut pv = shown_preview(rect_selection(Rect::new(10, 10, 90, 50)), Rect::new(0, 0, 100, 60), 1); - let first = ant_outline(&mut pv, (1.0, [0.0, 0.0, 100.0, 60.0]), false).unwrap().as_ptr(); - let key = pv.outline.as_ref().unwrap().0; - let panned = ant_outline(&mut pv, (1.0, [3.0, 2.0, 103.0, 62.0]), false).unwrap().as_ptr(); + let mut ants = shown_ants(rect_selection(Rect::new(10, 10, 90, 50)), Rect::new(0, 0, 100, 60), 1); + let first = ant_outline(&mut ants, (1.0, [0.0, 0.0, 100.0, 60.0]), false).as_ptr(); + let key = ants.outline.as_ref().unwrap().0; + let panned = ant_outline(&mut ants, (1.0, [3.0, 2.0, 103.0, 62.0]), false).as_ptr(); assert_eq!(first, panned, "a small pan keeps the trace"); - assert_eq!(pv.outline.as_ref().unwrap().0, key); - let zoomed = ant_outline(&mut pv, (0.25, [0.0, 0.0, 400.0, 240.0]), false).unwrap().len(); - assert_eq!(pv.outline.as_ref().unwrap().0.step, 4, "zoomed out to 25 %: one sample per 4 px"); + assert_eq!(ants.outline.as_ref().unwrap().0, key); + let zoomed = ant_outline(&mut ants, (0.25, [0.0, 0.0, 400.0, 240.0]), false).len(); + assert_eq!(ants.outline.as_ref().unwrap().0.step, 4, "zoomed out to 25 %: one sample per 4 px"); assert_eq!(zoomed, 4); } @@ -850,14 +854,19 @@ fn the_preview_job_traces_the_outline_for_the_view() { let area = ERect::from_min_size(pos2(50.0, 60.0), vec2(800.0, 500.0)); let w = ws_mut(&mut app); (w.view_area, w.zoom, w.center) = (Some((area, 1.5)), 2.0, [80.0, 50.0]); + // The other views keep no refined selection. + ui(&mut app, json!({"waitPreview": true})); + upload(&mut app, &egui::Context::default()); + assert!(ws(&app).preview.ants.is_none(), "Onion Skin"); ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); upload(&mut app, &egui::Context::default()); let w = ws_mut(&mut app); let view = ant_view(View { area, zoom: w.zoom, center: w.center }, 1.5); - let traced = w.preview.outline.as_ref().map(|(key, segs)| (*key, segs.as_ptr())).expect("traced in the job"); - assert_eq!(traced.0, outline_key(w.preview.k, w.preview.trace_bounds, view)); - assert_eq!(ant_outline(&mut w.preview, view, false).unwrap().as_ptr(), traced.1, "drawn without tracing again"); - assert_eq!(w.preview.outline.as_ref().unwrap().1.len(), 4, "the 20 × 20 selection"); + let ants = w.preview.ants.as_mut().unwrap(); + let traced = ants.outline.as_ref().map(|(key, segs)| (*key, segs.as_ptr())).expect("traced in the job"); + assert_eq!(traced.0, outline_key(ants.k, ants.bounds, view)); + assert_eq!(ant_outline(ants, view, false).as_ptr(), traced.1, "drawn without tracing again"); + assert_eq!(ants.outline.as_ref().unwrap().1.len(), 4, "the 20 × 20 selection"); } /// Until the preview at the new scale arrives, the ants keep the scale of the preview they outline. @@ -869,10 +878,11 @@ fn the_outline_keeps_its_previews_scale_while_high_quality_is_toggled() { ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); upload(&mut app, &egui::Context::default()); ui(&mut app, json!({"highQualityPreview": true})); - let w = ws_mut(&mut app); - assert_eq!((w.proxy_k(), w.preview.k), (1, 3)); - let k = w.preview.k as i32; - let segs = ant_outline(&mut w.preview, (1.0, [0.0, 0.0, 3300.0, 60.0]), false).unwrap(); + assert_eq!(ws(&app).proxy_k(), 1); + let ants = ants_mut(&mut app); + assert_eq!(ants.k, 3); + let k = ants.k as i32; + let segs = ant_outline(ants, (1.0, [0.0, 0.0, 3300.0, 60.0]), false); let mut doc: Vec<_> = segs.iter().map(|(a, b)| ([a[0] * k, a[1] * k], [b[0] * k, b[1] * k])).collect(); doc.sort(); assert_eq!(doc, vec![([30, 15], [30, 45]), ([30, 15], [60, 15]), ([30, 45], [60, 45]), ([60, 15], [60, 45])]); @@ -885,15 +895,33 @@ fn an_inverted_selection_outlines_the_canvas_border() { let area = Rect::new(0, 0, 3000, 2000); let mut inverted = Surface::with_default(photocraft_color::PixelFormat::GRAY8, &[1.0]); inverted.fill_rect(Rect::new(1000, 800, 1400, 1200), &[0.0]); - let mut pv = shown_preview(inverted, area, 1); - assert_eq!(pv.trace_bounds, area); - let segs = ant_outline(&mut pv, (0.25, [0.0, 0.0, 3000.0, 2000.0]), false).unwrap(); + let mut ants = shown_ants(inverted, area, 1); + assert_eq!(ants.bounds, area); + let segs = ant_outline(&mut ants, (0.25, [0.0, 0.0, 3000.0, 2000.0]), false); assert_eq!(segs.len(), 8, "{segs:?}"); for border in [([0, 0], [3000, 0]), ([0, 2000], [3000, 2000]), ([0, 0], [0, 2000]), ([3000, 0], [3000, 2000])] { assert!(segs.contains(&border), "{border:?} in {segs:?}"); } } +/// The reduced copy covers whole blocks of `k` px, past the canvas when its size isn't a multiple +/// of `k`; the ants stay on the canvas border, not on the pasteboard beyond it. +#[test] +fn the_border_ants_stay_on_the_canvas_of_a_reduced_copy() { + let mut app = app_sized(3301, 60); + open(&mut app).unwrap(); + ui(&mut app, json!({"invert": true, "view": "marchingAnts", "waitPreview": true})); + upload(&mut app, &egui::Context::default()); + let canvas = ws(&app).canvas; + let ants = ants_mut(&mut app); + assert_eq!(ants.k, 3); + let k = ants.k; + let segs = ant_outline(ants, (0.5, [0.0, 0.0, 3301.0, 60.0]), false); + let points: Vec<[f64; 2]> = segs.iter().flat_map(|(a, b)| [*a, *b]).map(|p| ant_point(p, k, canvas)).collect(); + assert!(points.iter().all(|p| (0.0..=3301.0).contains(&p[0]) && (0.0..=60.0).contains(&p[1])), "{points:?}"); + assert!(points.iter().any(|p| p[0] == 3301.0) && points.iter().any(|p| p[1] == 60.0), "the right and bottom border: {points:?}"); +} + /// A document edit while the workspace is open drops the old preview's ants with its image. #[test] fn a_document_edit_clears_the_old_ants() { @@ -901,7 +929,7 @@ fn a_document_edit_clears_the_old_ants() { open(&mut app).unwrap(); ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); upload(&mut app, &egui::Context::default()); - assert!(ant_outline(&mut ws_mut(&mut app).preview, (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_some_and(|s| !s.is_empty())); + assert!(!ant_outline(ants_mut(&mut app), (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_empty()); app.session .edit("paint", |doc, _| { doc.layers[0].surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 0.0, 1.0]); @@ -909,15 +937,14 @@ fn a_document_edit_clears_the_old_ants() { }) .unwrap(); follow_revision(&mut app); - let pv = &mut ws_mut(&mut app).preview; - assert!(pv.selection.is_none() && pv.outline.is_none()); - assert!(ant_outline(pv, (1.0, [0.0, 0.0, 160.0, 100.0]), false).is_none()); + assert!(ws(&app).preview.ants.is_none()); } /// With nothing selected the Marching Ants view draws no ants, and drawing it doesn't panic. #[test] fn marching_ants_without_a_selection_draw_nothing() { - assert!(ant_outline(&mut Preview::default(), (1.0, [0.0, 0.0, 100.0, 100.0]), true).is_none()); + let empty = Surface::new(photocraft_color::PixelFormat::GRAY8); + assert!(ant_outline(&mut shown_ants(empty, Rect::new(0, 0, 100, 100), 1), (1.0, [0.0, 0.0, 100.0, 100.0]), true).is_empty()); let mut app = app_with_selection(); open(&mut app).unwrap(); ui(&mut app, json!({"clearSelection": true, "view": "marchingAnts", "waitPreview": true})); @@ -934,7 +961,8 @@ fn marching_ants_without_a_selection_draw_nothing() { PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); h.run_steps(4); let w = h.state().distort.select_mask.as_ref().unwrap(); - assert!(w.preview.outline.as_ref().is_some_and(|(_, segs)| segs.is_empty()), "traced, and nothing to outline"); + let outline = w.preview.ants.as_ref().and_then(|a| a.outline.as_ref()); + assert!(outline.is_some_and(|(_, segs)| segs.is_empty()), "traced, and nothing to outline"); } type GpuHarness = egui_kittest::Harness<'static, PhotocraftApp>; @@ -1078,8 +1106,9 @@ fn select_and_mask_ants_march_rather_than_blink() { h.step(); let (b, tb) = row(&mut h); assert!((tb - ta - 0.125).abs() < 1e-6, "frames {ta} and {tb}"); - let phase = |t: f64| ((t * 10.0) % 8.0) as usize; - let shift = (phase(tb) + 8 - phase(ta)) % 8; + // How far the canvas's ants march between the two frames. + let ((pa, period), (pb, _)) = (crate::ants::Style::new(1.0, ta).march(), crate::ants::Style::new(1.0, tb).march()); + let shift = (pb - pa).rem_euclid(period) as usize; assert!(shift > 0, "the pattern moves"); let dark = a.iter().filter(|d| **d).count(); assert!((a.len() * 2..=a.len() * 8).contains(&(dark * 10)), "the edge has dashes: {dark} of {} px dark", a.len()); From 2394937bc1d62d9eb2fe83cf27df0393bdbaffcc Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:16:44 +0100 Subject: [PATCH 4/7] Content-Aware Fill: no ants repaint for an empty fill area (#10506) Skip the 100 ms repaint when the fill area has no outline to draw, and check that a speckled fill area falls back to its bounding box. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/caf_ui/tests.rs | 1 + crates/ui-egui/src/dialogs/caf_ui/view.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/crates/ui-egui/src/dialogs/caf_ui/tests.rs b/crates/ui-egui/src/dialogs/caf_ui/tests.rs index 4c1632b9ba..27ca44bc3b 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/tests.rs @@ -509,4 +509,5 @@ fn a_speckled_fill_area_falls_back_to_its_bounds() { *cell = (i % 1000).is_multiple_of(2) && (i / 1000).is_multiple_of(2); } assert!(outline(&b).is_none()); + assert_eq!(lifecycle::bounds(&b), Rect::new(0, 0, 999, 999), "the box drawn instead"); } diff --git a/crates/ui-egui/src/dialogs/caf_ui/view.rs b/crates/ui-egui/src/dialogs/caf_ui/view.rs index 0c8ef922dd..113aedf4a7 100644 --- a/crates/ui-egui/src/dialogs/caf_ui/view.rs +++ b/crates/ui-egui/src/dialogs/caf_ui/view.rs @@ -382,6 +382,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { } // The fill area's outline: marching ants, as the canvas draws them. match &w.outline { + Some(segs) if segs.is_empty() => {} Some(segs) => { let time = ui.input(|i| i.time); crate::canvas::marching_ants_mapped(&clip, segs, time, |p| v.to_screen([f64::from(p[0]), f64::from(p[1])])); From 191747a6c684978bb5316b815ed1b727b0e95cf1 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:23:24 +0100 Subject: [PATCH 5/7] Select and Mask: plain test comment (#10506) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs/select_mask_ui/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index c45b2f524e..96c7771dcd 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -888,8 +888,8 @@ fn the_outline_keeps_its_previews_scale_while_high_quality_is_toggled() { assert_eq!(doc, vec![([30, 15], [30, 45]), ([30, 15], [60, 15]), ([30, 45], [60, 45]), ([60, 15], [60, 45])]); } -/// An inverted selection (selected by default) is outlined along the canvas border too, as -/// Photoshop does, on a canvas past the old ants' 4 MP limit. +/// An inverted selection (selected by default) is outlined along the canvas border too, on a +/// canvas past the old ants' 4 MP limit. #[test] fn an_inverted_selection_outlines_the_canvas_border() { let area = Rect::new(0, 0, 3000, 2000); From 402d289fe5aa7241cc03032cf72047f0ea202852 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:02:21 +0100 Subject: [PATCH 6/7] test(select-mask): dialog ants have the canvas's phase at 1x and 2x Checks every pixel of the top edge's band against ants::Style::new(ppp, time) at the frame's time, at 100 % and 200 %, with a phase that isn't a whole dash. Co-Authored-By: Claude Opus 5.5 --- .../src/dialogs/select_mask_ui/tests.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index 9a5eb1d0d4..dfd0c267ad 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -1137,3 +1137,34 @@ fn select_and_mask_ants_march_rather_than_blink() { assert!(shifted * 10 < n, "the dashes shift by {shift} px: {shifted} of {n} pixels don't"); assert!(inverted * 10 < n * 9, "black and white don't swap: {inverted} of {n} pixels changed"); } + +/// #10506: at 100 % and 200 % the dialog's ants are the canvas's ants at the frame's time: every +/// pixel of the top edge's band is black exactly where `ants::Style::new(ppp, time)` puts a dash. +/// The dialog reads the same frame clock as the canvas, so the pattern doesn't restart when it +/// opens; and it is fixed to the screen, so the two line up. +#[test] +fn select_and_mask_ants_have_the_canvas_phase() { + let _gpu = photocraft_testkit::gpu_lock(); + for ppp in [1.0f32, 2.0] { + // 0.37 s steps, so the march has a phase that isn't zero or a whole dash. + let Some(mut h) = ants_harness(ppp, 0.37) else { return }; + let img = frame(&mut h); + let time = h.ctx.input(|i| i.time); + let (phase, period) = crate::ants::Style::new(ppp, time).march(); + let (dash, w) = (period / 2, period / 8); + assert_eq!(w, ppp.ceil() as i64); + assert!(phase % dash != 0, "@{ppp}x: phase {phase} at {time} s"); + let ((x0, ay), (x1, _)) = (device(&h, ppp, [100.0, 80.0]), device(&h, ppp, [300.0, 80.0])); + let mut wrong = Vec::new(); + for y in ay - w / 2..ay - w / 2 + w { + for x in x0 + 12..x1 - 12 { + let black = (x + w * y + phase).rem_euclid(period) < dash; + let l = img.luma(x, y).unwrap_or(128); + if (l < 64) != black || (24..232).contains(&l) { + wrong.push((x, y, l)); + } + } + } + assert!(wrong.is_empty(), "@{ppp}x phase {phase}: {} pixels differ from the canvas's ants, first {:?}", wrong.len(), wrong.first()); + } +} From 3d7d92cd4a7459d2cc69ffe3ae80bf4f114ff822 Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:29:58 +0100 Subject: [PATCH 7/7] test(select-mask): open the dialog after the canvas clock has run, so a dialog-local ant clock fails the phase test (review) Co-Authored-By: Claude Opus 5.5 --- .../src/dialogs/select_mask_ui/tests.rs | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs index dfd0c267ad..8cb61b63e2 100644 --- a/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/select_mask_ui/tests.rs @@ -1005,14 +1005,13 @@ impl Frame { } /// The workspace open on a white 400 × 300 document with (100, 80)–(300, 220) selected, in the -/// Marching Ants view at 100 %, on an offscreen wgpu harness; `None` without a GPU adapter. -fn ants_harness(ppp: f32, step_dt: f32) -> Option { +/// Marching Ants view at 100 %, on an offscreen wgpu harness, and the frame time the workspace +/// opened at (after three frames); `None` without a GPU adapter. +fn ants_harness(ppp: f32, step_dt: f32) -> Option<(GpuHarness, f64)> { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap(); app.run("select.rect", json!({"x": 100, "y": 80, "width": 200, "height": 140})).unwrap(); app.sync_views(); - open(&mut app).unwrap(); - ui(&mut app, json!({"view": "marchingAnts", "waitPreview": true})); // `wgpu()` creates the render state and panics when no adapter is found. let builder = std::panic::catch_unwind(|| { egui_kittest::Harness::::builder().with_size(vec2(1000.0, 700.0)).with_pixels_per_point(ppp).with_step_dt(step_dt).wgpu() @@ -1028,11 +1027,17 @@ fn ants_harness(ppp: f32, step_dt: f32) -> Option { app, ); PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + // The canvas's clock runs a few frames before the dialog opens, so a clock of the dialog's + // own, started when it opens, would be out of phase with it. + h.run_steps(3); + let opened = h.ctx.input(|i| i.time); + open(h.state_mut()).unwrap(); + ui(h.state_mut(), json!({"view": "marchingAnts", "waitPreview": true})); h.run_steps(4); let w = h.state_mut().distort.select_mask.as_mut().unwrap(); (w.zoom, w.center) = (1.0, [200.0, 150.0]); h.run_steps(2); - Some(h) + Some((h, opened)) } fn frame(h: &mut GpuHarness) -> Frame { @@ -1078,7 +1083,7 @@ fn scan(img: &Frame, a: (i64, i64), b: (i64, i64)) -> (Vec>, usize) { fn select_and_mask_ants_match_the_canvas() { let _gpu = photocraft_testkit::gpu_lock(); for ppp in [1.0f32, 1.25] { - let Some(mut h) = ants_harness(ppp, 1.0 / 60.0) else { return }; + let Some((mut h, _)) = ants_harness(ppp, 1.0 / 60.0) else { return }; let img = frame(&mut h); let w = ppp.ceil() as usize; let [tl, tr, br, bl] = [[100.0, 80.0], [300.0, 80.0], [300.0, 220.0], [100.0, 220.0]].map(|p| device(&h, ppp, p)); @@ -1111,7 +1116,7 @@ fn select_and_mask_ants_match_the_canvas() { #[test] fn select_and_mask_ants_march_rather_than_blink() { let _gpu = photocraft_testkit::gpu_lock(); - let Some(mut h) = ants_harness(1.0, 0.125) else { return }; + let Some((mut h, _)) = ants_harness(1.0, 0.125) else { return }; let row = |h: &mut GpuHarness| { let img = frame(h); let ((x0, y), (x1, _)) = (device(h, 1.0, [100.0, 80.0]), device(h, 1.0, [300.0, 80.0])); @@ -1146,8 +1151,12 @@ fn select_and_mask_ants_march_rather_than_blink() { fn select_and_mask_ants_have_the_canvas_phase() { let _gpu = photocraft_testkit::gpu_lock(); for ppp in [1.0f32, 2.0] { - // 0.37 s steps, so the march has a phase that isn't zero or a whole dash. - let Some(mut h) = ants_harness(ppp, 0.37) else { return }; + // 0.31 s steps, so the march has a phase that isn't zero or a whole dash at the frame, nor + // zero when the dialog opens. + let Some((mut h, opened)) = ants_harness(ppp, 0.31) else { return }; + // A clock restarted when the dialog opened would be off by the canvas's phase then. + let (at_open, period) = crate::ants::Style::new(ppp, opened).march(); + assert!(at_open.rem_euclid(period) != 0, "@{ppp}x: phase {at_open} when the dialog opened at {opened} s"); let img = frame(&mut h); let time = h.ctx.input(|i| i.time); let (phase, period) = crate::ants::Style::new(ppp, time).march();