From 911aa4dede1b09b1912ba2551050db37879bfe27 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 12:40:16 -0600 Subject: [PATCH 1/7] =?UTF-8?q?Drag=20a=20layer=20mask=20onto=20another=20?= =?UTF-8?q?layer=20or=20group=20to=20move=20it,=20=E2=8C=A5=20to=20copy=20?= =?UTF-8?q?it=20(#10485)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In Photoshop, dragging a layer mask's thumbnail onto another layer or group moves the mask there, and ⌥-dragging copies it. PhotoCraft's mask thumbnails could only be dragged to the trash, so dropping one on a group did nothing. - engine: layer.layerMask.moveTo {layer, to, copy, replace}: one history step; a layer that already has a mask keeps it unless `replace`; the Background becomes a layer first. - Layers panel: a layer mask thumbnail dropped on another row (layer or group, without a mask of its own) moves the mask there, ⌥ copies it. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd.rs | 11 ++- crates/engine/src/cmd/ops.rs | 73 +++++++++++++++++++ crates/ui-egui/src/panels/layer_drag.rs | 16 ++++ crates/ui-egui/src/panels/layer_row.rs | 3 +- .../src/panels/mask_thumbs_ui/tests.rs | 28 +++++++ 5 files changed, 129 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4b402f2164..43fc7f5322 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -169,7 +169,7 @@ use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_layer, has_pixel pub use layer_params::blend_from_str; pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; pub(crate) use layer_references::{recorded_drop, recorded_layer}; -use ops::{arrange, merge_group, set_mask, set_mask_and_deselect}; +use ops::{arrange, merge_group, move_mask, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer}; use params::{bad, set_clipped}; pub(crate) use params::{check_f32_values, cmyk_param, color_param, int, int_i32, parse_hex, u32_id, u32_id_param}; @@ -807,6 +807,15 @@ fn build() -> Vec { "Delete Layer Mask", None )), + cmd!( + "layer.layerMask.moveTo", + "Move Layer Mask", + [], + None, + r##"{"layer":id? (the mask's layer, default active),"to":id (the layer or group it goes to),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, + has_layer, + move_mask + ), cmd!("layer.mergeDown", "Merge Down", ["Layer"], None, r##"{"layer":id?}"##, has_layer, |s, p| { let id = layer_param(s, p)?; s.edit("Merge Down", |doc, active| { diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index b34aab7623..b63ead114b 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -97,6 +97,39 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option Result { + let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() }; + let from = layer_param(s, p)?; + let to = p.get("to").and_then(Value::as_u64).map(LayerId).ok_or_else(|| bad("`to` must be a layer id"))?; + let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); + let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false); + if from == to { + return Err(bad("the mask is already on that layer")); + } + let label = if copy { "Copy Layer Mask" } else { "Move Layer Mask" }; + s.edit(label, |doc, _| { + let mask = doc.layer(from).ok_or(EngineError::NoLayer(from))?.mask.clone().ok_or_else(|| bad("the layer has no layer mask"))?; + if doc.layer(to).ok_or(EngineError::NoLayer(to))?.mask.is_some() && !replace { + return Err(bad("the layer already has a layer mask (pass `replace`)")); + } + check_all_unlocked(doc, to)?; + if !copy { + check_all_unlocked(doc, from)?; + } + // The Background can't hold a mask, so it becomes a normal layer first, as for Add Mask. + crate::extra_cmds::background_to_layer_for_mask(doc, to); + doc.layer_mut(to).ok_or(EngineError::NoLayer(to))?.mask = Some(mask); + if !copy { + doc.layer_mut(from).ok_or(EngineError::NoLayer(from))?.mask = None; + } + Ok(()) + })?; + Ok(json!({"layer": from.0, "to": to.0, "copy": copy})) +} + /// Move a layer's pixels, linked mask and type by whole pixels (vectors move via /// `vector_cmds::translate_vectors`). pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) { @@ -188,3 +221,43 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result { })?; Ok(json!({ "layer": id.0 })) } + +#[cfg(test)] +mod tests { + use serde_json::json; + + use crate::Session; + + /// #10485: dragging a layer's mask onto a group moves it there, ⌥ copies it (Photoshop). A + /// layer that has a mask already keeps it unless asked to replace it; one undo puts it back. + #[test] + fn a_layer_mask_moves_or_copies_onto_another_layer_or_group() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + let b = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let group = s.execute("layer.groupLayers", json!({"layer": b})).unwrap()["layer"].as_u64().unwrap(); + let mask_of = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.clone(); + let original = mask_of(&s, a).expect("a has a mask"); + // Move onto the group. + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).unwrap(); + assert!(mask_of(&s, a).is_none(), "moved away"); + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "the same mask on the group"); + // One undo puts it back. + s.execute("edit.undo", json!({})).unwrap(); + assert!(mask_of(&s, a).is_some() && mask_of(&s, group).is_none()); + // ⌥: a copy. + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "copy": true})).unwrap(); + assert!(mask_of(&s, a).is_some() && mask_of(&s, group).is_some()); + // The group has one now: refused unless replacing. + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err()); + s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "replace": true})).unwrap(); + assert!(mask_of(&s, a).is_none()); + // Bad input. + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err(), "no mask to move"); + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group, "to": group})).is_err(), "onto itself"); + assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group})).is_err(), "no target"); + } +} diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs index 35903dcf61..36aaeb63d6 100644 --- a/crates/ui-egui/src/panels/layer_drag.rs +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -314,6 +314,22 @@ pub(super) fn fx_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, } } +/// A layer mask's thumbnail dropped on another layer or group moves the mask there, ⌥ copies it, +/// as in Photoshop (#10485). A row that has a layer mask already doesn't take the drop (Photoshop +/// asks whether to replace it). +pub(super) fn mask_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) { + let Some((from, MaskKind::Pixel)) = ctx.data(|d| d.get_temp::(mask_drag_key())) else { return }; + let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; + if from == l.id.0 || l.mask.is_some() || !rect.contains(p) { + return; + } + let t = Tokens::get(ctx); + ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside); + if ctx.input(|i| i.pointer.any_released()) { + actions.push(("layer.layerMask.moveTo".into(), json!({"layer": from, "to": l.id.0, "copy": ctx.input(|i| i.modifiers.alt)}))); + } +} + /// Photoshop shows a layer's effects as indented sub-rows ("Effects", then each effect). The eye /// on "Effects" shows or hides them all, the eye on an effect's row just that one (#1622). pub(super) fn effect_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth: usize, actions: &mut Vec<(String, Value)>) { diff --git a/crates/ui-egui/src/panels/layer_row.rs b/crates/ui-egui/src/panels/layer_row.rs index d622a0e9db..e9b984d81f 100644 --- a/crates/ui-egui/src/panels/layer_row.rs +++ b/crates/ui-egui/src/panels/layer_row.rs @@ -1,4 +1,4 @@ -use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, start_fx_drag, starts_mask_drag}; +use super::layer_drag::{MaskDrag, fx_drop, layer_drag_and_drop, mask_drag_key, mask_drop, start_fx_drag, starts_mask_drag}; use super::layers::simple_lock_toggle; use super::{ Color32, CornerRadius, Layer, LayerContent, PhotocraftApp, Pos2, Rect, Sense, Stroke, StrokeKind, Tokens, Value, icons, json, pos2, theme, vec2, widgets, @@ -207,6 +207,7 @@ pub(super) fn layer_row( let mask_drag = mask_drag.is_some(); layer_drag_and_drop(app, ctx, ui, l, rect, &resp, actions); fx_drop(ctx, ui, l, rect, actions); + mask_drop(ctx, ui, l, rect, actions); crate::smart_ui::drop_on_row(ctx, ui, l, rect, actions); if resp.drag_started() && !mask_drag { crate::layer_transfer::begin_from_panel(app, ctx, l.id); diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs index aeb8538256..d9aa53729b 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -869,3 +869,31 @@ fn selecting_an_adjustment_layer_from_another_layer_targets_its_mask() { assert!(!h.state().ui.mask_target && !h.state().ui.vector_mask_target, "{command}: a pixel layer targets its contents"); } } + +/// #10485: dragging the layer mask's thumbnail onto a group's row moves the mask to the group, and +/// ⌥ copies it, as in Photoshop. It had no effect. +#[test] +fn dragging_the_mask_thumbnail_onto_a_group_moves_or_copies_it() { + for copy in [false, true] { + let (mut s, masked, shape) = session(); + let group = s.execute("layer.groupLayers", json!({"layer": shape, "name": "Grp"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let to = h.get_by_label("Grp").rect().center(); + let modifiers = if copy { Modifiers::ALT } else { Modifiers::NONE }; + h.hover_at(from); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + for k in 1..=8 { + h.event(egui::Event::PointerMoved(from + (to - from) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(3); + assert!(layer(&h, group).mask.is_some(), "copy: {copy}: the group has the mask"); + assert_eq!(layer(&h, masked).mask.is_some(), copy, "copy: {copy}: the original stays only with ⌥"); + } +} From 5c8549910a15fb39ad3672e4ad85186d6b94dc84 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 13:12:58 -0600 Subject: [PATCH 2/7] Layers panel: scroll at the list's edge while dragging a layer mask (CodeRabbit review on crates/ui-egui/src/panels/layer_drag.rs:298) The edge scroll's drag check knew layer, fx and Smart Filter drags but not mask drags, so a mask held at the list's edge left it in place and couldn't reach a row out of view. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/layers.rs | 1 + .../src/panels/mask_thumbs_ui/tests.rs | 42 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 835b370af2..bd047dd7b4 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -262,6 +262,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let held = ctx.data(|d| { d.get_temp::(egui::Id::unique("layer-drag")).is_some() || d.get_temp::(fx_drag_key()).is_some() + || d.get_temp::(mask_drag_key()).is_some() || d.get_temp::(crate::smart_ui::drag_key()).is_some() }); let dragging = held && ctx.input(|i| i.pointer.primary_down()); diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs index d9aa53729b..fe499c0ee5 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -897,3 +897,45 @@ fn dragging_the_mask_thumbnail_onto_a_group_moves_or_copies_it() { assert_eq!(layer(&h, masked).mask.is_some(), copy, "copy: {copy}: the original stays only with ⌥"); } } + +/// #10485: a layer mask dragged to the Layers list's bottom edge scrolls the list, as a layer +/// drag does, so it can be dropped on a layer scrolled out of view. The list stayed put. +#[test] +fn dragging_a_mask_to_the_list_edge_scrolls_to_rows_out_of_view() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let target = s.execute("layer.new.layer", json!({"name": "Target"})).unwrap()["layer"].as_u64().unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let window_bottom = h.ctx.content_rect().bottom(); + assert!(h.get_by_label("Target").rect().top() > window_bottom, "the target starts out of view"); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let start = h.get_by_label("Masked").rect(); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerMoved(from + vec2(0.0, 12.0))); + h.run_steps(2); + // Held at the bottom of the window, below the list's last visible row. + let bottom = pos2(from.x, window_bottom - 2.0); + for _ in 0..240 { + h.event(egui::Event::PointerMoved(bottom)); + h.run_steps(1); + } + let moved = h.get_by_label("Masked").rect(); + assert!(moved.top() < start.top() - 1.0, "the list scrolled down: {start:?} → {moved:?}"); + let to = h.get_by_label("Target").rect().center(); + assert!(to.y < window_bottom, "the target scrolled into view: {to:?}"); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(bottom + (to - bottom) * (k as f32 / 4.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(layer(&h, target).mask.is_some(), "the target has the mask"); + assert!(layer(&h, masked).mask.is_none(), "moved, not copied"); +} From 84696c3b03b2dc9409a81afa4a842e8f19e0d64b Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 13:15:58 -0600 Subject: [PATCH 3/7] engine: check a replaced layer mask's content in the mask move test (CodeRabbit review on crates/engine/src/cmd/ops.rs:224) The group now has a mask of its own, unlike the source's, before the replacing move, and the test checks the group ends up with the source's mask, so a replacement that does nothing fails. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/ops.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index b63ead114b..177c8eb46c 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -251,10 +251,15 @@ mod tests { // ⌥: a copy. s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "copy": true})).unwrap(); assert!(mask_of(&s, a).is_some() && mask_of(&s, group).is_some()); - // The group has one now: refused unless replacing. + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "the copy on the group"); + // The group gets a mask of its own: refused unless replacing, which leaves a's on it. + s.execute("layer.layerMask.delete", json!({"layer": group})).unwrap(); + s.execute("layer.layerMask.hideAll", json!({"layer": group})).unwrap(); + assert_ne!(mask_of(&s, group).unwrap().surface, original.surface, "the group's own mask differs"); assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err()); s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group, "replace": true})).unwrap(); assert!(mask_of(&s, a).is_none()); + assert_eq!(mask_of(&s, group).unwrap().surface, original.surface, "a's mask replaced the group's"); // Bad input. assert!(s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": group})).is_err(), "no mask to move"); assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group, "to": group})).is_err(), "onto itself"); From f57bcddbb51f4f56d6fab6729183f4c24b45a406 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 23:19:59 -0600 Subject: [PATCH 4/7] engine: test mask drops on the mask's own layer and undo after a copy or replace (FredApps review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dropping a mask on its own layer (any copy/replace combination) is refused and leaves the mask's pixels, enabled state and density, the document and the history as they were. One undo after an ⌥-copy, an ⌥-copy that replaces, or a move that replaces puts both layers' masks back exactly. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/ops.rs | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index 177c8eb46c..bd5b2bccc2 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -265,4 +265,66 @@ mod tests { assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group, "to": group})).is_err(), "onto itself"); assert!(s.execute("layer.layerMask.moveTo", json!({"layer": group})).is_err(), "no target"); } + + /// #10485: dropping a mask back on its own layer's row is a no-op: the mask keeps its pixels, + /// enabled state and density, nothing else in the document changes, and no history step is added. + #[test] + fn dropping_a_layer_mask_on_its_own_layer_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("layer.layerMask.edit", json!({"layer": a, "density": 40})).unwrap(); + s.execute("layer.layerMask.enabled", json!({"layer": a, "enabled": false})).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let mask = doc.layer(photocraft_doc::LayerId(a)).unwrap().mask.clone().expect("a has a mask"); + assert!(!mask.enabled && (mask.density - 0.4).abs() < 1e-6, "set up: disabled, 40% density"); + let history = s.active().unwrap().history.entries(); + for (copy, replace) in [(false, false), (true, false), (false, true), (true, true)] { + let r = s.execute("layer.layerMask.moveTo", json!({"layer": a, "to": a, "copy": copy, "replace": replace})); + assert!(r.is_err(), "copy: {copy}, replace: {replace}: refused"); + let st = s.active().unwrap(); + assert_eq!(st.doc.layer(photocraft_doc::LayerId(a)).unwrap().mask.as_ref(), Some(&mask), "copy: {copy}, replace: {replace}: the mask is untouched"); + assert!(st.doc == doc, "copy: {copy}, replace: {replace}: the document is unchanged"); + assert_eq!(st.history.entries(), history, "copy: {copy}, replace: {replace}: no history step"); + } + } + + /// #10485: one undo after an ⌥-copy, or after a move or copy that replaces the target's own + /// mask, puts both layers' masks back exactly (pixels, enabled, density, feather). + #[test] + fn undo_restores_both_masks_after_a_copy_or_a_replace() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + let a = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 10})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + s.execute("layer.layerMask.edit", json!({"layer": a, "density": 60, "feather": 3})).unwrap(); + let b = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 18, "y": 2, "width": 6, "height": 20})).unwrap(); + s.execute("layer.layerMask.hideSelection", json!({"layer": b})).unwrap(); + s.execute("layer.layerMask.enabled", json!({"layer": b, "enabled": false})).unwrap(); + let c = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap(); + let mask_of = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.clone(); + let (mask_a, mask_b) = (mask_of(&s, a).expect("a has a mask"), mask_of(&s, b).expect("b has a mask")); + assert_ne!(mask_a, mask_b, "set up: two different masks"); + let doc = s.active().unwrap().doc.clone(); + let history = s.active().unwrap().history.entries().len(); + let cases = [ + ("⌥-copy onto a layer without a mask", json!({"layer": a, "to": c, "copy": true}), c), + ("⌥-copy replacing a mask", json!({"layer": a, "to": b, "copy": true, "replace": true}), b), + ("move replacing a mask", json!({"layer": a, "to": b, "replace": true}), b), + ]; + for (case, params, to) in cases { + s.execute("layer.layerMask.moveTo", params).unwrap(); + assert_eq!(mask_of(&s, to).as_ref(), Some(&mask_a), "{case}: the target has a's mask"); + assert_eq!(s.active().unwrap().history.entries().len(), history + 1, "{case}: one history step"); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(mask_of(&s, a).as_ref(), Some(&mask_a), "{case}: a's mask is back"); + assert_eq!(mask_of(&s, b).as_ref(), Some(&mask_b), "{case}: b's mask is back"); + assert!(mask_of(&s, c).is_none(), "{case}: c has no mask again"); + assert!(s.active().unwrap().doc == doc, "{case}: the document is as before"); + } + } } From 23e25237aeaa9a2510d46ad70ff0ae7d9fe55268 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 23:25:15 -0600 Subject: [PATCH 5/7] Layers panel: test that a mask thumbnail dropped on a masked row or its own row does nothing (FredApps review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dropped on a row whose layer has a mask already (with or without ⌥), or back on its own row, the drag runs no command: no refused-command error, no history step, and both masks unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/panels/mask_thumbs_ui/tests.rs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs index fe499c0ee5..a549587dc7 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -898,6 +898,50 @@ fn dragging_the_mask_thumbnail_onto_a_group_moves_or_copies_it() { } } +/// #10485: a layer mask's thumbnail dropped on a row that has a layer mask already (with or +/// without ⌥), or back on its own row, does nothing: no command runs, so no error, no history step, +/// and both masks stay as they were. Photoshop asks before replacing a mask; the panel doesn't offer +/// the drop at all. +#[test] +fn dropping_a_mask_thumbnail_on_a_masked_row_or_its_own_row_does_nothing() { + for (target, copy) in [("Badge", false), ("Badge", true), ("Masked", false), ("Masked", true)] { + let (mut s, masked, shape) = session(); + s.execute("layer.layerMask.hideAll", json!({"layer": shape})).unwrap(); + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + let doc = h.state().session.active().unwrap().doc.clone(); + let history = h.state().session.active().unwrap().history.entries(); + let (mask_masked, mask_shape) = (layer(&h, masked).mask, layer(&h, shape).mask); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + let to = h.get_by_label(target).rect().center(); + let modifiers = if copy { Modifiers::ALT } else { Modifiers::NONE }; + h.hover_at(from); + h.event(egui::Event::ModifiersChanged(modifiers)); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + h.run_steps(1); + // Out of the thumbnail and back onto the target, so the drop on its own row is a drag. + let away = from + vec2(0.0, 40.0); + for k in 1..=4 { + h.event(egui::Event::PointerMoved(from + (away - from) * (k as f32 / 4.0))); + h.run_steps(1); + } + for k in 1..=8 { + h.event(egui::Event::PointerMoved(away + (to - away) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + h.run_steps(3); + let case = format!("onto {target}, copy: {copy}"); + assert!(!h.state().ui.status_error, "{case}: no refused command: {}", h.state().ui.status); + assert_eq!(layer(&h, masked).mask, mask_masked, "{case}: the dragged mask stays"); + assert_eq!(layer(&h, shape).mask, mask_shape, "{case}: the target keeps its own mask"); + let st = h.state().session.active().unwrap(); + assert!(st.doc == doc, "{case}: the document is unchanged"); + assert_eq!(st.history.entries(), history, "{case}: no history step"); + } +} + /// #10485: a layer mask dragged to the Layers list's bottom edge scrolls the list, as a layer /// drag does, so it can be dropped on a layer scrolled out of view. The list stayed put. #[test] From d46c7b46237c019af4f4c6580e13a8f8179be9c7 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sat, 31 Oct 2026 23:59:13 -0600 Subject: [PATCH 6/7] Layers panel: take mask drops only where the list shows the row (CodeRabbit review on crates/ui-egui/src/panels/layer_drag.rs:301) A row scrolled out of the Layers list keeps its rect, which still lies under the panel's header or footer: a mask thumbnail released there was moved to that hidden row. mask_drop now tests the row's rect clipped to the list. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/layer_drag.rs | 5 +- .../src/panels/mask_thumbs_ui/tests.rs | 66 +++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/layer_drag.rs b/crates/ui-egui/src/panels/layer_drag.rs index 36aaeb63d6..aea09ab6ee 100644 --- a/crates/ui-egui/src/panels/layer_drag.rs +++ b/crates/ui-egui/src/panels/layer_drag.rs @@ -316,11 +316,12 @@ pub(super) fn fx_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, /// A layer mask's thumbnail dropped on another layer or group moves the mask there, ⌥ copies it, /// as in Photoshop (#10485). A row that has a layer mask already doesn't take the drop (Photoshop -/// asks whether to replace it). +/// asks whether to replace it). Only the part of the row the list shows takes it: a row scrolled +/// out of view still lies under the panel's header or footer. pub(super) fn mask_drop(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) { let Some((from, MaskKind::Pixel)) = ctx.data(|d| d.get_temp::(mask_drag_key())) else { return }; let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return }; - if from == l.id.0 || l.mask.is_some() || !rect.contains(p) { + if from == l.id.0 || l.mask.is_some() || !rect.intersect(ui.clip_rect()).contains(p) { return; } let t = Tokens::get(ctx); diff --git a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs index a549587dc7..19a058ddb9 100644 --- a/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs +++ b/crates/ui-egui/src/panels/mask_thumbs_ui/tests.rs @@ -983,3 +983,69 @@ fn dragging_a_mask_to_the_list_edge_scrolls_to_rows_out_of_view() { assert!(layer(&h, target).mask.is_some(), "the target has the mask"); assert!(layer(&h, masked).mask.is_none(), "moved, not copied"); } + +/// #10485: a layer mask dropped outside the Layers list, over the panel's header, doesn't land on +/// the row scrolled out of view underneath it. The rows take drops only where the list shows them. +#[test] +fn dropping_a_mask_over_the_panel_header_skips_rows_scrolled_out_of_view() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 64, "height": 64})).unwrap(); + let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap(); + for i in 0..40 { + s.execute("layer.new.layer", json!({"name": format!("Filler {i}")})).unwrap(); + } + s.execute("layer.select", json!({"layer": masked})).unwrap(); + let mut h = harness(s, 0, 1.0, 290.0); + // Scrolled to the bottom: "Masked" shows, the top rows went up under the header. + h.hover_at(h.get_by_label("Filler 39").rect().center()); + h.run_steps(2); + for _ in 0..80 { + h.event(egui::Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, -1.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + }); + h.run_steps(1); + } + h.run_steps(10); + let window = h.ctx.content_rect(); + let fill = h.get_all_by_label("Fill").next().unwrap().rect(); + let from = mask_rect(&h, masked, MaskKind::Pixel).center(); + assert!(from.y > fill.bottom() && from.y < window.bottom(), "the masked row shows: {from:?}"); + // The empty header space between Blend Mode and Opacity, over a row scrolled out of view. + let (blend, opacity) = (h.get_by_label("Blend Mode").rect(), h.get_all_by_label("Opacity").next().unwrap().rect()); + let over = pos2((blend.right() + opacity.left()) / 2.0, blend.center().y); + let (target, row) = (0..40) + .map(|i| format!("Filler {i}")) + .map(|name| { + let rect = h.get_by_label(&name).rect(); + (name, rect) + }) + .find(|(_, rect)| rect.contains(over)) + .expect("a row lies under the header"); + assert!(row.bottom() <= fill.bottom(), "{target} is scrolled out of the list: {row:?}"); + let target = h.state().session.active().unwrap().doc.layers.iter().find(|l| l.name == target).unwrap().id.0; + let doc = h.state().session.active().unwrap().doc.clone(); + let history = h.state().session.active().unwrap().history.entries(); + h.hover_at(from); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + // Up through the list, clear of its edges (which scroll it), then out over the header and + // released there at once. + let inside = pos2(from.x, fill.bottom() + 48.0); + for k in 1..=8 { + h.event(egui::Event::PointerMoved(from + (inside - from) * (k as f32 / 8.0))); + h.run_steps(1); + } + h.event(egui::Event::PointerMoved(over)); + h.event(egui::Event::PointerButton { pos: over, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert!(layer(&h, target).mask.is_none(), "the row under the header took no mask"); + assert!(layer(&h, masked).mask.is_some(), "the mask stays where it was"); + let st = h.state().session.active().unwrap(); + assert!(st.doc == doc, "the document is unchanged"); + assert_eq!(st.history.entries(), history, "no history step"); +} From 4fae86901868518ba043955f77cb89f699b5e5fc Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Thu, 5 Nov 2026 22:33:42 -0600 Subject: [PATCH 7/7] Masks: a recorded mask drop replays on another document (CodeRabbit review on cmd.rs:815) The journal made `layer` portable for layer.layerMask.moveTo but kept `to` as the document's layer id. Replayed on another document, that id names some other layer or none: the mask silently went to an unrelated layer or the step failed. Before the fix, recorded_mask_drop_replays_on_another_document recorded `"to": 8` and replay moved the mask onto "Extra" instead of "Shadow". Recording now keeps `to` as the layer's name (from the document before the step, since a drop on the Background renames it "Layer 0"), plus `toOccurrence` when several layers share the name. move_mask resolves a name (requiring `toOccurrence` when it is ambiguous), and explicit calls still take a numeric id. This matches how layer.moveTo records its drop target (`target` + `targetOccurrence`). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/actions_record.rs | 21 ++++++ crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/actions_cmds/tests.rs | 78 +++++++++++++++++++++ crates/engine/src/cmd/ops.rs | 26 ++++++- 4 files changed, 125 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/actions_record.rs b/crates/engine/src/actions_record.rs index 4bfb54befa..1076950e28 100644 --- a/crates/engine/src/actions_record.rs +++ b/crates/engine/src/actions_record.rs @@ -9,6 +9,8 @@ //! - any other `layer` id becomes the layer's name when the name is unique in the document, and //! `layer.select` always does (selecting is choosing a layer by name, as Photoshop records //! it); an ambiguous name keeps the id, which still replays on the recording document; +//! - a mask drop's destination (`layer.layerMask.moveTo`'s `to`) becomes the layer's name, with +//! `toOccurrence` when several layers share it; //! - the Type tool's keystrokes fold into the `type.create` that made the layer. On an existing //! layer, each replacement stays separate so replay keeps style runs between edited spans. //! @@ -69,6 +71,9 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before object.insert("yPercent".into(), serde_json::json!(y_percent)); } } + if id == "layer.layerMask.moveTo" { + portable_mask_destination(doc, &mut params); + } let Some(target) = params.get("layer").and_then(Value::as_u64).map(LayerId) else { return params }; let Some(obj) = params.as_object_mut() else { return params }; let only_selected = before.selected.len() <= 1; @@ -85,6 +90,22 @@ pub(crate) fn portable(s: &Session, id: &str, mut params: Value, before: &Before params } +/// A mask drop's `to` id becomes the layer's name, and `toOccurrence` which of several layers of +/// that name it is, in document order. Moving a mask leaves the stack as it is, so the count means +/// the same layer when the step replays. It is taken from the document before the step: dropping +/// on the Background renames it "Layer 0". +fn portable_mask_destination(doc: &Document, params: &mut Value) { + let Some(to) = params.get("to").and_then(Value::as_u64).map(LayerId) else { return }; + let Some(layer) = doc.layer(to) else { return }; + let matches: Vec<_> = doc.walk().into_iter().filter(|(_, _, l)| l.name == layer.name).map(|(_, _, l)| l.id).collect(); + let Some(occurrence) = matches.iter().position(|id| *id == to) else { return }; + let Some(fields) = params.as_object_mut() else { return }; + fields.insert("to".into(), Value::String(layer.name.clone())); + if matches.len() > 1 { + fields.insert("toOccurrence".into(), occurrence.into()); + } +} + /// The text layer a journaled `type.create` made or `type.edit` changed, so the keystrokes that /// follow fold into that entry only when they type into the same layer (the Type tool selects /// a clicked layer without a command, so the journal alone cannot tell). diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 43fc7f5322..91f571f637 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -812,7 +812,7 @@ fn build() -> Vec { "Move Layer Mask", [], None, - r##"{"layer":id? (the mask's layer, default active),"to":id (the layer or group it goes to),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, + r##"{"layer":id? (the mask's layer, default active),"to":id|name (the layer or group it goes to; a recorded step names it),"toOccurrence":n? (which of several layers named `to`, in document order),"copy":bool=false (⌥-drag: a copy goes and the original stays),"replace":bool=false (replace a mask already there; otherwise refused)} → {layer,to,copy}"##, has_layer, move_mask ), diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 08d5a178d7..6a18a871f1 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -600,6 +600,84 @@ fn recorded_layer_selection_replays_by_name_on_another_document() { /// #7845: dragging a layer in the Layers panel while recording keeps the drop target by name, /// so the action plays on another document (whose layer ids differ) instead of failing with /// "no such layer". The reporter's steps, replayed on a new document. +/// #10485: a mask thumbnail dropped on another layer while recording keeps its destination by +/// name, so the action moves the mask to the same layer in another document (whose ids differ) +/// rather than to whichever layer has the recorded id there. +#[test] +fn recorded_mask_drop_replays_on_another_document() { + let masked = |s: &mut Session, name: &str| { + let id = s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 1, "width": 4, "height": 4})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + id + }; + let has_mask = |s: &Session, name: &str| s.active().unwrap().doc.walk().iter().any(|(_, _, l)| l.name == name && l.mask.is_some()); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + let photo = masked(&mut s, "Photo"); + let shadow = s.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("actions.record", json!({"name": "Mask to shadow"})).unwrap(); + s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": shadow, "copy": false})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"layer": "Photo", "to": "Shadow", "copy": false})); + // Another document: an extra layer between them, so the recorded id is a different layer. + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + replay.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + masked(&mut replay, "Photo"); + replay.execute("layer.new.layer", json!({"name": "Extra"})).unwrap(); + replay.execute("layer.new.layer", json!({"name": "Shadow"})).unwrap(); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(has_mask(&replay, "Shadow"), "the mask went to Shadow"); + assert!(!has_mask(&replay, "Photo") && !has_mask(&replay, "Extra"), "and nowhere else"); +} + +/// A mask dropped on one of several same-named layers records which of them it is, so replay +/// picks the same one (not the topmost of that name), and an explicit name needs the occurrence. +#[test] +fn recorded_mask_drop_onto_a_duplicate_name_replays_on_the_same_layer() { + let build = |s: &mut Session, extra: bool| { + s.execute("file.new", json!({"width": 8, "height": 8})).unwrap(); + if extra { + s.execute("layer.new.layer", json!({"name": "Extra"})).unwrap(); + } + let photo = s.execute("layer.new.layer", json!({"name": "Photo"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("select.rect", json!({"x": 1, "y": 1, "width": 4, "height": 4})).unwrap(); + s.execute("layer.layerMask.revealSelection", json!({})).unwrap(); + let lower = s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap(); + let upper = s.execute("layer.new.layer", json!({"name": "Twin"})).unwrap()["layer"].as_u64().unwrap(); + (photo, lower, upper) + }; + let mask_on = |s: &Session, id: u64| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().mask.is_some(); + let mut s = Session::new(); + let (photo, lower, upper) = build(&mut s, false); + s.execute("actions.record", json!({"name": "Copy mask"})).unwrap(); + s.execute("layer.layerMask.moveTo", json!({"layer": photo, "to": lower, "copy": true})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + assert_eq!(s.actions.list[0].steps[0].1, json!({"layer": "Photo", "to": "Twin", "toOccurrence": 0, "copy": true})); + assert!(mask_on(&s, lower) && !mask_on(&s, upper)); + let saved = serde_json::to_string(&s.actions.list).unwrap(); + let mut replay = Session::new(); + replay.actions.list = serde_json::from_str(&saved).unwrap(); + let (photo2, lower2, upper2) = build(&mut replay, true); + assert_ne!((photo, lower, upper), (photo2, lower2, upper2), "the ids differ"); + let result = replay.execute("actions.play", json!({"action": 0})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(mask_on(&replay, photo2), "a copy: the original stays"); + assert!(mask_on(&replay, lower2), "the copy went to the lower Twin"); + assert!(!mask_on(&replay, upper2), "not to the upper one"); + // Explicit calls: a name shared by several layers needs `toOccurrence`; ids still work. + let err = replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": "Twin", "copy": true})).unwrap_err().to_string(); + assert!(err.contains("toOccurrence"), "{err}"); + replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": "Twin", "toOccurrence": 1, "copy": true})).unwrap(); + assert!(mask_on(&replay, upper2), "occurrence 1 is the upper Twin"); + replay.execute("layer.layerMask.delete", json!({"layer": upper2})).unwrap(); + replay.execute("layer.layerMask.moveTo", json!({"layer": photo2, "to": upper2})).unwrap(); + assert!(mask_on(&replay, upper2) && !mask_on(&replay, photo2), "a numeric id still names the layer"); +} + #[test] fn recorded_layer_drag_replays_on_another_document() { for depth in [8, 16, 32] { diff --git a/crates/engine/src/cmd/ops.rs b/crates/engine/src/cmd/ops.rs index bd5b2bccc2..0d1b91aa1f 100644 --- a/crates/engine/src/cmd/ops.rs +++ b/crates/engine/src/cmd/ops.rs @@ -103,7 +103,7 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option Result { let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() }; let from = layer_param(s, p)?; - let to = p.get("to").and_then(Value::as_u64).map(LayerId).ok_or_else(|| bad("`to` must be a layer id"))?; + let to = mask_destination(s, p)?; let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false); let replace = p.get("replace").and_then(Value::as_bool).unwrap_or(false); if from == to { @@ -130,6 +130,30 @@ pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result { Ok(json!({"layer": from.0, "to": to.0, "copy": copy})) } +/// `layer.layerMask.moveTo`'s `to`: an id, or a name (as a recorded step keeps it) with +/// `toOccurrence` choosing among the layers that share it, in document order (required when +/// several do). +fn mask_destination(s: &Session, p: &Value) -> Result { + let bad = |m: String| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m }; + match p.get("to") { + Some(Value::String(name)) => { + let occurrence = p + .get("toOccurrence") + .map(|v| v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("`toOccurrence` must be a non-negative integer".into()))) + .transpose()?; + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; + let matches: Vec<_> = doc.walk().into_iter().filter(|(_, _, l)| &l.name == name).map(|(_, _, l)| l.id).collect(); + if matches.len() > 1 && occurrence.is_none() { + return Err(bad(format!("multiple layers named `{name}`; specify `toOccurrence`"))); + } + let index = occurrence.unwrap_or(0); + matches.get(index).copied().ok_or_else(|| bad(format!("no layer named `{name}` at occurrence {index}"))) + } + Some(v) => v.as_u64().map(LayerId).ok_or_else(|| bad("`to` must be a layer id or name".into())), + None => Err(bad("missing `to`".into())), + } +} + /// Move a layer's pixels, linked mask and type by whole pixels (vectors move via /// `vector_cmds::translate_vectors`). pub(crate) fn translate_layer(doc: &Document, l: &mut Layer, dx: i32, dy: i32) {