From f3b21c363c2fd7235f47f0ed8f81b01aa43d9be1 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:42:48 +0200 Subject: [PATCH 1/5] Free Transform several selected layers together (#3592) Ctrl+T with several layers selected opens one box around all of their content; OK applies the same transform to each as one history step. --- crates/engine/src/transform_cmds.rs | 240 ++++++++++++++++++--- crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/transform_tool.rs | 102 ++++++++- crates/ui-egui/src/transform_undo_tests.rs | 84 ++++++++ crates/ui-egui/src/type_transform.rs | 1 + 5 files changed, 398 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index 698fa4acfe..b09cfa9b04 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -404,36 +404,40 @@ fn with_panel_target(s: &Session, p: &Value) -> Value { p } -fn transform(s: &mut Session, p: &Value) -> Result { - let p = &with_panel_target(s, p); - let st = s.active().ok_or(EngineError::NoDocument)?; - let id = match p.get("layer").and_then(Value::as_u64) { - Some(v) => Some(LayerId(v)), - None => st.active_layer, - }; - let lone = lone_target(&st.doc, id, p)?; - let id = match (id, lone.is_some() && crate::channel_cmds::is_channel_target(p)) { - (_, true) => None, - (Some(id), false) => Some(id), - (None, false) => return Err(EngineError::Other("no active layer".into())), - }; - let rect = match p.get("rect").and_then(Value::as_array) { - Some(r) if r.len() == 4 => { - let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - [v[0], v[1], v[2], v[3]] +/// Does `l` hold the layer `id` somewhere inside it (not counting `l` itself)? +fn holds(l: &Layer, id: LayerId) -> bool { + matches!(&l.content, LayerContent::Group(g) if g.children.iter().any(|c| c.id == id || holds(c, id))) +} + +/// The layers a Free Transform of several selected layers moves together (#3592), bottom to top as +/// `ids` lists them: ids no longer in the document, layers inside a selected group (the group moves +/// them already), adjustment layers without a mask and layers with nothing to frame are left out. +/// Hidden layers stay in, as in Photoshop. Fewer than two left means a single-layer transform. +pub fn multi_targets(doc: &Document, ids: &[LayerId]) -> Vec { + let mut out: Vec = Vec::new(); + for &id in ids { + let Some(l) = doc.layer(id) else { continue }; + if out.contains(&id) || ids.iter().any(|&o| o != id && doc.layer(o).is_some_and(|g| holds(g, id))) { + continue; } - _ => { - let b = match (lone, id) { - (Some(surf), _) => target_bounds(&st.doc, surf), - (None, Some(id)) => transform_bounds(&st.doc, st.doc.layer(id).ok_or(EngineError::NoLayer(id))?), - (None, None) => Rect::EMPTY, - }; - if b.is_empty() { - return Err(EngineError::Other("nothing to transform".into())); - } - [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64] + if matches!(l.content, LayerContent::Adjustment(_)) && l.mask.is_none() { + continue; } - }; + if transform_bounds(doc, l).is_empty() { + continue; + } + out.push(id); + } + out +} + +/// The shared frame of [`multi_targets`]: the union of each layer's [`transform_bounds`]. +pub fn multi_bounds(doc: &Document, ids: &[LayerId]) -> Rect { + ids.iter().filter_map(|&id| doc.layer(id)).fold(Rect::EMPTY, |r, l| r.union(&transform_bounds(doc, l))) +} + +/// The homography `p` asks for over `rect`: its `quad` (where the corners go) or affine `matrix`. +fn homography(p: &Value, rect: [f64; 4]) -> Result { let h = if let Some(q) = quad_param(p) { Homography::rect_to_quad(rect, q).ok_or_else(|| bad("degenerate quad"))? } else if let Some(m) = p.get("matrix").and_then(Value::as_array) { @@ -449,9 +453,115 @@ fn transform(s: &mut Session, p: &Value) -> Result { if h.inverse().is_none() { return Err(bad("the transform collapses the layer")); } + Ok(h) +} + +fn affine_of(h: &Homography) -> Option { let m = h.0; - let affine = - (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] }); + (m[6].abs() < 1e-12 && m[7].abs() < 1e-12).then(|| Affine { m: [m[0] / m[8], m[3] / m[8], m[1] / m[8], m[4] / m[8], m[2] / m[8], m[5] / m[8]] }) +} + +fn rect_param(p: &Value) -> Option<[f64; 4]> { + match p.get("rect").and_then(Value::as_array) { + Some(r) if r.len() == 4 => { + let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); + Some([v[0], v[1], v[2], v[3]]) + } + _ => None, + } +} + +/// Free Transform of several layers at once (#3592): one frame around all of them, the same +/// projective map applied to each (so they keep their places relative to each other), one step. +fn transform_many(s: &mut Session, p: &Value, ids: Vec) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + if let Some(&id) = ids.iter().find(|&&id| locked_for_transform(&st.doc, id)) { + let name = st.doc.layer(id).map_or_else(String::new, |l| l.name.clone()); + return Err(EngineError::Other(format!("Could not transform: layer \"{name}\" is locked"))); + } + let rect = match rect_param(p) { + Some(r) => r, + None => { + let b = multi_bounds(&st.doc, &ids); + if b.is_empty() { + return Err(EngineError::Other("nothing to transform".into())); + } + [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64] + } + }; + let h = homography(p, rect)?; + let affine = affine_of(&h); + let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); + s.edit("Free Transform", |doc, _| { + let sel = doc.selection.clone(); + for &id in &ids { + let is_group = doc.layer(id).is_some_and(Layer::is_group); + let group = group_locks(doc, id); + let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; + transform_layer(if is_group { None } else { sel.as_ref() }, group, l, &h, affine, interp)?; + } + let snapshot = doc.clone(); + for &id in &ids { + if let Some(l) = doc.layer_mut(id) { + refresh_text(&snapshot, l); + } + } + if let Some(sel) = &doc.selection { + doc.selection = Some(warp_gray(sel, &h, Interp::Bilinear)?).filter(|s| !s.content_bounds().is_empty()); + } + Ok(()) + })?; + Ok(json!({"rect": rect, "layers": ids.iter().map(|l| l.0).collect::>()})) +} + +fn transform(s: &mut Session, p: &Value) -> Result { + if let Some(list) = p.get("layers").and_then(Value::as_array) + && p.get("target").is_none() + { + let st = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = list.iter().filter_map(Value::as_u64).map(LayerId).collect(); + let many = multi_targets(&st.doc, &ids); + if many.len() > 1 { + return transform_many(s, p, many); + } + if let Some(&one) = many.first() { + let mut p = p.clone(); + p["layer"] = json!(one.0); + if let Some(m) = p.as_object_mut() { + m.remove("layers"); + } + return transform(s, &p); + } + return Err(EngineError::Other("nothing to transform".into())); + } + let p = &with_panel_target(s, p); + let st = s.active().ok_or(EngineError::NoDocument)?; + let id = match p.get("layer").and_then(Value::as_u64) { + Some(v) => Some(LayerId(v)), + None => st.active_layer, + }; + let lone = lone_target(&st.doc, id, p)?; + let id = match (id, lone.is_some() && crate::channel_cmds::is_channel_target(p)) { + (_, true) => None, + (Some(id), false) => Some(id), + (None, false) => return Err(EngineError::Other("no active layer".into())), + }; + let rect = match rect_param(p) { + Some(r) => r, + None => { + let b = match (lone, id) { + (Some(surf), _) => target_bounds(&st.doc, surf), + (None, Some(id)) => transform_bounds(&st.doc, st.doc.layer(id).ok_or(EngineError::NoLayer(id))?), + (None, None) => Rect::EMPTY, + }; + if b.is_empty() { + return Err(EngineError::Other("nothing to transform".into())); + } + [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64] + } + }; + let h = homography(p, rect)?; + let affine = affine_of(&h); let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); let lone = lone.is_some(); s.edit("Free Transform", |doc, _| { @@ -493,7 +603,7 @@ pub fn specs() -> Vec { label: "Free Transform", menu: &[], shortcut: None, - params: r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (source frame; default = layer content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"interpolation":"bicubic|bilinear|nearest"="bicubic","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, + params: r##"{"layer":id?,"layers":[id]? (several layers transformed together around one shared frame, one step; #3592),"rect":[x0,y0,x1,y1]? (source frame; default = layer content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"interpolation":"bicubic|bilinear|nearest"="bicubic","target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, enabled: has_layer, journal: true, run: transform, @@ -848,4 +958,72 @@ mod tests { let st = s.active().unwrap(); assert_eq!(transform_bounds(&st.doc, st.doc.layer(st.active_layer.unwrap()).unwrap()), Rect::new(10, 10, 15, 20)); } + + /// Two layers: the session's red rect at (10,10)-(30,20) and a blue one at (60,50)-(80,70), + /// both selected; returns (bottom, top). + fn two_layers() -> (Session, LayerId, LayerId) { + let mut s = session(); + let a = s.active().unwrap().active_layer.unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(60, 50, 80, 70), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let b = s.active().unwrap().active_layer.unwrap(); + (s, a, b) + } + + fn bounds_of(s: &Session, id: LayerId) -> Rect { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds() + } + + #[test] + fn several_layers_scale_around_one_shared_frame_in_one_step() { + let (mut s, a, b) = two_layers(); + assert_eq!(multi_bounds(&s.active().unwrap().doc, &[a, b]), Rect::new(10, 10, 80, 70)); + let steps = s.active().unwrap().history.entries().len(); + // Halve the shared frame about its top-left corner. + let r = s.execute("edit.transform", json!({"layers": [a.0, b.0], "quad": [[10, 10], [45, 10], [45, 40], [10, 40]]})).unwrap(); + assert_eq!(r["rect"], json!([10.0, 10.0, 80.0, 70.0])); + assert_eq!(bounds_of(&s, a), Rect::new(10, 10, 20, 15)); + assert_eq!(bounds_of(&s, b), Rect::new(35, 30, 45, 40)); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one history step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(10, 10, 30, 20)); + assert_eq!(bounds_of(&s, b), Rect::new(60, 50, 80, 70)); + } + + #[test] + fn several_layers_move_and_rotate_consistently() { + let (mut s, a, b) = two_layers(); + s.execute("edit.transform", json!({"layers": [a.0, b.0], "matrix": [1, 0, 0, 1, 5, 7]})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(15, 17, 35, 27)); + assert_eq!(bounds_of(&s, b), Rect::new(65, 57, 85, 77)); + s.execute("edit.undo", json!({})).unwrap(); + // 180° about the shared centre (45, 40): each rect lands where the other's mirror is. + s.execute("edit.transform", json!({"layers": [a.0, b.0], "quad": [[80, 70], [10, 70], [10, 10], [80, 10]], "interpolation": "nearest"})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(60, 60, 80, 70)); + assert_eq!(bounds_of(&s, b), Rect::new(10, 10, 30, 30)); + } + + #[test] + fn several_layers_refuse_when_one_is_locked_and_skip_the_empty() { + let (mut s, a, b) = two_layers(); + s.execute("layer.new.layer", json!({})).unwrap(); + let empty = s.active().unwrap().active_layer.unwrap(); + assert_eq!(multi_targets(&s.active().unwrap().doc, &[a, b, empty]), vec![a, b]); + s.edit("lock", |doc, _| { + doc.layer_mut(b).unwrap().locks.position = true; + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().history.entries().len(); + assert!(s.execute("edit.transform", json!({"layers": [a.0, b.0], "matrix": [1, 0, 0, 1, 5, 0]})).is_err()); + assert_eq!(bounds_of(&s, a), Rect::new(10, 10, 30, 20), "nothing moved"); + assert_eq!(s.active().unwrap().history.entries().len(), before); + // One layer left: the single-layer path, with its own frame. + s.execute("edit.transform", json!({"layers": [a.0, empty.0], "matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(15, 10, 35, 20)); + } } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 52d44b9b2b..cffcf6e5e3 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -880,6 +880,10 @@ pub struct TransformSession { /// Edit › Transform › Skew / Distort / Perspective (`Free` for Free Transform). #[serde(default)] pub mode: TransformMode, + /// Free Transform of several selected layers at once (#3592): every layer the box moves, bottom + /// to top, around one shared frame (`layer` stays the active one). Empty for a single layer. + #[serde(default)] + pub layers: Vec, } /// Why a Free Transform session's layer was made for it. diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 444e0faf9a..52484fee72 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -171,6 +171,11 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> return begin_lone(app, ctx, doc, surf, target); } let id = st.active_layer.ok_or("no active layer")?; + // Several layers selected: one box around all of them (#3592). + let many = photocraft_engine::transform_cmds::multi_targets(&doc, &st.selected_layers()); + if many.len() > 1 { + return begin_many(app, ctx, doc, id, many); + } let layer = doc.layer(id).ok_or("no layer")?; if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) { // Photoshop refuses before the box opens rather than when it is committed (#2585). @@ -237,6 +242,91 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> path: None, made: None, mode: Default::default(), + layers: Vec::new(), + }); + start_steps(app); + Ok(()) +} + +/// Free Transform of several selected layers together (#3592), like Photoshop: the box frames all +/// of their content (within the selection for pixel layers), the moving layers preview as one +/// composite over the document with them hidden (or their selected pixels lifted out), and OK +/// commits one `edit.transform` step with `"layers"`. Warp, a lone mask/channel target and edits +/// followed live while the box is open stay single-layer features. +fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, active: LayerId, ids: Vec) -> Result<(), String> { + use photocraft_engine::transform_cmds as tc; + if ids.iter().any(|&id| tc::locked_for_transform(&doc, id)) { + app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default()); + return Err(LOCKED.into()); + } + let b = tc::multi_bounds(&doc, &ids); + if b.is_empty() { + return Err("Could not transform: the layers are empty".into()); + } + crate::type_tool::commit(app); + let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; + let session = app.ui.alloc_id(); + // `pd`: the document under the box; `solo`: just what moves. + let (mut pd, mut solo) = ((*doc).clone(), (*doc).clone()); + for &id in &ids { + let lift = doc.selection.as_ref().filter(|_| doc.layer(id).is_some_and(|l| !tc::moves_whole(l) && l.surface().is_some())); + match (lift, doc.layer(id).and_then(|l| l.surface())) { + (Some(sel), Some(surf)) => { + let (moving, rest) = tc::split_selected(surf, sel).map_err(|e| e.to_string())?; + if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()) { + *s = rest; + } + if let Some(s) = solo.layer_mut(id).and_then(|l| l.surface_mut()) { + *s = moving; + } + } + _ => { + if let Some(l) = pd.layer_mut(id) { + l.visible = false; + } + } + } + } + show_only(&mut solo.layers, &ids); + let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + // What covers the topmost moving layer draws over the preview. + let top = *ids.last().unwrap_or(&active); + let above = Above::new(ctx, format!("transform-{session}-above"), &doc, top, max_side); + above.hide_in(&mut pd.layers); + let (image, uv) = composite_image(&solo, b, max_side); + let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + app.transform_preview = Some(TransformPreview { + session, + doc: Arc::new(pd), + texture, + // The composite already carries each layer's opacity and masks. + opacity: 1.0, + above: Some(above), + follow: None, + gesture: None, + warp_drag: None, + split_tool: None, + split_pointer: None, + split_placing: false, + split_quick: false, + steps: Steps::default(), + tool: app.ui.tool, + path: None, + }); + app.ui.transform = Some(TransformSession { + session, + layer: active.0, + rect, + quad: corners(rect), + pivot: [(rect[0] + rect[2]) / 2.0, (rect[1] + rect[3]) / 2.0], + interpolation: "bicubic".into(), + warp: None, + selection: false, + target: None, + path: None, + made: None, + mode: Default::default(), + layers: ids.iter().map(|l| l.0).collect(), }); start_steps(app); Ok(()) @@ -375,6 +465,7 @@ fn begin_lone( path: None, made: None, mode: Default::default(), + layers: Vec::new(), }); start_steps(app); Ok(()) @@ -423,6 +514,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: path: Some(params), made: None, mode: Default::default(), + layers: Vec::new(), }); start_steps(app); Ok(()) @@ -503,6 +595,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( path: None, made: None, mode: Default::default(), + layers: Vec::new(), }); start_steps(app); Ok(()) @@ -528,8 +621,9 @@ pub fn enter_warp(app: &mut PhotocraftApp) { 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 only: a lone mask, channel or path keeps the box, and so does a box + // around several layers (#3592: warping them together isn't supported yet). + if t.warp.is_some() || t.target.is_some() || t.path.is_some() || t.layers.len() > 1 { return; } if t.quad == corners(t.rect) @@ -822,6 +916,9 @@ pub fn commit(app: &mut PhotocraftApp) { return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays } let mut p = json!({"layer": t.layer, "rect": t.rect, "quad": t.quad, "interpolation": t.interpolation}); + if t.layers.len() > 1 { + p["layers"] = json!(t.layers); + } if let Some(target) = t.target { p["target"] = target; } @@ -2310,6 +2407,7 @@ mod tests { path: None, made: None, mode: Default::default(), + layers: Vec::new(), } } diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 3607702319..bbbee86218 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -277,3 +277,87 @@ fn the_first_drag_from_the_move_tools_controls_undoes() { key(&mut h, Modifiers::COMMAND, Key::Z); assert!(close(quad(&h), [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]]), "{:?}", quad(&h)); } + +/// The harness's red layer plus a blue 50 × 50 one at (250, 200), both selected (#3592). +fn two_selected(h: &mut Harness<'static, PhotocraftApp>) -> (u64, u64) { + let app = h.state_mut(); + let red = app.session.active().unwrap().active_layer.unwrap().0; + app.run("layer.new.layer", json!({})).unwrap(); + app.run("select.rect", json!({"x": 250, "y": 200, "width": 50, "height": 50})).unwrap(); + app.run("edit.fill", json!({"color": "#0000ff"})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + let blue = app.session.active().unwrap().active_layer.unwrap().0; + app.run("layer.select", json!({"layer": red, "mode": "add"})).unwrap(); + app.sync_views(); + h.run_steps(2); + (red, blue) +} + +fn bounds(h: &Harness<'static, PhotocraftApp>, id: u64) -> photocraft_geom::Rect { + let st = h.state().session.active().unwrap(); + st.doc.layer(photocraft_doc::LayerId(id)).unwrap().surface().unwrap().content_bounds() +} + +#[test] +fn free_transform_moves_every_selected_layer_in_one_step() { + let mut h = harness(); + let (red, blue) = two_selected(&mut h); + let steps = history(&h); + begin(&mut h); + let t = h.state().ui.transform.clone().expect("transforming"); + assert_eq!(t.layers.len(), 2, "both layers move: {:?}", t.layers); + assert!(close(t.quad, [[100.0, 100.0], [300.0, 100.0], [300.0, 250.0], [100.0, 250.0]]), "one box around both: {:?}", t.quad); + // Scale the shared box by ½ about its top-left corner. + h.state_mut().ui.transform.as_mut().unwrap().quad = [[100.0, 100.0], [200.0, 100.0], [200.0, 175.0], [100.0, 175.0]]; + key(&mut h, Modifiers::NONE, Key::Enter); + assert!(h.state().ui.transform.is_none()); + assert_eq!(history(&h), steps + 1, "one history step"); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 150, 130)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(175, 150, 200, 175)); + // One Undo restores both. + key(&mut h, Modifiers::COMMAND, Key::Z); + assert_eq!(history(&h), steps); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 200, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(250, 200, 300, 250)); +} + +#[test] +fn cancelling_a_multi_layer_transform_leaves_every_layer() { + let mut h = harness(); + let (red, blue) = two_selected(&mut h); + let steps = history(&h); + begin(&mut h); + key(&mut h, Modifiers::NONE, Key::ArrowRight); + key(&mut h, Modifiers::NONE, Key::ArrowDown); + assert!(close(quad(&h), [[101.0, 101.0], [301.0, 101.0], [301.0, 251.0], [101.0, 251.0]]), "{:?}", quad(&h)); + key(&mut h, Modifiers::NONE, Key::Escape); + assert!(h.state().ui.transform.is_none()); + assert_eq!(history(&h), steps); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 200, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(250, 200, 300, 250)); +} + +#[test] +fn a_single_selected_layer_keeps_its_own_box() { + let mut h = harness(); + begin(&mut h); + let t = h.state().ui.transform.clone().expect("transforming"); + assert!(t.layers.is_empty()); + assert!(close(t.quad, [[100.0, 100.0], [200.0, 100.0], [200.0, 160.0], [100.0, 160.0]])); +} + +#[test] +fn a_locked_layer_in_the_selection_refuses_the_box() { + let mut h = harness(); + let (_, blue) = two_selected(&mut h); + h.state_mut() + .session + .edit("lock", |doc, _| { + doc.layer_mut(photocraft_doc::LayerId(blue)).unwrap().locks.position = true; + Ok(()) + }) + .unwrap(); + let ctx = h.ctx.clone(); + assert!(crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).is_err()); + assert!(h.state().ui.transform.is_none()); +} diff --git a/crates/ui-egui/src/type_transform.rs b/crates/ui-egui/src/type_transform.rs index a51c450eb1..a409c75128 100644 --- a/crates/ui-egui/src/type_transform.rs +++ b/crates/ui-egui/src/type_transform.rs @@ -125,6 +125,7 @@ pub(crate) fn frame(app: &mut PhotocraftApp) -> Option { path: None, made: None, mode: Default::default(), + layers: Vec::new(), }) } From 2006c72e98c76719574c3f9cab94b9691fc6d536 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Sun, 11 Oct 2026 18:55:56 +0200 Subject: [PATCH 2/5] Warp, transform a copy, flip/rotate and live preview for several layers (#3592) - edit.transform.warp takes "layers": one shared mesh over the combined box, applied to each layer as one Warp step; Warp mode now works on a multi-layer box. - Edit > Transform flip/rotate turn every selected layer around their shared box in one step (a named "layer" still turns alone). - The multi-layer box rebuilds its preview from the live document, so opacity/visibility edits made while it is open show. - Tests for these and for Free Transform a Copy with several layers. --- crates/engine/src/extra_cmds.rs | 12 +- crates/engine/src/transform_cmds.rs | 41 ++++++ crates/engine/src/warp_cmds.rs | 68 ++++++++- crates/ui-egui/src/transform_tex.rs | 8 + crates/ui-egui/src/transform_tool.rs | 164 ++++++++++++++++----- crates/ui-egui/src/transform_undo_tests.rs | 78 ++++++++++ 6 files changed, 335 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs index f25ea9a2e9..fe572e25e0 100644 --- a/crates/engine/src/extra_cmds.rs +++ b/crates/engine/src/extra_cmds.rs @@ -344,8 +344,16 @@ fn transform_preset(s: &mut Session, p: &Value, kind: &str) -> Result { Some(surf) => (crate::transform_cmds::target_bounds(&d.doc, surf), json!({"target": p.get("target")})), None => { let id = d.active_layer.ok_or(EngineError::Other("no active layer".into()))?; - let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; - (crate::transform_cmds::transform_bounds(&d.doc, l), json!({"layer": id.0})) + // Several selected layers turn together around their shared box (#3592), unless a + // `layer` is named. + let many = if p.get("layer").is_none() { crate::transform_cmds::multi_targets(&d.doc, &d.selected_layers()) } else { Vec::new() }; + if many.len() > 1 { + (crate::transform_cmds::multi_bounds(&d.doc, &many), json!({"layers": many.iter().map(|l| l.0).collect::>()})) + } else { + let id = p.get("layer").and_then(Value::as_u64).map_or(id, LayerId); + let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?; + (crate::transform_cmds::transform_bounds(&d.doc, l), json!({"layer": id.0})) + } } }; if b.is_empty() { diff --git a/crates/engine/src/transform_cmds.rs b/crates/engine/src/transform_cmds.rs index b09cfa9b04..7094f50066 100644 --- a/crates/engine/src/transform_cmds.rs +++ b/crates/engine/src/transform_cmds.rs @@ -1026,4 +1026,45 @@ mod tests { s.execute("edit.transform", json!({"layers": [a.0, empty.0], "matrix": [1, 0, 0, 1, 5, 0]})).unwrap(); assert_eq!(bounds_of(&s, a), Rect::new(15, 10, 35, 20)); } + + #[test] + fn flip_and_rotate_turn_every_selected_layer_around_the_shared_box() { + let (mut s, a, b) = two_layers(); + s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap(); + let steps = s.active().unwrap().history.entries().len(); + s.execute("edit.transform.flipHorizontal", json!({})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(60, 10, 80, 20)); + assert_eq!(bounds_of(&s, b), Rect::new(10, 50, 30, 70)); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1, "one step"); + s.execute("edit.undo", json!({})).unwrap(); + s.execute("edit.transform.rotate180", json!({})).unwrap(); + assert_eq!(bounds_of(&s, a), Rect::new(60, 60, 80, 70)); + assert_eq!(bounds_of(&s, b), Rect::new(10, 10, 30, 30)); + s.execute("edit.undo", json!({})).unwrap(); + // A named layer still turns alone, around its own box. + s.execute("edit.transform.flipVertical", json!({"layer": a.0})).unwrap(); + assert_eq!((bounds_of(&s, a), bounds_of(&s, b)), (Rect::new(10, 10, 30, 20), Rect::new(60, 50, 80, 70))); + } + + #[test] + fn warp_applies_one_shared_warp_to_every_listed_layer_in_one_step() { + let (mut s, a, b) = two_layers(); + let before = (bounds_of(&s, a), bounds_of(&s, b)); + let steps = s.active().unwrap().history.entries().len(); + let r = s.execute("edit.transform.warp", json!({"layers": [a.0, b.0], "style": "arc", "bend": 50})).unwrap(); + assert_eq!(r["rect"], json!([10, 10, 80, 70]), "the shared box"); + assert_ne!(bounds_of(&s, a), before.0); + assert_ne!(bounds_of(&s, b), before.1); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!((bounds_of(&s, a), bounds_of(&s, b)), before); + // A locked layer refuses the whole warp. + s.edit("lock", |doc, _| { + doc.layer_mut(b).unwrap().locks.position = true; + Ok(()) + }) + .unwrap(); + assert!(s.execute("edit.transform.warp", json!({"layers": [a.0, b.0], "style": "arc", "bend": 50})).is_err()); + assert_eq!(bounds_of(&s, a), before.0); + } } diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rs index daecc6b9c7..7f005c7d7b 100644 --- a/crates/engine/src/warp_cmds.rs +++ b/crates/engine/src/warp_cmds.rs @@ -208,7 +208,73 @@ fn target(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, Rect)> { Ok((id, rect)) } +/// Warp of several layers at once (#3592): one warp over the shared frame (the union of each +/// layer's [`warp_bounds`] unless `rect` is given), applied to every layer, one step. +fn apply_many(s: &mut Session, p: &Value, cmd: &str, ids: Vec) -> Result { + let st = s.active().ok_or(EngineError::NoDocument)?; + if let Some(l) = ids.iter().find(|&&id| crate::transform_cmds::locked_for_transform(&st.doc, id)).and_then(|&id| st.doc.layer(id)) { + return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); + } + let rect = match p.get("rect").and_then(Value::as_array) { + Some(r) if r.len() == 4 => { + let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0).round() as i32).collect(); + Rect::new(v[0], v[1], v[2], v[3]) + } + _ => ids.iter().filter_map(|&id| st.doc.layer(id)).fold(Rect::EMPTY, |r, l| r.union(&warp_bounds(&st.doc, l))), + }; + if rect.is_empty() { + return Err(bad(cmd, "nothing to warp")); + } + if rect.width() > MAX_WARP_SIDE || rect.height() > MAX_WARP_SIDE { + return Err(bad(cmd, format!("rect too large for warp: {} x {} (max {MAX_WARP_SIDE} per side)", rect.width(), rect.height()))); + } + let w = warp_from_params(cmd, p, rect_f(rect))?; + let out = ids.iter().map(|l| l.0).collect::>(); + if w.is_identity() { + return Ok(json!({"layers": out, "changed": false})); + } + let interp = Interp::parse(p.get("interpolation").and_then(Value::as_str).unwrap_or("bicubic")); + s.edit("Warp", |doc, _| { + let sel = doc.selection.clone(); + for &id in &ids { + let is_group = doc.layer(id).is_some_and(Layer::is_group); + let group = crate::transform_cmds::group_locks(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)?; + } + let snapshot = doc.clone(); + for &id in &ids { + 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(()) + })?; + Ok(json!({"layers": out, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]})) +} + fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result { + if cmd == "edit.transform.warp" + && let Some(list) = p.get("layers").and_then(Value::as_array) + { + let st = s.active().ok_or(EngineError::NoDocument)?; + let ids: Vec = list.iter().filter_map(Value::as_u64).map(LayerId).collect(); + let many = crate::transform_cmds::multi_targets(&st.doc, &ids); + if many.len() > 1 { + return apply_many(s, p, cmd, many); + } + let mut p = p.clone(); + if let Some(m) = p.as_object_mut() { + m.remove("layers"); + if let Some(one) = many.first() { + m.insert("layer".into(), json!(one.0)); + } + } + return apply(s, &p, cmd); + } let (id, rect) = target(s, cmd, p)?; let w = warp_from_params(cmd, p, rect_f(rect))?; let is_smart = matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Smart(_))); @@ -407,7 +473,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { } pub fn specs() -> Vec { - const P: &str = r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"}"##; + const P: &str = r##"{"layer":id?,"layers":[id]? (edit.transform.warp: several layers warped together over one shared box, one step; #3592),"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"}"##; const S: &str = r##"{"warp":{…}? (the warp being edited; returned split),"rect":[x0,y0,x1,y1]?,"at":[x,y]? (document point; default = middle of the patch)} — without `warp`, edits the active smart object's warp. A 1×1 custom mesh is divided at the thirds first (the guides drawn on the default grid), so splitWarpCrosswise on an identity custom warp returns a 4×4 mesh (knots at 0, 1/3, 1/2, 2/3 and 1), not a 2×2. A preset is fitted as one patch and split without that step."##; const G: &str = r##"{"warp":{…}? (the warp being edited; returned with the new mesh),"rect":[x0,y0,x1,y1]?,"size":n|"default"|"3"|"4"|"5" (square patches, 1..=64; 1 and "default" are the single-patch grid)} — without `warp`/`style`/`mesh`, edits the active smart object's warp. The surface is kept and the new lines are real splits at i/n."##; vec![ diff --git a/crates/ui-egui/src/transform_tex.rs b/crates/ui-egui/src/transform_tex.rs index 2811a6b586..7a351a5e7e 100644 --- a/crates/ui-egui/src/transform_tex.rs +++ b/crates/ui-egui/src/transform_tex.rs @@ -47,6 +47,14 @@ impl PreviewTextures { } /// Size of the full-resolution level in texels. + /// Level 0's texel at (`x`, `y`) (tests). + #[cfg(test)] + pub fn texel(&self, x: usize, y: usize) -> Option { + let images = self.images.lock().ok()?; + let img = images.first()?; + img.pixels.get(y * img.size[0] + x).copied() + } + pub fn size(&self) -> [usize; 2] { self.images.lock().unwrap_or_else(PoisonError::into_inner).first().map_or([0, 0], |i| i.size) } diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index 52484fee72..d19c362648 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -82,6 +82,51 @@ pub struct TransformPreview { /// A layer's session keeps `doc` and `opacity` up to date with edits made while the box is /// open ([`follow_edits`]); `None` for a lone mask or channel and Transform Selection. follow: Option, + /// A box around several layers (#3592): what [`follow_edits`] needs to rebuild its preview. + many: Option, +} + +/// The moving part of a box around several layers: the layers, and for each pixel layer a +/// selection lifted out of, its moving pixels and what stays behind. +struct Many { + ctx: egui::Context, + ids: Vec, + lifted: Vec<(LayerId, photocraft_raster::Surface, photocraft_raster::Surface)>, + bounds: photocraft_geom::Rect, + max_side: usize, +} + +impl Many { + /// From `doc` (the live document): the document under the box (`pd`) and one with just what + /// moves (`solo`), each layer keeping its current opacity, visibility, blending and masks. + fn docs(&self, doc: &Document) -> (Document, Document) { + let (mut pd, mut solo) = (doc.clone(), doc.clone()); + for &id in &self.ids { + match self.lifted.iter().find(|(l, ..)| *l == id) { + Some((_, moving, rest)) => { + if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()) { + *s = rest.clone(); + } + if let Some(s) = solo.layer_mut(id).and_then(|l| l.surface_mut()) { + *s = moving.clone(); + } + } + None => { + if let Some(l) = pd.layer_mut(id) { + l.visible = false; + } + } + } + } + show_only(&mut solo.layers, &self.ids); + (pd, solo) + } + + /// The preview texture of what moves. + fn texture(&self, solo: &Document, name: String) -> crate::transform_tex::PreviewTextures { + let (image, uv) = composite_image(solo, self.bounds, self.max_side); + crate::transform_tex::PreviewTextures::new(&self.ctx, name, image, uv) + } } /// What [`follow_edits`] needs to rebuild the preview document. @@ -174,7 +219,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> // Several layers selected: one box around all of them (#3592). let many = photocraft_engine::transform_cmds::multi_targets(&doc, &st.selected_layers()); if many.len() > 1 { - return begin_many(app, ctx, doc, id, many); + return begin_many(app, ctx, doc, revision, id, many); } let layer = doc.layer(id).ok_or("no layer")?; if photocraft_engine::transform_cmds::locked_for_transform(&doc, id) { @@ -227,6 +272,7 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> split_quick: false, steps: Steps::default(), tool: app.ui.tool, + many: None, path: None, }); app.ui.transform = Some(TransformSession { @@ -251,9 +297,8 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> /// Free Transform of several selected layers together (#3592), like Photoshop: the box frames all /// of their content (within the selection for pixel layers), the moving layers preview as one /// composite over the document with them hidden (or their selected pixels lifted out), and OK -/// commits one `edit.transform` step with `"layers"`. Warp, a lone mask/channel target and edits -/// followed live while the box is open stay single-layer features. -fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, active: LayerId, ids: Vec) -> Result<(), String> { +/// commits one `edit.transform` (or, in Warp, `edit.transform.warp`) step with `"layers"`. +fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, revision: u64, active: LayerId, ids: Vec) -> Result<(), String> { use photocraft_engine::transform_cmds as tc; if ids.iter().any(|&id| tc::locked_for_transform(&doc, id)) { app.ui.open_dialog(crate::state::DialogKind::Error, json!({"message": tl!(LOCKED)}).as_object().cloned().unwrap_or_default()); @@ -266,35 +311,24 @@ fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, crate::type_tool::commit(app); let rect = [b.x0 as f64, b.y0 as f64, b.x1 as f64, b.y1 as f64]; let session = app.ui.alloc_id(); - // `pd`: the document under the box; `solo`: just what moves. - let (mut pd, mut solo) = ((*doc).clone(), (*doc).clone()); + let mut lifted = Vec::new(); for &id in &ids { let lift = doc.selection.as_ref().filter(|_| doc.layer(id).is_some_and(|l| !tc::moves_whole(l) && l.surface().is_some())); - match (lift, doc.layer(id).and_then(|l| l.surface())) { - (Some(sel), Some(surf)) => { - let (moving, rest) = tc::split_selected(surf, sel).map_err(|e| e.to_string())?; - if let Some(s) = pd.layer_mut(id).and_then(|l| l.surface_mut()) { - *s = rest; - } - if let Some(s) = solo.layer_mut(id).and_then(|l| l.surface_mut()) { - *s = moving; - } - } - _ => { - if let Some(l) = pd.layer_mut(id) { - l.visible = false; - } - } + if let (Some(sel), Some(surf)) = (lift, doc.layer(id).and_then(|l| l.surface())) { + let (moving, rest) = tc::split_selected(surf, sel).map_err(|e| e.to_string())?; + lifted.push((id, moving, rest)); } } - show_only(&mut solo.layers, &ids); let max_side = ctx.input(|i| i.max_texture_side).max(app.gpu.as_ref().map_or(1, |g| g.max_texture_side())); + let many = Many { ctx: ctx.clone(), ids, lifted, bounds: b, max_side }; + // `pd`: the document under the box; `solo`: just what moves. + let (mut pd, solo) = many.docs(&doc); // What covers the topmost moving layer draws over the preview. - let top = *ids.last().unwrap_or(&active); + let top = *many.ids.last().unwrap_or(&active); let above = Above::new(ctx, format!("transform-{session}-above"), &doc, top, max_side); above.hide_in(&mut pd.layers); - let (image, uv) = composite_image(&solo, b, max_side); - let texture = crate::transform_tex::PreviewTextures::new(ctx, format!("transform-{session}"), image, uv); + let texture = many.texture(&solo, format!("transform-{session}")); + let layers = many.ids.iter().map(|l| l.0).collect(); app.transform_preview = Some(TransformPreview { session, doc: Arc::new(pd), @@ -302,7 +336,7 @@ fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, // The composite already carries each layer's opacity and masks. opacity: 1.0, above: Some(above), - follow: None, + follow: Some(Follow { revision, hidden: true }), gesture: None, warp_drag: None, split_tool: None, @@ -311,6 +345,7 @@ fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, split_quick: false, steps: Steps::default(), tool: app.ui.tool, + many: Some(many), path: None, }); app.ui.transform = Some(TransformSession { @@ -326,7 +361,7 @@ fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, path: None, made: None, mode: Default::default(), - layers: ids.iter().map(|l| l.0).collect(), + layers, }); start_steps(app); Ok(()) @@ -450,6 +485,7 @@ fn begin_lone( split_quick: false, steps: Steps::default(), tool: app.ui.tool, + many: None, path: None, }); app.ui.transform = Some(TransformSession { @@ -497,6 +533,7 @@ fn begin_path(app: &mut PhotocraftApp, ctx: &egui::Context, params: serde_json:: split_quick: false, steps: Steps::default(), tool: app.ui.tool, + many: None, path: Some(path), above: None, follow: None, @@ -580,6 +617,7 @@ pub fn begin_selection(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<( split_quick: false, steps: Steps::default(), tool: app.ui.tool, + many: None, path: None, }); app.ui.transform = Some(TransformSession { @@ -618,12 +656,15 @@ pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St /// Switch to Warp mode: a smart object's existing warp (when the box is untouched), else a /// custom mesh following the current box (so a transform made first carries over). pub fn enter_warp(app: &mut PhotocraftApp) { - 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)); + // A box around several layers starts a fresh mesh: no one smart object's warp applies. + let existing = app.session.active().and_then(|d| { + let t = app.ui.transform.as_ref().filter(|t| t.layers.len() <= 1)?; + d.doc.layer(LayerId(t.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, and so does a box - // around several layers (#3592: warping them together isn't supported yet). - if t.warp.is_some() || t.target.is_some() || t.path.is_some() || t.layers.len() > 1 { + // Warp moves layers only: a lone mask, channel or path keeps the box. A box around several + // layers warps them all with one mesh (#3592). + if t.warp.is_some() || t.target.is_some() || t.path.is_some() { return; } if t.quad == corners(t.rect) @@ -910,7 +951,11 @@ pub fn commit(app: &mut PhotocraftApp) { if w.is_identity() { return; } - app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation})) + let mut p = json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation}); + if t.layers.len() > 1 { + p["layers"] = json!(t.layers); + } + app.run("edit.transform.warp", p) } else { if t.quad == corners(t.rect) { return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays @@ -982,6 +1027,22 @@ pub fn follow_edits(app: &mut PhotocraftApp) { let (Some(t), Some(pv)) = (&app.ui.transform, app.transform_preview.as_mut()) else { return }; let Some(follow) = pv.follow.as_mut() else { return }; let Some(st) = app.session.active().filter(|st| st.doc.id == pv.doc.id && st.revision != follow.revision) else { return }; + // Several layers (#3592): rebuild both sides from the live document, so opacity, visibility, + // blending and mask edits to any moving layer show in the moving composite. + if let Some(many) = &pv.many { + if many.ids.iter().any(|&id| st.doc.layer(id).is_none()) { + return; + } + let (mut pd, solo) = many.docs(&st.doc); + if let Some(a) = pv.above.as_mut() { + a.rebuild(&st.doc, *many.ids.last().unwrap_or(&LayerId(t.layer))); + a.hide_in(&mut pd.layers); + } + pv.texture = many.texture(&solo, format!("transform-{}", pv.session)); + follow.revision = st.revision; + pv.doc = Arc::new(pd); + return; + } let id = LayerId(t.layer); let (Some(live), Some(moving)) = (st.doc.layer(id), pv.doc.layer(id)) else { return }; let mut pd = (*st.doc).clone(); @@ -3409,6 +3470,43 @@ mod tests { assert!(!crate::canvas_tool_menu::available(&app, &menu, "edit.transform.warp")); } + /// #3592: with several layers in the box, opacity and visibility edits made while it is open + /// show in the moving composite, and the document under the box follows other edits. + #[test] + fn a_multi_layer_box_follows_opacity_and_visibility_edits() { + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let red = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.new.layer", json!({})).unwrap(); + app.session + .edit("paint", |doc, a| { + doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(40, 40, 56, 56), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let blue = app.session.active().unwrap().active_layer.unwrap(); + app.session.execute("layer.select", json!({"layer": red.0, "mode": "add"})).unwrap(); + app.sync_views(); + begin(&mut app, &egui::Context::default()).unwrap(); + let texel = |app: &PhotocraftApp, x: usize, y: usize| app.transform_preview.as_ref().unwrap().texture.texel(x, y).unwrap(); + // The box is (8, 8)-(56, 56): red at its top-left texel, blue at (32, 32). + assert_eq!(texel(&app, 0, 0).a(), 255); + assert_eq!(texel(&app, 40, 40).a(), 255); + app.session + .edit("opacity", |doc, _| { + doc.layer_mut(red).unwrap().opacity = 0.5; + doc.layer_mut(blue).unwrap().visible = false; + Ok(()) + }) + .unwrap(); + follow_edits(&mut app); + let a = texel(&app, 0, 0).a(); + assert!((120..=135).contains(&a), "half-opaque red: {a}"); + assert_eq!(texel(&app, 40, 40).a(), 0, "hidden blue drops out of the preview"); + let pv = app.transform_preview.as_ref().unwrap(); + assert!(!pv.doc.layer(red).unwrap().visible && !pv.doc.layer(blue).unwrap().visible, "both still hidden under the box"); + assert_eq!(app.ui.transform.as_ref().unwrap().layers, vec![red.0, blue.0]); + } + fn app_with_square(size: u32, fill: photocraft_geom::Rect) -> PhotocraftApp { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", json!({"width": size, "height": size})).unwrap(); diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index bbbee86218..88a76cb5de 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -361,3 +361,81 @@ fn a_locked_layer_in_the_selection_refuses_the_box() { assert!(crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransform", json!({})).is_err()); assert!(h.state().ui.transform.is_none()); } + +fn shift_x(q: [[f64; 2]; 4], dx: f64) -> [[f64; 2]; 4] { + q.map(|p| [p[0] + dx, p[1]]) +} + +#[test] +fn warp_with_several_layers_warps_them_all_with_one_mesh() { + let mut h = harness(); + let (red, blue) = two_selected(&mut h); + let steps = history(&h); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.transform.warp", json!({})).unwrap(); + h.run_steps(2); + let t = h.state().ui.transform.clone().expect("warping"); + assert_eq!(t.layers.len(), 2); + assert_eq!(t.rect, [100.0, 100.0, 300.0, 250.0], "one mesh over both"); + let w = t.warp.expect("in Warp"); + // Slide the whole mesh 10 px right: a warp that moves both layers. + let mesh = w.mesh.clone().unwrap().map_points(|p| [p[0] + 10.0, p[1]]); + h.state_mut().ui.transform.as_mut().unwrap().warp = Some(photocraft_geom::warp::Warp::custom(mesh, t.rect)); + key(&mut h, Modifiers::NONE, Key::Enter); + assert!(h.state().ui.transform.is_none()); + assert_eq!(history(&h), steps + 1, "one Warp step"); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(110, 100, 210, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(260, 200, 310, 250)); + key(&mut h, Modifiers::COMMAND, Key::Z); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 200, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(250, 200, 300, 250)); +} + +#[test] +fn free_transform_a_copy_duplicates_every_selected_layer_and_moves_the_copies() { + let mut h = harness(); + let (red, blue) = two_selected(&mut h); + let steps = history(&h); + let count = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().doc.walk().len(); + let n = count(&h); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + h.run_steps(2); + let t = h.state().ui.transform.clone().expect("transforming"); + assert_eq!(t.layers.len(), 2, "both copies in the box"); + assert!(!t.layers.contains(&red) && !t.layers.contains(&blue), "the copies move, not the originals"); + assert_eq!(count(&h), n + 2); + h.state_mut().ui.transform.as_mut().unwrap().quad = shift_x(t.quad, 20.0); + key(&mut h, Modifiers::NONE, Key::Enter); + assert_eq!(history(&h), steps + 1, "the copies and their transform are one step"); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 200, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(250, 200, 300, 250)); + assert_eq!(bounds(&h, t.layers[0]), photocraft_geom::Rect::new(120, 100, 220, 160)); + assert_eq!(bounds(&h, t.layers[1]), photocraft_geom::Rect::new(270, 200, 320, 250)); + key(&mut h, Modifiers::COMMAND, Key::Z); + assert_eq!((count(&h), history(&h)), (n, steps), "one Undo takes both copies back"); + + // Esc takes the copies back too, leaving nothing to redo. + crate::menus::invoke(h.state_mut(), &ctx, "edit.freeTransformCopy", json!({})).unwrap(); + h.run_steps(2); + key(&mut h, Modifiers::NONE, Key::Escape); + assert_eq!((count(&h), history(&h)), (n, steps)); +} + +#[test] +fn flip_and_rotate_menu_items_turn_every_selected_layer_around_the_shared_box() { + let mut h = harness(); + let (red, blue) = two_selected(&mut h); + let steps = history(&h); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "edit.transform.flipHorizontal", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(history(&h), steps + 1); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(200, 100, 300, 160)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(100, 200, 150, 250)); + key(&mut h, Modifiers::COMMAND, Key::Z); + crate::menus::invoke(h.state_mut(), &ctx, "edit.transform.rotate180", json!({})).unwrap(); + h.run_steps(2); + assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(200, 190, 300, 250)); + assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(100, 100, 150, 150)); +} From 139ddc92fb065a0072ac828b3b26c524811a6cbe Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:20:55 +0200 Subject: [PATCH 3/5] fix(ui): multi-layer Free Transform sets main's new styled preview field to None (#3653) --- crates/ui-egui/src/transform_tool.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rs index bc84d72b89..75ff477c71 100644 --- a/crates/ui-egui/src/transform_tool.rs +++ b/crates/ui-egui/src/transform_tool.rs @@ -363,6 +363,9 @@ fn begin_many(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc, steps: Steps::default(), tool: app.ui.tool, many: Some(many), + // The composite is rendered with each layer's styles already (#3653's styled preview is + // for one unlifted layer). + styled: None, path: None, content_aware: None, }); From c55f84546f7f169d7bb9a71a5ae4fe0f7f38dded Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Fri, 30 Oct 2026 09:55:18 +0100 Subject: [PATCH 4/5] style: format reconciled multi-layer targets --- crates/engine/src/cmd/transform_cmds.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs index a4b6d264d3..6db3335646 100644 --- a/crates/engine/src/cmd/transform_cmds.rs +++ b/crates/engine/src/cmd/transform_cmds.rs @@ -306,10 +306,7 @@ pub(crate) fn layers_param(doc: &Document, p: &Value) -> Result Vec { - crate::layer_multi_cmds::top_level(doc, ids) - .into_iter() - .filter(|id| doc.layer(*id).is_some_and(|layer| !transform_bounds(doc, layer).is_empty())) - .collect() + crate::layer_multi_cmds::top_level(doc, ids).into_iter().filter(|id| doc.layer(*id).is_some_and(|layer| !transform_bounds(doc, layer).is_empty())).collect() } /// Content bounds of the explicitly selected transform targets. From 242b005a8b78d4800c77c962e8661965b5863aee Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 6 Nov 2026 23:05:59 +0100 Subject: [PATCH 5/5] PR #3597: drop multi-layer Warp, keep shared Flip/Rotate The reference application greys Edit > Transform > Warp and the Split Warp items with several layers selected (measured with two pixel layers), so the shared Warp this PR added is taken back out: main's rule (Warp greyed for a box over several layers) stays. This also removes the two open review findings (type inside a selected group, an already-warped smart object), which were only reachable through that shared Warp. Kept: Flip and Rotate presets turn every selected layer around the shared box in one step, which matches the reference application (Flip Horizontal on A+B flips both about their union, one "Flip Horizontal" step), plus the tests. A new UI test pins Warp greyed and Rotate/Flip enabled for two selected pixel layers. Co-Authored-By: FredApps <153173854+FredApps@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/transform_cmds.rs | 12 +-- .../transform_cmds/reconciliation_tests.rs | 69 +++------------ crates/engine/src/cmd/warp_cmds.rs | 87 +------------------ crates/ui-egui/src/menus/enable_rules.rs | 2 +- .../ui-egui/src/tools/transform_tool/begin.rs | 18 ++-- .../src/tools/transform_tool/commit.rs | 12 +-- .../ui-egui/src/tools/transform_tool/draw.rs | 2 +- crates/ui-egui/src/transform_several_tests.rs | 2 +- crates/ui-egui/src/transform_undo_tests.rs | 31 +++---- 9 files changed, 40 insertions(+), 195 deletions(-) diff --git a/crates/engine/src/cmd/transform_cmds.rs b/crates/engine/src/cmd/transform_cmds.rs index 0dae313727..8c5debe740 100644 --- a/crates/engine/src/cmd/transform_cmds.rs +++ b/crates/engine/src/cmd/transform_cmds.rs @@ -301,7 +301,7 @@ pub fn box_targets(doc: &Document, targets: &[LayerId]) -> Vec { /// The `layers` param: the layers one box transforms together (at most 10000, each in the /// document), without those a listed group carries. `None` when it isn't given. -pub(crate) fn layers_param(doc: &Document, p: &Value) -> Result>> { +fn layers_param(doc: &Document, p: &Value) -> Result>> { let a = match p.get("layers") { None | Some(Value::Null) => return Ok(None), Some(Value::Array(a)) if !a.is_empty() && a.len() <= 10_000 => a, @@ -320,16 +320,6 @@ pub(crate) fn layers_param(doc: &Document, p: &Value) -> Result Vec { - crate::layer_multi_cmds::top_level(doc, ids).into_iter().filter(|id| doc.layer(*id).is_some_and(|layer| !transform_bounds(doc, layer).is_empty())).collect() -} - -/// Content bounds of the explicitly selected transform targets. -pub fn multi_bounds(doc: &Document, ids: &[LayerId]) -> Rect { - transform_bounds_of(doc, ids) -} - /// The box Free Transform opens on the layers `ids` together: their frames ([`transform_frame`]) /// joined, as Show Transform Controls draws it. Empty when none of them has anything to move. pub fn transform_frame_of(doc: &Document, ids: &[LayerId]) -> Rect { diff --git a/crates/engine/src/cmd/transform_cmds/reconciliation_tests.rs b/crates/engine/src/cmd/transform_cmds/reconciliation_tests.rs index 28775fd0e6..04e990daae 100644 --- a/crates/engine/src/cmd/transform_cmds/reconciliation_tests.rs +++ b/crates/engine/src/cmd/transform_cmds/reconciliation_tests.rs @@ -39,7 +39,7 @@ fn bounds_of(s: &Session, id: LayerId) -> Rect { #[test] fn several_layers_scale_around_one_shared_frame_in_one_step() { let (mut s, a, b) = two_layers(); - assert_eq!(multi_bounds(&s.active().unwrap().doc, &[a, b]), Rect::new(10, 10, 80, 70)); + assert_eq!(transform_bounds_of(&s.active().unwrap().doc, &[a, b]), Rect::new(10, 10, 80, 70)); let steps = s.active().unwrap().history.entries().len(); // Halve the shared frame about its top-left corner. let r = s.execute("edit.transform", json!({"layers": [a.0, b.0], "quad": [[10, 10], [45, 10], [45, 40], [10, 40]]})).unwrap(); @@ -83,7 +83,6 @@ fn several_layers_refuse_when_one_is_locked_and_skip_the_empty() { let (mut s, a, b) = two_layers(); s.execute("layer.new.layer", json!({})).unwrap(); let empty = s.active().unwrap().active_layer.unwrap(); - assert_eq!(multi_targets(&s.active().unwrap().doc, &[a, b, empty]), vec![a, b]); s.edit("lock", |doc, _| { doc.layer_mut(b).unwrap().locks.position = true; Ok(()) @@ -118,60 +117,20 @@ fn flip_and_rotate_turn_every_selected_layer_around_the_shared_box() { } #[test] -fn warp_applies_one_shared_warp_to_every_listed_layer_in_one_step() { - let (mut s, a, b) = two_layers(); - let before = (bounds_of(&s, a), bounds_of(&s, b)); - let steps = s.active().unwrap().history.entries().len(); - let r = s.execute("edit.transform.warp", json!({"layers": [a.0, b.0], "style": "arc", "bend": 50})).unwrap(); - assert_eq!(r["rect"], json!([10, 10, 80, 70]), "the shared box"); - assert_ne!(bounds_of(&s, a), before.0); - assert_ne!(bounds_of(&s, b), before.1); - assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); +fn several_layers_convert_the_background_for_transform() { + let mut s = session(); + let bg = s.active().unwrap().doc.layers[0].id; + let layer = s.active().unwrap().active_layer.unwrap(); + assert!(s.active().unwrap().doc.is_background(bg)); + let before = s.active().unwrap().doc.clone(); + let steps = s.active().unwrap().history.past_len(); + s.execute("edit.transform", json!({"layers": [bg.0, layer.0], "dx": 5})).unwrap(); + let st = s.active().unwrap(); + assert!(!st.doc.is_background(bg)); + assert!(st.doc.layer(bg).unwrap().surface().unwrap().format().alpha); + assert_eq!(st.history.past_len(), steps + 1); s.execute("edit.undo", json!({})).unwrap(); - assert_eq!((bounds_of(&s, a), bounds_of(&s, b)), before); - // A locked layer refuses the whole warp. - s.edit("lock", |doc, _| { - doc.layer_mut(b).unwrap().locks.position = true; - Ok(()) - }) - .unwrap(); - assert!(s.execute("edit.transform.warp", json!({"layers": [a.0, b.0], "style": "arc", "bend": 50})).is_err()); - assert_eq!(bounds_of(&s, a), before.0); -} - -#[test] -fn several_layers_convert_the_background_for_transform_and_warp() { - for warp in [false, true] { - let mut s = session(); - let bg = s.active().unwrap().doc.layers[0].id; - let layer = s.active().unwrap().active_layer.unwrap(); - assert!(s.active().unwrap().doc.is_background(bg)); - let before = s.active().unwrap().doc.clone(); - let steps = s.active().unwrap().history.past_len(); - if warp { - s.execute("edit.transform.warp", json!({"layers": [bg.0, layer.0], "style": "arc", "bend": 20})).unwrap(); - } else { - s.execute("edit.transform", json!({"layers": [bg.0, layer.0], "dx": 5})).unwrap(); - } - let st = s.active().unwrap(); - assert!(!st.doc.is_background(bg)); - assert!(st.doc.layer(bg).unwrap().surface().unwrap().format().alpha); - assert_eq!(st.history.past_len(), steps + 1); - s.execute("edit.undo", json!({})).unwrap(); - assert!(s.active().unwrap().doc == before); - } -} - -#[test] -fn an_empty_warp_target_list_never_falls_back_to_the_active_layer() { - for layers in [json!([]), json!([u64::MAX]), json!(["invalid"])] { - let mut s = session(); - let before = s.active().unwrap().doc.clone(); - let steps = s.active().unwrap().history.past_len(); - assert!(s.execute("edit.transform.warp", json!({"layers": layers, "style": "arc", "bend": 50})).is_err()); - assert!(s.active().unwrap().doc == before); - assert_eq!(s.active().unwrap().history.past_len(), steps); - } + assert!(s.active().unwrap().doc == before); } #[test] diff --git a/crates/engine/src/cmd/warp_cmds.rs b/crates/engine/src/cmd/warp_cmds.rs index 37a6eb72d5..4b94af82a9 100644 --- a/crates/engine/src/cmd/warp_cmds.rs +++ b/crates/engine/src/cmd/warp_cmds.rs @@ -381,72 +381,6 @@ fn target(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, Rect)> { Ok((id, rect)) } -/// Warp of several layers at once (#3592): one warp over the shared frame (the union of each -/// layer's [`warp_bounds`] unless `rect` is given), applied to every layer, one step. -fn apply_many(s: &mut Session, p: &Value, cmd: &str, ids: Vec) -> Result { - let st = s.active().ok_or(EngineError::NoDocument)?; - if let Some(l) = ids.iter().find(|&&id| crate::transform_cmds::locked_for_transform(&st.doc, id)).and_then(|&id| st.doc.layer(id)) { - return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name))); - } - let rect = match p.get("rect").and_then(Value::as_array) { - Some(r) if r.len() == 4 => { - let v: Vec = r.iter().map(|x| x.as_f64().unwrap_or(0.0).round() as i32).collect(); - Rect::new(v[0], v[1], v[2], v[3]) - } - _ => ids.iter().filter_map(|&id| st.doc.layer(id)).fold(Rect::EMPTY, |r, l| r.union(&warp_bounds(&st.doc, l))), - }; - if rect.is_empty() { - return Err(bad(cmd, "nothing to warp")); - } - if rect.width() > MAX_WARP_SIDE || rect.height() > MAX_WARP_SIDE { - return Err(bad(cmd, format!("rect too large for warp: {} x {} (max {MAX_WARP_SIDE} per side)", rect.width(), rect.height()))); - } - let w = warp_from_params(cmd, p, rect_f(rect))?; - let out = ids.iter().map(|l| l.0).collect::>(); - if w.is_identity() { - return Ok(json!({"layers": out, "changed": false})); - } - 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(); - crate::jobs::edit_job( - s, - "Warp", - move |doc, _, ctx| { - ctx.stage(0.0, 1.0, "Warping", |ctl| { - let sel = doc.selection.clone(); - let frames = content_knots.then(|| { - let mut f = Frames::new(); - for &id in &ids { - if let Some(l) = doc.layer(id) { - source_frames(doc, l, &mut f); - } - } - f - }); - for &id in &ids { - cancelled(ctl)?; - 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(); - for &id in &ids { - 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(()) - }) - }, - move |()| json!({"layers": out, "changed": true, "rect": [rect.x0, rect.y0, rect.x1, rect.y1]}), - ) -} - /// The Warp Text settings a transform warp gives a type layer: a preset style (or none) keeps the /// type editable, as Photoshop's Edit › Transform › Warp on type does (#3004). fn type_warp(cmd: &str, w: &Warp) -> Result> { @@ -490,25 +424,6 @@ fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp) -> Result< } fn apply(s: &mut Session, p: &Value, cmd: &str) -> Result { - if cmd == "edit.transform.warp" - && let Some(ids) = crate::transform_cmds::layers_param(&s.active().ok_or(EngineError::NoDocument)?.doc, p)? - { - if !matches!(p.get("layer"), None | Some(Value::Null)) || p.get("target").is_some() { - return Err(bad(cmd, "pass layers without a layer or channel target")); - } - let many = crate::transform_cmds::multi_targets(&s.active().ok_or(EngineError::NoDocument)?.doc, &ids); - if many.len() > 1 { - return apply_many(s, p, cmd, many); - } - let id = many.first().ok_or_else(|| bad(cmd, "nothing to warp"))?; - let mut one = p.clone(); - if let Some(params) = one.as_object_mut() { - params.remove("layers"); - params.insert("layer".into(), json!(id.0)); - } - return apply(s, &one, cmd); - } - let (id, rect) = target(s, cmd, p)?; let w = warp_from_params(cmd, p, rect_f(rect))?; if matches!(s.active().and_then(|d| d.doc.layer(id)).map(|l| &l.content), Some(LayerContent::Text(_))) { @@ -732,7 +647,7 @@ fn grid(s: &mut Session, p: &Value) -> Result { } pub fn specs() -> Vec { - const P: &str = r##"{"layer":id?,"layers":[id]? (edit.transform.warp: shared frame, one undo step),"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist|cylinder","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"values":[left,bottom,right,top,topDepth,bottomDepth,wrap]? (cylinder: silhouettes and edges in document px, the ellipses' depths in half-axis units, wrap 0..1; horizontal only),"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px; on a smart object `us`/`vs` span the source contents, so points equal to the placement are an identity warp even when it is skewed),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"} — on a type layer a style (or none) sets its Warp Text and the type stays editable"##; + const P: &str = r##"{"layer":id?,"rect":[x0,y0,x1,y1]? (warp box; default = layer content ∩ selection),"style":"custom|none|arc|arcLower|arcUpper|arch|bulge|shellLower|shellUpper|flag|wave|fish|rise|fisheye|inflate|squeeze|twist|cylinder","bend":%=50,"hDistort":%,"vDistort":%,"vertical":bool,"values":[left,bottom,right,top,topDepth,bottomDepth,wrap]? (cylinder: silhouettes and edges in document px, the ellipses' depths in half-axis units, wrap 0..1; horizontal only),"mesh":{"us":[0,…,1],"vs":[0,…,1],"points":[[x,y]…]} ((3c+1)×(3r+1) control points, row-major, document px; on a smart object `us`/`vs` span the source contents, so points equal to the placement are an identity warp even when it is skewed),"grid":[cols,rows]?,"warp":{full warp object}?,"interpolation":"bicubic|bilinear|nearest"} — on a type layer a style (or none) sets its Warp Text and the type stays editable"##; const S: &str = r##"{"warp":{…}? (the warp being edited; returned split),"rect":[x0,y0,x1,y1]?,"at":[x,y]? (document point; default = middle of the patch)} — without `warp`, edits the active smart object's warp. A 1×1 custom mesh is divided at the thirds first (the guides drawn on the default grid), so splitWarpCrosswise on an identity custom warp returns a 4×4 mesh (knots at 0, 1/3, 1/2, 2/3 and 1), not a 2×2. A preset is fitted as one patch and split without that step."##; const G: &str = r##"{"warp":{…}? (the warp being edited; returned with the new mesh),"rect":[x0,y0,x1,y1]?,"size":n|"default"|"3"|"4"|"5" (square patches, 1..=64; 1 and "default" are the single-patch grid)} — without `warp`/`style`/`mesh`, edits the active smart object's warp. The surface is kept and the new lines are real splits at i/n."##; vec![ diff --git a/crates/ui-egui/src/menus/enable_rules.rs b/crates/ui-egui/src/menus/enable_rules.rs index 207a921dcb..1060107d79 100644 --- a/crates/ui-egui/src/menus/enable_rules.rs +++ b/crates/ui-egui/src/menus/enable_rules.rs @@ -141,7 +141,7 @@ pub fn disabled(app: &crate::PhotocraftApp, id: &str) -> bool { | "edit.transform.splitWarpCrosswise" | "edit.transform.splitWarpHorizontally" | "edit.transform.splitWarpVertically" - | "edit.transform.removeWarpSplit" => text, + | "edit.transform.removeWarpSplit" => true, "edit.transform.distort" | "edit.transform.perspective" => text, _ => false, }; diff --git a/crates/ui-egui/src/tools/transform_tool/begin.rs b/crates/ui-egui/src/tools/transform_tool/begin.rs index cda8d6c491..3ab5f513a1 100644 --- a/crates/ui-egui/src/tools/transform_tool/begin.rs +++ b/crates/ui-egui/src/tools/transform_tool/begin.rs @@ -250,7 +250,7 @@ pub(super) fn moves_kind(app: &PhotocraftApp, t: &TransformSession, kind: fn(&La app.session.active().is_some_and(|st| moving_layers(t).iter().any(|id| st.doc.layer(*id).is_some_and(|l| kind(&l.content)))) } -/// Why a shared warp containing editable type is refused. +/// Why Warp refuses with several layers selected. pub const WARP_ONE_LAYER: &str = "Warp works on one layer at a time: select a single layer"; /// Free Transform on a copy (⌥⌘T, no menu item): duplicates the active layer (with a selection, @@ -654,13 +654,13 @@ pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St if app.ui.transform.as_ref().is_some_and(|t| t.content_aware.is_some()) { return Err(CAS_ONLY_SCALES.into()); } - if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty() && super::commit::moves_type(app, t)) { + if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty()) { return Err(WARP_ONE_LAYER.into()); } let fresh = app.ui.transform.is_none(); if fresh { begin(app, ctx)?; - if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty() && super::commit::moves_type(app, t)) { + if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty()) { cancel(app); return Err(WARP_ONE_LAYER.into()); } @@ -678,20 +678,18 @@ pub fn begin_warp(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), St /// gets its own Warp Text style instead ([`enter_type_warp`]). pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { // Several layers keep the box (#6501), even when the active one is type. - if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty() && super::commit::moves_type(app, t)) { + if app.ui.transform.as_ref().is_some_and(|t| !t.layers.is_empty()) { return; } if app.ui.transform.as_ref().is_some_and(|t| t.warp.is_none()) && warps_type(app) { return enter_type_warp(app, ctx); } - let existing = app.session.active().and_then(|d| { - let t = app.ui.transform.as_ref().filter(|t| t.layers.is_empty())?; - d.doc.layer(LayerId(t.layer)).and_then(photocraft_engine::warp_cmds::smart_warp_doc_space) - }); + 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 and paths (#3027): a lone mask or channel keeps the box, and so do // several layers (#6501). - if t.warp.is_some() || t.target.is_some() { + if t.warp.is_some() || t.target.is_some() || !t.layers.is_empty() { return; } if t.quad == corners(t.rect) @@ -716,7 +714,7 @@ pub fn enter_warp(app: &mut PhotocraftApp, ctx: &egui::Context) { /// the selection). Its Warp is Warp Text: only the styles, and the type stays editable (#3004). pub fn warps_type(app: &PhotocraftApp) -> bool { let Some(t) = &app.ui.transform else { return false }; - if t.selection || t.target.is_some() || t.path.is_some() || !t.layers.is_empty() { + if t.selection || t.target.is_some() || t.path.is_some() { return false; } app.session.active().and_then(|st| st.doc.layer(LayerId(t.layer))).is_some_and(|l| matches!(l.content, LayerContent::Text(_))) diff --git a/crates/ui-egui/src/tools/transform_tool/commit.rs b/crates/ui-egui/src/tools/transform_tool/commit.rs index f8f646ef8d..dcdbf2a099 100644 --- a/crates/ui-egui/src/tools/transform_tool/commit.rs +++ b/crates/ui-egui/src/tools/transform_tool/commit.rs @@ -76,13 +76,7 @@ pub fn commit(app: &mut PhotocraftApp) { if w.is_identity() && !type_layer { return; } - let mut p = json!({"rect": t.rect, "warp": w, "interpolation": t.interpolation}); - if t.layers.is_empty() { - p["layer"] = json!(t.layer); - } else { - p["layers"] = json!(t.layers); - } - app.run("edit.transform.warp", p) + app.run("edit.transform.warp", json!({"layer": t.layer, "rect": t.rect, "warp": w, "interpolation": t.interpolation})) } else { if t.quad == corners(t.rect) { return; // untouched: nothing to do and no history step; a ⌥⌘T copy or a place stays @@ -339,14 +333,14 @@ pub fn is_enabled(app: &PhotocraftApp, id: &str) -> Option { SAVE_FOR_WEB => Some(false), // Rotate and Flip turn the box (not while warping, where the mesh is the box). _ if box_preset(id).is_some() => Some(t.warp.is_none()), - // Editable type among shared targets cannot take a mesh warp. + // One box over several layers doesn't warp (#6501). "edit.transform.warp" | "layer.smartObjects.warp" | "edit.transform.splitWarpCrosswise" | "edit.transform.splitWarpHorizontally" | "edit.transform.splitWarpVertically" | "edit.transform.removeWarpSplit" - if !t.layers.is_empty() && moves_type(app, t) => + if !t.layers.is_empty() => { Some(false) } diff --git a/crates/ui-egui/src/tools/transform_tool/draw.rs b/crates/ui-egui/src/tools/transform_tool/draw.rs index 85b3a3ed82..544e7a8359 100644 --- a/crates/ui-egui/src/tools/transform_tool/draw.rs +++ b/crates/ui-egui/src/tools/transform_tool/draw.rs @@ -524,7 +524,7 @@ fn draw_warp_content( pv: &TransformPreview, display: Option<&photocraft_engine::display_color::CanvasDisplay>, ) { - let r = pv.several.as_ref().map_or(t.rect, |sv| [sv.rect.x0, sv.rect.y0, sv.rect.x1, sv.rect.y1].map(f64::from)); + let r = t.rect; let m = w.to_mesh(1, 1); let (us, vs) = crate::warp_preview::samples(&m, xf.zoom as f64); let (tex, uv) = pv.texture.pick_display(painter.ctx(), xf.zoom * painter.ctx().pixels_per_point(), 1.0, t.interpolation == "nearest", display); diff --git a/crates/ui-egui/src/transform_several_tests.rs b/crates/ui-egui/src/transform_several_tests.rs index bb65b9b2bd..ee593e341f 100644 --- a/crates/ui-egui/src/transform_several_tests.rs +++ b/crates/ui-egui/src/transform_several_tests.rs @@ -124,7 +124,7 @@ fn warp_is_greyed_and_distort_too_while_type_is_among_them() { app.run("layer.select", json!({"layer": paint.0, "mode": "add"})).unwrap(); assert_eq!(app.session.active().unwrap().selected_layers().len(), 2); assert!(crate::menus::is_enabled(&app, "edit.transform.distort") && crate::menus::is_enabled(&app, "edit.transform.perspective")); - assert!(crate::menus::is_enabled(&app, "edit.transform.warp")); + assert!(!crate::menus::is_enabled(&app, "edit.transform.warp")); } #[test] diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 8c598bee3a..af1eea10ea 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -476,28 +476,17 @@ fn shift_x(q: [[f64; 2]; 4], dx: f64) -> [[f64; 2]; 4] { } #[test] -fn warp_with_several_layers_warps_them_all_with_one_mesh() { +fn several_layers_grey_warp_but_not_rotate_and_flip() { + // As in the reference application: Edit › Transform › Warp and its split items are greyed + // with two pixel layers selected; Rotate and Flip turn both around the shared box. let mut h = harness(); - let (red, blue) = two_selected(&mut h); - let steps = history(&h); - let ctx = h.ctx.clone(); - crate::menus::invoke(h.state_mut(), &ctx, "edit.transform.warp", json!({})).unwrap(); - h.run_steps(2); - let t = h.state().ui.transform.clone().expect("warping"); - assert_eq!(t.layers.len(), 2); - assert_eq!(t.rect, [100.0, 100.0, 300.0, 250.0], "one mesh over both"); - let w = t.warp.expect("in Warp"); - // Slide the whole mesh 10 px right: a warp that moves both layers. - let mesh = w.mesh.clone().unwrap().map_points(|p| [p[0] + 10.0, p[1]]); - h.state_mut().ui.transform.as_mut().unwrap().warp = Some(photocraft_geom::warp::Warp::custom(mesh, t.rect)); - key(&mut h, Modifiers::NONE, Key::Enter); - assert!(h.state().ui.transform.is_none()); - assert_eq!(history(&h), steps + 1, "one Warp step"); - assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(110, 100, 210, 160)); - assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(260, 200, 310, 250)); - key(&mut h, Modifiers::COMMAND, Key::Z); - assert_eq!(bounds(&h, red), photocraft_geom::Rect::new(100, 100, 200, 160)); - assert_eq!(bounds(&h, blue), photocraft_geom::Rect::new(250, 200, 300, 250)); + two_selected(&mut h); + for id in ["edit.transform.warp", "edit.transform.splitWarpCrosswise", "edit.transform.removeWarpSplit"] { + assert!(!crate::menus::is_enabled(h.state(), id), "{id}"); + } + for id in ["edit.transform.flipHorizontal", "edit.transform.flipVertical", "edit.transform.rotate180", "edit.transform.rotate90Cw"] { + assert!(crate::menus::is_enabled(h.state(), id), "{id}"); + } } #[test]