PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Content-Aware Fill workspace: review follow-ups (#2376)
Unemars66c0e4ce13b3
diff --git a/crates/ui-egui/src/caf_ui.rs b/crates/ui-egui/src/caf_ui.rsindex de2b62e40..747e9d4bc 100644--- a/crates/ui-egui/src/caf_ui.rs+++ b/crates/ui-egui/src/caf_ui.rs@@ -24,8 +24,9 @@//! what gets written. The settings are remembered for the next time (`prefs.dialogs`).use egui::{Align2, Color32, FontId, Pos2, Rect as ERect, Sense, Stroke, TextureHandle, pos2, vec2};-use photocraft_algo::content_aware::SamplingStroke;+use photocraft_algo::content_aware::{SamplingStroke, paint_strokes};use photocraft_doc::LayerId;+use photocraft_engine::edit_menu_cmds::{MAX_CAF_EDITS, MAX_CAF_POINTS};use photocraft_geom::Rect;use serde_json::{Value, json};@@ -240,6 +241,25 @@ struct Preview {error: Option<String>,}+impl Preview {+ /// Takes the result of the preview of state `generation`: an image to upload, or the error,+ /// which stands for that state until it changes (the same preview is not started again).+ fn finish(&mut self, generation: u64, r: Result<(Rect, egui::ColorImage), String>) {+ self.shown = generation;+ self.tex = None;+ match r {+ Ok(img) => {+ self.pending_image = Some(img);+ self.error = None;+ }+ Err(e) => {+ self.pending_image = None;+ self.error = Some(e);+ }+ }+ }+}+pub struct CafWorkspace {pub layer: LayerId,layer_name: String,@@ -266,8 +286,17 @@ pub struct CafWorkspace {k: usize,pw: usize,ph: usize,- /// Per proxy pixel: 0 not sampled, 1 sampled, 2 fill area.- state: Vec<u8>,+ /// Per proxy pixel: the sampling option's area (before the strokes), the fill area, and the+ /// sampling area after the strokes so far (the first painted with them in order, as the+ /// engine's `paint_strokes` paints the full-resolution one).+ base_px: Vec<bool>,+ hole_px: Vec<bool>,+ mask: Vec<bool>,+ /// The pointer is down on the view with a tool: one press is one `Down`, egui's drag (which+ /// starts a few pixels later) continues it.+ pressed: bool,+ /// The device's texture side limit, as the context reports it each frame.+ texture_limit: usize,image_tex: Option<TextureHandle>,overlay_tex: Option<TextureHandle>,overlay_dirty: bool,@@ -300,7 +329,7 @@ fn plan_params(w: &CafWorkspace, strokes: bool) -> Value {impl CafWorkspace {pub fn describe(&self) -> Value {- let sampled = self.state.iter().filter(|s| **s == 1).count();+ let sampled = self.mask.iter().zip(&self.hole_px).filter(|(m, h)| **m && !**h).count();json!({"layer": self.layer.0,"tool": self.tool.name(),@@ -323,50 +352,60 @@ impl CafWorkspace {})}- /// The sampling state of document pixel `(x, y)` from the base and the strokes so far.- fn sampled_at(&self, x: f64, y: f64) -> bool {- let b = &self.base;- let i = b.index(x, y);- if i.is_some_and(|i| b.hole.get(i).copied().unwrap_or(false)) {- return false;- }- let mut on = i.is_some_and(|i| b.base.get(i).copied().unwrap_or(false));- for s in self.strokes.iter().chain(self.cur.iter()) {- if covers(s, x, y) {- on = s.add;- }- }- on+ /// The proxy, in proxy px.+ fn proxy_area(&self) -> Rect {+ Rect::new(0, 0, self.pw as i32, self.ph as i32)}- fn in_hole(&self, x: f64, y: f64) -> bool {- let b = &self.base;- b.index(x, y).is_some_and(|i| b.hole.get(i).copied().unwrap_or(false))+ /// `s` in proxy coordinates: proxy pixel `(px, py)` is centred on document point+ /// `canvas.x0 + (px + 0.5) k`, so the stroke's points and size scale by `1 / k`.+ fn proxy_stroke(&self, s: &SamplingStroke) -> SamplingStroke {+ let k = self.k as f64;+ let (ox, oy) = (f64::from(self.canvas.x0), f64::from(self.canvas.y0));+ SamplingStroke { add: s.add, size: s.size / k, points: s.points.iter().map(|p| [(p[0] - ox) / k, (p[1] - oy) / k]).collect() }}- /// Recompute the proxy's per-pixel state inside proxy rect `r` (x0, y0, x1, y1).- fn restate(&mut self, r: [usize; 4]) {+ /// Paints `s` (a stroke, or one segment of the one being drawn) into the proxy's sampling+ /// area: only the pixels within the brush of its path are visited, whatever came before.+ fn paint(&mut self, s: &SamplingStroke) {+ let (s, area) = (self.proxy_stroke(s), self.proxy_area());+ paint_strokes(&mut self.mask, area, &[s]);+ self.overlay_dirty = true;+ }++ /// Takes a new base: its option's area and fill area at the proxy's pixel centres, then the+ /// strokes over it.+ fn set_base(&mut self, b: Base) {+ self.outline = outline(&b);let k = self.k as f64;- for py in r[1]..r[3].min(self.ph) {- for px in r[0]..r[2].min(self.pw) {+ for py in 0..self.ph {+ for px in 0..self.pw {let (x, y) = (f64::from(self.canvas.x0) + (px as f64 + 0.5) * k, f64::from(self.canvas.y0) + (py as f64 + 0.5) * k);- let v = if self.in_hole(x, y) { 2 } else { u8::from(self.sampled_at(x, y)) };- self.state[py * self.pw + px] = v;+ let i = b.index(x, y);+ let at = |v: &[bool]| i.is_some_and(|i| v.get(i).copied().unwrap_or(false));+ self.base_px[py * self.pw + px] = at(&b.base);+ self.hole_px[py * self.pw + px] = at(&b.hole);}}- self.overlay_dirty = true;+ self.base = b;+ self.restate_all();}+ /// Rebuilds the proxy's sampling area: the base painted with every stroke in order. Each+ /// stroke costs its own pixels, so this is linear in the strokes, not strokes × pixels.fn restate_all(&mut self) {- self.restate([0, 0, self.pw, self.ph]);+ self.mask.clone_from(&self.base_px);+ let strokes: Vec<SamplingStroke> = self.strokes.iter().chain(self.cur.iter()).map(|s| self.proxy_stroke(s)).collect();+ let area = self.proxy_area();+ paint_strokes(&mut self.mask, area, &strokes);+ self.overlay_dirty = true;}- /// The proxy pixels a stroke segment touches.- fn proxy_rect(&self, r: Rect) -> [usize; 4] {- let k = self.k as i32;- let c = self.canvas;- let f = |v: i32, o: i32| ((v - o).max(0) / k) as usize;- [f(r.x0, c.x0), f(r.y0, c.y0), f(r.x1, c.x0) + 2, f(r.y1, c.y0) + 2]+ /// Points in the strokes and lasso edits so far, against the engine's budget.+ fn points_used(&self) -> usize {+ let strokes: usize = self.strokes.iter().chain(self.cur.iter()).map(|s| s.points.len()).sum();+ let lassos: usize = self.fill_edits.iter().map(|e| e.get("points").and_then(Value::as_array).map_or(0, Vec::len)).sum();+ strokes + lassos}/// The preview is out of date.@@ -375,14 +414,31 @@ impl CafWorkspace {}fn begin_stroke(&mut self, p: [f64; 2], alt: bool) {+ // The engine takes at most MAX_CAF_EDITS strokes and MAX_CAF_POINTS points in all: the+ // brush stops there, so Apply and the preview never fail on what was painted.+ if self.strokes.len() >= MAX_CAF_EDITS {+ self.error = Some(format!("at most {MAX_CAF_EDITS} sampling strokes: undo some, or reset the sampling area"));+ return;+ }+ if self.points_used() >= MAX_CAF_POINTS {+ self.error = Some(points_limit());+ return;+ }+ self.error = None;let add = self.brush_add != alt;let s = SamplingStroke { add, size: self.brush_size, points: vec![p] };- let r = self.proxy_rect(s.bounds());+ self.paint(&s);self.cur = Some(s);- self.restate(r);}fn extend_stroke(&mut self, p: [f64; 2]) {+ if self.cur.is_none() {+ return;+ }+ if self.points_used() >= MAX_CAF_POINTS {+ self.error = Some(points_limit());+ return;+ }let Some(s) = self.cur.as_mut() else { return };if s.points.last().is_some_and(|l| l[0] == p[0] && l[1] == p[1]) {return;@@ -390,8 +446,7 @@ impl CafWorkspace {let last = *s.points.last().unwrap_or(&p);s.points.push(p);let seg = SamplingStroke { add: s.add, size: s.size, points: vec![last, p] };- let r = self.proxy_rect(seg.bounds());- self.restate(r);+ self.paint(&seg);}fn end_stroke(&mut self) {@@ -411,21 +466,8 @@ impl CafWorkspace {}}-/// Does stroke `s` cover document point `(x, y)` (a pixel centre)?-fn covers(s: &SamplingStroke, x: f64, y: f64) -> bool {- let r2 = (s.size / 2.0).max(0.5).powi(2);- let near = |a: [f64; 2], b: [f64; 2]| {- let (dx, dy) = (b[0] - a[0], b[1] - a[1]);- let l2 = dx * dx + dy * dy;- let t = if l2 > 0.0 { (((x - a[0]) * dx + (y - a[1]) * dy) / l2).clamp(0.0, 1.0) } else { 0.0 };- let (qx, qy) = (a[0] + t * dx - x, a[1] + t * dy - y);- qx * qx + qy * qy <= r2- };- match s.points.as_slice() {- [] => false,- [p] => near(*p, *p),- pts => pts.windows(2).any(|w| near(w[0], w[1])),- }+fn points_limit() -> String {+ format!("at most {MAX_CAF_POINTS} points in all sampling strokes and lasso edits: undo some, or reset")}/// The plan without strokes: the window, fill area and the option's area. Custom starts empty@@ -481,13 +523,14 @@ fn rebase(app: &mut PhotocraftApp) {let Some(w) = app.distort.caf.as_mut() else { return };match r {Ok(b) => {- w.outline = outline(&b);- w.base = b;+ w.set_base(b);w.error = None;}- Err(e) => w.error = Some(e),+ Err(e) => {+ w.error = Some(e);+ w.restate_all();+ }}- w.restate_all();w.stale();}@@ -529,7 +572,11 @@ pub fn open(app: &mut PhotocraftApp) -> Result<(), String> {k,pw,ph,- state: vec![0; pw * ph],+ base_px: vec![false; pw * ph],+ hole_px: vec![false; pw * ph],+ mask: vec![false; pw * ph],+ pressed: false,+ texture_limit: 2048,image_tex: None,overlay_tex: None,overlay_dirty: true,@@ -542,9 +589,7 @@ pub fn open(app: &mut PhotocraftApp) -> Result<(), String> {w.brush_add = w.opts.sampling == "custom";let base = compute_base(app, &w)?;w.brush_size = photocraft_algo::content_aware::default_brush_size(bounds(&base));- w.outline = outline(&base);- w.base = base;- w.restate_all();+ w.set_base(base);w.stale();app.distort.caf = Some(w);Ok(())@@ -691,6 +736,15 @@ fn redo(app: &mut PhotocraftApp) {fn fill_edit(app: &mut PhotocraftApp, edit: Value) {let Some(w) = app.distort.caf.as_mut() else { return };w.end_stroke();+ // The engine's limits, kept here (see `begin_stroke`).+ if w.fill_edits.len() >= MAX_CAF_EDITS {+ w.error = Some(format!("at most {MAX_CAF_EDITS} lasso edits: undo some, or reset the fill area"));+ return;+ }+ if w.points_used() + edit.get("points").and_then(Value::as_array).map_or(0, Vec::len) > MAX_CAF_POINTS {+ w.error = Some(points_limit());+ return;+ }w.fill_edits.push(edit.clone());w.push(Step::Fill(edit));rebase(app);@@ -852,30 +906,28 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {/// Computes the preview now, on this thread (tests and the control channel).fn wait_preview(app: &mut PhotocraftApp) -> Result<(), String> {- let (doc, layer, p, want) = {+ let (doc, layer, p, want, limit) = {let w = app.distort.caf.as_ref().ok_or("Content-Aware Fill is not open")?;let st = app.session.active().ok_or("no document")?;- (st.doc.clone(), w.layer, plan_params(w, true), w.preview.want)+ (st.doc.clone(), w.layer, plan_params(w, true), w.preview.want, w.texture_limit)};- let r = compute_preview(&doc, layer, &p, &photocraft_raster::Interrupt::NONE);+ let r = compute_preview(&doc, layer, &p, &photocraft_raster::Interrupt::NONE, limit);let w = app.distort.caf.as_mut().ok_or("Content-Aware Fill is not open")?;- match r {- Ok((rect, img)) => {- w.preview.error = None;- w.preview.shown = want;- w.preview.tex = None;- w.preview.pending_image = Some((rect, img));- Ok(())- }- Err(e) => {- w.preview.error = Some(e.clone());- Err(e)- }- }+ let err = r.as_ref().err().cloned();+ w.preview.finish(want, r);+ err.map_or(Ok(()), Err)}-/// The filled rectangle as an image (what Apply would write there).-fn compute_preview(doc: &photocraft_doc::Document, layer: LayerId, p: &Value, ctl: &photocraft_raster::Interrupt) -> Result<(Rect, egui::ColorImage), String> {+/// The filled rectangle as an image (what Apply would write there), as a texture no wider than+/// `max_side`: past the device's limit it is box-averaged to fit (the rectangle it is drawn over+/// stays the plan's).+fn compute_preview(+ doc: &photocraft_doc::Document,+ layer: LayerId,+ p: &Value,+ ctl: &photocraft_raster::Interrupt,+ max_side: usize,+) -> Result<(Rect, egui::ColorImage), String> {let plan = photocraft_engine::edit_menu_cmds::content_aware_plan_with(doc, layer, p, CMD, ctl).map_err(|e| match e {photocraft_engine::EngineError::Cancelled => "cancelled".to_string(),e => e.to_string(),@@ -885,22 +937,48 @@ fn compute_preview(doc: &photocraft_doc::Document, layer: LayerId, p: &Value, ctlet filled =photocraft_algo::content_aware::fill_with(w, h, n, &plan.img, &plan.hole, &plan.source, &plan.opts, ctl).map_err(|_| "cancelled".to_string())?;let own = plan.layer_pixels();- let mut px = Vec::with_capacity(w * h);- for i in 0..w * h {+ // Pixel `i`: the fill over the fill area (a partly selected pixel by its coverage), the+ // layer's own pixels elsewhere.+ let pixel = |i: usize| -> [f32; 4] {let src = if plan.hole[i] { &filled[i * n..(i + 1) * n] } else { &own[i * n..(i + 1) * n] };let mut c = photocraft_raster::to_rgba(&plan.fmt, src);if plan.hole[i] {- // A partly selected pixel shows the fill by its coverage.let k = plan.cover[i];let under = photocraft_raster::to_rgba(&plan.fmt, &own[i * n..(i + 1) * n]);for j in 0..4 {c[j] = under[j] + (c[j] - under[j]) * k;}}- let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;- px.push(Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])));+ c+ };+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ let color = |c: [f32; 4]| Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3]));+ let f = crate::filter_preview_ui::texture_factor(w as u32, h as u32, max_side) as usize;+ if f == 1 {+ let px = (0..w * h).map(|i| color(pixel(i))).collect();+ return Ok((plan.rect, egui::ColorImage::new([w, h], px)));+ }+ let (tw, th) = (w.div_ceil(f), h.div_ceil(f));+ let mut px = Vec::with_capacity(tw * th);+ for ty in 0..th {+ for tx in 0..tw {+ // The block's premultiplied average.+ let (mut acc, mut count) = ([0.0f32; 4], 0.0f32);+ for y in ty * f..((ty + 1) * f).min(h) {+ for x in tx * f..((tx + 1) * f).min(w) {+ let c = pixel(y * w + x);+ for j in 0..3 {+ acc[j] += c[j] * c[3];+ }+ acc[3] += c[3];+ count += 1.0;+ }+ }+ let c = if acc[3] > 0.0 { [acc[0] / acc[3], acc[1] / acc[3], acc[2] / acc[3], acc[3] / count] } else { [0.0; 4] };+ px.push(color(c));+ }}- Ok((plan.rect, egui::ColorImage::new([w, h], px)))+ Ok((plan.rect, egui::ColorImage::new([tw, th], px)))}/// Starts a background preview when the shown one is out of date (and the pointer is up), and@@ -917,13 +995,8 @@ fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context, dragging: bool) {pv.running = None;if generation == pv.want {match r {- Ok(img) => {- pv.pending_image = Some(img);- pv.shown = generation;- pv.error = None;- }- Err(e) if e != "cancelled" => pv.error = Some(e),- Err(_) => {}+ Err(e) if e == "cancelled" => {}+ r => pv.finish(generation, r),}}}@@ -944,13 +1017,13 @@ fn drive_preview(app: &mut PhotocraftApp, ctx: &egui::Context, dragging: bool) {return;}let Some(doc) = doc else { return };- let (layer, p, generation) = (w.layer, plan_params(w, true), w.preview.want);+ let (layer, p, generation, limit) = (w.layer, plan_params(w, true), w.preview.want, w.texture_limit);let (tx, rx) = std::sync::mpsc::sync_channel(1);let job = photocraft_engine::jobs::JobCtx::new();let work = job.clone();let repaint = ctx.clone();let spawned = std::thread::Builder::new().name("caf-preview".into()).spawn(move || {- let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.stage(0.0, 1.0, "", |ctl| compute_preview(&doc, layer, &p, ctl))))+ let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| work.stage(0.0, 1.0, "", |ctl| compute_preview(&doc, layer, &p, ctl, limit)))).unwrap_or_else(|_| Err("the preview failed".into()));let _ = tx.send(r);repaint.request_repaint();@@ -1089,11 +1162,7 @@ impl View {fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) {let need_image = app.distort.caf.as_ref().is_some_and(|w| w.image_tex.is_none());if need_image {- let img = app.distort.caf.as_ref().and_then(|w| {- let st = app.session.active()?;- let surf = st.doc.layer(w.layer)?.surface()?;- Some(crate::distort_ui::surface_image(surf, w.canvas, PROXY_SIDE))- });+ let img = view_image(app);if let (Some(w), Some(img)) = (app.distort.caf.as_mut(), img) {w.image_tex = Some(ctx.load_texture("caf-image", img, egui::TextureOptions::LINEAR));}@@ -1104,15 +1173,10 @@ fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) {let [r, g, b] = w.opts.color;let a = (w.opts.opacity / 100.0 * 255.0).round() as u8;let tint = Color32::from_rgba_unmultiplied(r, g, b, a);- let px: Vec<Color32> = w- .state- .iter()- .map(|s| match (*s, w.opts.show_overlay, w.opts.excluded) {- (_, false, _) | (2, _, _) => Color32::TRANSPARENT,- (1, true, false) | (0, true, true) => tint,- _ => Color32::TRANSPARENT,- })- .collect();+ // The tint marks the sampling area (with Indicates: Excluded Area, what is left out);+ // the fill area is never tinted.+ let px: Vec<Color32> =+ w.mask.iter().zip(&w.hole_px).map(|(m, h)| if w.opts.show_overlay && !*h && *m != w.opts.excluded { tint } else { Color32::TRANSPARENT }).collect();let img = egui::ColorImage::new([w.pw, w.ph], px);match &mut w.overlay_tex {Some(t) => t.set(img, egui::TextureOptions::NEAREST),@@ -1124,6 +1188,16 @@ fn upload(app: &mut PhotocraftApp, ctx: &egui::Context) {}}+/// The document as the view shows it: the visible layers composited, as on the canvas (so an+/// Apply to a new layer shows), reduced to the proxy.+fn view_image(app: &PhotocraftApp) -> Option<egui::ColorImage> {+ let w = app.distort.caf.as_ref()?;+ let st = app.session.active()?;+ let buf = photocraft_compose::render_reduced(&st.doc, w.pw as u32, w.ph as u32);+ let (display, _) = crate::canvas::canvas_display(app, &st.doc, None);+ Some(crate::canvas::display_image(display.as_deref(), &buf))+}+/// Draws the workspace (a full-window layer over the app).pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {// An Apply (or anything else) changed the document: refresh.@@ -1145,6 +1219,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {egui::Area::new(egui::Id::new("caf-workspace")).order(egui::Order::Foreground).fixed_pos(screen.min).show(ctx, |ui| {let Some(w) = app.distort.caf.as_mut() else { return };let before = w.opts.clone();+ w.texture_limit = ctx.input(|i| i.max_texture_side);let (full, _) = ui.allocate_exact_size(screen.size(), Sense::hover());let painter = ui.painter().clone();painter.rect_filled(full, 0.0, t.chrome);@@ -1304,22 +1379,18 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {ui.label(egui::RichText::new(e.as_str()).color(t.danger).size(11.0));}});- // Footer: reset all, OK, Apply, Cancel.+ // Footer, in Photoshop's order on every platform: reset all at the left, then OK, Apply,+ // Cancel against the right edge.let foot = ERect::from_min_size(pos2(right.left() + 10.0, right.bottom() - 48.0), vec2(PANEL_W - 20.0, 32.0));let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center)));- if let Some(role) = widgets::dialog_buttons(- &mut fb,- &[- widgets::DialogButton::new(widgets::ButtonRole::Cancel, tl!("Cancel"), 70.0),- widgets::DialogButton::new(widgets::ButtonRole::Apply, tl!("Apply"), 70.0),- widgets::DialogButton::new(widgets::ButtonRole::Default, tl!("OK"), 64.0),- ],- ) {- action = Some(match role {- widgets::ButtonRole::Default => "ok",- widgets::ButtonRole::Cancel => "cancel",- _ => "apply",- });+ if widgets::secondary_button(&mut fb, tl!("Cancel"), 70.0).clicked() {+ action = Some("cancel");+ }+ if widgets::secondary_button(&mut fb, tl!("Apply"), 70.0).clicked() {+ action = Some("apply");+ }+ if widgets::primary_button(&mut fb, tl!("OK"), 64.0).clicked() {+ action = Some("ok");}if crate::icons::button(&mut fb, "undo-2", 24.0, false, tl!("Reset")).clicked() {reset_what = Some("all");@@ -1345,8 +1416,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {let img_rect = pv.rect(w.canvas);widgets::checker(&pclip, img_rect.intersect(pv_area), 8.0);if let Some(tex) = &w.image_tex {- let pr = ERect::from_min_size(img_rect.min, vec2((w.pw * w.k) as f32 * pv.zoom, (w.ph * w.k) as f32 * pv.zoom));- pclip.image(tex.id(), pr, uv, Color32::WHITE);+ pclip.image(tex.id(), img_rect, uv, Color32::WHITE);}if let Some((tex, r)) = &w.preview.tex {pclip.image(tex.id(), pv.rect(*r), uv, Color32::WHITE);@@ -1401,21 +1471,22 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {let clip = painter.with_clip_rect(area);let img = v.rect(w.canvas);widgets::checker(&clip, img.intersect(area), 8.0);- 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));if let Some(tex) = &w.image_tex {- clip.image(tex.id(), pr, uv, Color32::WHITE);+ clip.image(tex.id(), img, uv, Color32::WHITE);}if let Some(tex) = &w.overlay_tex {- clip.image(tex.id(), pr, uv, Color32::WHITE);+ // The proxy's blocks are `k` document px; its last row and column may reach past the+ // canvas, so the overlay is clipped to it.+ 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;match &w.outline {Some(edges) => {- for (i, e) in edges.iter().enumerate() {+ 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);- let _ = i;clip.line_segment([a, b], Stroke::new(1.0, if dark { Color32::BLACK } else { Color32::WHITE }));}}@@ -1445,19 +1516,25 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {if pan && resp.dragged() {let dl = resp.drag_delta();w.center = [w.center[0] - f64::from(dl.x / w.zoom), w.center[1] - f64::from(dl.y / w.zoom)];- } else if let Some(pp) = resp.interact_pointer_pos() {+ } else if !pan+ && resp.is_pointer_button_down_on()+ && let Some(pp) = resp.interact_pointer_pos()+ {+ // The press is the first point; the frames before egui's drag threshold and the drag+ // itself continue it (a second `Down` would start the stroke over, dropping them).let q = v.to_doc(pp);mods = ui.input(|i| i.modifiers);- let active = w.cur.is_some() || w.lasso.is_some();- if resp.drag_started() || (resp.is_pointer_button_down_on() && !active) {- events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 });- } else if resp.dragged() || resp.is_pointer_button_down_on() {+ if w.pressed {events.push(ToolEvent::Move { x: q[0], y: q[1], pressure: 1.0 });ctx.request_repaint();+ } else {+ w.pressed = true;+ events.push(ToolEvent::Down { x: q[0], y: q[1], pressure: 1.0 });}dragging = true;}- if (resp.drag_stopped() || resp.clicked()) && !pan {+ if w.pressed && !resp.is_pointer_button_down_on() {+ w.pressed = false;let q = w.hover.unwrap_or(w.center);events.push(ToolEvent::Up { x: q[0], y: q[1] });dragging = false;@@ -1675,4 +1752,221 @@ mod tests {assert_eq!(r["filled"], json!(400));assert!(app.distort.caf.is_none());}++ /// The engine's sampling area over the plan's rectangle (what the fill samples) and its fill+ /// area.+ fn engine_source(app: &PhotocraftApp) -> (Rect, Vec<bool>, Vec<bool>) {+ let w = ws(app);+ let st = app.session.active().unwrap();+ let plan = photocraft_engine::edit_menu_cmds::content_aware_plan(&st.doc, w.layer, &plan_params(w, true), CMD).unwrap();+ (plan.rect, plan.source, plan.hole)+ }++ /// Each stroke is painted into the proxy once, over its own pixels: 400 strokes of 50 points+ /// and the undo and redo that rebuild the proxy stay cheap (they used to test every proxy+ /// pixel against every segment), and the overlay is exactly what the engine samples (at one+ /// proxy px per document px).+ #[test]+ fn strokes_are_painted_once_and_the_overlay_is_the_engines_sampling_area() {+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ control(&mut app, &json!({"sampling": "rectangular"})).unwrap();+ let start = std::time::Instant::now();+ for i in 0..400u32 {+ // Lines across the document, most subtracting, every fifth adding (Alt).+ let y = 2.0 + f64::from(i % 40) * 4.0;+ let pts: Vec<[f64; 2]> = (0..50).map(|j| [f64::from(j) * 4.0 + f64::from(i % 3), y + f64::from(j % 2)]).collect();+ control(&mut app, &json!({"stroke": {"points": pts, "size": 6 + (i % 4) * 3, "alt": i % 5 == 0}})).unwrap();+ }+ let painted = start.elapsed();+ let start = std::time::Instant::now();+ control(&mut app, &json!({"undo": true})).unwrap();+ control(&mut app, &json!({"redo": true})).unwrap();+ let rebuilt = start.elapsed();+ assert!(painted.as_secs_f64() < 10.0 && rebuilt.as_secs_f64() < 10.0, "400 strokes {painted:?}, undo + redo {rebuilt:?}");+ let w = ws(&app);+ assert_eq!((w.k, w.strokes.len()), (1, 400));+ let (rect, source, hole) = engine_source(&app);+ assert_eq!(rect, w.canvas, "Rectangular's window is the whole 200 × 160 canvas");+ let differ = (0..source.len()).filter(|&i| (w.mask[i] && !w.hole_px[i]) != (source[i] && !hole[i])).count();+ assert_eq!(differ, 0, "proxy pixels that differ from the engine's sampling area");+ assert!(w.describe()["sampledProxyPixels"].as_u64().unwrap() > 1000);+ }++ /// `edit.contentAwareFill {"ui": …}` addresses the workspace: with it closed that is an+ /// error, not a fill with the default settings (an agent polling the state after an Esc+ /// used to add a fill per poll).+ #[test]+ fn ui_params_with_the_workspace_closed_are_an_error_not_a_fill() {+ let ctx = egui::Context::default();+ let mut app = app_with_selection();+ let steps = app.session.active().unwrap().history.past_len();+ for ui in [json!({}), json!({"cancel": true}), json!({"sampling": "rectangular"})] {+ let r = crate::menus::invoke(&mut app, &ctx, "edit.contentAwareFill", json!({"ui": ui}));+ assert!(r.as_ref().is_err_and(|e| e.contains("not open")), "{r:?}");+ }+ assert_eq!(app.session.active().unwrap().history.past_len(), steps, "nothing was filled");+ assert!(app.distort.caf.is_none());+ }++ /// The press is the first point of a stroke (and of a lasso), and the pointer's moves before+ /// egui's drag threshold are its next ones: the drag, which starts a few pixels later, goes+ /// on with the same stroke rather than beginning another over it.+ #[test]+ fn a_stroke_keeps_its_points_from_before_the_drag_threshold() {+ use egui::{Modifiers, PointerButton};+ for tool in ["brush", "lasso"] {+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ control(&mut app, &json!({"tool": tool, "sampling": "rectangular"})).unwrap();+ let mut h = egui_kittest::Harness::builder().with_size(vec2(1600.0, 1000.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()))) {+ return;+ }+ show(app, &ctx);+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.run_steps(4);+ // The document view sits between the tool strip and the Preview panel, under the+ // title and the options bar; its centre shows the document's centre.+ let view = ERect::from_min_max(pos2(LEFT_W, 30.0 + BAR_H), pos2(1600.0 - PANEL_W - PREVIEW_W, 1000.0));+ let c = view.center();+ let at = |dx: f32, dy: f32| pos2(c.x + dx, c.y + dy);+ let press = |h: &mut egui_kittest::Harness<'_, PhotocraftApp>, down: bool, p: Pos2| {+ h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });+ h.run_steps(1);+ };+ h.event(egui::Event::PointerMoved(at(0.0, 0.0)));+ h.run_steps(1);+ press(&mut h, true, at(0.0, 0.0));+ // Within egui's click distance (6 px): no drag yet, but these are the stroke's points.+ // Then past it: the drag starts. (Not collinear: the lasso's polygon needs an area.)+ for (dx, dy) in [(2.0, 1.0), (4.0, 2.0), (30.0, 20.0), (60.0, -10.0), (90.0, 40.0)] {+ h.event(egui::Event::PointerMoved(at(dx, dy)));+ h.run_steps(1);+ }+ press(&mut h, false, at(90.0, 40.0));+ h.run_steps(2);+ let w = h.state().distort.caf.as_ref().unwrap();+ let points: Vec<[f64; 2]> = match tool {+ "brush" => {+ assert_eq!(w.strokes.len(), 1, "one stroke");+ w.strokes[0].points.clone()+ }+ _ => {+ assert_eq!(w.fill_edits.len(), 1, "one lasso edit");+ serde_json::from_value(w.fill_edits[0]["points"].clone()).unwrap()+ }+ };+ let centre = [f64::from(w.canvas.x0 + w.canvas.x1) / 2.0, f64::from(w.canvas.y0 + w.canvas.y1) / 2.0];+ assert_eq!(points.len(), 6, "{tool}: the press and every move are points: {points:?}");+ let d = ((points[0][0] - centre[0]).powi(2) + (points[0][1] - centre[1]).powi(2)).sqrt();+ assert!(d < 1.0, "{tool}: the first point is the press ({:?} vs {centre:?})", points[0]);+ assert!(w.cur.is_none() && w.lasso.is_none() && !w.pressed, "{tool}: the release ended it");+ }+ }++ /// The preview texture fits the device: a plan rectangle wider than the texture limit is+ /// box-averaged to fit, and is still drawn over the plan's rectangle.+ #[test]+ fn the_preview_texture_respects_the_device_limit() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());+ app.session.execute("file.new", json!({"width": 2200, "height": 40, "depth": 8})).unwrap();+ app.session.execute("layer.new.layer", json!({})).unwrap();+ app.session+ .edit("paint", |doc, active| {+ let s = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap();+ s.fill_rect(Rect::new(0, 0, 2200, 40), &[0.2, 0.6, 0.4, 1.0]);+ s.fill_rect(Rect::new(1090, 10, 1110, 30), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ app.session.execute("select.rect", json!({"x": 1090, "y": 10, "width": 20, "height": 20})).unwrap();+ app.sync_views();+ open(&mut app).unwrap();+ // Custom sampling with a stroke across the whole width: the plan's rectangle is 2200 px wide.+ control(&mut app, &json!({"sampling": "custom", "stroke": {"points": [[0.0, 5.0], [2200.0, 5.0]], "size": 8}})).unwrap();+ for (limit, want) in [(2048usize, 1100usize), (4096, 2200)] {+ let w = app.distort.caf.as_mut().unwrap();+ w.texture_limit = limit;+ w.stale();+ control(&mut app, &json!({"waitPreview": true})).unwrap();+ let (rect, img) = ws(&app).preview.pending_image.clone().unwrap();+ assert_eq!((rect.width(), img.size[0]), (2200, want), "limit {limit}");+ assert!(img.size.iter().all(|s| *s <= limit), "limit {limit}: {:?}", img.size);+ let (sum, n) = img.pixels.iter().fold((0u32, 0u32), |(s, n), p| (s + u32::from(p.g()), n + 1));+ assert!(sum / n > 100, "limit {limit}: the reduced preview keeps the image ({})", sum / n);+ }+ }++ /// A preview that fails stands for that state: nothing is shown, the error is reported, and+ /// the same preview is not started again on every frame.+ #[test]+ fn a_failing_preview_is_reported_once_not_restarted() {+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ control(&mut app, &json!({"waitPreview": true})).unwrap();+ assert!(ws(&app).preview.pending_image.is_some());+ // The selection goes away under the workspace: there is nothing to fill.+ app.session.execute("select.deselect", json!({})).unwrap();+ app.distort.caf.as_mut().unwrap().stale();+ assert!(control(&mut app, &json!({"waitPreview": true})).is_err());+ let pv = &ws(&app).preview;+ assert_eq!(pv.shown, pv.want, "the failed state counts as shown: no retry");+ assert!(pv.pending_image.is_none() && pv.tex.is_none());+ let d = ws(&app).describe();+ assert_eq!(d["previewReady"], json!(false));+ assert!(d["previewError"].as_str().is_some_and(|e| e.contains("selection")), "{d}");+ }++ /// The view shows the document, not the layer alone: after Apply to a new layer the fill+ /// (on that layer) covers the blemish.+ #[test]+ fn the_view_shows_the_document_after_an_apply_to_a_new_layer() {+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ let red = |img: &egui::ColorImage| {+ let p = img.pixels[80 * img.size[0] + 100];+ p.r() > 200 && p.g() < 60+ };+ let before = view_image(&app).unwrap();+ assert_eq!(before.size, [200, 160]);+ assert!(red(&before), "the blemish shows before the fill");+ control(&mut app, &json!({"output": "new", "colorAdaptation": "none", "apply": true})).unwrap();+ assert!(!red(&view_image(&app).unwrap()), "the fill on the new layer shows");+ }++ /// The engine's limits (MAX_CAF_EDITS strokes or lasso edits, MAX_CAF_POINTS points in all)+ /// hold at the brush: a stroke past them is refused with a message, so Apply and the+ /// preview never fail on what was painted.+ #[test]+ fn strokes_past_the_engines_limits_are_refused_at_the_brush() {+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ control(&mut app, &json!({"sampling": "rectangular"})).unwrap();+ for i in 0..MAX_CAF_EDITS {+ let x = (i % 190) as f64;+ control(&mut app, &json!({"stroke": {"points": [[x, 5.0], [x + 3.0, 5.0]], "size": 2}})).unwrap();+ }+ let d = control(&mut app, &json!({"stroke": {"points": [[10.0, 50.0], [20.0, 50.0]], "size": 2}})).unwrap();+ assert_eq!(d["strokes"], json!(MAX_CAF_EDITS));+ assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}");+ control(&mut app, &json!({"waitPreview": true})).unwrap();+ // The points budget: a long stroke stops at it.+ let mut app = app_with_selection();+ open(&mut app).unwrap();+ let pts: Vec<[f64; 2]> = (0..MAX_CAF_POINTS + 100).map(|i| [10.0 + i as f64 * 0.0005, 5.0]).collect();+ let d = control(&mut app, &json!({"stroke": {"points": pts, "size": 2}})).unwrap();+ assert_eq!(ws(&app).points_used(), MAX_CAF_POINTS);+ assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}");+ control(&mut app, &json!({"waitPreview": true})).unwrap();+ // A lasso edit past the points budget is refused too.+ let d = control(&mut app, &json!({"lasso": {"op": "add", "points": [[130.0, 70.0], [150.0, 70.0], [150.0, 90.0]]}})).unwrap();+ assert_eq!(d["fillEdits"], json!(0));+ assert!(d["error"].as_str().is_some_and(|e| e.contains("at most")), "{d}");+ }}diff --git a/crates/ui-egui/src/distort_ui.rs b/crates/ui-egui/src/distort_ui.rsindex da1f24b55..4987d8cc4 100644--- a/crates/ui-egui/src/distort_ui.rs+++ b/crates/ui-egui/src/distort_ui.rs@@ -115,6 +115,8 @@ pub fn menu(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Val"filter.liquify" if empty => Some(crate::liquify_ui::open(app, ctx).map(|_| json!({"liquify": app.distort.describe()["liquify"]}))),"filter.liquify" if ui.is_some() && app.distort.liquify.is_some() => Some(crate::liquify_ui::control(app, ui.unwrap_or(&Value::Null))),"edit.contentAwareFill" if ui.is_some() && app.distort.caf.is_some() => Some(crate::caf_ui::control(app, ui.unwrap_or(&Value::Null))),+ // `ui` addresses the workspace: closed, that is an error, not a fill with the defaults.+ "edit.contentAwareFill" if ui.is_some() => Some(Err("Content-Aware Fill is not open".into())),"edit.puppetWarp" | "layer.smartObjects.puppetWarp" if empty => {Some(crate::puppet_ui::begin(app, ctx, id).map(|_| json!({"puppet": app.distort.describe()["puppet"]})))}diff --git a/crates/ui-egui/src/filter_preview_ui.rs b/crates/ui-egui/src/filter_preview_ui.rsindex 90eaf4f6f..463155981 100644--- a/crates/ui-egui/src/filter_preview_ui.rs+++ b/crates/ui-egui/src/filter_preview_ui.rs@@ -237,7 +237,7 @@ fn upload(ctx: &egui::Context, app: &PhotocraftApp, name: &str, doc: &Document)}/// The reduction that fits a `w`×`h` image inside a `max_side` texture (1: it already fits).-fn texture_factor(w: u32, h: u32, max_side: usize) -> u32 {+pub(crate) fn texture_factor(w: u32, h: u32, max_side: usize) -> u32 {let max_side = u32::try_from(max_side).unwrap_or(u32::MAX).max(1);w.max(h).div_ceil(max_side).max(1)}