PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Warp: apply a large layer's warp in the background, with progress and Esc to cancel (#1015)
Ian Swopea053f9bc4eaf
diff --git a/crates/algo/src/warp.rs b/crates/algo/src/warp.rsindex 54a6c7c86..23c5d2923 100644--- a/crates/algo/src/warp.rs+++ b/crates/algo/src/warp.rs@@ -15,7 +15,7 @@use photocraft_color::PixelFormat;use photocraft_geom::{Rect, TileCoord};-use photocraft_raster::{Surface, Tile};+use photocraft_raster::{Interrupt, Surface, Tile};use std::sync::Arc;use crate::transform::{Interp, bicubic};@@ -75,6 +75,16 @@ pub fn place_source_projective(/// coordinates → destination document coordinates). Output has `src`'s format with alpha/// added; pixels outside the warped area are transparent.pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync), interp: Interp) -> Surface {+ mesh(src, src_rect, f, interp, &Interrupt::NONE)+}++/// [`warp_mesh_surface`] reporting progress per destination tile; `None` once `ctl` is cancelled.+pub fn warp_mesh_surface_with(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync), interp: Interp, ctl: &Interrupt) -> Option<Surface> {+ let out = mesh(src, src_rect, f, interp, ctl);+ (!ctl.cancelled()).then_some(out)+}++fn mesh(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync), interp: Interp, ctl: &Interrupt) -> Surface {if src_rect.is_empty() {let fmt = src.format();return Surface::new(PixelFormat::new(fmt.mode, fmt.sample, true));@@ -104,7 +114,7 @@ pub fn warp_mesh_surface(src: &Surface, src_rect: Rect, f: &(dyn Fn(f64, f64) ->tris.push([a, a + w1 + 1, a + w1]);}}- warp_triangles(src, src_rect, &verts, &tris, interp)+ triangles(src, src_rect, &verts, &tris, interp, ctl)}/// Probe lines per axis [`mapped_lengths`] follows through the map.@@ -149,6 +159,12 @@ fn mapped_lengths(src_rect: Rect, f: &(dyn Fn(f64, f64) -> (f64, f64) + Sync)) -/// interpolation of its source positions. Later triangles in `tris` draw over earlier ones (the/// order is the depth order). Output has `src`'s format with alpha added.pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2])], tris: &[[usize; 3]], interp: Interp) -> Surface {+ triangles(src, src_rect, verts, tris, interp, &Interrupt::NONE)+}++/// [`warp_triangles`], reporting progress per destination tile to `ctl`. A cancelled `ctl` skips+/// the remaining tiles; the caller discards the result.+fn triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2])], tris: &[[usize; 3]], interp: Interp, ctl: &Interrupt) -> Surface {let mut fmt = src.format();let converted;let src = if fmt.alpha {@@ -208,7 +224,16 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2}let n = fmt.channels();let a = n - 1;+ // Tiles finished so far, for progress reported per tile (from any worker thread).+ let finished = std::sync::atomic::AtomicUsize::new(0);+ let total = tiles.len().max(1);let work = |(t, tris): (&Rect, &Vec<[usize; 3]>)| -> Option<(TileCoord, Arc<Tile>)> {+ if ctl.cancelled() {+ return None;+ }+ let k = finished.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;+ // The last few percent are putting the tiles in place.+ ctl.progress(0.98 * k as f32 / total as f32);if tris.is_empty() {return None;}@@ -430,6 +455,9 @@ pub fn warp_triangles(src: &Surface, src_rect: Rect, verts: &[([f64; 2], [f64; 2};#[cfg(target_arch = "wasm32")]let done: Vec<(TileCoord, Arc<Tile>)> = tiles.iter().zip(bins.iter()).filter_map(work).collect();+ if ctl.cancelled() {+ return out;+ }out.put_tiles(done);out}@@ -503,6 +531,28 @@ mod tests {assert!(alpha(100, 55) > 0.99 && alpha(100, 20) < 0.01, "third {} {}", alpha(100, 55), alpha(100, 20));}+ #[test]+ fn the_interruptible_mesh_warp_reports_progress_and_stops_when_cancelled() {+ let mut s = Surface::new(PixelFormat::RGBA8);+ s.fill_rect(Rect::new(0, 0, 600, 400), &[0.2, 0.4, 0.6, 1.0]);+ let r = s.content_bounds();+ let w = Warp::preset(WarpStyle::Arc, 30.0, [0.0, 0.0, 600.0, 400.0]);+ let map = |x: f64, y: f64| w.map(x, y);+ let reported = std::sync::Mutex::new(0.0f32);+ let progress = |p: f32| {+ let mut m = reported.lock().unwrap();+ *m = m.max(p);+ };+ let never = || false;+ let out = warp_mesh_surface_with(&s, r, &map, Interp::Bicubic, &Interrupt::new(&never, &progress)).expect("not cancelled");+ let want = warp_mesh_surface(&s, r, &map, Interp::Bicubic);+ assert_eq!(out.content_bounds(), want.content_bounds());+ assert_eq!(out.read_region(want.content_bounds()), want.read_region(want.content_bounds()));+ assert!(*reported.lock().unwrap() > 0.9);+ let always = || true;+ assert!(warp_mesh_surface_with(&s, r, &map, Interp::Bicubic, &Interrupt::cancel_only(&always)).is_none());+ }+#[test]fn a_mesh_warp_far_off_canvas_writes_only_the_two_regions() {// #995: the old and warped regions were cleared as one dense `src ∪ warped` buffer, aboutdiff --git a/crates/engine/src/jobs_tests.rs b/crates/engine/src/jobs_tests.rsindex 2bcdda76f..77b476480 100644--- a/crates/engine/src/jobs_tests.rs+++ b/crates/engine/src/jobs_tests.rs@@ -94,6 +94,36 @@ fn free_transform_runs_as_a_job_with_the_inline_result() {assert_eq!(pixels(&s), pixels(&inline), "same pixels as the synchronous command");}+#[test]+fn warp_runs_as_a_job_with_the_inline_result() {+ let arc = json!({"style": "arc", "bend": 30});+ let mut inline = session(300, 200);+ inline.execute("edit.transform.warp", arc.clone()).unwrap();++ let mut s = session(300, 200);+ let steps = s.active().unwrap().history.past_len();+ let id = job(s.start("edit.transform.warp", arc).unwrap());+ let e = wait_event(&mut s, id);+ assert!(matches!(e.outcome, JobOutcome::Done(_)), "{e:?}");+ assert_eq!(e.label, "Warp");+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one undo step");+ assert_eq!(pixels(&s), pixels(&inline), "same pixels as the synchronous command");+}++#[test]+fn a_cancelled_warp_leaves_the_document_unchanged() {+ let mut s = session(1600, 1200);+ let doc_before = s.active().unwrap().doc.clone();+ let steps = s.active().unwrap().history.past_len();+ let id = job(s.start("edit.transform.warp", json!({"style": "flag", "bend": 40})).unwrap());+ assert!(s.cancel_job(id));+ assert_eq!(wait_event(&mut s, id).outcome, JobOutcome::Cancelled);+ s.join_cancelled_jobs();+ let st = s.active().unwrap();+ assert!(Arc::ptr_eq(&st.doc, &doc_before), "the document snapshot was not replaced");+ assert_eq!(st.history.past_len(), steps);+}+#[test]fn cancel_leaves_the_document_byte_identical() {let mut s = session(1600, 1200);diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rsindex 8e2ab3c4f..90b3361e4 100644--- a/crates/engine/src/warp_cmds.rs+++ b/crates/engine/src/warp_cmds.rs@@ -9,10 +9,10 @@//! what the Free Transform warp UI uses) or the active smart object's stored warp (a history step).use photocraft_algo::transform::{Homography, Interp};-use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface};+use photocraft_algo::warp::{warp_mesh_gray, warp_mesh_surface_with};use photocraft_doc::{Document, Layer, LayerContent, LayerId, Locks, Rect};use photocraft_geom::warp::{BezierMesh, Warp, WarpStyle};-use photocraft_raster::Surface;+use photocraft_raster::{Interrupt, Surface};use serde_json::{Value, json};use crate::commands::CommandSpec;@@ -112,7 +112,24 @@ pub fn warp_from_params(cmd: &str, p: &Value, rect: [f64; 4]) -> Result<Warp> {/// A Background is turned into a normal layer by the caller first/// ([`crate::extra_cmds::background_to_layer`]).-fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp, rect: Rect, interp: Interp, frames: Option<&Frames>) -> Result<()> {+/// `Err(Cancelled)` once `ctl` is cancelled: between the steps of a warp that don't check it.+fn cancelled(ctl: &Interrupt) -> Result<()> {+ if ctl.cancelled() { Err(EngineError::Cancelled) } else { Ok(()) }+}++/// `ctl` reports progress and cancels (`Err(Cancelled)`, the layer left half-done for the caller+/// to discard).+#[allow(clippy::too_many_arguments)]+fn warp_layer(+ doc_sel: Option<&Surface>,+ group: Locks,+ l: &mut Layer,+ w: &Warp,+ rect: Rect,+ interp: Interp,+ frames: Option<&Frames>,+ ctl: &Interrupt,+) -> Result<()> {let locks = l.locks.union(group);if locks.position || locks.all {return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));@@ -127,7 +144,7 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,match &mut l.content {LayerContent::Group(g) => {for c in g.children.iter_mut() {- warp_layer(None, locks, c, w, rect, interp, frames)?;+ warp_layer(None, locks, c, w, rect, interp, frames, ctl)?;}}LayerContent::Text(_) => return Err(EngineError::Other("Warp needs rasterized type (or use Type › Warp Text)".into())),@@ -154,7 +171,7 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,sm.warp = src_warp.filter(|w| !w.is_identity());// Fallback appearance for sources that can't be re-rendered.if let Some(c) = &mut sm.cache {- *c = warp_mesh_surface(c, rect, &map, interp);+ *c = warp_mesh_surface_with(c, rect, &map, interp, ctl).ok_or(EngineError::Cancelled)?;}if let Some(m) = &mut sm.filter_mask {m.surface = warp_mesh_gray(&m.surface, &map, interp);@@ -165,7 +182,8 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,*surf = match doc_sel {Some(sel) => {let (lifted, mut rest) = crate::transform_cmds::split_selected(surf, sel)?;- let moved = warp_mesh_surface(&lifted, rect, &map, interp);+ let moved = warp_mesh_surface_with(&lifted, rect, &map, interp, ctl).ok_or(EngineError::Cancelled)?;+ cancelled(ctl)?;crate::transform_cmds::composite_over(&mut rest, &moved);rest.prune();rest@@ -173,12 +191,20 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,None => {// Content outside the warp box stays where it is.let fmt = surf.format();- let warped = warp_mesh_surface(surf, rect, &map, interp);- let mut rest = surf.convert(photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true));+ let warped = warp_mesh_surface_with(surf, rect, &map, interp, ctl).ok_or(EngineError::Cancelled)?;+ cancelled(ctl)?;+ // Tiles are shared, so a surface that has alpha already costs nothing to copy.+ let mut rest = if fmt.alpha { surf.clone() } else { surf.convert(photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true)) };crate::pixels::try_clear_surface(&mut rest, rect, None)?;- crate::transform_cmds::composite_over(&mut rest, &warped);- rest.prune();- rest+ if rest.content_bounds().is_empty() {+ // The box held all of the layer: the warp is the whole result.+ warped+ } else {+ cancelled(ctl)?;+ crate::transform_cmds::composite_over(&mut rest, &warped);+ rest.prune();+ rest+ }}};}@@ -189,7 +215,12 @@ fn warp_layer(doc_sel: Option<&Surface>, group: Locks, l: &mut Layer, w: &Warp,{let whole = |m: &Surface| Ok(warp_mesh_gray(m, &map, interp));m.surface = match mask_sel {- Some(sel) => crate::transform_cmds::move_gray_selected(&m.surface, sel, &|lifted, src| Ok(warp_mesh_surface(lifted, src, &map, interp)), &whole)?,+ Some(sel) => crate::transform_cmds::move_gray_selected(+ &m.surface,+ sel,+ &|lifted, src| warp_mesh_surface_with(lifted, src, &map, interp, &Interrupt::NONE).ok_or(EngineError::Cancelled),+ &whole,+ )?,None => whole(&m.surface)?,};}@@ -350,30 +381,39 @@ fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {}let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic"));let content_knots = p.get("mesh").is_some() && p.get("warp").is_none();- s.edit("Warp", |doc, _| {- let sel = doc.selection.clone();- let frames = content_knots.then(|| {- let mut f = Frames::new();- if let Some(l) = doc.layer(id) {- source_frames(doc, l, &mut f);- }- f- });- let is_group = doc.layer(id).is_some_and(Layer::is_group);- let group = crate::transform_cmds::group_locks(doc, id);- crate::extra_cmds::background_to_layer(doc, id);- let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;- warp_layer(if is_group { None } else { sel.as_ref() }, group, l, &w, rect, interp, frames.as_ref())?;- let snapshot = doc.clone();- if let Some(l) = doc.layer_mut(id) {- crate::transform_cmds::refresh_text(&snapshot, l);- }- if let Some(sel) = &doc.selection {- doc.selection = Some(warp_mesh_gray(sel, &|x, y| w.map(x, y), Interp::Bilinear)).filter(|s| !s.content_bounds().is_empty());+ // A background job when started with `Session::start` (as Free Transform, #4218): the warp of+ // a large layer runs on a worker with progress, and can be cancelled.+ crate::jobs::edit_job(+ s,+ "Warp",+ move |doc, _, ctx| ctx.stage(0.0, 1.0, "Warping", |ctl| warp_doc(doc, id, &w, rect, interp, content_knots, ctl)),+ move |()| json!({"layer": id.0, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]}),+ )+}++/// The edit of [`apply`]: the layer and the selection outline.+fn warp_doc(doc: &mut Document, id: LayerId, w: &Warp, rect: Rect, interp: Interp, content_knots: bool, ctl: &Interrupt) -> Result<()> {+ let sel = doc.selection.clone();+ let frames = content_knots.then(|| {+ let mut f = Frames::new();+ if let Some(l) = doc.layer(id) {+ source_frames(doc, l, &mut f);}- Ok(())- })?;- Ok(json!({"layer": id.0, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]}))+ f+ });+ let is_group = doc.layer(id).is_some_and(Layer::is_group);+ let group = crate::transform_cmds::group_locks(doc, id);+ crate::extra_cmds::background_to_layer(doc, id);+ let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ warp_layer(if is_group { None } else { sel.as_ref() }, group, l, w, rect, interp, frames.as_ref(), ctl)?;+ let snapshot = doc.clone();+ if let Some(l) = doc.layer_mut(id) {+ crate::transform_cmds::refresh_text(&snapshot, l);+ }+ if let Some(sel) = &doc.selection {+ doc.selection = Some(warp_mesh_gray(sel, &|x, y| w.map(x, y), Interp::Bilinear)).filter(|s| !s.content_bounds().is_empty());+ }+ Ok(())}#[derive(Clone, Copy)]@@ -630,6 +670,36 @@ pub fn specs() -> Vec<CommandSpec> {mod tests {use super::*;+ #[test]+ fn a_warp_box_holding_the_whole_layer_gives_what_compositing_over_the_cleared_layer_did() {+ for depth in [8, 16, 32] {+ let s = session(depth);+ let st = s.active().unwrap();+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap().clone();+ let surf = l.surface().unwrap().clone();+ let rect = surf.content_bounds();+ let w = Warp::preset(WarpStyle::Flag, 35.0, rect_f(rect));+ // What the warp built before the shortcut: the warp composited over the cleared layer.+ let map = |x: f64, y: f64| w.map(x, y);+ let warped = warp_mesh_surface_with(&surf, rect, &map, Interp::Bicubic, &Interrupt::NONE).unwrap();+ let mut want = surf.clone();+ crate::pixels::try_clear_surface(&mut want, rect, None).unwrap();+ crate::transform_cmds::composite_over(&mut want, &warped);+ want.prune();+ let mut got = l.clone();+ warp_layer(None, Locks::default(), &mut got, &w, rect, Interp::Bicubic, None, &Interrupt::NONE).unwrap();+ let got = got.surface().unwrap();+ let b = want.content_bounds();+ assert_eq!(got.content_bounds(), b, "depth {depth}");+ let (g, wv) = (got.read_region(b), want.read_region(b));+ // Exact at 8 and 16 bits. At 32 the composite's `t·a / a` rounds a few values by an+ // ulp; the shortcut keeps the warp's own.+ let tol = if depth == 32 { 1e-6 } else { 0.0 };+ let worst = g.iter().zip(&wv).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);+ assert!(worst <= tol, "depth {depth}: off by {worst}");+ }+ }+fn session(depth: u64) -> Session {let mut s = Session::new();s.execute("file.new", json!({"width": 80, "height": 60, "depth": depth})).unwrap();diff --git a/crates/ui-egui/src/jobs_ui_tests.rs b/crates/ui-egui/src/jobs_ui_tests.rsindex 70ce973be..e33db9877 100644--- a/crates/ui-egui/src/jobs_ui_tests.rs+++ b/crates/ui-egui/src/jobs_ui_tests.rs@@ -784,6 +784,60 @@ fn esc_cancels_a_background_free_transform_commit() {assert_eq!(st.doc.layers.len(), before.layers.len());}+/// Warp the active layer into an arc, then ↩.+fn warp_and_commit(h: &mut Harness<'static, PhotocraftApp>) {+ let ctx = h.ctx.clone();+ let app = h.state_mut();+ crate::transform_tool::begin(app, &ctx).unwrap();+ let t = app.ui.transform.as_mut().unwrap();+ t.warp = Some(photocraft_geom::warp::Warp::preset(photocraft_geom::warp::WarpStyle::Arc, 40.0, t.rect));+ crate::transform_tool::commit(app);+}++#[test]+fn a_warp_commit_runs_in_the_background_and_keeps_its_preview() {+ let mut h = app_harness();+ let steps = h.state().session.active().unwrap().history.past_len();+ warp_and_commit(&mut h);+ let app = h.state();+ let job = crate::transform_tool::committing(app).expect("the commit runs as a job");+ assert!(app.session.job(job).is_some_and(|j| j.label == "Warp"));+ assert!(app.ui.transform.is_some() && app.transform_preview.is_some());+ assert_eq!(h.state_mut().run("edit.undo", json!({})).err().as_deref(), Some("Warp is still being applied"));+ let t = Instant::now();+ while h.state().session.has_jobs() && t.elapsed() < Duration::from_secs(10) {+ h.step();+ }+ h.run_steps(2);+ let app = h.state();+ assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "the session ends with the job");+ let st = app.session.active().unwrap();+ assert_eq!(st.history.past_len(), steps + 1);+ assert_eq!(st.history.undo_label(), Some("Warp"));+ // The arc bulges the layer past its old edges.+ let b = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds();+ assert_ne!(b, photocraft_geom::Rect::new(0, 0, 320, 240), "the layer was warped");+}++#[test]+fn esc_cancels_a_background_warp_commit() {+ let mut h = app_harness();+ let steps = h.state().session.active().unwrap().history.past_len();+ let before = h.state().session.active().unwrap().doc.clone();+ warp_and_commit(&mut h);+ let job = crate::transform_tool::committing(h.state()).expect("the commit runs as a job");+ crate::transform_tool::cancel(h.state_mut());+ h.run_steps(3);+ let app = h.state();+ assert!(app.session.job(job).is_none());+ assert!(app.ui.transform.is_none() && app.transform_preview.is_none());+ let st = app.session.active().unwrap();+ assert_eq!(st.history.past_len(), steps);+ let id = st.active_layer.unwrap();+ let px = |d: &photocraft_doc::Document| d.layer(id).unwrap().surface().unwrap().read_region(photocraft_geom::Rect::new(0, 0, 320, 240));+ assert_eq!(px(&st.doc), px(&before), "the layer is untouched");+}+/// #4559: a background open (the desktop app's) also warns, when its document arrives, about/// type in a font that isn't installed.#[test]diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex 45ef0b152..b69d13138 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -1011,8 +1011,9 @@ fn contains(l: &photocraft_doc::Layer, id: LayerId) -> bool {l.id == id || matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| contains(c, id)))}-/// Undo and Redo while the commit runs in the background.+/// Undo and Redo while the commit runs in the background (Free Transform, or Warp).const STILL_APPLYING: &str = "Free Transform is still being applied";+const STILL_WARPING: &str = "Warp is still being applied";pub fn commit(app: &mut PhotocraftApp) {if committing(app).is_some() {@@ -1309,7 +1310,7 @@ fn box_command(id: &str) -> bool {pub fn intercept(app: &mut PhotocraftApp, id: &str) -> Option<Result<serde_json::Value, String>> {let warping = app.ui.transform.as_ref()?.warp.is_some();if committing(app).is_some() {- return box_command(id).then(|| Err(STILL_APPLYING.into()));+ return box_command(id).then(|| Err(if warping { STILL_WARPING } else { STILL_APPLYING }.into()));}match id {"edit.undo" => Some(Ok(step(app, false))),