PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Transform Path: Distort, Perspective and Warp apply to paths (#3027) (#3032)
Valentin Klein62e03351164b
diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rsindex a6ce6449d..21cc0a16d 100644--- a/crates/engine/src/vector_cmds.rs+++ b/crates/engine/src/vector_cmds.rs@@ -917,11 +917,62 @@ fn clipping_path_clear(s: &mut Session, _p: &Value) -> Result<Value> {Ok(Value::Null)}+/// The path `path.transform` edits: `layer`'s shape path or vector mask, else the work path or a+/// saved path.+fn transform_target(s: &Session, name: &str, layer: Option<LayerId>) -> Result<Path> {+ let Some(id) = layer else { return resolve_path(s, Some(name)) };+ let d = s.active().ok_or(EngineError::NoDocument)?;+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ match &l.content {+ LayerContent::Shape(sh) => Ok(sh.path.clone()),+ _ => l.vector_mask.as_ref().map(|v| v.path.clone()).ok_or_else(|| EngineError::Other("target layer has no shape path or vector mask".into())),+ }+}++/// `n` numbers at `key` (`[x0, y0, x1, y1]` or `[[x, y] × 4]`, flattened): finite, magnitude at+/// most 1000000. `None` when `key` is absent.+fn coords(p: &Value, key: &str, n: usize) -> Result<Option<Vec<f64>>> {+ const CMD: &str = "path.transform";+ let Some(v) = p.get(key) else { return Ok(None) };+ let flat: Vec<&Value> = match v.as_array() {+ Some(a) if a.iter().all(Value::is_array) => a.iter().filter_map(Value::as_array).flatten().collect(),+ Some(a) => a.iter().collect(),+ None => Vec::new(),+ };+ let nums: Vec<f64> = flat.iter().filter_map(|v| v.as_f64()).filter(|x| x.is_finite() && x.abs() <= 1_000_000.0).collect();+ if flat.len() != n || nums.len() != n {+ return Err(bad(CMD, format!("`{key}` must hold {n} finite numbers with magnitude at most 1000000")));+ }+ Ok(Some(nums))+}++/// How `path.transform` moves the path.+enum PathMap {+ Affine(Affine),+ /// Distort / Perspective: the box's corners go to a quad.+ Projective(photocraft_algo::transform::Homography),+ Warp(Box<photocraft_geom::warp::Warp>),+}+fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {const CMD: &str = "path.transform";let name = p.get("name").and_then(Value::as_str).unwrap_or("work").to_owned();let layer_id = if name == "layer" { Some(layer_id(s, p)?) } else { None };- let transform = if let Some(values) = p.get("matrix") {+ // The box Distort, Perspective and Warp frame: `rect`, else the path's control bounds.+ let frame = |s: &Session| -> Result<[f64; 4]> {+ let r = match coords(p, "rect", 4)? {+ Some(r) => [r[0], r[1], r[2], r[3]],+ None => {+ let (x0, y0, x1, y1) = transform_target(s, &name, layer_id)?.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?;+ [x0, y0, x1, y1]+ }+ };+ if r[2] - r[0] <= 0.0 || r[3] - r[1] <= 0.0 {+ return Err(bad(CMD, "`rect` must have a positive width and height (a straight path needs a `rect`)"));+ }+ Ok(r)+ };+ let map = if let Some(values) = p.get("matrix") {let values = values.as_array().filter(|values| values.len() == 6).ok_or_else(|| bad(CMD, "`matrix` must contain six numbers"))?;let mut m = [0.0; 6];for (slot, value) in m.iter_mut().zip(values) {@@ -930,7 +981,26 @@ fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {.filter(|number| number.is_finite() && number.abs() <= 1_000_000.0).ok_or_else(|| bad(CMD, "matrix entries must be finite numbers with magnitude at most 1000000"))?;}- Affine { m }+ PathMap::Affine(Affine { m })+ } else if let Some(q) = coords(p, "quad", 8)? {+ // Distort and Perspective (#3027): where the frame's corners go, clockwise from top-left.+ let quad = [[q[0], q[1]], [q[2], q[3]], [q[4], q[5]], [q[6], q[7]]];+ let h = photocraft_algo::transform::Homography::rect_to_quad(frame(s)?, quad)+ .filter(|h| h.0.iter().all(|v| v.is_finite()) && h.inverse().is_some())+ .ok_or_else(|| bad(CMD, "degenerate quad"))?;+ let [a, b, c, d, e, f, g, hh, i] = h.0;+ if g.abs() < 1e-12 && hh.abs() < 1e-12 && i.abs() > 1e-12 {+ // A parallelogram is affine: a live shape stays live.+ PathMap::Affine(Affine { m: [a / i, d / i, b / i, e / i, c / i, f / i] })+ } else {+ PathMap::Projective(h)+ }+ } else if ["warp", "style", "mesh"].iter().any(|key| p.get(*key).is_some()) {+ let w = crate::warp_cmds::warp_from_params(CMD, p, frame(s)?)?;+ if [w.bend, w.h_distort, w.v_distort].iter().chain(w.bounds.iter()).any(|v| !v.is_finite() || v.abs() > 1_000_000.0) {+ return Err(bad(CMD, "warp values must be finite numbers with magnitude at most 1000000"));+ }+ PathMap::Warp(Box::new(w))} else {let number = |key: &str, default: f64| -> Result<f64> {match p.get(key) {@@ -942,50 +1012,51 @@ fn path_transform(s: &mut Session, p: &Value) -> Result<Value> {}};if !["translateX", "translateY", "scaleX", "scaleY", "angle"].iter().any(|key| p.get(*key).is_some()) {- return Err(bad(CMD, "pass `matrix` or translate/scale/angle parameters"));+ return Err(bad(CMD, "pass `matrix`, `quad`, a warp (`style`, `mesh` or `warp`) or translate/scale/angle parameters"));}let (tx, ty) = (number("translateX", 0.0)?, number("translateY", 0.0)?);let (sx, sy) = (number("scaleX", 1.0)?, number("scaleY", 1.0)?);let angle = number("angle", 0.0)?;- // An explicit `layer` parameter must determine both the transformed path and its- // pivot. resolve_path("layer") otherwise reads the currently active layer (#3062).- let path = if let Some(id) = layer_id {- let layer = s.active().and_then(|st| st.doc.layer(id)).ok_or(EngineError::NoLayer(id))?;- match &layer.content {- LayerContent::Shape(shape) => shape.path.clone(),- _ => layer- .vector_mask- .as_ref()- .map(|mask| mask.path.clone())- .ok_or_else(|| EngineError::Other("target layer has no shape path or vector mask".into()))?,- }- } else {- resolve_path(s, Some(&name))?- };+ // An explicit `layer` parameter determines both the transformed path and its pivot (#3062).+ let path = transform_target(s, &name, layer_id)?;let (x0, y0, x1, y1) = path.control_bounds().ok_or_else(|| bad(CMD, "path has no points to transform"))?;let (cx, cy) = ((x0 + x1) * 0.5, (y0 + y1) * 0.5);- Affine::translate(-cx, -cy)- .then(&Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] })- .then(&Affine::rotate(angle.to_radians()))- .then(&Affine::translate(cx + tx, cy + ty))+ PathMap::Affine(+ Affine::translate(-cx, -cy)+ .then(&Affine { m: [sx, 0.0, 0.0, sy, 0.0, 0.0] })+ .then(&Affine::rotate(angle.to_radians()))+ .then(&Affine::translate(cx + tx, cy + ty)),+ )+ };+ let out = match &map {+ PathMap::Affine(a) => json!({ "name": name, "matrix": a.m }),+ PathMap::Projective(h) => json!({ "name": name, "homography": h.0 }),+ PathMap::Warp(_) => json!({ "name": name, "warp": true }),};- let m = transform.m;if let Some(id) = layer_id&& s.active().and_then(|d| d.doc.layer(id)).is_some_and(|layer| matches!(layer.content, LayerContent::Shape(_))){with_shape(s, id, "Transform Path", |shape, _| {- transform_shape(shape, &transform);+ match &map {+ PathMap::Affine(a) => transform_shape(shape, a),+ PathMap::Projective(h) => map_shape(shape, Some(h), None)?,+ PathMap::Warp(w) => map_shape(shape, None, Some(w))?,+ }shape.psd_raw = None;Ok(())})?;- return Ok(json!({ "name": name, "matrix": m }));+ return Ok(out);}s.edit("Transform Path", |doc, _| {let path = path_mut(doc, &name, layer_id)?;- *path = path.transform(&transform);+ *path = match &map {+ PathMap::Affine(a) => path.transform(a),+ PathMap::Projective(h) => map_path(path, Some(h), None)?,+ PathMap::Warp(w) => map_path(path, None, Some(w))?,+ };Ok(())})?;- Ok(json!({ "name": name, "matrix": m }))+ Ok(out)}fn path_rename(s: &mut Session, p: &Value) -> Result<Value> {@@ -1562,7 +1633,7 @@ pub fn specs() -> Vec<CommandSpec> {"path.transform","Free Transform Path",[],- r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"matrix":[a,b,c,d,e,f] | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?} (numeric transforms pivot on path bounds center)"##,+ r##"{"name":str|"work"|"layer"="work","layer":id? (with layer target),"matrix":[a,b,c,d,e,f] | "quad":[[x,y]×4] (Distort/Perspective: where the frame's corners go, clockwise from top-left) | "style"|"mesh"|"warp":… (Warp, as edit.transform.warp) | "translateX":px?,"translateY":px?,"scaleX":factor?,"scaleY":factor?,"angle":degrees?,"rect":[x0,y0,x1,y1]? (the quad's or warp's frame; default = path control bounds)} (numeric transforms pivot on path bounds center)"##,has_doc,path_transform),diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rsindex a9ddcf3df..582033dcf 100644--- a/crates/engine/src/vector_cmds/tests.rs+++ b/crates/engine/src/vector_cmds/tests.rs@@ -467,6 +467,37 @@ fn transform_work_saved_and_shape_paths() {assert!(shape(&s, id).cache.is_some());}+/// Distort / Perspective and Warp of a path (#3027): the anchors land on the quad's corners, one+/// undo step; hostile quads and warps are refused without a step.+#[test]+fn transform_path_distort_and_warp() {+ let mut s = session(100, 100, 8);+ s.execute("path.set", json!({"path":{"subpaths":[{"closed":true,"knots":[[10,10],[30,10],[30,20],[10,20]]}]}})).unwrap();+ let steps = s.active().unwrap().history.past_len();+ for bad in [+ json!({"quad":[[0,0],[0,0],[0,0],[0,0]]}),+ json!({"quad":[[10,10],[40,5],[45,30]]}),+ json!({"quad":[[10,10],[40,5],[45,30],[5,"x"]]}),+ json!({"quad":[[10,10],[40,5],[45,30],[5,1e30]]}),+ json!({"quad":[[10,10],[40,5],[45,30],[5,25]],"rect":[10,10,10,20]}),+ json!({"style":"nope"}),+ json!({"style":"arc","rect":[0,0,1e30,1]}),+ ] {+ assert!(s.execute("path.transform", bad.clone()).is_err(), "{bad}");+ }+ assert_eq!(s.active().unwrap().history.past_len(), steps);+ let quad = [[12.0, 8.0], [40.0, 5.0], [45.0, 30.0], [5.0, 25.0]];+ s.execute("path.transform", json!({ "quad": quad })).unwrap();+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step");+ let anchors: Vec<[f64; 2]> = doc(&s).work_path.as_ref().unwrap().subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();+ assert_eq!(anchors.len(), 4);+ for (a, q) in anchors.iter().zip(quad) {+ assert!((a[0] - q[0]).abs() < 1e-9 && (a[1] - q[1]).abs() < 1e-9, "{anchors:?}");+ }+ s.execute("path.transform", json!({"style":"arc","bend":50})).unwrap();+ assert!(doc(&s).work_path.as_ref().unwrap().subpaths[0].knots.len() > 4, "the warp bends the edges");+}+#[test]fn copy_and_paste_shape_fill_and_stroke() {let mut s = session(100, 100, 8);diff --git a/crates/ui-egui/src/canvas_tool_menu.rs b/crates/ui-egui/src/canvas_tool_menu.rsindex ac1d45571..5674e909b 100644--- a/crates/ui-egui/src/canvas_tool_menu.rs+++ b/crates/ui-egui/src/canvas_tool_menu.rs@@ -383,9 +383,9 @@ pub fn entry_enabled(app: &PhotocraftApp, menu: &CanvasToolMenu, command: &str)if menu.pasteboard {return PASTEBOARD_MENU.iter().flatten().any(|(_, id)| *id == command);}- // Warp needs a layer or selection box: a lone mask, channel or path keeps the plain box.+ // Warp needs a layer, selection or path box: a lone mask or channel keeps the plain box.if menu.transform && command == "edit.transform.warp" {- return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none() && t.path.is_none());+ return app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none() && t.target.is_none());}if menu.anchor.is_some() && command == FILL_SCREEN {return app.session.active().is_some();diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex 4933b9290..7e4eef019 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -429,7 +429,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json::}/// The affine map taking `rect`'s corners to `quad`'s; `None` when the box was distorted out of a-/// parallelogram (Distort, Perspective), which an affine path transform can't follow.+/// parallelogram (Distort, Perspective): the path then goes as a `quad`.fn rect_to_quad_affine(r: [f64; 4], q: [[f64; 2]; 4]) -> Option<photocraft_geom::Affine> {let (w, h) = (r[2] - r[0], r[3] - r[1]);if w <= 0.0 || h <= 0.0 {@@ -532,12 +532,13 @@ pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) {let existing =app.session.active().and_then(|d| d.doc.layer(LayerId(app.ui.transform.as_ref()?.layer)).and_then(photocraft_engine::warp_cmds::smart_warp_doc_space));let Some(t) = app.ui.transform.as_mut() else { return };- // Warp moves layers only: a lone mask, channel or path keeps the box.- if t.warp.is_some() || t.target.is_some() || t.path.is_some() {+ // Warp moves layers and paths (#3027): a lone mask or channel keeps the box.+ if t.warp.is_some() || t.target.is_some() {return;}if t.quad == corners(t.rect)&& !t.selection+ && t.path.is_none()&& let Some(w) = existing{t.rect = w.bounds;@@ -861,15 +862,20 @@ pub fn commit(app: &mut PhotocraftApp) {return;}if let Some(target) = t.path {- if t.warp.is_some() || t.quad == corners(t.rect) {- return;- }- let Some(a) = rect_to_quad_affine(t.rect, t.quad) else {- app.ui.status = "Distort and Perspective can't be applied to a path".into();- return;- };let mut p = target;- p["matrix"] = json!(a.m);+ match &t.warp {+ Some(w) if w.is_identity() => return,+ Some(w) => p["warp"] = json!(w),+ None if t.quad == corners(t.rect) => return,+ // Distort and Perspective map the path through the box (#3027).+ None => match rect_to_quad_affine(t.rect, t.quad) {+ Some(a) => p["matrix"] = json!(a.m),+ None => {+ p["rect"] = json!(t.rect);+ p["quad"] = json!(t.quad);+ }+ },+ }if let Err(e) = app.run("path.transform", p) {app.ui.status = e;}@@ -1988,6 +1994,18 @@ fn draw_warp(painter: &egui::Painter, xf: &ViewXform, t: &TransformSession, w: &a.draw(painter, xf);}let accent = crate::theme::Tokens::get(painter.ctx()).accent;+ // Transform Path › Warp: the path drawn through the warp.+ if let Some(path) = &pv.path {+ crate::vector_ui::draw_outline(+ painter,+ path,+ &|q| {+ let (x, y) = w.map(q[0], q[1]);+ xf.to_screen(x as f32, y as f32)+ },+ accent,+ );+ }let line = Stroke::new(1.0, accent);let thin = Stroke::new(0.75, accent.gamma_multiply(0.7));let curve = |fixed_u: Option<f64>, fixed_v: Option<f64>| -> Vec<Pos2> {@@ -3559,14 +3577,15 @@ mod tests {}#[test]- fn right_click_menu_warp_row_is_off_for_a_lone_path() {+ fn right_click_menu_offers_warp_for_a_path() {+ // Photoshop's Transform Path menu has Warp too (#3027).let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24));let ctx = egui::Context::default();begin(&mut app, &ctx).unwrap();app.ui.transform.as_mut().unwrap().path = Some(json!({}));assert!(crate::canvas_tool_menu::open_transform(&mut app, &ctx, [10.0, 10.0]));let menu = app.ui.canvas_tool_menu.clone().unwrap();- assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp"));+ assert!(crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp"));}fn app_with_square(size: u32, fill: photocraft_geom::Rect) -> PhotocraftApp {@@ -4138,12 +4157,25 @@ mod tests {assert_eq!(anchors, vec![[10.0, 15.0], [50.0, 15.0], [50.0, 25.0], [10.0, 25.0]]);assert_eq!(st.doc.layers[0].surface().cloned(), pixels, "the pixels stay put");- // A box pulled out of a parallelogram (Distort) can't be applied to a path: an error, no step.+ // ⌘-drag of a corner (Distort) maps the path onto the box (#3027): one step.crate::menus::invoke(&mut app, &ctx, "edit.freeTransform", json!({})).unwrap();app.ui.transform.as_mut().unwrap().quad[2] = [70.0, 40.0];commit(&mut app);- assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);- assert!(!app.ui.status.is_empty());+ let st = app.session.active().unwrap();+ assert_eq!(st.history.past_len(), steps + 2, "one step: {}", app.ui.status);+ let anchors: Vec<[f64; 2]> = st.doc.work_path.as_ref().unwrap().subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect();+ let want = [[10.0, 15.0], [50.0, 15.0], [70.0, 40.0], [10.0, 25.0]];+ assert!(anchors.iter().zip(want).all(|(a, b)| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9), "{anchors:?}");++ // Edit › Transform Path › Warp bends it: one more step.+ crate::menus::invoke(&mut app, &ctx, "edit.transform.warp", json!({})).unwrap();+ let t = app.ui.transform.as_mut().unwrap();+ assert!(t.warp.is_some(), "Warp mode on a path");+ t.warp = Some(Warp { style: WarpStyle::Arc, bend: 50.0, ..Warp::none(t.rect) });+ commit(&mut app);+ let st = app.session.active().unwrap();+ assert_eq!(st.history.past_len(), steps + 3, "one step: {}", app.ui.status);+ assert!(st.doc.work_path.as_ref().unwrap().subpaths[0].knots.len() > 4, "the warp bends the edges");// Without a path tool, ⌘T is the pixel transform again.app.ui.tool = Tool::Move;