PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fix #1531: duplicate artboards beside the original, drag boards with the Move tool (#1584)
BFlat3e8d54896d59
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rsindex 13fdd72ae..87fa4ff1a 100644--- a/crates/engine/src/artboard_cmds.rs+++ b/crates/engine/src/artboard_cmds.rs@@ -145,8 +145,44 @@ fn xywh(r: Rect) -> [i64; 4] {[i64::from(r.x0), i64::from(r.y0), i64::from(r.width()), i64::from(r.height())]}+/// Layer › Duplicate on an artboard (#1531): Photoshop never stacks the copy on the original,+/// it puts it right of the board, a [`GAP`] away, sliding further right past any board in the+/// way. Moves the copy, layer `id` (just inserted on top of its original), there with its+/// contents and grows the canvas to show it; anything that isn't an artboard is left alone.+pub(crate) fn place_copy(doc: &mut Document, id: LayerId) -> Result<()> {+ let l = doc.layer(id).ok_or(EngineError::NoLayer(id))?;+ let Some(r) = l.artboard().map(|a| a.rect) else { return Ok(()) };+ let name = l.name.clone();+ let boards: Vec<Rect> = doc.artboards().iter().filter(|b| b.0 != id).map(|b| b.2.rect).collect();+ let (y0, y1, w) = (i64::from(r.y0), i64::from(r.y1), i64::from(r.width()));+ // In i64: `x1 + GAP` passes i32::MAX for a board at the far right edge (#931).+ let mut x = i64::from(r.x1) + i64::from(GAP);+ // Each round clears every board in the way, so one round per board settles it.+ for _ in 0..=boards.len() {+ let blocked =+ boards.iter().filter(|b| i64::from(b.x0) < x + w && i64::from(b.x1) > x && i64::from(b.y0) < y1 && i64::from(b.y1) > y0).map(|b| b.x1).max();+ match blocked {+ Some(edge) => x = i64::from(edge) + i64::from(GAP),+ None => break,+ }+ }+ let fits = x.checked_add(w).is_some_and(|x1| x1 <= i64::from(i32::MAX));+ let dx = i32::try_from(x - i64::from(r.x0)).ok().filter(|_| fits).ok_or_else(|| {+ EngineError::Other(format!("no room for a copy of artboard \"{name}\" right of it; duplicate it in place (\"inPlace\": true) and move it"))+ })?;+ // Grow the canvas first, so shapes on the board re-render uncut where they land.+ let x1 = i64::from(doc.size.width).max(x + w);+ doc.size = Size::new(x1.clamp(1, 300_000) as u32, doc.size.height);+ let snapshot = doc.clone();+ let copy = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;+ crate::commands::translate_layer(&snapshot, copy, dx, 0);+ crate::vector_cmds::translate_vectors(&snapshot, copy, f64::from(dx), 0.0);+ fit_canvas(doc);+ Ok(())+}+/// Grow the canvas (right/bottom) so every artboard fits.-fn fit_canvas(doc: &mut Document) {+pub(crate) fn fit_canvas(doc: &mut Document) {let (mut w, mut h) = (doc.size.width as i64, doc.size.height as i64);for (_, _, a) in doc.artboards() {w = w.max(i64::from(a.rect.x1));diff --git a/crates/engine/src/artboard_cmds/tests.rs b/crates/engine/src/artboard_cmds/tests.rsindex 3715bc4b6..4f6cbf420 100644--- a/crates/engine/src/artboard_cmds/tests.rs+++ b/crates/engine/src/artboard_cmds/tests.rs@@ -305,3 +305,83 @@ fn export_rejects_a_board_too_far_from_the_origin() {assert_eq!((one.size.width, one.size.height), (50, 50));assert_eq!(one.artboards()[0].2.rect, Rect::new(0, 0, 50, 50));}++/// #1531: a board 40×40 at (10, 10) holding a red square at (10..30)², the artboard active.+fn board_with_square(s: &mut Session) -> LayerId {+ add_square(s, Rect::new(10, 10, 30, 30), [1.0, 0.0, 0.0, 1.0]);+ let gid = LayerId(s.execute("layer.new.artboardFromLayers", json!({"name": "Board"})).unwrap()["layer"].as_u64().unwrap());+ s.execute("layer.artboard.set", json!({"width": 40, "height": 40})).unwrap();+ s.execute("layer.select", json!({"layer": gid.0})).unwrap();+ gid+}++fn red_at(s: &Session, x: i32, y: i32) -> bool {+ let px = photocraft_compose::render(doc(s), Rect::new(x, y, x + 1, y + 1)).px[0];+ px[0] > 0.99 && px[1] < 0.01 && px[3] > 0.99+}++#[test]+fn duplicate_artboard_lands_beside_the_original_with_its_contents() {+ // #1531: the copy sat exactly on the original, so nothing visible happened.+ let mut s = session(8);+ let gid = board_with_square(&mut s);+ let size = doc(&s).size;+ let r = s.execute("layer.duplicate", json!({})).unwrap();+ let copy = r["layer"].as_u64().unwrap();+ assert_eq!(board_rect(&s, gid.0), Rect::new(10, 10, 50, 50), "the original stays");+ // Photoshop: right of the original with the artboard gap, the canvas growing to show it.+ assert_eq!(board_rect(&s, copy), Rect::new(150, 10, 190, 50));+ assert!(doc(&s).size.width >= 190, "{:?}", doc(&s).size);+ assert!(red_at(&s, 155, 15), "the copy's contents moved with it");+ assert!(red_at(&s, 15, 15), "the original's contents stay");+ assert_eq!(doc(&s).layer(LayerId(copy)).unwrap().name, "Board copy");+ // Again from the original: the spot beside it is taken, so the next free one.+ s.execute("layer.select", json!({"layer": gid.0})).unwrap();+ let copy2 = s.execute("layer.duplicate", json!({})).unwrap()["layer"].as_u64().unwrap();+ assert_eq!(board_rect(&s, copy2), Rect::new(290, 10, 330, 50));+ // One undo step each: the copy and the canvas growth go together.+ s.undo();+ s.undo();+ assert_eq!(doc(&s).artboards().len(), 1);+ assert_eq!(doc(&s).size, size);+ // `inPlace` (the Move tool's ⌥-drag) keeps the copy on the original.+ s.execute("layer.select", json!({"layer": gid.0})).unwrap();+ let copy3 = s.execute("layer.duplicate", json!({"inPlace": true})).unwrap()["layer"].as_u64().unwrap();+ assert_eq!(board_rect(&s, copy3), Rect::new(10, 10, 50, 50));+}++#[test]+fn duplicating_several_artboards_places_each_copy_in_a_free_spot() {+ let mut s = session(8);+ let a = board_with_square(&mut s);+ let b = s.execute("layer.new.artboard", json!({"rect": [10, 100, 40, 40]})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.select", json!({"layer": a.0})).unwrap();+ s.execute("layer.select", json!({"layer": b, "mode": "add"})).unwrap();+ let r = s.execute("layer.duplicate", json!({})).unwrap();+ assert_eq!(r["layers"].as_array().unwrap().len(), 2);+ let boards: Vec<Rect> = doc(&s).artboards().iter().map(|b| b.2.rect).collect();+ assert_eq!(boards.len(), 4);+ for (i, x) in boards.iter().enumerate() {+ for y in &boards[i + 1..] {+ assert!(x.intersect(y).is_empty(), "{x:?} overlaps {y:?}");+ }+ }+ let canvas = doc(&s).bounds();+ assert!(boards.iter().all(|r| r.intersect(&canvas) == *r), "{boards:?} in {canvas:?}");+ // One undo step.+ s.undo();+ assert_eq!(doc(&s).artboards().len(), 2);+}++#[test]+fn moving_an_artboard_past_the_canvas_grows_it() {+ // #1531: a board dragged right of the canvas was cut off at the old edge.+ let mut s = session(8);+ let gid = board_with_square(&mut s);+ s.execute("layer.translate", json!({"dx": 200, "dy": 60})).unwrap();+ assert_eq!(board_rect(&s, gid.0), Rect::new(210, 70, 250, 110));+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (250, 110));+ assert!(red_at(&s, 215, 75));+ s.undo();+ assert_eq!((doc(&s).size.width, doc(&s).size.height), (100, 80));+}diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 5eba60aab..7abc459ba 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -514,19 +514,31 @@ fn build() -> Vec<CommandSpec> {has_layer,crate::layer_multi_cmds::group_layers),- cmd!("layer.duplicate", "Duplicate Layer…", ["Layer"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| {- if crate::layer_multi_cmds::multi(s, p) {- return crate::layer_multi_cmds::duplicate_selected(s);+ cmd!(+ "layer.duplicate",+ "Duplicate Layer…",+ ["Layer"],+ None,+ r##"{"layer":id?,"inPlace":bool=false (artboards: keep the copy on the original instead of beside it)} (no layer: every selected layer)"##,+ has_layer,+ |s, p| {+ let in_place = p.get("inPlace").and_then(Value::as_bool).unwrap_or(false);+ if crate::layer_multi_cmds::multi(s, p) {+ return crate::layer_multi_cmds::duplicate_selected(s, in_place);+ }+ let id = layer_param(s, p)?;+ let nid = s.edit("Duplicate Layer", |doc, active| {+ let dup = layer_copy(doc, id)?;+ let nid = doc.insert_above(Some(id), dup);+ if !in_place {+ crate::artboard_cmds::place_copy(doc, nid)?;+ }+ *active = Some(nid);+ Ok(nid)+ })?;+ Ok(json!({ "layer": nid.0 }))}- let id = layer_param(s, p)?;- let nid = s.edit("Duplicate Layer", |doc, active| {- let dup = layer_copy(doc, id)?;- let nid = doc.insert_above(Some(id), dup);- *active = Some(nid);- Ok(nid)- })?;- Ok(json!({ "layer": nid.0 }))- }),+ ),cmd!("layer.delete", "Delete Layer", ["Layer", "Delete"], None, r##"{"layer":id?} (no layer: every selected layer)"##, has_layer, |s, p| {if crate::layer_multi_cmds::multi(s, p) {return crate::layer_multi_cmds::delete_selected(s);diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rsindex f9634d2f5..9277f5979 100644--- a/crates/engine/src/layer_multi_cmds.rs+++ b/crates/engine/src/layer_multi_cmds.rs@@ -258,6 +258,10 @@ pub fn translate(s: &mut Session, p: &Value) -> Result<Value> {}let moves: Vec<_> = ids.iter().map(|&id| (id, dx, dy)).collect();move_layers(doc, &moves)?;+ // A board moved past the right or bottom edge grows the canvas, as a new one does (#1531).+ if ids.iter().any(|id| doc.layer(*id).is_some_and(|l| l.artboard().is_some())) {+ crate::artboard_cmds::fit_canvas(doc);+ }Ok(ids)})?;note_damage(s, &before, &ids);@@ -1068,8 +1072,9 @@ pub fn delete_selected(s: &mut Session) -> Result<Value> {}/// Duplicate Layer with several layers selected: each copy goes above its original and the-/// copies become the selection.-pub fn duplicate_selected(s: &mut Session) -> Result<Value> {+/// copies become the selection. Artboard copies go beside their boards unless `in_place`+/// ([`crate::artboard_cmds::place_copy`]).+pub fn duplicate_selected(s: &mut Session, in_place: bool) -> Result<Value> {let sel = selected(s);let old_active = s.active().and_then(|d| d.active_layer);let (copies, active) = s.edit("Duplicate Layers", |doc, active| {@@ -1079,6 +1084,9 @@ pub fn duplicate_selected(s: &mut Session) -> Result<Value> {let mut dup = doc.layer(id).ok_or(EngineError::NoLayer(id))?.duplicate();dup.name = doc.copy_name(&dup.name);let nid = doc.insert_above(Some(id), dup);+ if !in_place {+ crate::artboard_cmds::place_copy(doc, nid)?;+ }if Some(id) == old_active {new_active = Some(nid);}diff --git a/crates/engine/src/pick_cmds.rs b/crates/engine/src/pick_cmds.rsindex cb5c42a91..0dd983cba 100644--- a/crates/engine/src/pick_cmds.rs+++ b/crates/engine/src/pick_cmds.rs@@ -26,6 +26,17 @@ pub fn layers_at(doc: &Document, x: i32, y: i32) -> Vec<LayerId> {if !(1..=path.len()).all(|n| doc.layer_at(&path[..n]).is_some_and(|a| a.visible)) {continue;}+ // An artboard clips its layers to the board (#1531): pixels past its edge aren't shown,+ // so they can't be picked. The board itself is hit anywhere on it, below its layers+ // (the walk lists them first), as a Photoshop click on an empty spot selects the board.+ let board = path.first().and_then(|i| doc.layers.get(*i)).and_then(|t| t.artboard());+ if board.is_some_and(|a| !a.rect.contains(x, y)) {+ continue;+ }+ if l.artboard().is_some() {+ out.push(l.id);+ continue;+ }if matches!(l.content, LayerContent::Group(_) | LayerContent::Adjustment(_)) {continue;}@@ -53,9 +64,12 @@ pub fn layers_at(doc: &Document, x: i32, y: i32) -> Vec<LayerId> {out}-/// The outermost group containing `id` (the layer itself when it isn't in a group).+/// The outermost group containing `id` (the layer itself when it isn't in a group). An artboard+/// is not a group here: Group mode stops at the outermost group on the board.fn top_group(doc: &Document, id: LayerId) -> LayerId {- doc.walk().iter().find(|(_, _, l)| l.id == id).and_then(|(path, _, _)| doc.layer_at(&path[..1])).map_or(id, |l| l.id)+ let Some((path, _, _)) = doc.walk().into_iter().find(|(_, _, l)| l.id == id) else { return id };+ let depth = if path.get(..1).and_then(|p| doc.layer_at(p)).is_some_and(|t| t.artboard().is_some()) { 2 } else { 1 };+ path.get(..depth).and_then(|p| doc.layer_at(p)).map_or(id, |l| l.id)}fn pick(s: &mut Session, p: &Value) -> Result<Value> {@@ -173,6 +187,41 @@ mod tests {assert!(st.is_layer_selected(a) && st.is_layer_selected(b));}+ #[test]+ fn a_click_on_an_artboard_picks_the_board_or_the_layers_on_it() {+ // #1531: an empty spot on a board picked the Background under it, so a Move-tool drag+ // there never moved the board.+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();+ let bg = s.active().unwrap().doc.layers[0].id;+ s.execute("layer.new.layer", json!({"name": "A"})).unwrap();+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ s.execute("select.deselect", json!({})).unwrap();+ let a = s.active().unwrap().active_layer.unwrap();+ let board = s.execute("layer.new.artboardFromLayers", json!({})).unwrap()["layer"].as_u64().unwrap();+ s.execute("layer.artboard.set", json!({"width": 30, "height": 30})).unwrap();+ // A's pixels past the board's edge are clipped away, so they can't be picked either.+ s.edit("paint outside", |doc, _| {+ doc.layer_mut(a).unwrap().surface_mut().unwrap().fill_rect(Rect::new(32, 32, 36, 36), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ let pick =+ |s: &mut Session, x: i32, y: i32, target: &str| s.execute("layer.pickAt", json!({"x": x, "y": y, "target": target})).unwrap()["layer"].clone();+ assert_eq!(pick(&mut s, 5, 5, "layer"), a.0, "the layer on the board");+ assert_eq!(pick(&mut s, 5, 5, "group"), a.0, "Group mode stops inside the board");+ assert_eq!(pick(&mut s, 20, 20, "layer"), board, "an empty spot on the board picks the board");+ assert_eq!(s.active().unwrap().active_layer, Some(LayerId(board)));+ assert_eq!(pick(&mut s, 33, 33, "layer"), bg.0, "off the board: the Background, not A's clipped pixels");+ let list = s.execute("layer.pickAt", json!({"x": 5, "y": 5, "list": true})).unwrap();+ let ids: Vec<u64> = list["layers"].as_array().unwrap().iter().map(|l| l["layer"].as_u64().unwrap()).collect();+ assert_eq!(ids, vec![a.0, board, bg.0]);+ // A hidden board is skipped with its layers.+ s.execute("layer.setProps", json!({"layer": board, "visible": false})).unwrap();+ assert_eq!(pick(&mut s, 5, 5, "layer"), bg.0);+ }+#[test]fn hostile_params_are_errors_or_misses_not_panics() {let (mut s, _, _) = two_squares();diff --git a/crates/ui-egui/src/artboard_ui.rs b/crates/ui-egui/src/artboard_ui.rsindex 41f6e7765..1d7ff388c 100644--- a/crates/ui-egui/src/artboard_ui.rs+++ b/crates/ui-egui/src/artboard_ui.rs@@ -225,6 +225,44 @@ mod tests {}}+ fn drag(app: &mut PhotocraftApp, from: [f64; 2], by: [f64; 2], mods: egui::Modifiers) {+ use crate::canvas::{ToolEvent, tool_event};+ tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, mods);+ for t in [0.5, 1.0] {+ tool_event(app, ToolEvent::Move { x: from[0] + by[0] * t, y: from[1] + by[1] * t, pressure: 1.0 }, mods);+ }+ tool_event(app, ToolEvent::Up { x: from[0] + by[0], y: from[1] + by[1] }, mods);+ }++ fn boards(app: &PhotocraftApp) -> Vec<photocraft_geom::Rect> {+ app.session.active().unwrap().doc.artboards().iter().map(|b| b.2.rect).collect()+ }++ /// #1531: the Move tool drags a board by an empty spot on it (Auto-Select picks the board, not+ /// the Background under it), and ⌥-drag drags a copy off the original.+ #[test]+ fn move_tool_drags_an_artboard_by_its_empty_area() {+ let (mut app, _) = app();+ app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 40]})).unwrap();+ let bg = app.session.active().unwrap().doc.layers[0].id.0;+ app.run("layer.select", json!({"layer": bg})).unwrap();+ app.ui.tool = crate::state::Tool::Move;+ app.ui.extras.snap = false;+ app.ui.view.show.smart_guides = false;+ drag(&mut app, [20.0, 20.0], [10.0, 5.0], egui::Modifiers::NONE);+ assert_eq!(boards(&app), vec![photocraft_geom::Rect::new(10, 5, 50, 45)]);+ let st = app.session.active().unwrap();+ assert_eq!(st.active_layer, Some(st.doc.artboards()[0].0));+ // ⌥-drag: the copy follows the pointer, the original stays.+ drag(&mut app, [20.0, 20.0], [50.0, 0.0], egui::Modifiers::ALT);+ let mut got = boards(&app);+ got.sort_by_key(|r| r.x0);+ assert_eq!(got, vec![photocraft_geom::Rect::new(10, 5, 50, 45), photocraft_geom::Rect::new(60, 5, 100, 45)]);+ // One undo step takes the copy back.+ app.run("edit.undo", json!({})).unwrap();+ assert_eq!(boards(&app).len(), 1);+ }+#[test]fn comp_target_follows_selection_then_last_applied() {let (mut app, _) = app();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 6190eef2d..537358ed6 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -3057,7 +3057,7 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)// selections.if command_moves_layer(app, tool, [x, y], mods) {if mods.alt- && let Err(e) = app.run("layer.duplicate", json!({}))+ && let Err(e) = app.run("layer.duplicate", json!({"inPlace": true})){app.ui.status = e;app.ui.status_error = true;diff --git a/crates/ui-egui/src/move_mods.rs b/crates/ui-egui/src/move_mods.rsindex 18badd58b..74aa2ab3b 100644--- a/crates/ui-egui/src/move_mods.rs+++ b/crates/ui-egui/src/move_mods.rs@@ -87,7 +87,8 @@ fn moving(app: &PhotocraftApp) -> bool {/// length before so [`fold_history`] can merge the copy and the move into one step.fn duplicate(app: &mut PhotocraftApp) -> Option<usize> {let before = past_len(app)?;- match app.run("layer.duplicate", json!({})) {+ // In place: the copy follows the pointer from the original, artboards too (#1531).+ match app.run("layer.duplicate", json!({"inPlace": true})) {Ok(_) => Some(before),Err(e) => {app.ui.status = e;diff --git a/crates/ui-egui/src/transform_tool.rs b/crates/ui-egui/src/transform_tool.rsindex 8c21361cd..9b78d3faa 100644--- a/crates/ui-egui/src/transform_tool.rs+++ b/crates/ui-egui/src/transform_tool.rs@@ -201,7 +201,8 @@ pub fn begin(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String>/// its selected pixels, as Layer via Copy) and transforms the copy (#352).pub fn begin_copy(app: &mut PhotocraftApp, ctx: &egui::Context) -> Result<(), String> {let selection = app.session.active().is_some_and(|d| d.doc.selection.is_some());- app.run(if selection { "layer.new.layerViaCopy" } else { "layer.duplicate" }, json!({}))?;+ let params = if selection { json!({}) } else { json!({"inPlace": true}) };+ app.run(if selection { "layer.new.layerViaCopy" } else { "layer.duplicate" }, params)?;let made = app.session.active().and_then(|st| st.active_layer.map(|layer| (st.doc.id, layer)));if let Err(e) = begin(app, ctx) {if let Some((document, layer)) = made {