PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Move tool: moving selected pixels shrinks the selection to them, as in Photoshop (#7538)
Hector Villarreal987753e76eef
diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rsindex e5450b233..8de2c3a7f 100644--- a/crates/engine/src/float_cmds.rs+++ b/crates/engine/src/float_cmds.rs@@ -12,11 +12,12 @@//! which puts it back and then returns to the chosen state.//!//! While floating, the document is unchanged; [`displayed`] gives the document with the piece at-//! its offset, for the canvas. The selection stays where it was until the drop.+//! its offset, for the canvas. The selection stays where it was until the drop, when it becomes+//! the piece's outline ([`CutParts::outline`]); the canvas shows that outline from the start.use std::sync::Arc;-use photocraft_color::PixelFormat;+use photocraft_color::{ColorMode, PixelFormat};use photocraft_doc::{Document, LayerContent, LayerId};use photocraft_raster::Surface;use serde_json::{Value, json};@@ -32,6 +33,10 @@ pub struct CutParts {pub layer: LayerId,rest: Surface,piece: Surface,+ /// The selection the moved pixels take, unmoved: the selection limited to the layer's+ /// transparency (Photoshop shrinks the marching ants to the piece as the drag starts, #7538).+ /// `None` keeps the selection: a mask has no transparency, and an empty piece no outline.+ outline: Option<Surface>,/// The pieces are the layer's mask (`"target":"mask"`), not its pixels.mask: bool,}@@ -59,6 +64,7 @@ impl CutParts {// 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 mut outline = Surface::new(PixelFormat::new(ColorMode::Grayscale, sel.format().sample, false));let fill = !copy && (mask || doc.is_background(layer));// 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() });@@ -86,10 +92,21 @@ impl CutParts {crate::pixels::try_fill_surface(&mut rest, b, background, Some(sel), true)?;}rest.prune();+ if !mask {+ // The piece's alpha is the selection times the layer's transparency.+ outline.write_region(b, &pp.chunks_exact(n).map(|p| p[a]).collect::<Vec<_>>());+ outline.prune();+ }piece.write_region(b, &pp);piece.prune();}- Ok(Self { layer, rest, piece, mask })+ let outline = (!outline.content_bounds().is_empty()).then_some(outline);+ Ok(Self { layer, rest, piece, outline, mask })+ }++ /// The selection the moved pixels take, where they were cut (`None`: the selection stays).+ pub fn outline(&self) -> Option<&Surface> {+ self.outline.as_ref()}/// `doc` with the piece moved by whole pixels (dx, dy) over the cut-out layer.@@ -184,7 +201,8 @@ fn float(s: &mut Session, p: &Value) -> Result<Value> {Ok(json!({"layer": f.layer.0, "offset": [f.offset.0, f.offset.1]}))}-/// Drop the floating piece into its layer and move the selection with it (one history step).+/// Drop the floating piece into its layer and move the selection with it, shrunk to the piece's+/// outline (one history step).pub fn drop_floating(s: &mut Session) -> Result<Value> {let Some(st) = s.active_mut() else { return Ok(json!({"dropped": false})) };let Some(f) = floating(st).cloned() else {@@ -198,7 +216,8 @@ pub fn drop_floating(s: &mut Session) -> Result<Value> {}s.edit("Move", |doc, _| {f.parts.place(doc, dx, dy)?;- doc.selection = doc.selection.as_ref().map(|sel| photocraft_algo::resample::translate_surface(sel, dx, dy));+ let sel = f.parts.outline().or(doc.selection.as_ref());+ doc.selection = sel.map(|sel| photocraft_algo::resample::translate_surface(sel, dx, dy));Ok(())})?;Ok(json!({"dropped": true, "offset": [dx, dy]}))@@ -251,7 +270,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Drop Floating Selection",menu: &[],shortcut: None,- params: r##"{} → {dropped, offset} (drops the floating piece into its layer and moves the selection with it: one history step)"##,+ params: r##"{} → {dropped, offset} (drops the floating piece into its layer and moves the selection with it, shrunk to the moved pixels: the selection times the layer's transparency, as in Photoshop; a mask or an empty piece keeps the selection's shape; one history step)"##,enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document".into()),journal: true,run: |s, _| drop_floating(s),diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/float_cmds/tests.rsindex bb2ba5b91..bb75eccf4 100644--- a/crates/engine/src/float_cmds/tests.rs+++ b/crates/engine/src/float_cmds/tests.rs@@ -189,3 +189,93 @@ fn cutting_an_untouched_part_of_the_mask_moves_it_and_leaves_the_background_coloassert!((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);}++/// Coverage of `d`'s selection at (x, y).+fn selected(d: &Document, x: i32, y: i32) -> f32 {+ d.selection.as_ref().map_or(0.0, |s| s.sample_channel(x, y, 0))+}++/// #7538: a marquee drawn loosely around an object on a transparent layer shrinks to the object+/// once its pixels move, as in Photoshop, at every depth and when moving a copy.+#[test]+fn moving_shrinks_the_selection_to_the_moved_pixels_at_every_depth() {+ for depth in [8, 16, 32] {+ for copy in [false, true] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 80, "height": 60, "background": "transparent", "depth": depth})).unwrap();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ // A marquee with empty space all round the red square.+ s.execute("select.rect", json!({"x": 4, "y": 6, "width": 34, "height": 30})).unwrap();+ s.execute("select.float", json!({"dx": 20, "dy": 5, "copy": copy})).unwrap();+ let st = s.active().unwrap();+ let outline = floating(st).unwrap().parts.outline().unwrap();+ assert_eq!(outline.content_bounds(), Rect::new(10, 10, 30, 30), "{depth}-bit, copy {copy}: the outline while floating");+ assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(4, 6, 38, 36), "the document's is untouched");+ s.execute("select.drop", json!({})).unwrap();+ let doc = &s.active().unwrap().doc;+ assert_eq!(doc.selection.as_ref().unwrap().content_bounds(), Rect::new(30, 15, 50, 35), "{depth}-bit, copy {copy}");+ assert_eq!((selected(doc, 40, 25), selected(doc, 26, 13)), (1.0, 0.0), "{depth}-bit, copy {copy}: the moved square only");+ // Undo brings back the marquee as it was drawn.+ s.undo();+ assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), Rect::new(4, 6, 38, 36), "{depth}-bit, copy {copy}");+ }+ }+}++/// The new selection is the old one times the layer's transparency: a soft selection over+/// half-transparent pixels keeps both (Photoshop's selection ∩ transparency).+#[test]+fn the_outline_keeps_soft_edges_and_partial_transparency() {+ let (mut s, id) = session();+ s.edit("soften", |doc, _| {+ // Half-transparent red over (30..40, 10..30), beside the opaque (10..30)² square.+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(Rect::new(30, 10, 40, 30), &[1.0, 0.0, 0.0, 0.5]);+ let mut sel = Surface::new(PixelFormat::GRAY8);+ sel.fill_rect(Rect::new(0, 0, 60, 50), &[0.5]);+ sel.fill_rect(Rect::new(10, 10, 20, 30), &[1.0]);+ doc.selection = Some(sel);+ Ok(())+ })+ .unwrap();+ s.execute("select.float", json!({"dx": 10, "dy": 0})).unwrap();+ s.execute("select.drop", json!({})).unwrap();+ let doc = &s.active().unwrap().doc;+ let near = |x: i32, y: i32, want: f32| assert!((selected(doc, x, y) - want).abs() < 0.01, "({x}, {y}): {} for {want}", selected(doc, x, y));+ near(25, 20, 1.0); // fully selected, opaque+ near(35, 20, 0.5); // half selected, opaque+ near(45, 20, 0.25); // half selected, half transparent+ near(5, 5, 0.0); // selected, but nothing there+ assert_eq!(doc.selection.as_ref().unwrap().content_bounds(), Rect::new(20, 10, 50, 30));+}++/// Where the selection is the moved piece already (the Background, which has no transparency)+/// or the piece has no outline (a mask, or only transparent pixels), the selection just moves.+#[test]+fn the_selection_just_moves_without_transparency_to_shrink_to() {+ // The Background.+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 40})).unwrap();+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 10, "height": 10})).unwrap();+ s.execute("select.float", json!({"dx": 15, "dy": 0})).unwrap();+ s.execute("select.drop", json!({})).unwrap();+ assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), Rect::new(20, 5, 30, 15), "the Background");+ // Only transparent pixels selected.+ let (mut s, _) = session();+ s.execute("select.rect", json!({"x": 40, "y": 5, "width": 10, "height": 10})).unwrap();+ s.execute("select.float", json!({"dx": 5, "dy": 0})).unwrap();+ assert!(floating(s.active().unwrap()).unwrap().parts.outline().is_none());+ s.execute("select.drop", json!({})).unwrap();+ assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), Rect::new(45, 5, 55, 15), "an empty piece");+ // The mask: it has no transparency of its own.+ let (mut s, id) = session();+ s.edit("mask", |doc, _| {+ doc.layer_mut(id).unwrap().mask = Some(photocraft_doc::LayerMask::reveal_all());+ Ok(())+ })+ .unwrap();+ s.execute("select.rect", json!({"x": 5, "y": 5, "width": 40, "height": 40})).unwrap();+ s.execute("select.float", json!({"dx": 5, "dy": 0, "target": "mask"})).unwrap();+ s.execute("select.drop", json!({})).unwrap();+ assert_eq!(s.active().unwrap().doc.selection.as_ref().unwrap().content_bounds(), Rect::new(10, 5, 50, 45), "the mask");+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 0d5fbe1b8..d5501fbc5 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -3224,8 +3224,10 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:// Select and Mask outlines its refined selection (on its preview proxy, reduced by `k`) in// the Marching Ants view and hides the ants in the others.let refined = crate::select_mask_view::ants(app, idx);+ // A floating piece's ants hug the pixels being moved.+ let floated = floating_outline(app, idx);let (outlined, k) = match &refined {- None => (doc.selection.as_ref(), 1),+ None => (floated.as_ref().or(doc.selection.as_ref()), 1),Some(None) => (None, 1),Some(Some((proxy, k))) => (proxy.selection.as_ref(), (*k).max(1)),};@@ -5760,6 +5762,16 @@ pub(crate) fn selection_drag_delta(app: &PhotocraftApp) -> Option<(i32, i32)> {Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32))}+/// The selection a floating piece on document `idx` shows its ants for, before its offset: the+/// moved pixels' outline, as in Photoshop (#7538); `None` outlines the document's selection. The+/// surface's tiles are shared, so the clone is cheap.+pub(crate) fn floating_outline(app: &PhotocraftApp, idx: usize) -> Option<photocraft_raster::Surface> {+ if app.session.active_index() != Some(idx) {+ return None;+ }+ photocraft_engine::float_cmds::floating(app.session.active()?)?.parts.outline().cloned()+}+/// Where the selection is drawn relative to where it is: a floating piece's offset plus a drag/// in progress.fn selection_shown_offset(app: &PhotocraftApp) -> Option<(i32, i32)> {diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rsindex fb49b0247..347151660 100644--- a/crates/ui-egui/src/move_ui.rs+++ b/crates/ui-egui/src/move_ui.rs@@ -478,6 +478,28 @@ mod tests {}}+ /// #7538: a loose marquee round the red square shrinks to it as the drag starts: the canvas+ /// outlines the moved pixels while they float, and the dropped selection is theirs. Alt-drag+ /// (a copy) too.+ #[test]+ fn dragging_selected_pixels_shrinks_the_ants_to_them() {+ for depth in [8, 16, 32] {+ for m in [egui::Modifiers::NONE, egui::Modifiers::ALT] {+ let (mut app, _) = selected_pixels(depth);+ app.session.execute("select.rect", json!({"x": 2, "y": 2, "width": 30, "height": 30})).unwrap();+ drag(&mut app, [16.0, 16.0], [26.0, 21.0], m);+ assert_eq!(offset(&app), Some((10, 5)), "{depth}-bit, {m:?}: floating");+ let ants = crate::canvas::floating_outline(&app, 0).map(|s| s.content_bounds());+ assert_eq!(ants, Some(Rect::new(8, 8, 24, 24)), "{depth}-bit, {m:?}: the ants hug the red square");+ assert!(crate::canvas::floating_outline(&app, 1).is_none(), "only the active document's");+ app.run("select.drop", json!({})).unwrap();+ let sel = app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds());+ assert_eq!(sel, Some(Rect::new(18, 13, 34, 29)), "{depth}-bit, {m:?}: dropped");+ assert!(crate::canvas::floating_outline(&app, 0).is_none(), "nothing floats");+ }+ }+ }+/// ⌘-drag with a painting tool drags the selected pixels as the Move tool does, also when ⌘/// comes with the event (control channel, MCP) rather than as the held-key override.#[test]diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex e0b122c37..f8d9c0bbf 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -101,11 +101,26 @@ fn moving_rect(app: &PhotocraftApp, tool: Tool) -> Option<[f64; 4]> {union(st.selected_layers().into_iter().filter_map(|id| layer_rect(&st.doc, id)))}-/// The selection's bounds where it is shown: moved by its floating piece's offset.+/// The bounds of the pixels a selection moves, where they are shown (#7538): its floating piece's+/// outline at its offset. Before a drag first cuts the piece, the selection's bounds over the+/// active layer's pixels, which hold the outline (exactly when the pixels lie in the selection).+/// A targeted mask, an opaque layer or no pixels selected: the selection's own bounds.fn selection_rect(app: &PhotocraftApp) -> Option<[f64; 4]> {let st = app.session.active()?;- let (dx, dy) = photocraft_engine::float_cmds::floating(st).map_or((0, 0), |f| f.offset);- let r = st.doc.selection.as_ref()?.content_bounds().translate(dx, dy);+ let sel = st.doc.selection.as_ref()?;+ let r = match photocraft_engine::float_cmds::floating(st) {+ Some(f) => f.parts.outline().unwrap_or(sel).content_bounds().translate(f.offset.0, f.offset.1),+ None => {+ let b = sel.content_bounds();+ let pixels = st+ .active_layer+ .filter(|&id| !st.doc.is_background(id) && crate::canvas::paint_target(app) == "pixels")+ .and_then(|id| st.doc.layer(id)?.surface())+ .filter(|s| s.format().alpha)+ .map(|s| b.intersect(&s.content_bounds()));+ pixels.filter(|p| !p.is_empty()).unwrap_or(b)+ }+ };(!r.is_empty()).then(|| [r.x0, r.y0, r.x1, r.y1].map(f64::from))}@@ -555,6 +570,23 @@ mod tests {app}+ /// #7538: moving selected pixels snaps (and frames) the pixels, not a loose marquee round them:+ /// the box hugs the moved pixels before the first drag cuts them and while they float.+ #[test]+ fn moving_selected_pixels_snaps_their_bounds_not_the_marquee() {+ let mut app = app_with_box();+ app.ui.tool = Tool::Move;+ app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap();+ assert_eq!(moving_rect(&app, Tool::Move), Some([40.0, 40.0, 90.0, 80.0]), "before the cut");+ app.run("select.float", json!({"dx": 10, "dy": 5})).unwrap();+ assert_eq!(moving_rect(&app, Tool::Move), Some([50.0, 45.0, 100.0, 85.0]), "floating");+ app.run("select.drop", json!({})).unwrap();+ // The Background has no transparency to shrink to.+ app.run("layer.select", json!({"name": "Background"})).unwrap();+ app.run("select.rect", json!({"x": 20, "y": 20, "width": 100, "height": 90})).unwrap();+ assert_eq!(moving_rect(&app, Tool::Move), Some([20.0, 20.0, 120.0, 110.0]), "the Background");+ }+fn mover_bounds(app: &PhotocraftApp) -> photocraft_geom::Rect {let st = app.session.active().unwrap();st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().content_bounds()diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 793f09840..b5f960e50 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -1,6 +1,6 @@# UI parity: tools, handles, modifiers and feel-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-15 · **Change:** minor (Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-18 · **Change:** minor (Move tool: dragged selected pixels take their own outline as the selection, #7538; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, thehandles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,@@ -94,6 +94,7 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme| Arrow nudge of path points with Direct Selection | missing | no arrow handling in `direct_select.rs` || ⌘-arrow nudges the layer from any tool | missing | #2474 || ⌥-drag duplicates, ⇧ constrains to 45° | done | `move_mods.rs` |+| Dragging selected pixels shrinks the selection to them (the selection times the layer's transparency) as the drag starts, also with ⌥; the move box and snapping use the moved pixels' bounds | done | #7538, `canvas.rs` `floating_outline`, `snap_ui.rs` `selection_rect`, engine `float_cmds.rs` `CutParts::outline` || Auto-Select with hover outline, box-select layers, double-click fit | missing | TOOL-214-4 || Auto-Select bounding box and snapping follow the picked layer | partial | follow the previous layer (#2666) || Several layers selected (⇧-click adds, box-select): Show Transform Controls frames them all, with every selected shape's outline | partial: the shared frame has no handles, since Free Transform works on one layer (`canvas.rs` `transform_controls_layers`, `several_selected_layers_share_one_frame_without_handles`; `move_auto_select_tests.rs`) | |@@ -257,3 +258,4 @@ Paragraph; the rest open as in-app floating windows.| 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit || 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) || 2026-10-14 | minor | Move › Show Transform Controls frames every selected layer and outlines the selected shapes |+| 2026-10-18 | minor | Move tool: dragging selected pixels shrinks the marching ants to the moved pixels as the drag starts, and the dropped selection is theirs, as in Photoshop (#7538) |