GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
//! Move tool marquee (#2844), as in Photoshop: with Auto-Select on (or ⌘ held with it off), a drag
//! that starts where no layer would be picked (an empty, transparent spot, or the pasteboard
//! outside the canvas) draws a box instead of moving anything. Releasing selects every layer whose
//! content touches the box (`layer.selectInRect`; Auto-Select: Group selects their outermost
//! groups), ⇧ adds them to the layers already selected. A click there selects nothing.

use serde_json::json;

use craft::behavior::kurbo::{Point, Rect};
use craft::ui::canvas_controls::Marquee;
use craft::ui::contract::Show as _;

use crate::PhotocraftApp;

/// The marquee being dragged, in document pixels.
#[derive(Clone, Copy, Debug)]
pub(crate) struct LayerBox {
    start: [f64; 2],
    end: [f64; 2],
    /// ⇧ at the press: add to the layer selection.
    add: bool,
    /// The actual Move tool skips Position locks. Temporary Move keeps ordinary rectangle picks.
    move_auto_select: bool,
    /// An empty plain marquee from a locked-only hit clears the selection.
    clear_on_empty: bool,
}

/// Start the marquee at `p` after an empty or locked-only hit. With `move_auto_select`, the
/// real Move tool skips effective Position as well as All locks. Set `clear_on_empty` for its
/// locked-only press so an empty replacement marquee clears the selection.
/// Temporary Move keeps ordinary lock filtering.
pub(crate) fn begin(app: &mut PhotocraftApp, p: [f64; 2], add: bool, move_auto_select: bool, clear_on_empty: bool) {
    app.layer_box = Some(LayerBox { start: p, end: p, add, move_auto_select, clear_on_empty });
}

/// No visible layer has pixels at document point `p` (locked ones included).
pub(crate) fn empty_at(app: &mut PhotocraftApp, p: [f64; 2]) -> bool {
    app.run("layer.pickAt", json!({"x": p[0], "y": p[1], "list": true})).is_ok_and(|v| v["layers"].as_array().is_some_and(Vec::is_empty))
}

/// The pointer moved to document point `p` while a marquee is dragged (unsnapped, unconstrained):
/// true when a marquee is running.
pub(crate) fn drag_to(app: &mut PhotocraftApp, p: [f64; 2]) -> bool {
    let Some(b) = app.layer_box.as_mut() else { return false };
    b.end = p;
    true
}

/// The button came up at document point `p`: selects the layers the box touches. True when a
/// marquee was running.
pub(crate) fn release(app: &mut PhotocraftApp, p: [f64; 2]) -> bool {
    let Some(b) = app.layer_box.take() else { return false };
    let b = LayerBox { end: p, ..b };
    let (w, h) = (b.end[0] - b.start[0], b.end[1] - b.start[1]);
    if w == 0.0 && h == 0.0 && !b.add {
        // A click on the pasteboard clears the layer target; a drag from there still
        // uses the marquee, and a click on transparent pixels inside the canvas does not.
        if let Some(st) = app.session.active() {
            let rect = st.doc.bounds();
            let outside =
                b.start[0] < f64::from(rect.x0) || b.start[1] < f64::from(rect.y0) || b.start[0] >= f64::from(rect.x1) || b.start[1] >= f64::from(rect.y1);
            if outside {
                let _ = app.run("select.deselectLayers", json!({}));
            }
        }
    }
    if w == 0.0 || h == 0.0 {
        return true;
    }
    let target = app.ui.tool_options.move_target.clone();
    let mode = if b.add { "add" } else { "replace" };
    let p = json!({
        "x": b.start[0], "y": b.start[1], "width": w, "height": h, "target": target, "mode": mode,
        "moveAutoSelect": b.move_auto_select, "clearOnEmpty": b.clear_on_empty,
    });
    if let Err(e) = app.run("layer.selectInRect", p) {
        app.ui.status = e;
        app.ui.status_error = true;
    }
    true
}

/// The drag ends without selecting anything.
pub(crate) fn cancel(app: &mut PhotocraftApp) {
    app.layer_box = None;
}

/// The marquee being dragged, over the canvas `canvas`.
pub(crate) fn show(app: &PhotocraftApp, ui: &mut egui::Ui, canvas: egui::Rect) {
    let Some(b) = app.layer_box else { return };
    let rect = Rect::from_points(Point::new(b.start[0], b.start[1]), Point::new(b.end[0], b.end[1]));
    Marquee::rect(tl!("Layer marquee"), rect).show_at(ui, canvas);
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::PhotocraftApp;
    use crate::canvas::{ToolEvent, tool_event};
    use crate::state::Tool;

    fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], m: egui::Modifiers) {
        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);
    }

    /// #2844: a drag from the pasteboard selects the layers its box touches (⇧ adds) and moves
    /// nothing.
    #[test]
    fn a_drag_from_an_empty_spot_selects_the_layers_it_touches() {
        let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
        app.session.execute("file.new", json!({"width": 64, "height": 64})).unwrap();
        app.sync_views();
        let mut ids = Vec::new();
        for x in [8, 40] {
            app.session.execute("layer.new.layer", json!({})).unwrap();
            app.session.execute("select.rect", json!({"x": x, "y": 8, "width": 16, "height": 16})).unwrap();
            app.session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
            ids.push(app.session.active().unwrap().active_layer.unwrap());
        }
        app.session.execute("select.deselect", json!({})).unwrap();
        app.ui.tool = Tool::Move;
        app.ui.tool_options.move_auto_select = true;
        drag(&mut app, [-10.0, -10.0], [10.0, 10.0], egui::Modifiers::NONE);
        let st = app.session.active().unwrap();
        assert_eq!(st.selected_layers(), vec![ids[0]], "the box touched the first square only");
        assert_eq!(st.doc.layer(ids[1]).unwrap().surface().unwrap().content_bounds().x0, 40, "nothing moved");
        assert!(app.layer_box.is_none());
        // ⇧ adds the second square, dragged up and left from beyond the right edge.
        drag(&mut app, [70.0, 30.0], [50.0, 20.0], egui::Modifiers::SHIFT);
        let mut sel = app.session.active().unwrap().selected_layers();
        sel.sort_unstable_by_key(|l| l.0);
        assert_eq!(sel, ids);
    }

    /// #4923: clicking the pasteboard, but not empty canvas pixels, clears layer targets.
    /// A Shift-click preserves the selection, and a pasteboard drag remains a marquee.
    #[test]
    fn pasteboard_click_deselects_layers_without_affecting_empty_canvas_clicks() {
        let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
        app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap();
        app.run("layer.new.layer", json!({})).unwrap();
        app.ui.tool = Tool::Move;
        app.ui.tool_options.move_auto_select = true;
        let layer = app.session.active().unwrap().active_layer.unwrap();
        assert_eq!(app.session.active().unwrap().selected_layers(), vec![layer]);
        let click = |app: &mut PhotocraftApp, p: [f64; 2], mods| {
            tool_event(app, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, mods);
            tool_event(app, ToolEvent::Up { x: p[0], y: p[1] }, mods);
        };
        click(&mut app, [30.0, 30.0], egui::Modifiers::NONE);
        assert_eq!(app.session.active().unwrap().selected_layers(), vec![layer], "empty pixels are still in the canvas");
        click(&mut app, [-10.0, 30.0], egui::Modifiers::SHIFT);
        assert_eq!(app.session.active().unwrap().selected_layers(), vec![layer], "Shift adds, not clears");
        click(&mut app, [-10.0, 30.0], egui::Modifiers::NONE);
        let st = app.session.active().unwrap();
        assert!(st.selected_layers().is_empty() && st.active_layer.is_none());
        assert!(app.layer_box.is_none());
    }

    /// #10665: a fill layer, or pixels hanging past the canvas edge, aren't drawn on the
    /// pasteboard, so a click there still clears the layer selection rather than picking them.
    #[test]
    fn pasteboard_click_deselects_over_fill_layers_and_off_canvas_pixels() {
        let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
        app.run("file.new", json!({"width": 64, "height": 64, "background": "transparent"})).unwrap();
        app.run("layer.newFillLayer.solidColor", json!({"color": "#00ff00"})).unwrap();
        app.run("layer.new.layer", json!({})).unwrap();
        let off = app.session.active().unwrap().active_layer.unwrap();
        app.session
            .edit("paint past the edge", |doc, _| {
                doc.layer_mut(off).unwrap().surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(-20, 0, 10, 64), &[1.0, 0.0, 0.0, 1.0]);
                Ok(())
            })
            .unwrap();
        app.run("layer.new.layer", json!({})).unwrap();
        app.ui.tool = Tool::Move;
        app.ui.tool_options.move_auto_select = true;
        tool_event(&mut app, ToolEvent::Down { x: -10.0, y: 30.0, pressure: 1.0 }, egui::Modifiers::NONE);
        tool_event(&mut app, ToolEvent::Up { x: -10.0, y: 30.0 }, egui::Modifiers::NONE);
        let st = app.session.active().unwrap();
        assert!(st.selected_layers().is_empty() && st.active_layer.is_none(), "selected {:?}", st.selected_layers());
        assert_eq!(st.doc.layer(off).unwrap().surface().unwrap().content_bounds().x0, -20, "nothing moved");
    }

    /// #4058: a drag that starts on the locked Background draws the layer marquee. It does not
    /// open the move-lock dialog, and releasing selects the unlocked layer the box touches.
    #[test]
    fn a_drag_on_the_locked_background_selects_instead_of_erroring() {
        let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
        app.run("file.new", json!({"width": 80, "height": 60})).unwrap();
        app.sync_views();
        app.run("layer.new.layer", json!({})).unwrap();
        app.run("select.rect", json!({"x": 40, "y": 8, "width": 16, "height": 16})).unwrap();
        app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
        app.run("select.deselect", json!({})).unwrap();
        let paint = app.session.active().unwrap().active_layer.unwrap();
        app.ui.tool = Tool::Move;
        app.ui.tool_options.move_auto_select = true;
        drag(&mut app, [8.0, 8.0], [50.0, 20.0], egui::Modifiers::NONE);
        assert!(!app.dialog_open(), "no lock dialog");
        assert!(app.layer_box.is_none());
        assert_eq!(app.session.active().unwrap().selected_layers(), vec![paint]);
    }
}