Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Move tool: moving several layers carries the selection with them (#7538)

Hector Villarrealdf94c0442bb1
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index cd7f5d606..3e9cff45c 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1120,7 +1120,7 @@ fn build() -> Vec<CommandSpec> {
"Move Layer",
[],
None,
- r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels"} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer)"##,
+ r##"{"layer":id?,"dx":i32,"dy":i32,"units":"px"|"pt"="px" (pt: points, whole pixels at the document's resolution),"target":"pixels"|"mask"="pixels","selection":bool=false} (no layer: every selected layer; linked layers follow; target mask: a layer whose mask is unlinked moves that mask alone, a linked mask moves with the layer; selection: the selection moves too, in the same step)"##,
has_layer,
crate::layer_multi_cmds::translate
),
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 1b71e966a..aadb4023f 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -372,6 +372,10 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
return Err(EngineError::Other("no active layer".into()));
}
let mask_target = p.get("target").and_then(Value::as_str) == Some("mask");
+ let carry = match p.get("selection") {
+ None | Some(Value::Null) => false,
+ Some(v) => v.as_bool().ok_or_else(|| bad("layer.translate", "`selection` must be a boolean"))?,
+ };
let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let ids = s.edit("Move", |doc, _| {
let (alone, rest): (Vec<LayerId>, Vec<LayerId>) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone));
@@ -396,6 +400,11 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {
if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {
crate::artboard_cmds::fit_canvas(doc);
}
+ // The Move tool carries the selection along when it moves several layers whole, as
+ // Photoshop does (#7538): one step, so Undo takes both back.
+ if carry {
+ doc.selection = doc.selection.as_ref().map(|sel| shift_surface(sel, dx, dy));
+ }
Ok(ids)
})?;
note_damage(s, &before, &ids);
@@ -2725,4 +2734,32 @@ mod tests {
assert_eq!(v["selectedLayers"], json!([a.0, b.0]));
assert_eq!(v["layers"][0]["selected"], true);
}
+
+ /// #7538: `selection: true` moves the selection with the layers in the same step, as the Move
+ /// tool does with several layers selected; without it the selection stays.
+ #[test]
+ fn translate_can_carry_the_selection_in_the_same_step() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 100, "height": 100, "background": "transparent"})).unwrap();
+ let a = s.active().unwrap().active_layer.unwrap();
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ let b = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap());
+ s.execute("select.rect", json!({"x": 50, "y": 10, "width": 20, "height": 20})).unwrap();
+ s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ s.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap();
+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 70, "height": 30})).unwrap();
+ let sel = |s: &Session| s.active().unwrap().doc.selection.as_ref().map(|m| m.content_bounds());
+ let bounds = |s: &Session, id: LayerId| s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().content_bounds();
+ let steps = s.active().unwrap().history.past_len();
+ s.execute("layer.translate", json!({"dx": 7, "dy": 20, "selection": true})).unwrap();
+ assert_eq!((bounds(&s, a), bounds(&s, b)), (Rect::new(17, 30, 37, 50), Rect::new(57, 30, 77, 50)));
+ assert_eq!(sel(&s), Some(Rect::new(12, 25, 82, 55)), "the selection came along");
+ assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step");
+ s.undo();
+ assert_eq!((sel(&s), bounds(&s, a)), (Some(Rect::new(5, 5, 75, 35)), Rect::new(10, 10, 30, 30)), "undone together");
+ s.execute("layer.translate", json!({"dx": 7, "dy": 20})).unwrap();
+ assert_eq!(sel(&s), Some(Rect::new(5, 5, 75, 35)), "without it the selection stays");
+ assert!(s.execute("layer.translate", json!({"dx": 1, "selection": "yes"})).is_err(), "a bad `selection` is an error");
+ }
}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index e642f6234..3267c409c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -5784,7 +5784,18 @@ pub(crate) fn floating_outline(app: &PhotocraftApp, idx: usize) -> Option<photoc
/// Where the selection is drawn relative to where it is: a floating piece's offset plus a drag
/// in progress.
fn selection_shown_offset(app: &PhotocraftApp) -> Option<(i32, i32)> {
- crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app))
+ crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app)).or_else(|| carried_selection_delta(app))
+}
+
+/// Whole-pixel offset of a Move drag of several layers, which carries the selection along
+/// (`move_ui::carries_selection`): their ants follow the layers while they move (#7538).
+fn carried_selection_delta(app: &PhotocraftApp) -> Option<(i32, i32)> {
+ let d = app.drag.as_ref().filter(|d| d.tool == Tool::Move && d.sel_move.is_none())?;
+ if !crate::move_ui::carries_selection(app) {
+ return None;
+ }
+ let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]);
+ Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32))
}
/// End of a selection drag: move the outline, or the floating piece. A click without moving
@@ -8415,6 +8426,41 @@ mod transform_controls_tests {
assert_eq!(frame(&app), [50, 45, 100, 85], "dropped");
}
+ /// #7538: with several layers selected the Move tool moves them whole, and the selection goes
+ /// with them, as in Photoshop: its ants follow the drag and it lands with them in one step.
+ #[test]
+ fn moving_several_layers_carries_the_selection() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 200, "background": "transparent"})).unwrap();
+ let a = app.session.active().unwrap().active_layer.unwrap();
+ app.session.execute("select.rect", json!({"x": 40, "y": 40, "width": 50, "height": 40})).unwrap();
+ app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ app.session.execute("layer.new.layer", json!({})).unwrap();
+ app.session.execute("select.rect", json!({"x": 120, "y": 120, "width": 30, "height": 30})).unwrap();
+ app.session.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
+ app.session.execute("layer.select", json!({"layer": a.0, "mode": "add"})).unwrap();
+ app.session.execute("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap();
+ app.sync_views();
+ app.ui.tool = Tool::Move;
+ app.ui.tool_options.move_auto_select = false;
+ app.ui.extras.snap = false;
+ app.ui.view.show.smart_guides = false;
+ let steps = app.session.active().unwrap().history.past_len();
+ let m = egui::Modifiers::NONE;
+ tool_event(&mut app, ToolEvent::Down { x: 60.0, y: 60.0, pressure: 1.0 }, m);
+ tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 68.0, pressure: 1.0 }, m);
+ assert_eq!(selection_shown_offset(&app), Some((12, 8)), "the ants follow the layers");
+ tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 68.0 }, m);
+ let st = app.session.active().unwrap();
+ assert!(photocraft_engine::float_cmds::floating(st).is_none(), "whole layers moved, nothing floats");
+ assert_eq!(st.doc.selection.as_ref().map(|s| s.content_bounds()), Some(photocraft_geom::Rect::new(32, 28, 132, 118)));
+ assert_eq!(st.doc.layer(a).unwrap().surface().unwrap().content_bounds(), photocraft_geom::Rect::new(52, 48, 102, 88));
+ assert_eq!(st.history.past_len(), steps + 1, "one Move step");
+ assert!(app.session.undo());
+ let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds());
+ assert_eq!(sel, Some(photocraft_geom::Rect::new(20, 20, 120, 110)), "Undo takes the selection back too");
+ }
+
/// A transparent 200² document: a red square (40..90, 40..80) on its layer, a loose marquee
/// (20..120, 20..110) round it, cut and floated 10, 5 to the right and down.
fn floating_square() -> PhotocraftApp {
diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rs
index 86e567521..f0b857e01 100644
--- a/crates/ui-egui/src/move_ui.rs
+++ b/crates/ui-egui/src/move_ui.rs
@@ -259,6 +259,13 @@ pub(crate) fn is_preview_key(key: u64) -> bool {
key > BASE && key < BASE << 1
}
+/// Does a Move drag of whole layers take the selection along? With several layers selected, as
+/// in Photoshop (#7538): their selected pixels can't float, so the layers move and the marching
+/// ants follow them.
+pub(crate) fn carries_selection(app: &PhotocraftApp) -> bool {
+ app.session.active().is_some_and(|st| st.doc.selection.is_some() && st.selected_layers().len() > 1)
+}
+
/// Release: one `layer.translate` by the drag's offset. The canvas already shows the result, so
/// its caches are told it showed the document: the command's damage rect refreshes that area.
pub(crate) fn finish(app: &mut PhotocraftApp, dx: f64, dy: f64) {
@@ -268,7 +275,7 @@ pub(crate) fn finish(app: &mut PhotocraftApp, dx: f64, dy: f64) {
if dx == 0.0 && dy == 0.0 {
return;
}
- if app.run("layer.translate", json!({"dx": dx, "dy": dy})).is_err() {
+ if app.run("layer.translate", json!({"dx": dx, "dy": dy, "selection": carries_selection(app)})).is_err() {
return;
}
let Some(p) = shown else { return };
diff --git a/docs/ui-parity.md b/docs/ui-parity.md
index 008204400..a21c9b84e 100644
--- a/docs/ui-parity.md
+++ b/docs/ui-parity.md
@@ -95,6 +95,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme
| ⌘-arrow nudges the layer from any tool | missing | #2474 |
| ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` |
| Dragging selected pixels shrinks the selection to them (the selection limited to where the layer has pixels, so moving again leaves no edge behind) as the drag starts, also with ⌥; the move box, snapping and Show Transform Controls use the moved pixels' bounds | done | #7538, `canvas.rs` `floating_outline` and `transform_controls_rect`, `snap_ui.rs` `follow_cut`, engine `float_cmds.rs` `CutParts::outline` |
+| With several layers selected and a selection, the Move tool moves the layers whole and the selection with them (ants follow the drag; one Move step) | done | #7538, `move_ui.rs` `carries_selection`, engine `layer.translate` `selection` |
| Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 |
| Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) |
| Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline | partial: the shared frame has no handles, since Free Transform works on one layer (`canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_without_handles`; `move_auto_select_tests.rs`) | |