Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Selection tools: ⌘ moves like the Move tool; ⌘⌥ copies (pixels inside the selection, the layer outside) (#896)

jason4short26b6aac9ac01
diff --git a/crates/engine/src/float_cmds.rs b/crates/engine/src/float_cmds.rs
index e2978a147..81be4c333 100644
--- a/crates/engine/src/float_cmds.rs
+++ b/crates/engine/src/float_cmds.rs
@@ -33,8 +33,9 @@ pub struct CutParts {
}
impl CutParts {
- /// Split `layer` of `doc` by its selection. Errors without a selection or pixels.
- pub fn new(doc: &Document, layer: LayerId) -> Result<Self> {
+ /// Split `layer` of `doc` by its selection. With `copy` the selected pixels stay in the layer
+ /// too (the piece is a duplicate). Errors without a selection or pixels.
+ pub fn new(doc: &Document, layer: LayerId, copy: 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 {
@@ -58,7 +59,9 @@ impl CutParts {
} else {
p[a] *= k;
}
- r[a] *= 1.0 - k;
+ if !copy {
+ r[a] *= 1.0 - k;
+ }
}
rest.write_region(b, &rp);
rest.prune();
@@ -129,10 +132,11 @@ fn can_float(s: &Session) -> std::result::Result<(), String> {
fn float(s: &mut Session, p: &Value) -> Result<Value> {
let (dx, dy) = (int_param(p, "dx"), int_param(p, "dy"));
+ let copy = p.get("copy").and_then(Value::as_bool).unwrap_or(false);
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)?;
+ let parts = CutParts::new(&st.doc, layer, copy)?;
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)?;
@@ -192,7 +196,7 @@ pub fn specs() -> Vec<CommandSpec> {
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)"##,
+ 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; 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,
diff --git a/crates/engine/src/float_cmds/tests.rs b/crates/engine/src/float_cmds/tests.rs
index 1914077c9..c554628af 100644
--- a/crates/engine/src/float_cmds/tests.rs
+++ b/crates/engine/src/float_cmds/tests.rs
@@ -98,3 +98,14 @@ fn float_drag_bench() {
}
eprintln!("6000×4000 layer, 500×400 piece: cut {cut:?}, then {:?} per pointer move", t.elapsed() / 20);
}
+
+#[test]
+fn copy_floats_a_duplicate_and_leaves_the_original() {
+ let (mut s, id) = session();
+ s.execute("select.float", json!({"dx": 30, "dy": 0, "copy": true})).unwrap();
+ let shown = displayed(s.active().unwrap(), (0, 0)).unwrap();
+ assert!(alpha(&shown, id, 12, 12) == 1.0 && alpha(&shown, id, 42, 12) == 1.0, "original kept, copy shown");
+ s.execute("select.drop", json!({})).unwrap();
+ let doc = &s.active().unwrap().doc;
+ assert!(alpha(doc, id, 12, 12) == 1.0 && alpha(doc, id, 42, 12) == 1.0, "dropped: both");
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 1f3c31961..b4a801c4b 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -2586,12 +2586,37 @@ 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;
}
+ // ⌘ with a selection tool is the Move tool for the drag: outside the selection (or
+ // without one) it moves the whole layer, ⌘⌥ a duplicate of it. It never combines
+ // selections.
+ if command_moves_layer(app, tool, [x, y], mods) {
+ if mods.alt
+ && let Err(e) = app.run("layer.duplicate", json!({}))
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ return;
+ }
+ app.drag = Some(Drag::new(Tool::Move, [x, y], vec![[x, y, pressure as f64]], mods, false));
+ 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) {
+ // ⌘⌥ on a floating piece leaves it where it is and drags a copy of it.
+ if cut
+ && mods.alt
+ && mods.command
+ && app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some())
+ && let Err(e) = app.run("select.drop", json!({}))
+ {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ return;
+ }
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}))
+ && let Err(e) = app.run("select.float", json!({"dx": 0, "dy": 0, "copy": mods.alt}))
{
app.ui.status = e;
app.ui.status_error = true;
@@ -2716,24 +2741,39 @@ fn inside_selection(app: &PhotocraftApp, p: [f64; 2]) -> bool {
}
/// 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),
+/// moves the floating piece (⌘ cuts one first, ⌘⌥ copies; a floating piece moves with a plain
+/// drag; the Polygonal Lasso and Magic Wand need ⌘, as a plain press there places or samples),
/// `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) {
+ // Click-driven selection tools (a press places a point or samples): only ⌘ drags the
+ // selection, and not while a polygon is being drawn.
+ let clicky = matches!(tool, Tool::PolygonLasso | Tool::MagicWand);
+ if !(clicky || matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso)) || (clicky && !app.ui.polygon.is_empty()) {
return None;
}
+ // ⌘ cuts, ⌘⌥ copies (`select.float`'s `copy`).
+ let cut = mods.command && !mods.shift;
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);
+ return (on && !mods.shift && (!mods.alt || mods.command) && (cut || !clicky)).then_some(true);
}
if !inside_selection(app, p) {
return None;
}
- if mods.command && !mods.shift && !mods.alt {
+ if cut {
return Some(true);
}
- (!mods.command && selection_mode(app, mods) == "replace").then_some(false)
+ (!clicky && !mods.command && selection_mode(app, mods) == "replace").then_some(false)
+}
+
+/// Does a ⌘ (⌘⌥) press with selection tool `tool` at `p` move the whole layer (a duplicate with
+/// ⌥), as the Move tool would? Outside the selection or without one; inside it, ⌘ drags the
+/// selected pixels instead (`selection_drag_kind`).
+fn command_moves_layer(app: &PhotocraftApp, tool: Tool, p: [f64; 2], mods: egui::Modifiers) -> bool {
+ let selection_tool = matches!(tool, Tool::RectMarquee | Tool::EllipseMarquee | Tool::Lasso | Tool::PolygonLasso | Tool::MagicWand);
+ let floating = app.session.active().is_some_and(|st| photocraft_engine::float_cmds::floating(st).is_some());
+ selection_tool && mods.command && !mods.shift && !floating && app.ui.polygon.is_empty() && !inside_selection(app, p)
}
/// Whole-pixel offset of a selection drag in progress (`Drag::sel_move`).
diff --git a/crates/ui-egui/src/marquee_tests.rs b/crates/ui-egui/src/marquee_tests.rs
index 14c6a9f96..49d588a58 100644
--- a/crates/ui-egui/src/marquee_tests.rs
+++ b/crates/ui-egui/src/marquee_tests.rs
@@ -290,3 +290,16 @@ fn mouse_drag_inside_the_selection_moves_it() {
release_at(&mut h, 170.0, 130.0, Modifiers::NONE);
assert_eq!(selection(&h), Rect::new(120, 90, 220, 170), "moved by (20, 10)");
}
+
+/// ⌘⌥-drag copies the selected pixels instead of cutting them: the original stays.
+#[test]
+fn cmd_alt_drag_floats_a_copy() {
+ let (mut app, layer) = painted();
+ let alpha = |d: &photocraft_doc::Document, x, y| d.layer(layer).unwrap().surface().unwrap().rgba(x, y)[3];
+ let cmd_alt = Modifiers { alt: true, ..Modifiers::COMMAND };
+ drag(&mut app, [20.0, 20.0], [45.0, 20.0], cmd_alt);
+ app.run("select.drop", json!({})).unwrap();
+ let d = app.session.active().unwrap().doc.clone();
+ assert!(alpha(&d, 12, 20) == 1.0, "the original stays");
+ assert!(alpha(&d, 50, 20) == 1.0, "the copy dropped 25 px right");
+}
diff --git a/crates/ui-egui/src/polygon_lasso_tests.rs b/crates/ui-egui/src/polygon_lasso_tests.rs
index 31b779c89..519c098c2 100644
--- a/crates/ui-egui/src/polygon_lasso_tests.rs
+++ b/crates/ui-egui/src/polygon_lasso_tests.rs
@@ -240,3 +240,48 @@ fn lasso_tools_apply_the_options_bar_feather() {
drag(&mut app, Tool::Patch);
assert_eq!((coverage(&app, 37), coverage(&app, 41)), (0.0, 1.0), "patch: a hard edge");
}
+
+fn polygon_app() -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.run("file.new", json!({"width": 400, "height": 300, "background": "transparent"})).unwrap();
+ app.sync_views();
+ app.ui.extras.snap = false;
+ app.ui.tool = Tool::PolygonLasso;
+ app
+}
+
+fn ev(app: &mut PhotocraftApp, kind: &str, x: f64, y: f64, m: Modifiers) {
+ use crate::canvas::{ToolEvent, tool_event};
+ let e = match kind {
+ "down" => ToolEvent::Down { x, y, pressure: 1.0 },
+ "up" => ToolEvent::Up { x, y },
+ _ => ToolEvent::Move { x, y, pressure: 1.0 },
+ };
+ tool_event(app, e, m);
+}
+
+/// ⌘-drag inside a selection with the Polygonal Lasso cuts and floats the pixels, as with the
+/// marquee; a plain press there still places a point.
+#[test]
+fn cmd_drag_inside_the_selection_floats_it_with_the_polygonal_lasso() {
+ let mut app = polygon_app();
+ 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();
+ ev(&mut app, "down", 20.0, 20.0, Modifiers::COMMAND);
+ ev(&mut app, "move", 40.0, 20.0, Modifiers::COMMAND);
+ ev(&mut app, "up", 40.0, 20.0, Modifiers::COMMAND);
+ let f = photocraft_engine::float_cmds::floating(app.session.active().unwrap()).map(|f| f.offset);
+ assert_eq!(f, Some((20, 0)));
+ assert!(app.ui.polygon.is_empty(), "no polygon point was placed");
+ app.run("select.drop", json!({})).unwrap();
+ // A plain press inside the selection starts a polygon.
+ ev(&mut app, "down", 35.0, 20.0, Modifiers::NONE);
+ ev(&mut app, "up", 35.0, 20.0, Modifiers::NONE);
+ assert_eq!(app.ui.polygon.len(), 1);
+}
diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/tool_feedback.rs
index e1f3ed14f..b25c60d6e 100644
--- a/crates/ui-egui/src/tool_feedback.rs
+++ b/crates/ui-egui/src/tool_feedback.rs
@@ -87,6 +87,10 @@ pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option<Badg
if !is_selection_tool(tool) {
return None;
}
+ // ⌘ (⌘⌥) drags pixels or the layer instead of combining selections.
+ if m.command && app.drag.is_none() {
+ return None;
+ }
let m = app.drag.as_ref().filter(|d| d.tool == Tool::Lasso && tool == Tool::Lasso).map_or(m, |d| d.modifiers);
Badge::from_mode(selection_mode(tool, app.ui.selection_mode, m))
}