Skip to content

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

Layers panel: Alt-drag a row to copy the layer there, as in Photoshop (#1216)

Ca11MeZaMalkob8235e132a42
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index d3beb6dbd..a1ea1928d 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -471,14 +471,7 @@ fn build() -> Vec<CommandSpec> {
}
let id = layer_param(s, p)?;
let nid = s.edit("Duplicate Layer", |doc, active| {
- let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
- // A copy of the Background layer is an ordinary, unlocked layer (Photoshop).
- let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id);
- let mut dup = src.duplicate();
- dup.name = doc.copy_name(&dup.name);
- if from_background {
- dup.locks = Default::default();
- }
+ let dup = layer_copy(doc, id)?;
let nid = doc.insert_above(Some(id), dup);
*active = Some(nid);
Ok(nid)
@@ -724,7 +717,7 @@ fn build() -> Vec<CommandSpec> {
"Reorder Layer",
[],
None,
- r##"{"layer":id?| "layers":[id,…]?, "target":id,"position":"above|below|into"="above"} (layers: one undoable move, document order preserved)"##,
+ r##"{"layer":id?| "layers":[id,…]?, "target":id,"position":"above|below|into"="above","copy":bool=false} (layers: one undoable move, document order preserved; copy: place duplicates there and leave the layers, as ⌥-dragging a Layers panel row)"##,
has_layer,
crate::layer_multi_cmds::move_to
),
@@ -1179,3 +1172,18 @@ pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {
_ => {}
}
}
+
+/// A copy of layer `id` as Layer › Duplicate Layer makes it, not yet in the document: a fresh id,
+/// "… copy" appended to the name, and a copy of the Background layer is an ordinary, unlocked
+/// layer (Photoshop).
+pub(crate) fn layer_copy(doc: &Document, id: LayerId) -> Result<Layer> {
+ let src = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ // A copy of the Background layer is an ordinary, unlocked layer (Photoshop).
+ let from_background = src.name == "Background" && src.locks.transparency && doc.layers.first().is_some_and(|b| b.id == id);
+ let mut dup = src.duplicate();
+ dup.name = doc.copy_name(&dup.name);
+ if from_background {
+ dup.locks = Default::default();
+ }
+ Ok(dup)
+}
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index a0f33b117..f9634d2f5 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -783,6 +783,8 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(pos, "above" | "below" | "into") {
return Err(bad(CMD, "position must be above, below, or into"));
}
+ // ⌥-drag in the Layers panel: duplicates land at the target and the layers stay put.
+ let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false);
let batch = p.get("layers");
if batch.is_some() && p.get("layer").is_some() {
@@ -811,14 +813,16 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let moved_ids = top_level(doc, &requested);
- if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() {
+ if moved_ids.len() == 1 && moved_ids[0] == target && batch.is_none() && !copy {
// Preserve single-layer drag-to-self semantics.
return Ok(Value::Null);
}
// Also rejects dragging a selected group onto any of its descendants.
for id in &moved_ids {
let path = doc.path_of(*id).ok_or(EngineError::NoLayer(*id))?;
- if target_path.starts_with(&path) {
+ // A copy may land beside its own source (not inside it).
+ let beside_itself = copy && *id == target && pos != "into";
+ if target_path.starts_with(&path) && !beside_itself {
return Err(bad(CMD, "target cannot be one of the moved layers or its descendant"));
}
}
@@ -827,11 +831,12 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
}
let original_active = st.active_layer;
- let count = s.edit("Reorder Layers", |doc, active| {
+ let (count, copies) = s.edit(if copy { "Duplicate Layer" } else { "Reorder Layers" }, |doc, active| {
let mut moved = Vec::with_capacity(moved_ids.len());
for &id in &moved_ids {
- moved.push(doc.remove(id).ok_or(EngineError::NoLayer(id))?);
+ moved.push(if copy { crate::commands::layer_copy(doc, id)? } else { doc.remove(id).ok_or(EngineError::NoLayer(id))? });
}
+ let copies: Vec<LayerId> = if copy { moved.iter().map(|l| l.id).collect() } else { Vec::new() };
// Look up the destination AFTER removing every source: its indices may have shifted.
let path = doc.path_of(target).ok_or(EngineError::NoLayer(target))?;
if pos == "into" {
@@ -848,13 +853,24 @@ pub fn move_to(s: &mut Session, p: &Value) -> Result<Value> {
siblings.splice(at..at, moved);
}
check_group_depth(doc, "Reorder Layer")?;
- *active = if batch.is_some() {
+ *active = if copy {
+ copies.last().copied()
+ } else if batch.is_some() {
original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied())
} else {
moved_ids.first().copied()
};
- Ok(moved_ids.len())
+ Ok((moved_ids.len(), copies))
})?;
+ if copy {
+ let ids: Vec<u64> = copies.iter().map(|id| id.0).collect();
+ if batch.is_some() {
+ let active = copies.last().copied();
+ reselect(s, copies, active);
+ return Ok(json!({"moved": count, "layers": ids}));
+ }
+ return Ok(json!({"layer": ids.first()}));
+ }
if batch.is_some() {
let active = original_active.filter(|id| requested.contains(id)).or_else(|| requested.last().copied());
reselect(s, requested, active);
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 9deeea251..c553c383f 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -636,6 +636,73 @@ fn move_to_reorders_and_nests() {
assert_eq!(names(&s), ["Background", "B", "A", "G"]);
}
+/// ⌥-dragging a Layers panel row: `copy` leaves the layer where it is and drops a duplicate at the
+/// target, as one "Duplicate Layer" step, with the copy active.
+#[test]
+fn move_to_copy_places_a_duplicate_in_one_step() {
+ let mut s = session_with_doc();
+ let a = s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
+ let b = s.execute("layer.new.layer", json!({"name": "B"})).unwrap()["layer"].as_u64().unwrap();
+ let g = s.execute("layer.new.group", json!({"name": "G"})).unwrap()["layer"].as_u64().unwrap();
+ let names = |s: &Session| s.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
+ let steps = |s: &Session| s.active().unwrap().history.past_len();
+ let before = steps(&s);
+ // bottom->top: Background, A, B, G ; copy A above B
+ let r = s.execute("layer.moveTo", json!({"layer": a, "target": b, "position": "above", "copy": true})).unwrap();
+ let copy = r["layer"].as_u64().expect("the copy's id");
+ assert_ne!(copy, a);
+ assert_eq!(names(&s), ["Background", "A", "B", "A copy", "G"]);
+ assert_eq!(steps(&s), before + 1, "one history step");
+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Duplicate Layer"));
+ assert_eq!(s.active().unwrap().active_layer, Some(photocraft_doc::LayerId(copy)), "the copy is active");
+ let doc = &s.active().unwrap().doc;
+ let (orig, dup) = (doc.layer(photocraft_doc::LayerId(a)).unwrap(), doc.layer(photocraft_doc::LayerId(copy)).unwrap());
+ assert_eq!(orig.content, dup.content, "the pixels are copied");
+ // Below and into a group.
+ s.execute("layer.moveTo", json!({"layer": b, "target": a, "position": "below", "copy": true})).unwrap();
+ assert_eq!(names(&s), ["Background", "B copy", "A", "B", "A copy", "G"]);
+ s.execute("layer.moveTo", json!({"layer": a, "target": g, "position": "into", "copy": true})).unwrap();
+ // `document.inspect` lists the top of the stack first; "A copy" is taken, so this is "A copy 2".
+ assert_eq!(s.execute("document.inspect", json!({})).unwrap()["layers"][0]["children"][0]["name"], "A copy 2");
+ // A group can be copied beside itself, but not into itself.
+ s.execute("layer.moveTo", json!({"layer": g, "target": g, "position": "above", "copy": true})).unwrap();
+ assert_eq!(names(&s).last().map(String::as_str), Some("G copy"));
+ let past = steps(&s);
+ assert!(s.execute("layer.moveTo", json!({"layer": g, "target": g, "position": "into", "copy": true})).is_err());
+ assert_eq!(steps(&s), past, "a refused copy records nothing");
+ // A copy of the Background is an ordinary, unlocked layer.
+ let bg = s.active().unwrap().doc.layers[0].id.0;
+ s.execute("layer.moveTo", json!({"layer": bg, "target": b, "position": "above", "copy": true})).unwrap();
+ let doc = &s.active().unwrap().doc;
+ let bg_copy = doc.layers.iter().find(|l| l.name == "Background copy").expect("a Background copy");
+ assert!(!bg_copy.locks.transparency);
+ assert!(doc.layers[0].locks.transparency, "the Background keeps its lock");
+ // Undo removes each copy and nothing else.
+ for _ in 0..5 {
+ s.execute("edit.undo", json!({})).unwrap();
+ }
+ assert_eq!(names(&s), ["Background", "A", "B", "G"]);
+}
+
+#[test]
+fn move_to_copy_rejects_bad_params() {
+ let mut s = session_with_doc();
+ let a = s.execute("layer.new.layer", json!({"name": "A"})).unwrap()["layer"].as_u64().unwrap();
+ let past = s.active().unwrap().history.past_len();
+ for p in [
+ json!({"layer": a, "copy": true}),
+ json!({"layer": a, "target": "x", "copy": true}),
+ json!({"layer": a, "target": 9_999_999, "copy": true}),
+ json!({"layer": 9_999_999, "target": a, "copy": true}),
+ json!({"layer": a, "target": a, "position": "into", "copy": true}),
+ ] {
+ assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}");
+ }
+ assert_eq!(s.active().unwrap().history.past_len(), past, "no history step recorded");
+ assert_eq!(s.active().unwrap().doc.layers.len(), 2);
+}
+
#[test]
fn move_selected_layers_into_existing_group_preserves_order_selection_and_one_undo() {
let mut s = session_with_doc();
diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs
index 1102a864f..44e8b04e7 100644
--- a/crates/ui-egui/src/layer_row_ui/tests.rs
+++ b/crates/ui-egui/src/layer_row_ui/tests.rs
@@ -264,3 +264,50 @@ fn dropping_a_row_on_the_footer_buttons_duplicates_groups_and_deletes() {
assert!(!names(&h).iter().any(|n| n == "L2"));
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), n - 1);
}
+
+/// Photoshop: ⌥ held when a dragged row is dropped copies the layer there (one "Duplicate Layer"
+/// step) and leaves the original in place; without ⌥ the same drag moves it.
+#[test]
+fn alt_dragging_a_row_drops_a_copy_and_a_plain_drag_moves() {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ for i in 0..3 {
+ s.execute("layer.new.layer", json!({"name": format!("L{i}")})).unwrap();
+ }
+ let mut h = harness(s, 1.0, "promedium", 290.0);
+ let names = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().doc.layers.iter().map(|l| l.name.clone()).collect::<Vec<_>>();
+ let steps = |h: &Harness<'_, PhotocraftApp>| h.state().session.active().unwrap().history.past_len();
+ // Drag row `from` to the upper quarter of row `to` (= above it), with `release` held on drop.
+ let drag = |h: &mut Harness<'static, PhotocraftApp>, from: usize, to: usize, release: Modifiers| {
+ let rows = recorded(&h.ctx);
+ let a = rows[from].row.center();
+ let b = pos2(rows[to].row.center().x, rows[to].row.top() + rows[to].row.height() * 0.25);
+ h.event(egui::Event::PointerMoved(a));
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
+ h.run_steps(1);
+ for k in 1..=8 {
+ h.event(egui::Event::PointerMoved(a + (b - a) * (k as f32 / 8.0)));
+ h.run_steps(1);
+ }
+ // ⌥ only needs to be down when the row is dropped.
+ h.event(egui::Event::ModifiersChanged(release));
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: release });
+ h.run_steps(1);
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(3);
+ };
+ // Rows top to bottom: L2, L1, L0, Background. ⌥-drag L0 above L2.
+ let before = steps(&h);
+ drag(&mut h, 2, 0, Modifiers::ALT);
+ assert_eq!(names(&h), ["Background", "L0", "L1", "L2", "L0 copy"]);
+ assert_eq!(steps(&h), before + 1, "one undo step");
+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Duplicate Layer"));
+ let active = h.state().session.active().unwrap().active_layer;
+ assert_eq!(active, h.state().session.active().unwrap().doc.layers.last().map(|l| l.id), "the copy is active");
+ // Rows: L0 copy, L2, L1, L0, Background. A plain drag of L1 above L0 copy moves it.
+ drag(&mut h, 2, 0, Modifiers::NONE);
+ assert_eq!(names(&h), ["Background", "L0", "L2", "L0 copy", "L1"]);
+ assert_eq!(h.state().session.active().unwrap().history.undo_label(), Some("Reorder Layers"));
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index a0d8133b0..6dde57218 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -2686,7 +2686,8 @@ fn layer_drop_payload(dragged: u64, target: LayerId, position: &str, selected: &
}
}
-/// Drag a layer row to reorder: drop above, below, or inside an existing group.
+/// Drag a layer row to reorder: drop above, below, or inside an existing group. With ⌥ held on
+/// release the layers stay put and copies land there instead (Photoshop).
/// Multi-layer moves are atomic (one undo step), using the engine's stable document order.
fn layer_drag_and_drop(
app: &PhotocraftApp,
@@ -2705,11 +2706,15 @@ fn layer_drag_and_drop(
let Some(dragged) = ctx.data(|d| d.get_temp::<u64>(key)) else { return };
let pointer = ctx.input(|i| i.pointer.interact_pos());
let released = ctx.input(|i| i.pointer.any_released());
+ let copy = ctx.input(|i| i.modifiers.alt);
if dragged == l.id.0 {
- // Ghost label following the pointer.
+ // Ghost label following the pointer, and the copy cursor while ⌥ is held.
if let Some(p) = pointer {
crate::layer_transfer::ghost(ctx, p, &l.name);
}
+ if copy {
+ ctx.set_cursor_icon(egui::CursorIcon::Copy);
+ }
return;
}
let Some(p) = pointer else { return };
@@ -2738,7 +2743,11 @@ fn layer_drag_and_drop(
}
if released {
let selected = app.session.active().map(|st| st.selected_layers()).unwrap_or_default();
- actions.push(("layer.moveTo".into(), layer_drop_payload(dragged, l.id, position, &selected)));
+ let mut payload = layer_drop_payload(dragged, l.id, position, &selected);
+ if copy && let Some(o) = payload.as_object_mut() {
+ o.insert("copy".into(), json!(true));
+ }
+ actions.push(("layer.moveTo".into(), payload));
}
}