Float the layer mask, not the layer, when the mask is targeted (#2468) (#2486)

This commit is contained in:
MarekSpodBiedry authored and GitHub committed 2026-10-10 13:12:20 -04:00
1 parent 24fbf4a84f
commit 93629daedc
4 files changed
+90 -25

No files matched your search

+2 -1
View File
@@ -556,7 +556,8 @@ pub(crate) fn mask_target_enabled(s: &Session, id: &str, p: &Value) -> Option<st
/// Whether command `id` edits the targeted channel or mask when its params name no `"target"`
/// (filters, adjustments, paint and fill commands); the shell adds its mask target to these.
pub fn follows_target(id: &str) -> bool {
routed(id)
// Moving the selected pixels (⌘-drag, Move tool) moves the targeted mask's, not the layer's.
routed(id) || id == "select.float"
}
/// Commands whose target follows the Channels panel.
+46 -23
View File
@@ -31,29 +31,40 @@ pub struct CutParts {
pub layer: LayerId,
rest: Surface,
piece: Surface,
/// The pieces are the layer's mask (`"target":"mask"`), not its pixels.
mask: bool,
}
impl CutParts {
/// Split `layer` of `doc` by its selection. With `copy` the selected pixels stay in the layer
/// too (the piece is a duplicate). Without, they leave a transparent hole, or on the Background,
/// which can't hold transparency, one filled with `background` (Photoshop). Errors without a
/// selection or pixels.
pub fn new(doc: &Document, layer: LayerId, copy: bool, background: [f32; 4]) -> Result<Self> {
/// selection or pixels. With `mask` the layer's mask is split instead of its pixels; the hole it
/// leaves takes the background colour (as on the Background layer).
pub fn new(doc: &Document, layer: LayerId, copy: bool, background: [f32; 4], mask: bool) -> Result<Self> {
let sel = doc.selection.as_ref().ok_or_else(|| EngineError::Other("no selection".into()))?;
let l = doc.layer(layer).ok_or(EngineError::NoLayer(layer))?;
let LayerContent::Raster(surf) = &l.content else {
return Err(EngineError::Other("the layer has no pixels to move".into()));
let surf = if mask {
&l.mask.as_ref().ok_or_else(|| EngineError::Other("the layer has no mask".into()))?.surface
} else {
let LayerContent::Raster(surf) = &l.content else {
return Err(EngineError::Other("the layer has no pixels to move".into()));
};
surf
};
let fmt = surf.format();
let with_alpha = PixelFormat::new(fmt.mode, fmt.sample, true);
let mut rest = if fmt == with_alpha { surf.clone() } else { surf.convert(with_alpha) };
let full = if fmt == with_alpha { surf.clone() } else { surf.convert(with_alpha) };
// A mask has no alpha: it keeps its format, and the cut leaves background colour.
let mut rest = if mask { surf.clone() } else { full.clone() };
let mut piece = Surface::new(with_alpha);
let fill = !copy && crate::extra_cmds::is_background(l);
let b = sel.content_bounds().intersect(&surf.content_bounds());
let fill = !copy && (mask || crate::extra_cmds::is_background(l));
// A mask's untouched pixels (its default, e.g. white) move too, so take the whole canvas.
let b = sel.content_bounds().intersect(&if mask { doc.bounds() } else { surf.content_bounds() });
if !b.is_empty() {
let n = with_alpha.channels();
let a = n - 1;
let mut rp = rest.read_region(b);
let mut rp = full.read_region(b);
let mut pp = rp.clone();
let w = b.width() as usize;
for (i, (p, r)) in pp.chunks_exact_mut(n).zip(rp.chunks_exact_mut(n)).enumerate() {
@@ -67,7 +78,9 @@ impl CutParts {
r[a] *= 1.0 - k;
}
}
rest.write_region(b, &rp);
if !mask {
rest.write_region(b, &rp);
}
if fill {
crate::pixels::fill_surface(&mut rest, b, background, Some(sel), true);
}
@@ -75,22 +88,34 @@ impl CutParts {
piece.write_region(b, &pp);
piece.prune();
}
Ok(Self { layer, rest, piece })
Ok(Self { layer, rest, piece, mask })
}
/// `doc` with the piece moved by whole pixels (dx, dy) over the cut-out layer.
pub fn moved(&self, doc: &Document, dx: i32, dy: i32) -> Result<Document> {
let mut d = doc.clone();
let surf = d
.layer_mut(self.layer)
.ok_or(EngineError::NoLayer(self.layer))?
.surface_mut()
.ok_or_else(|| EngineError::Other("the layer has no pixels to move".into()))?;
let mut out = self.rest.clone();
crate::transform_cmds::composite_over(&mut out, &photocraft_algo::resample::translate_surface(&self.piece, dx, dy));
*surf = out;
self.place(&mut d, dx, dy)?;
Ok(d)
}
/// Put the piece, moved by (dx, dy), over the cut-out layer (or mask) of `doc`.
fn place(&self, doc: &mut Document, dx: i32, dy: i32) -> Result<()> {
let l = doc.layer_mut(self.layer).ok_or(EngineError::NoLayer(self.layer))?;
let surf = if self.mask {
l.mask.as_mut().map(|m| &mut m.surface).ok_or_else(|| EngineError::Other("the layer has no mask".into()))?
} else {
l.surface_mut().ok_or_else(|| EngineError::Other("the layer has no pixels to move".into()))?
};
let mut out = self.rest.clone();
let piece = photocraft_algo::resample::translate_surface(&self.piece, dx, dy);
if self.mask {
crate::fill_cmds::composite_over(&mut out, &piece, piece.content_bounds(), None);
} else {
crate::transform_cmds::composite_over(&mut out, &piece);
}
*surf = out;
Ok(())
}
}
/// A piece floating `offset` whole pixels from where it was cut, over document `revision`.
@@ -150,7 +175,7 @@ fn float(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.active_mut().ok_or(EngineError::NoDocument)?;
if floating(st).is_none() {
let layer = st.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
let parts = CutParts::new(&st.doc, layer, copy, background)?;
let parts = CutParts::new(&st.doc, layer, copy, background, crate::commands::is_mask_target(p))?;
st.floating = Some(Floating { layer, offset: (0, 0), revision: st.revision, parts: Arc::new(parts) });
}
let f = st.floating.as_mut().ok_or(EngineError::NoDocument)?;
@@ -171,9 +196,7 @@ pub fn drop_floating(s: &mut Session) -> Result<Value> {
return Ok(json!({"dropped": true, "offset": [0, 0]}));
}
s.edit("Move", |doc, _| {
let moved = f.parts.moved(doc, dx, dy)?;
let surf = moved.layer(f.layer).and_then(|l| l.surface()).cloned().ok_or(EngineError::NoLayer(f.layer))?;
*doc.layer_mut(f.layer).ok_or(EngineError::NoLayer(f.layer))?.surface_mut().ok_or(EngineError::NoLayer(f.layer))? = surf;
f.parts.place(doc, dx, dy)?;
doc.selection = doc.selection.as_ref().map(|sel| photocraft_algo::resample::translate_surface(sel, dx, dy));
Ok(())
})?;
@@ -210,7 +233,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Float Selection",
menu: &[],
shortcut: None,
params: r##"{"dx":px=0,"dy":px=0,"copy":bool=false} → {layer, offset} (cuts the selected pixels of the active layer into a floating piece the first time, or with copy leaves them and floats a duplicate; on the Background the hole takes the background colour; then moves it by whole pixels; dropped by select.drop or any other command, put back by edit.undo)"##,
params: r##"{"dx":px=0,"dy":px=0,"copy":bool=false,"target":"pixels"|"mask"="pixels" (mask: float the selected part of the layer's mask, the hole takes the background colour)} → {layer, offset} (cuts the selected pixels of the active layer into a floating piece the first time, or with copy leaves them and floats a duplicate; on the Background the hole takes the background colour; then moves it by whole pixels; dropped by select.drop or any other command, put back by edit.undo)"##,
enabled: can_float,
journal: true,
run: float,
+41
View File
@@ -148,3 +148,44 @@ fn copy_floats_a_duplicate_and_leaves_the_original() {
let doc = &s.active().unwrap().doc;
assert!(alpha(doc, id, 12, 12) == 1.0 && alpha(doc, id, 42, 12) == 1.0, "dropped: both");
}
#[test]
fn float_with_the_mask_target_moves_the_mask_not_the_layer() {
let (mut s, id) = session();
s.edit("mask", |doc, _| {
let l = doc.layer_mut(id).unwrap();
let mut m = photocraft_doc::LayerMask::reveal_all();
m.surface.fill_rect(Rect::new(10, 10, 30, 30), &[0.0]);
l.mask = Some(m);
Ok(())
})
.unwrap();
let mask_at = |s: &Session, x, y| s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0);
s.execute("select.float", json!({"dx": 25, "dy": 0, "copy": true, "target": "mask"})).unwrap();
s.execute("select.drop", json!({})).unwrap();
assert_eq!(mask_at(&s, 12, 12), 0.0, "the copy leaves the mask where it was");
assert_eq!(mask_at(&s, 37, 12), 0.0, "the mask's selected part moved");
assert_eq!(mask_at(&s, 60, 12), 1.0);
assert_eq!(alpha(&s.active().unwrap().doc, id, 37, 12), 0.0, "the layer's pixels did not move");
assert_eq!(alpha(&s.active().unwrap().doc, id, 12, 12), 1.0);
}
#[test]
fn cutting_an_untouched_part_of_the_mask_moves_it_and_leaves_the_background_colour() {
let (mut s, id) = session();
s.edit("mask", |doc, _| {
let mut m = photocraft_doc::LayerMask::hide_all();
m.surface.fill_rect(Rect::new(50, 10, 70, 30), &[1.0]);
doc.layer_mut(id).unwrap().mask = Some(m);
Ok(())
})
.unwrap();
s.tools.background = [0.5, 0.5, 0.5, 1.0];
let mask_at = |s: &Session, x, y| s.active().unwrap().doc.layer(id).unwrap().mask.as_ref().unwrap().surface.sample_channel(x, y, 0);
// (10..30)² is the mask's untouched black; it moves over the white at (50..70, 10..30).
s.execute("select.float", json!({"dx": 40, "dy": 0, "target": "mask"})).unwrap();
s.execute("select.drop", json!({})).unwrap();
assert_eq!(mask_at(&s, 55, 12), 0.0, "the untouched black moved");
assert!((mask_at(&s, 12, 12) - 0.5).abs() < 0.01, "the hole takes the background colour");
assert_eq!(mask_at(&s, 40, 12), 0.0);
}
+1 -1
View File
@@ -50,7 +50,7 @@ curl -sfL -o assets/icons/<name>.svg https://raw.githubusercontent.com/lucide-ic
| Free Transform | `transform_tool.rs` | ⌘T. Corners and edges scale proportionally (⇧ frees them: an edge then stretches one axis); ⌥ scales about the reference point; ⌘-corner distorts; dragging outside rotates (⇧ snaps to 15°); dragging inside moves. Preview = document without the moving pixels + a textured 24×24 mesh. ↩ or a double-click commits via `edit.transform {rect, quad}`. |
| Quick layer pick | `quick_pick.rs` | macOS: ⌘⌥⌃-click with any tool selects the topmost visible layer with pixels under the pointer (`layer.pickAt`) without switching tools; the drag and release are swallowed. Windows/Linux have no third modifier distinct from the ⌃⌥ brush resize, so the gesture is a no-op there (use the Move tool's Auto-Select). A failed pick is a status-bar error. |
| Layers rows | `panels.rs` | Double-click: on the name renames in place; on the Background makes it a normal layer; on an adjustment or fill thumbnail opens its Properties; on a Smart Object thumbnail opens its contents (Edit Contents); anywhere else on the row opens Layer Style. |
| Layer masks | `panels.rs` | Clicking the mask thumbnail targets the mask (corner-bracket frame; the tab reads "Layer, Layer Mask/8"). Brush, eraser (paints background colour), gradient and bucket then send `"target": "mask"`. Adjustment and fill layers target their mask automatically. |
| Layer masks | `panels.rs` | Clicking the mask thumbnail targets the mask (corner-bracket frame; the tab reads "Layer, Layer Mask/8"). Brush, eraser (paints background colour), gradient, bucket and moving the selected pixels (⌘-drag, `select.float`; the hole takes the background colour) then send `"target": "mask"`. Adjustment and fill layers target their mask automatically. |
| Levels / Curves | `tone.rs` | Histogram of the image *below* the adjustment. Curves: click to add a point, drag out to delete. Every change is a coalesced `layer.setAdjustment`, so one drag = one undo step and the canvas updates at full resolution on the GPU. |
While editing type, hold Ctrl (Windows/Linux) or Command (macOS) for an oriented transform