Merge pull request #10549 from hectorviov/fix/drag-mask-to-layer

Drag a layer mask onto another layer or group to move it, ⌥ to copy it (#10485)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-07 14:43:04 +01:00
commit adac9ca7cf
8 files changed
+473 -2

No files matched your search

+21
View File
@@ -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).
+10 -1
View File
@@ -171,7 +171,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};
@@ -809,6 +809,15 @@ fn build() -> Vec<CommandSpec> {
"Delete Layer Mask",
None
)),
cmd!(
"layer.layerMask.moveTo",
"Move Layer Mask",
[],
None,
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
),
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| {
@@ -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] {
+164
View File
@@ -97,6 +97,63 @@ fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask
Ok(Value::Null)
}
/// Drag a layer mask's thumbnail onto another layer or group in the Layers panel: the mask moves
/// there (⌥: a copy goes there and the original stays), as in Photoshop (#10485). A layer that
/// already has a mask keeps it unless `replace` (Photoshop asks first). One history step.
pub(super) fn move_mask(s: &mut Session, p: &Value) -> Result<Value> {
let bad = |m: &str| EngineError::BadParams { cmd: "layer.layerMask.moveTo".into(), msg: m.into() };
let from = layer_param(s, p)?;
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 {
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}))
}
/// `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<LayerId> {
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) {
@@ -188,3 +245,110 @@ pub(super) fn merge_group(s: &mut Session, id: LayerId) -> Result<Value> {
})?;
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());
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");
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");
}
}
}
+17
View File
@@ -314,6 +314,23 @@ 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). 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::<MaskDrag>(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.intersect(ui.clip_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)>) {
+2 -1
View File
@@ -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);
+1
View File
@@ -266,6 +266,7 @@ pub(super) fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let held = ctx.data(|d| {
d.get_temp::<u64>(egui::Id::unique("layer-drag")).is_some()
|| d.get_temp::<FxDrag>(fx_drag_key()).is_some()
|| d.get_temp::<MaskDrag>(mask_drag_key()).is_some()
|| d.get_temp::<crate::smart_ui::FilterDrag>(crate::smart_ui::drag_key()).is_some()
});
let dragging = held && ctx.input(|i| i.pointer.primary_down());
@@ -886,3 +886,183 @@ fn selecting_an_adjustment_layer_from_another_layer_targets_its_mask() {
}
}
}
/// #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 ⌥");
}
}
/// #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]
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");
}
/// #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");
}