PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Selections: drag to move the outline; ⌘-drag floats the selected pixels (engine commands) (#686)
jason4short6c7d01a0f3ff
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 9d0f229cc..9d53f6684 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -940,6 +940,7 @@ fn build() -> Vec<CommandSpec> {v.extend(crate::gradient_fill_cmds::specs());v.extend(crate::type_cmds::specs());v.extend(crate::transform_cmds::specs());+ v.extend(crate::float_cmds::specs());v.extend(crate::vector_cmds::specs());v.extend(crate::smartselect_cmds::specs());v.extend(crate::cutout_cmds::specs());diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rsnew file mode 100644index 000000000..988d9ae23--- /dev/null+++ b/crates/engine/src/float_cmds.rs@@ -0,0 +1,213 @@+//! Floating selection: the selected pixels of a layer cut out and moved as a piece, without+//! touching the document until the piece is dropped.+//!+//! - `select.float {"dx","dy"}` cuts the selected pixels of the active layer into a floating piece+//! (the first time) and moves it by whole pixels. Further calls move the same piece; nothing new+//! is cut.+//! - `select.drop` drops the piece into its layer and moves the selection with it, as one history+//! step.+//! - Any other command drops the piece first (so it lands exactly where it was shown), except Undo,+//! which puts it back where it was cut (nothing was changed yet).+//!+//! 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.++use std::sync::Arc;++use photocraft_color::PixelFormat;+use photocraft_doc::{Document, LayerContent, LayerId};+use photocraft_raster::Surface;+use serde_json::{Value, json};++use crate::commands::CommandSpec;+use crate::{DocState, EngineError, Result, Session};++/// A layer split by its selection: the layer with the selected pixels cut out, and the cut pixels+/// (cropped to the selection). Splitting touches only the selection's area, and placing the piece+/// ([`CutParts::moved`]) only the piece's: the cut-out layer's other tiles are shared.+#[derive(Clone, Debug)]+pub struct CutParts {+ pub layer: LayerId,+ rest: Surface,+ piece: Surface,+}++impl CutParts {+ /// Split `layer` of `doc` by its selection. Errors without a selection or pixels.+ pub fn new(doc: &Document, layer: LayerId) -> 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 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 mut piece = Surface::new(with_alpha);+ let b = sel.content_bounds().intersect(&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 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() {+ let k = sel.sample_channel(b.x0 + (i % w) as i32, b.y0 + (i / w) as i32, 0);+ if k <= 0.0 {+ p.fill(0.0);+ } else {+ p[a] *= k;+ }+ r[a] *= 1.0 - k;+ }+ rest.write_region(b, &rp);+ rest.prune();+ piece.write_region(b, &pp);+ piece.prune();+ }+ Ok(Self { layer, rest, piece })+ }++ /// `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;+ Ok(d)+ }+}++/// A piece floating `offset` whole pixels from where it was cut, over document `revision`.+#[derive(Clone, Debug)]+pub struct Floating {+ pub layer: LayerId,+ pub offset: (i32, i32),+ pub revision: u64,+ pub parts: Arc<CutParts>,+}++/// The floating piece of `st`, if it is still valid (the document hasn't changed under it).+pub fn floating(st: &DocState) -> Option<&Floating> {+ st.floating.as_ref().filter(|f| f.revision == st.revision && st.doc.selection.is_some())+}++/// The document as shown while a piece floats `extra` further than its offset (a drag of it in+/// progress); `None` when nothing floats.+pub fn displayed(st: &DocState, extra: (i32, i32)) -> Option<Document> {+ let f = floating(st)?;+ f.parts.moved(&st.doc, f.offset.0 + extra.0, f.offset.1 + extra.1).ok()+}++fn int_param(p: &Value, key: &str) -> i32 {+ p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()).map_or(0, |v| v.round().clamp(-1e7, 1e7) as i32)+}++fn can_float(s: &Session) -> std::result::Result<(), String> {+ let st = s.active().ok_or("no document")?;+ if floating(st).is_some() {+ return Ok(());+ }+ if st.doc.selection.is_none() {+ return Err("there is no selection".into());+ }+ let l = st.active_layer.and_then(|id| st.doc.layer(id)).ok_or("no active layer")?;+ if !matches!(l.content, LayerContent::Raster(_)) {+ return Err("the active layer has no pixels to move".into());+ }+ if l.locks.all || l.locks.position {+ return Err(format!("layer \"{}\" is locked", l.name));+ }+ Ok(())+}++fn float(s: &mut Session, p: &Value) -> Result<Value> {+ let (dx, dy) = (int_param(p, "dx"), int_param(p, "dy"));+ 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)?;+ 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)?;+ f.offset = (f.offset.0.saturating_add(dx), f.offset.1.saturating_add(dy));+ 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).+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 {+ st.floating = None;+ return Ok(json!({"dropped": false}));+ };+ st.floating = None;+ let (dx, dy) = f.offset;+ if (dx, dy) == (0, 0) {+ return Ok(json!({"dropped": true, "offset": [0, 0]}));+ }+ s.edit("Move Selected Pixels", |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;+ doc.selection = doc.selection.as_ref().map(|sel| photocraft_algo::resample::translate_surface(sel, dx, dy));+ Ok(())+ })?;+ Ok(json!({"dropped": true, "offset": [dx, dy]}))+}++/// Commands that leave a floating piece floating: its own, and ones that don't touch documents.+fn keeps_floating(id: &str) -> bool {+ matches!(id, "select.float" | "select.drop") || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p))+}++/// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up:+/// returns its result); every other command but the floating ones drops it first.+pub(crate) fn before_command(s: &mut Session, id: &str) -> Result<Option<Value>> {+ let Some(st) = s.active_mut() else { return Ok(None) };+ if floating(st).is_none() {+ st.floating = None;+ return Ok(None);+ }+ match id {+ "edit.undo" | "edit.stepBackward" => {+ st.floating = None;+ Ok(Some(json!({"floating": "returned"})))+ }+ _ if keeps_floating(id) => Ok(None),+ _ => drop_floating(s).map(|_| None),+ }+}++pub fn specs() -> Vec<CommandSpec> {+ vec![+ CommandSpec {+ id: "select.float",+ label: "Float Selection",+ menu: &[],+ shortcut: None,+ params: r##"{"dx":px=0,"dy":px=0} → {layer, offset} (cuts the selected pixels of the active layer into a floating piece the first time, 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,+ },+ CommandSpec {+ id: "select.drop",+ 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)"##,+ enabled: |s| s.active().map(|_| ()).ok_or_else(|| "no document".into()),+ journal: true,+ run: |s, _| drop_floating(s),+ },+ ]+}++#[cfg(test)]+mod tests;diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/float_cmds/tests.rsnew file mode 100644index 000000000..1914077c9--- /dev/null+++ b/crates/engine/src/float_cmds/tests.rs@@ -0,0 +1,100 @@+use photocraft_geom::Rect;+use serde_json::json;++use super::*;++/// An 80×60 transparent document whose layer is painted red over (10..30)²; (10..30)² selected.+fn session() -> (Session, LayerId) {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap();+ let id = s.active().unwrap().active_layer.unwrap();+ s.edit("paint", |doc, _| {+ doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();+ (s, id)+}++fn alpha(d: &Document, id: LayerId, x: i32, y: i32) -> f32 {+ d.layer(id).unwrap().surface().unwrap().rgba(x, y)[3]+}++#[test]+fn float_moves_a_cut_piece_without_touching_the_document_until_dropped() {+ let (mut s, id) = session();+ let steps = s.active().unwrap().history.past_len();+ assert_eq!(s.execute("select.float", json!({"dx": 15, "dy": 0})).unwrap()["offset"], json!([15, 0]));+ // Moving it again doesn't cut anything new.+ s.execute("select.float", json!({"dx": 0, "dy": 10})).unwrap();+ let st = s.active().unwrap();+ assert_eq!(floating(st).unwrap().offset, (15, 10));+ assert_eq!(alpha(&st.doc, id, 12, 12), 1.0, "the document is untouched while floating");+ assert_eq!(st.history.past_len(), steps);+ let shown = displayed(st, (0, 0)).unwrap();+ assert!(alpha(&shown, id, 12, 12) == 0.0 && alpha(&shown, id, 27, 22) == 1.0, "shown cut and moved");+ // Drop: one history step, pixels and selection where they were shown.+ s.execute("select.drop", json!({})).unwrap();+ let st = s.active().unwrap();+ assert!(floating(st).is_none());+ assert_eq!(st.history.past_len(), steps + 1);+ for (x, y) in [(12, 12), (27, 22), (44, 39), (40, 40)] {+ assert_eq!(alpha(&st.doc, id, x, y), alpha(&shown, id, x, y), "dropped as shown at ({x}, {y})");+ }+ assert_eq!(st.doc.selection.as_ref().unwrap().content_bounds(), Rect::new(25, 20, 45, 40));+ // Undo takes the whole move back.+ s.undo();+ assert_eq!(alpha(&s.active().unwrap().doc, id, 12, 12), 1.0);+}++#[test]+fn any_other_command_drops_it_and_undo_puts_it_back() {+ let (mut s, id) = session();+ let steps = s.active().unwrap().history.past_len();+ s.execute("select.float", json!({"dx": 20, "dy": 0})).unwrap();+ // Undo while floating: the piece goes back; nothing in the document or history changed.+ assert_eq!(s.execute("edit.undo", json!({})).unwrap()["floating"], json!("returned"));+ let st = s.active().unwrap();+ assert!(floating(st).is_none() && alpha(&st.doc, id, 12, 12) == 1.0 && st.history.past_len() == steps);+ // Float again, then deselect: dropped first (where it was shown), then deselected.+ s.execute("select.float", json!({"dx": 20, "dy": 0})).unwrap();+ s.execute("select.deselect", json!({})).unwrap();+ let st = s.active().unwrap();+ assert!(st.doc.selection.is_none() && floating(st).is_none());+ assert!(alpha(&st.doc, id, 12, 12) == 0.0 && alpha(&st.doc, id, 35, 20) == 1.0);+}++#[test]+fn needs_a_selection_and_an_unlocked_pixel_layer() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 20, "height": 20})).unwrap();+ assert!(!s.is_enabled("select.float"), "no selection");+ s.execute("select.all", json!({})).unwrap();+ assert!(!s.is_enabled("select.float"), "the Background is locked");+ s.execute("layer.new.layer", json!({})).unwrap();+ assert!(s.is_enabled("select.float"));+}++/// `cargo test --release -p photocraft-engine float_drag_bench -- --ignored --nocapture`+#[test]+#[ignore]+fn float_drag_bench() {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 6000, "height": 4000, "background": "transparent"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.edit("paint", |doc, a| {+ doc.layer_mut(a.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(0, 0, 6000, 4000), &[0.2, 0.4, 0.6, 1.0]);+ Ok(())+ })+ .unwrap();+ s.execute("select.rect", json!({"x": 1000, "y": 1000, "width": 500, "height": 400})).unwrap();+ let t = std::time::Instant::now();+ s.execute("select.float", json!({})).unwrap();+ let cut = t.elapsed();+ let t = std::time::Instant::now();+ for i in 0..20 {+ displayed(s.active().unwrap(), (i * 7, i * 3)).unwrap();+ }+ eprintln!("6000×4000 layer, 500×400 piece: cut {cut:?}, then {:?} per pointer move", t.elapsed() / 20);+}diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex a5fa43685..e91a1b2a3 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -594,6 +594,10 @@ impl Session {if !(params.is_object() || params.is_null()) {return Err(EngineError::BadParams { cmd: id.to_string(), msg: "params must be a JSON object".into() });}+ // A floating selection drops before any other command (Undo puts it back instead).+ if let Some(v) = crate::float_cmds::before_command(self, id)? {+ return Ok(Started::Done(v));+ }if let Err(why) = crate::smart_cmds::target_enabled(self, spec, ¶ms).unwrap_or_else(|| (spec.enabled)(self)) {return Err(EngineError::Disabled(id.to_string(), why));}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 0d9174205..009dad0b9 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -33,6 +33,7 @@ pub mod fill_cmds;pub mod fill_key_cmds;pub mod filters;pub mod filters_ext;+pub mod float_cmds;mod frame_cmds;pub mod fx_view_cmds;pub mod gallery_cmds;@@ -167,6 +168,9 @@ pub struct DocState {/// ⌥-click on a layer's eye (`layer.showOnly`): the layer shown alone and every layer's/// visibility before, so the next ⌥-click restores it (view state, not history).pub show_only: Option<(LayerId, Vec<(LayerId, bool)>)>,+ /// A floating selection (`select.float`): the cut piece and where it floats, until dropped+ /// (view state: the document is unchanged until `select.drop`).+ pub floating: Option<float_cmds::Floating>,}impl DocState {@@ -190,6 +194,7 @@ impl DocState {symmetry_path: None,fx_collapsed: Vec::new(),show_only: None,+ floating: None,}}/// The selected layers in bottom-to-top document order, always including the active layer.diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex fc9629b06..cbf71831c 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -49,11 +49,14 @@ pub struct Drag {/// The reposition key (Space) is held: pointer moves move the whole gesture instead of/// sizing it (marquees, lasso, shapes; `hold_keys`).pub reposition: bool,+ /// A marquee or lasso drag that started inside the selection moves it instead of drawing:+ /// `Some(false)` moves the outline, `Some(true)` moves the floating piece (`select.float`).+ pub sel_move: Option<bool>,}impl Drag {pub fn new(tool: Tool, start: [f64; 2], points: Vec<[f64; 3]>, modifiers: egui::Modifiers, erase: bool) -> Self {- Self { tool, start, points, modifiers, erase, constrain: None, live: modifiers, released: egui::Modifiers::NONE, reposition: false }+ Self { tool, start, points, modifiers, erase, constrain: None, live: modifiers, released: egui::Modifiers::NONE, reposition: false, sel_move: None }}/// Reposition: move the start and every point so the last one lands on `to` (same size).@@ -1584,7 +1587,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:}if let Some((_, _, segs)) = &app.outline_cache {let time = ui.input(|i| i.time);- marching_ants_segments(&painter, &xf, segs, time);+ // A floating piece (and a selection being dragged) draws its ants where it is shown.+ let mut shown = xf;+ if let Some((dx, dy)) = selection_shown_offset(app) {+ shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32];+ }+ marching_ants_segments(&painter, &shown, segs, time);ctx.request_repaint_after(std::time::Duration::from_millis(100));}}@@ -1840,6 +1848,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:ui.ctx().set_cursor_icon(c);} else if let Some(c) = response.hover_pos().filter(|_| tool == Tool::Crop).and_then(|p| crate::crop_ui::cursor(app, xf.to_doc(p))) {ui.ctx().set_cursor_icon(c);+ } else if app.drag.as_ref().is_some_and(|d| d.sel_move.is_some())+ || response.hover_pos().is_some_and(|p| app.drag.is_none() && selection_drag_kind(app, tool, xf.to_doc(p), ui.input(|i| i.modifiers)).is_some())+ {+ // Over the ants with a marquee or lasso: a press drags the selection.+ ui.ctx().set_cursor_icon(egui::CursorIcon::Move);} else if let Some(p) = response.hover_pos() {let alt = ui.input(|i| i.modifiers.alt);let icon = match tool {@@ -2128,6 +2141,10 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &Viewapp.trail = None;return;};+ // Dragging the selection: its own ants follow the pointer (`selection_shown_offset`).+ if d.sel_move.is_some() {+ return;+ }let last = d.points.last().map(|p| [p[0], p[1]]).unwrap_or(d.start);let marquee = matches!(d.tool, Tool::RectMarquee | Tool::EllipseMarquee).then(|| marquee_corners(&app.ui.tool_options, d, last));if let Some((a, b)) = marquee {@@ -2275,6 +2292,13 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)crate::transform_tool::end_if_left(app);// View › Snap / Snap To and smart guides (snap_ui.rs).let raw = ev;+ // A press anywhere but on the floating piece (or with ⇧ / ⌥, to draw) drops it first.+ if let ToolEvent::Down { x, y, .. } = raw+ && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some())+ && selection_drag_kind(app, app.ui.tool, [x, y], mods) != Some(true)+ {+ let _ = app.run("select.drop", json!({}));+ }let ev = crate::snap_ui::filter_event(app, ev, mods);// Free Transform picks the handle under the press where the user clicked: the snapped press// can land outside the corner's grab area and turn a corner drag into a move of the whole box.@@ -2362,6 +2386,22 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)if !sets_source && crate::rasterize_prompt::intercept(app, tool, x, y, pressure) {return;}+ // Marquee / lasso inside the selection: drag the outline, or ⌘-drag to cut the selected+ // pixels into a floating piece (`select.float`) and drag that.+ if let Some(cut) = selection_drag_kind(app, tool, [x, y], mods) {+ if cut+ && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_none())+ && let Err(e) = app.run("select.float", json!({"dx": 0, "dy": 0}))+ {+ app.ui.status = e;+ app.ui.status_error = true;+ return;+ }+ let mut d = Drag::new(tool, [x, y], vec![[x, y, pressure as f64]], mods, false);+ d.sel_move = Some(cut);+ app.drag = Some(d);+ return;+ }match tool {Tool::Pen => {crate::vector_ui::pen_down(app, x, y);@@ -2450,8 +2490,71 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)}}+/// Is document point `p` inside the active document's selection?+fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool {+ let Some(sel) = app.session.active().and_then(|st| st.doc.selection.as_ref()) else { return false };+ let mut v = [0.0f32];+ sel.read_pixel(p[0].floor() as i32, p[1].floor() as i32, &mut v);+ v[0] > 0.0+}++/// Does a press with `tool` at `p` drag the selection rather than draw a new one? `Some(true)`+/// moves the floating piece (⌘ cuts one first; a floating piece moves with a plain drag),+/// `Some(false)` just the outline (no ⇧ / ⌥ and the options bar on New Selection, so a combining+/// drag still draws).+pub fn selection_drag_kind(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> Option<bool> {+ if !matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso) {+ return None;+ }+ if let Some(f) = app.session.active().and_then(photocraft_engine::float_cmds::floating) {+ let on = inside_selection(app, [p[0] - f64::from(f.offset.0), p[1] - f64::from(f.offset.1)]);+ return (on && !mods.shift && !mods.alt).then_some(true);+ }+ if !inside_selection(app, p) {+ return None;+ }+ if mods.command && !mods.shift && !mods.alt {+ return Some(true);+ }+ (!mods.command && selection_mode(app, mods) == "replace").then_some(false)+}++/// Whole-pixel offset of a selection drag in progress (`Drag::sel_move`).+pub(crate) fn selection_drag_delta(app: &PhotocraftApp) -> Option<(i32, i32)> {+ let d = app.drag.as_ref().filter(|d| d.sel_move.is_some())?;+ let end = d.points.last().map_or(d.start, |p| [p[0], p[1]]);+ Some(((end[0] - d.start[0]).round().clamp(-1e7, 1e7) as i32, (end[1] - d.start[1]).round().clamp(-1e7, 1e7) as i32))+}++/// 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)> {+ crate::move_ui::floating_offset(app).or_else(|| selection_drag_delta(app))+}++/// End of a selection drag: move the outline, or the floating piece. A click without moving+/// deselects, like a marquee click (a click on a floating piece leaves it floating).+fn finish_selection_drag(app: &mut PhotocraftApp, floating: bool, start: [f64; 2], end: [f64; 2]) {+ let (dx, dy) = ((end[0] - start[0]).round(), (end[1] - start[1]).round());+ let r = match (floating, dx == 0.0 && dy == 0.0) {+ (true, true) => return,+ (false, true) if app.session.is_enabled("select.deselect") => app.run("select.deselect", json!({})),+ (false, true) => return,+ (true, false) => app.run("select.float", json!({"dx": dx, "dy": dy})),+ (false, false) => app.run("select.transformSelection", json!({"dx": dx, "dy": dy})),+ };+ if let Err(e) = r {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}+fn finish_gesture(app: &mut PhotocraftApp, d: Drag) {let end = d.points.last().copied().unwrap_or([d.start[0], d.start[1], 1.0]);+ if let Some(floating) = d.sel_move {+ finish_selection_drag(app, floating, d.start, [end[0], end[1]]);+ return;+ }// Where the next ⇧-click line starts.if crate::stroke_constraint::connects(d.tool)&& let Some(st) = app.session.active()diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rsindex f80c3f0c5..14c6a9f96 100644--- a/crates/ui-egui/src/marquee_tests.rs+++ b/crates/ui-egui/src/marquee_tests.rs@@ -204,3 +204,89 @@ fn marquee_drag_bench() {eprintln!("marquee drag on 6000x4000 (shift+alt, readout): {ms:.2} ms per frame");assert!(h.query_by_label("W:").is_some());}++/// An 80×60 transparent document, red over (10..30)², that square selected, Rectangular Marquee.+fn painted() -> (PhotocraftApp, photocraft_doc::LayerId) {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 80, "height": 60, "background": "transparent"})).unwrap();+ app.sync_views();+ app.ui.extras.snap = false;+ app.ui.tool = Tool::RectMarquee;+ let layer = app.session.active().unwrap().active_layer.unwrap();+ app.session+ .edit("paint", |doc, _| {+ doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(Rect::new(10, 10, 30, 30), &[1.0, 0.0, 0.0, 1.0]);+ Ok(())+ })+ .unwrap();+ app.run("select.rect", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();+ (app, layer)+}++fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: Modifiers) {+ use crate::canvas::{ToolEvent, tool_event};+ tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m);+ tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m);+}++/// A drag inside the ants moves the outline (`select.transformSelection`); ⇧ still draws (adds);+/// a click inside deselects.+#[test]+fn drag_inside_the_selection_moves_the_outline() {+ let (mut app, layer) = painted();+ let sel = |app: &PhotocraftApp| app.session.active().unwrap().doc.selection.as_ref().map(|s| s.content_bounds());+ drag(&mut app, [20.0, 20.0], [30.0, 25.0], Modifiers::NONE);+ assert_eq!(sel(&app), Some(Rect::new(20, 15, 40, 35)));+ assert_eq!(app.session.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().rgba(12, 12)[3], 1.0, "pixels stay put");+ drag(&mut app, [30.0, 20.0], [60.0, 50.0], Modifiers::SHIFT);+ assert_eq!(sel(&app), Some(Rect::new(20, 15, 60, 50)));+ drag(&mut app, [30.0, 20.0], [30.0, 20.0], Modifiers::NONE);+ assert_eq!(sel(&app), None);+}++/// ⌘-drag cuts the selected pixels into a floating piece (`select.float`): shown at the pointer+/// while dragging, moved again by plain drags, put back by Undo, dropped by Deselect.+#[test]+fn cmd_drag_floats_the_selected_pixels() {+ use crate::canvas::{ToolEvent, tool_event};+ let (mut app, layer) = painted();+ let alpha = |d: &photocraft_doc::Document, x, y| d.layer(layer).unwrap().surface().unwrap().rgba(x, y)[3];+ let doc = |app: &PhotocraftApp| app.session.active().unwrap().doc.clone();+ let offset = |app: &PhotocraftApp| photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset);+ let steps = app.session.active().unwrap().history.past_len();+ tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, Modifiers::COMMAND);+ tool_event(&mut app, ToolEvent::Move { x: 35.0, y: 20.0, pressure: 1.0 }, Modifiers::COMMAND);+ let (shown, _) = crate::move_ui::display_doc(&mut app, 0).expect("the piece shows at the pointer while dragging");+ assert!(alpha(&shown, 12, 20) == 0.0 && alpha(&shown, 40, 20) == 1.0);+ tool_event(&mut app, ToolEvent::Up { x: 35.0, y: 20.0 }, Modifiers::COMMAND);+ assert_eq!(offset(&app), Some((15, 0)));+ assert_eq!(alpha(&doc(&app), 12, 20), 1.0, "the document waits for the drop");+ // A plain drag on the piece moves it again.+ drag(&mut app, [30.0, 20.0], [30.0, 30.0], Modifiers::NONE);+ assert_eq!(offset(&app), Some((15, 10)));+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);+ // Undo puts it back.+ crate::menus::invoke(&mut app, &egui::Context::default(), "edit.undo", json!({})).unwrap();+ assert!(offset(&app).is_none() && alpha(&doc(&app), 12, 20) == 1.0);+ // Float again and deselect: dropped (one history step) where it was shown, then deselected.+ drag(&mut app, [20.0, 20.0], [35.0, 30.0], Modifiers::COMMAND);+ crate::menus::invoke(&mut app, &egui::Context::default(), "select.deselect", json!({})).unwrap();+ let d = doc(&app);+ assert!(d.selection.is_none() && offset(&app).is_none());+ assert!(alpha(&d, 12, 12) == 0.0 && alpha(&d, 26, 21) == 1.0 && alpha(&d, 44, 39) == 1.0);+ let labels: Vec<String> = app.session.active().unwrap().history.entries().into_iter().skip(steps + 1).map(|e| e.to_string()).collect();+ assert_eq!(labels.first().map(String::as_str), Some("Move Selected Pixels"), "{labels:?}");+}++/// Through the real canvas (mouse events): a drag inside the ants moves the selection.+#[test]+fn mouse_drag_inside_the_selection_moves_it() {+ let mut h = harness(Tool::RectMarquee);+ press_at(&mut h, 100.0, 80.0, Modifiers::NONE);+ release_at(&mut h, 200.0, 160.0, Modifiers::NONE);+ assert_eq!(selection(&h), Rect::new(100, 80, 200, 160), "drawn");+ press_at(&mut h, 150.0, 120.0, Modifiers::NONE);+ release_at(&mut h, 170.0, 130.0, Modifiers::NONE);+ assert_eq!(selection(&h), Rect::new(120, 90, 220, 170), "moved by (20, 10)");+}diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rsindex 7854b532f..89c4796ab 100644--- a/crates/ui-egui/src/move_ui.rs+++ b/crates/ui-egui/src/move_ui.rs@@ -27,6 +27,8 @@ pub(crate) struct MovePreview {offsets: Vec<(i32, i32)>,/// The document at the latest offset.shown: Option<Arc<Document>>,+ /// Shows a floating selection (`select.float`): offsets are the piece's, from where it was cut.+ floating: bool,}impl MovePreview {@@ -59,6 +61,12 @@ fn drag_offset(app: &PhotocraftApp) -> Option<(i32, i32)> {/// the pointer. `None` without a drag (or when the layers can't move: locked, say; the drag then/// shows its arrow and the release reports why).pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {+ if app.session.active_index() == Some(idx)+ && let Some(st) = app.session.documents().get(idx)+ && photocraft_engine::float_cmds::floating(st).is_some()+ {+ return floating_doc(app, idx);+ }// Preferences › Interface › Show bounding box when dragging layer: outline and arrow only.if app.session.active_index() != Some(idx) || app.session.prefs().interface.show_bounding_box_when_dragging_layer {return None;@@ -78,7 +86,7 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Dolet all = Rect::new(i32::MIN / 2, i32::MIN / 2, i32::MAX / 2, i32::MAX / 2);let bounds = ids.iter().try_fold(Rect::EMPTY, |acc, id| Some(acc.union(&photocraft_compose::change_bounds(doc.layer(*id)?, all)?)));let canvas = doc.bounds();- app.move_preview = Some(MovePreview { doc: doc_id, revision, ids, bounds, canvas, offsets: Vec::new(), shown: None });+ app.move_preview = Some(MovePreview { doc: doc_id, revision, ids, bounds, canvas, offsets: Vec::new(), shown: None, floating: false });}let p = app.move_preview.as_mut()?;if offset == (0, 0) && p.offsets.is_empty() {@@ -104,6 +112,42 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<DoSome((p.shown.clone()?, p.key()))}+/// A floating selection's offset plus a drag of it in progress (`canvas::selection_drag_delta`).+pub(crate) fn floating_offset(app: &PhotocraftApp) -> Option<(i32, i32)> {+ let f = photocraft_engine::float_cmds::floating(app.session.active()?)?;+ let d = crate::canvas::selection_drag_delta(app).unwrap_or((0, 0));+ Some((f.offset.0 + d.0, f.offset.1 + d.1))+}++/// The document shown while a selection floats: the cut piece at its offset, over the cut-out+/// layer. Only the piece's area changes between offsets, so each move costs the piece, not the+/// layer.+fn floating_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {+ let offset = floating_offset(app)?;+ let st = app.session.documents().get(idx)?;+ let f = photocraft_engine::float_cmds::floating(st)?;+ let (doc_id, revision) = (st.doc.id, st.revision);+ let fresh = app.move_preview.as_ref().is_some_and(|p| p.doc == doc_id && p.revision == revision && p.floating);+ if !fresh {+ let bounds = st.doc.selection.as_ref().map(|s| s.content_bounds());+ let canvas = st.doc.bounds();+ app.move_preview = Some(MovePreview { doc: doc_id, revision, ids: vec![f.layer], bounds, canvas, offsets: Vec::new(), shown: None, floating: true });+ }+ let st = app.session.documents().get(idx)?;+ let shown = app.move_preview.as_ref()?.offsets.last() != Some(&offset);+ if shown {+ let t0 = crate::gpu_canvas::now_ms();+ let d = photocraft_engine::float_cmds::displayed(st, crate::canvas::selection_drag_delta(app).unwrap_or((0, 0)))?;+ let d = photocraft_engine::mode_cmds::display_document(&d).unwrap_or(d);+ let p = app.move_preview.as_mut()?;+ p.shown = Some(Arc::new(d));+ p.offsets.push(offset);+ app.perf.span("floating preview", crate::gpu_canvas::now_ms() - t0);+ }+ let p = app.move_preview.as_ref()?;+ Some((p.shown.clone()?, p.key()))+}+/// What changed between preview (or document) key `seen` and `now` of the current Move drag on/// document `doc` at `revision`: where the moving layers were in both. `None` when either key/// isn't one of this drag's (the canvas then recomposites everything).diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rsindex bde66411d..975e5a2b4 100644--- a/crates/ui-egui/src/snap_ui.rs+++ b/crates/ui-egui/src/snap_ui.rs@@ -387,6 +387,8 @@ mod tests {assert_eq!((sel.x0, sel.y0, sel.x1), (0, 0, 120));// Zoomed in to 800%, 4 px is beyond the 1 px threshold: no snap.app.ui.views[0].zoom = 8.0;+ // (Deselect first: a drag starting inside the selection would move it.)+ app.run("select.deselect", json!({})).unwrap();crate::canvas::tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, m);crate::canvas::tool_event(&mut app, ToolEvent::Up { x: 116.0, y: 50.0 }, m);let sel = app.session.active().unwrap().doc.selection.as_ref().unwrap().content_bounds();