diff --git a/crates/engine-paint/src/cmd/pick_cmds.rs b/crates/engine-paint/src/cmd/pick_cmds.rs index 948844bb7b..92d12bd363 100644 --- a/crates/engine-paint/src/cmd/pick_cmds.rs +++ b/crates/engine-paint/src/cmd/pick_cmds.rs @@ -113,6 +113,56 @@ fn pick_target(doc: &Document, x: i32, y: i32, group: bool, move_auto_select: bo Some(if group { top_group(doc, hit) } else { hit }) } +/// The layers the Move tool's Show Previous / Next Layer Boundary keys step through at (x, y), +/// topmost first: the visible layers with pixels there that Auto-Select could pick (the same hit +/// test, the same locks skipped), never the Background or an artboard. +pub fn boundary_candidates(doc: &Document, x: i32, y: i32) -> Vec { + layers_hit(doc, x, y, true) + .into_iter() + .filter(|id| { + let locks = doc.effective_locks(*id); + !locks.all && !locks.position && !doc.is_background(*id) && doc.layer(*id).is_some_and(|l| l.artboard().is_none()) + }) + .collect() +} + +/// The layer the boundary box goes to from `from` among `candidates` (topmost first): `up` is one +/// layer up the stack, wrapping from the top to the bottom, else one down, wrapping from the bottom +/// to the top. A `from` that is not a candidate counts as the topmost. `None` when the next layer +/// is `active`: the active layer ends the cycle, it is never skipped. +pub fn next_boundary(candidates: &[LayerId], from: Option, up: bool, active: Option) -> Option { + let n = candidates.len(); + if n == 0 { + return None; + } + let at = from.and_then(|f| candidates.iter().position(|c| *c == f)).unwrap_or(0); + let next = if up { (at + n - 1) % n } else { (at + 1) % n }; + let id = candidates[next]; + (Some(id) != active).then_some(id) +} + +/// `move.showPreviousLayerBoundary` / `move.showNextLayerBoundary`: where the boundary box goes +/// from `from` at (x, y). Changes nothing; the shell shows the box and a click picks its layer. +fn boundary(s: &mut Session, p: &Value, up: bool) -> Result { + let cmd = if up { "move.showPreviousLayerBoundary" } else { "move.showNextLayerBoundary" }; + let coord = |k: &str| { + p.get(k) + .and_then(Value::as_f64) + .filter(|v| v.is_finite()) + .ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: format!("missing or invalid `{k}`") }) + }; + let px = |v: f64| v.floor().clamp(f64::from(i32::MIN / 2), f64::from(i32::MAX / 2)) as i32; + let (x, y) = (px(coord("x")?), px(coord("y")?)); + let from = match p.get("from") { + None | Some(Value::Null) => None, + Some(v) => Some(LayerId(v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "`from` must be a layer id".into() })?)), + }; + let st = s.active().ok_or(EngineError::NoDocument)?; + let candidates = boundary_candidates(&st.doc, x, y); + let layer = next_boundary(&candidates, from, up, st.active_layer); + Ok(json!({ "layer": layer.map(|l| l.0), "layers": candidates.iter().map(|l| l.0).collect::>() })) +} + /// List the hits for a context menu or pick one layer or group. A probe leaves the selection /// alone. A replace click on a selected member keeps the full multi-selection for dragging. fn pick(s: &mut Session, p: &Value) -> Result { @@ -223,6 +273,26 @@ pub fn specs() -> Vec { journal: true, run: select_in_rect, }, + CommandSpec { + id: "move.showPreviousLayerBoundary", + label: "Show Previous Layer Boundary", + menu: &[], + shortcut: None, + params: r##"{"x":px,"y":px,"from":layer id|null (the layer the box shows now; none = the topmost)} → {layer (one layer up the stack from `from`, wrapping to the bottom; null when that is the active layer), layers (the candidates, topmost first)}"##, + enabled: has_doc, + journal: false, + run: |s, p| boundary(s, p, true), + }, + CommandSpec { + id: "move.showNextLayerBoundary", + label: "Show Next Layer Boundary", + menu: &[], + shortcut: None, + params: r##"{"x":px,"y":px,"from":layer id|null (the layer the box shows now; none = the topmost)} → {layer (one layer down the stack from `from`, wrapping to the top; null when that is the active layer), layers (the candidates, topmost first)}"##, + enabled: has_doc, + journal: false, + run: |s, p| boundary(s, p, false), + }, CommandSpec { id: "layer.pickAt", label: "Auto-Select Layer", diff --git a/crates/engine/src/install/command_ids.txt b/crates/engine/src/install/command_ids.txt index d0616d2788..ecceee135e 100644 --- a/crates/engine/src/install/command_ids.txt +++ b/crates/engine/src/install/command_ids.txt @@ -945,6 +945,8 @@ file.package file.export.pathsToIllustrator edit.installedProfiles layer.selectInRect +move.showPreviousLayerBoundary +move.showNextLayerBoundary layer.pickAt layer.selectAbove layer.selectBelow diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index d10a998347..fe223d6c5e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -76,6 +76,7 @@ impl PhotocraftApp { preset_art: Default::default(), move_preview: None, move_hover: None, + move_boundary: None, move_distance: None, object_finder: None, blend_preview: None, diff --git a/crates/ui-egui/src/canvas/tools/move_tool.rs b/crates/ui-egui/src/canvas/tools/move_tool.rs index 4c53eba55d..0aafb39c7d 100644 --- a/crates/ui-egui/src/canvas/tools/move_tool.rs +++ b/crates/ui-egui/src/canvas/tools/move_tool.rs @@ -232,7 +232,12 @@ fn press_at(app: &mut PhotocraftApp, p: [f64; 2], mods: Mods, style: ConstrainSt }); let active_before = app.session.active().and_then(|st| st.active_layer); let revealed = crate::layer_reveal::mark(app); - let _ = app.run("layer.pickAt", json!({"x": p[0], "y": p[1], "target": target, "mode": mode, "moveAutoSelect": auto})); + // After Show Previous / Next Layer Boundary a plain Auto-Select click picks the layer the outline shows (#18432). + let plain_auto = app.ui.tool_options.move_auto_select && !mods.cmd && mode == "replace" && target == "layer"; + let _ = match plain_auto.then(|| crate::move_hover::cycled_layer(app, p)).flatten() { + Some(layer) => app.run("layer.select", json!({"layer": layer.0, "mode": "replace"})), + None => app.run("layer.pickAt", json!({"x": p[0], "y": p[1], "target": target, "mode": mode, "moveAutoSelect": auto})), + }; note_move_pick(app, active_before); crate::layer_reveal::file(app, revealed); if locked_hit { diff --git a/crates/ui-egui/src/input/shortcut_dispatch.rs b/crates/ui-egui/src/input/shortcut_dispatch.rs index f37a2aca7a..5fcbaeaa4b 100644 --- a/crates/ui-egui/src/input/shortcut_dispatch.rs +++ b/crates/ui-egui/src/input/shortcut_dispatch.rs @@ -296,6 +296,10 @@ pub(crate) fn command_rows(app: &PhotocraftApp) -> Vec { if def.paths.is_empty() { def.paths.extend(menu_path(&def.command.id)); } + // The Move tool's boundary keys are in no menu; they are filed under Tools, as in Photoshop's list. + if def.paths.is_empty() && crate::move_hover::boundary_command(&def.command.id).is_some() { + def.paths.push(vec!["Tools".into(), def.label.clone()]); + } push_row(&mut rows, &mut index, def); } @@ -712,6 +716,11 @@ fn run_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, f: &Fired) { return; } } + // With the Move tool the bracket keys step the rollover outline through the layers under the pointer (#18432). + if let Some(boundary) = crate::move_hover::bracket_command(app, id) { + dispatch(app, ctx, boundary); + return; + } if id == EditCommands::Delete.id() { // A finished work path shown by a Pen or Path Selection, or the path or segment Direct Selection targets: // ⌫/Delete edits the path, as in Photoshop (#5702, #12695, #13203), never Edit › Clear on the pixels under it. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 555ebcc427..f5b5931561 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -375,6 +375,8 @@ pub struct PhotocraftApp { pub(crate) move_preview: Option, /// Move tool › Show Highlight on Rollover: the last hover answer (`move_hover`). pub(crate) move_hover: Option, + /// Move tool › Show Previous / Next Layer Boundary: where the keys left the outline (`move_hover`). + pub(crate) move_boundary: Option, /// Smart Guides distances shown with ⌘ held over the canvas: the last answer (`move_distance`). pub(crate) move_distance: Option, /// Object Selection › Object Finder: the hover preview (`object_finder`). diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 8515d08a01..a6218dff6c 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -412,6 +412,9 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id: if id == "layer.selectUnderCursor" { return select_layer_under_cursor(app, ctx); } + if let Some(up) = crate::move_hover::boundary_command(id) { + return boundary_step(app, ctx, ¶ms, up); + } if let Some(result) = invoke_early_commands(app, ctx, id, ¶ms) { return result; } @@ -903,6 +906,17 @@ fn select_layer_under_cursor(app: &mut PhotocraftApp, ctx: &egui::Context) -> Re Ok(picked) } +/// Show Previous / Next Layer Boundary at the point the parameters name (`x`, `y`, document px), +/// else at the pointer over the active canvas (#18432). +fn boundary_step(app: &mut PhotocraftApp, ctx: &egui::Context, params: &Value, up: bool) -> Result { + let given = params.get("x").and_then(Value::as_f64).zip(params.get("y").and_then(Value::as_f64)); + let at = given.map(|(x, y)| [x, y]).or_else(|| { + let pointer = ctx.pointer_hover_pos()?; + crate::canvas::document_display::doc_point_at(app, pointer).map(|p| [p.x, p.y]) + }); + crate::move_hover::step(app, at, up) +} + #[cfg(test)] #[path = "view_show_grid_extras_off_tests.rs"] mod view_show_grid_extras_off_tests; diff --git a/crates/ui-egui/src/move_layer_boundary_cycle_tests.rs b/crates/ui-egui/src/move_layer_boundary_cycle_tests.rs new file mode 100644 index 0000000000..8e4107d5b2 --- /dev/null +++ b/crates/ui-egui/src/move_layer_boundary_cycle_tests.rs @@ -0,0 +1,202 @@ +//! Move tool › Show Previous / Next Layer Boundary (#18432): `]` and `[` step the rollover outline +//! through the visible layers under the pointer, the active layer ends the cycle, and a plain +//! Auto-Select click or drag then takes the layer the outline shows. + +use egui::{Key, Modifiers, PointerButton}; +use egui_kittest::Harness; +use photocraft_doc::LayerId; +use photocraft_geom::Rect; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::guide_cursor_tests::{harness, hover, screen}; +use crate::shortcut_dispatch::tests::tap; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +struct Stack { + background: LayerId, + red: LayerId, + blue: LayerId, + green: LayerId, +} + +fn paint(app: &mut PhotocraftApp, name: &str, bounds: Rect) -> LayerId { + let layer = LayerId(app.run("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()); + app.session + .edit("Paint fixture", |doc, _| { + doc.layer_mut(layer).unwrap().surface_mut().unwrap().fill_rect(bounds, &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + layer +} + +/// From the bottom up: Background, Red, Blue, Green (top). At (130, 130) all three have pixels, at +/// (100, 100) Blue and Red, at (70, 70) only Red. The guide the harness adds is at x = 200, away +/// from every point used. The Background is active. +fn stack() -> (H, Stack) { + let mut h = harness(Tool::Move); + let app = h.state_mut(); + let background = app.session.active().unwrap().doc.layers[0].id; + let red = paint(app, "Red", Rect::new(60, 60, 140, 140)); + let blue = paint(app, "Blue", Rect::new(90, 90, 170, 170)); + let green = paint(app, "Green", Rect::new(120, 120, 190, 190)); + app.ui.tool_options.move_auto_select = true; + app.run("layer.select", json!({"layer": background.0})).unwrap(); + h.run_steps(2); + (h, Stack { background, red, blue, green }) +} + +fn shown(h: &H) -> Option { + h.state().canvas_hover_layer +} + +/// `]` (Show Previous Layer Boundary) or `[` (Show Next Layer Boundary), then the outline. +fn key(h: &mut H, previous: bool) -> Option { + tap(h, if previous { Key::CloseBracket } else { Key::OpenBracket }, Modifiers::NONE); + h.run_steps(1); + shown(h) +} + +fn history(h: &H) -> usize { + h.state().session.active().unwrap().history.past_len() +} + +fn active(h: &H) -> Option { + h.state().session.active().unwrap().active_layer +} + +#[test] +fn the_two_commands_are_listed_under_tools_and_run_without_the_shell() { + let (h, _) = stack(); + let rows = crate::shortcut_dispatch::command_rows(h.state()); + for (id, label) in [("move.showPreviousLayerBoundary", "Show Previous Layer Boundary"), ("move.showNextLayerBoundary", "Show Next Layer Boundary")] { + let row = rows.iter().find(|r| r.command.id == id).unwrap_or_else(|| panic!("{id} has no Keyboard Shortcuts row")); + assert_eq!(row.paths, [vec!["Tools".to_string(), label.to_string()]], "{id} is filed under Tools"); + } + + // Headless: the engine answers for a pointer position and changes nothing. + let mut session = photocraft_engine::Session::new(); + let none = session.execute("move.showNextLayerBoundary", json!({"x": 130, "y": 130})); + assert!(none.is_err(), "no document: refused, not a crash"); + session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut ids = Vec::new(); + for (name, at) in [("Red", 60), ("Blue", 90), ("Green", 120)] { + ids.push(session.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()); + session.execute("select.rect", json!({"x": at, "y": at, "width": 80, "height": 80})).unwrap(); + session.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + } + session.execute("select.deselect", json!({})).unwrap(); + let (red, blue, green) = (ids[0], ids[1], ids[2]); + let background = session.active().unwrap().doc.layers[0].id; + session.execute("layer.select", json!({"layer": background.0})).unwrap(); + let before = (session.active().unwrap().revision, session.active().unwrap().active_layer); + let r = session.execute("move.showPreviousLayerBoundary", json!({"x": 130, "y": 130})).unwrap(); + assert_eq!(r["layers"], json!([green, blue, red]), "the candidates, topmost first, without the Background"); + assert_eq!(r["layer"], json!(red), "one layer up from the topmost wraps to the bottom"); + let r = session.execute("move.showNextLayerBoundary", json!({"x": 130, "y": 130, "from": red})).unwrap(); + assert_eq!(r["layer"], json!(green), "one layer down from the bottom wraps to the top"); + assert_eq!((session.active().unwrap().revision, session.active().unwrap().active_layer), before, "nothing changed"); + session.execute("layer.select", json!({"layer": green})).unwrap(); + let r = session.execute("move.showPreviousLayerBoundary", json!({"x": 130, "y": 130, "from": blue})).unwrap(); + assert_eq!(r["layer"], json!(null), "Green is active: the cycle ends there"); + assert!(session.execute("move.showNextLayerBoundary", json!({"y": 130})).is_err(), "missing x"); + assert!(session.execute("move.showNextLayerBoundary", json!({"x": 1, "y": 1, "from": "Red"})).is_err(), "a bad from"); +} + +#[test] +fn brackets_cycle_the_outline_through_the_layers_under_the_pointer() { + let (mut h, s) = stack(); + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + assert_eq!(shown(&h), Some(s.green), "the outline starts on the topmost layer"); + let h0 = history(&h); + let brush = h.state().session.tools.brush.size; + assert_eq!([key(&mut h, true), key(&mut h, true), key(&mut h, true), key(&mut h, true)], [Some(s.red), Some(s.blue), Some(s.green), Some(s.red)]); + hover(&mut h, 136.0, 130.0, Modifiers::NONE); + assert_eq!(shown(&h), Some(s.green), "a pointer move puts the outline back on the topmost layer"); + assert_eq!([key(&mut h, false), key(&mut h, false), key(&mut h, false)], [Some(s.blue), Some(s.red), Some(s.green)]); + assert_eq!(history(&h), h0, "the keys add no history state"); + assert_eq!(active(&h), Some(s.background), "the keys change no layer"); + assert_eq!(h.state().session.tools.brush.size, brush, "with the Move tool the keys leave the brush size"); + + // Two layers alternate; with one the outline stays, and the Background is never added. + hover(&mut h, 100.0, 100.0, Modifiers::NONE); + assert_eq!([shown(&h), key(&mut h, true), key(&mut h, true), key(&mut h, false)], [Some(s.blue), Some(s.red), Some(s.blue), Some(s.red)]); + hover(&mut h, 70.0, 70.0, Modifiers::NONE); + assert_eq!([shown(&h), key(&mut h, true), key(&mut h, false)], [Some(s.red); 3]); +} + +#[test] +fn hidden_layers_are_skipped() { + let (mut h, s) = stack(); + h.state_mut().run("layer.setProps", json!({"layer": s.blue.0, "visible": false})).unwrap(); + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + assert_eq!([shown(&h), key(&mut h, true), key(&mut h, true)], [Some(s.green), Some(s.red), Some(s.green)]); +} + +#[test] +fn the_active_layer_ends_the_cycle_until_the_pointer_moves() { + let (mut h, s) = stack(); + h.state_mut().run("layer.select", json!({"layer": s.blue.0})).unwrap(); + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + assert_eq!([shown(&h), key(&mut h, true), key(&mut h, true), key(&mut h, true), key(&mut h, false)], [Some(s.green), Some(s.red), None, None, None]); + hover(&mut h, 131.0, 130.0, Modifiers::NONE); + assert_eq!(shown(&h), None, "a 1 px move keeps the ended cycle"); + hover(&mut h, 134.0, 130.0, Modifiers::NONE); + assert_eq!(shown(&h), Some(s.green), "a 4 px move brings the outline back on the topmost layer"); + assert_eq!(key(&mut h, false), None, "from the topmost, the next layer down is the active one"); +} + +#[test] +fn a_click_or_drag_after_cycling_takes_the_layer_the_outline_shows() { + let (mut h, s) = stack(); + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + assert_eq!(key(&mut h, true), Some(s.red)); + let h0 = history(&h); + let p = screen(&h, 130.0, 130.0); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + h.event(egui::Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + assert_eq!(active(&h), Some(s.red), "the click picks the outlined layer, not the topmost Green"); + assert_eq!(history(&h), h0, "a click adds no history state"); + + // A drag after cycling moves the outlined layer. + let (mut h, s) = stack(); + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + assert_eq!(key(&mut h, true), Some(s.red)); + let h0 = history(&h); + let from = screen(&h, 130.0, 130.0); + h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(1); + for x in [140.0, 160.0, 170.0] { + h.event(egui::Event::PointerMoved(screen(&h, x, 130.0))); + h.run_steps(1); + } + let to = screen(&h, 170.0, 130.0); + h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + let bounds = |id: LayerId| photocraft_compose::bounds::content_bounds(st.doc.layer(id).unwrap().surface().unwrap()); + assert!(bounds(s.red).x0 > 60, "Red moved right: {:?}", bounds(s.red)); + assert_eq!(bounds(s.green).x0, 120, "Green stayed"); + assert_eq!(st.active_layer, Some(s.red)); + assert_eq!(st.history.past_len(), h0 + 1); + assert_eq!(st.history.entries().pop().as_deref(), Some("Move")); +} + +#[test] +fn other_tools_keep_the_brush_size_keys() { + let (mut h, s) = stack(); + h.state_mut().ui.tool = Tool::Brush; + hover(&mut h, 130.0, 130.0, Modifiers::NONE); + let size = h.state().session.tools.brush.size; + tap(&mut h, Key::CloseBracket, Modifiers::NONE); + assert!(h.state().session.tools.brush.size > size, "] grows the brush"); + tap(&mut h, Key::OpenBracket, Modifiers::NONE); + tap(&mut h, Key::OpenBracket, Modifiers::NONE); + assert!(h.state().session.tools.brush.size < size, "[ shrinks it"); + assert_eq!(active(&h), Some(s.background)); +} diff --git a/crates/ui-egui/src/tools/move_hover.rs b/crates/ui-egui/src/tools/move_hover.rs index d463804ff7..0aa2e09cb6 100644 --- a/crates/ui-egui/src/tools/move_hover.rs +++ b/crates/ui-egui/src/tools/move_hover.rs @@ -4,12 +4,17 @@ //! (`pick_cmds::move_auto_select_target`), so a type layer is outlined anywhere inside its text, as it //! is picked there (#2591). The answer is cached per document revision and pointer pixel: a //! pointer resting on the canvas costs nothing per frame. The active layer itself is never outlined. +//! +//! Show Previous / Next Layer Boundary (`]` / `[` with the Move tool, #18432) step the outline +//! through the layers under the pointer ([`step`]); a plain Auto-Select click then picks the layer +//! the outline shows ([`cycled_layer`]). use craft::behavior::kurbo; use craft::ui::canvas_controls::{HoverOutline, HoverShape}; use craft::ui::contract::Show as _; use photocraft_doc::{DocId, Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; +use serde_json::{Value, json}; use crate::PhotocraftApp; use crate::state::Tool; @@ -24,6 +29,97 @@ pub(crate) struct Hover { bounds: Option, } +/// Show Previous Layer Boundary: one layer up the stack (`]`). +pub(crate) const PREVIOUS_BOUNDARY: &str = "move.showPreviousLayerBoundary"; +/// Show Next Layer Boundary: one layer down the stack (`[`). +pub(crate) const NEXT_BOUNDARY: &str = "move.showNextLayerBoundary"; + +/// Where the boundary keys left the outline at a pointer pixel. `shown` is `None` once the cycle +/// reached the active layer: no outline, and the keys do nothing, until the pointer moves. +pub(crate) struct Cycle { + doc: DocId, + revision: u64, + at: [i32; 2], + shown: Option, +} + +/// A pointer move of this many document pixels (on either axis) ends a cycle: in the reference a +/// 1 px move kept it and a 4 px move ended it. +const CYCLE_SLACK: i32 = 2; + +/// The cycle still in force with the pointer at `at` on revision `revision` of `doc`: `Some(shown)`. +/// A cycle of another document or revision, or one the pointer moved away from, ends here. +fn live_cycle(app: &mut PhotocraftApp, doc: DocId, revision: u64, at: [i32; 2]) -> Option> { + let c = app.move_boundary.as_ref()?; + if c.doc == doc && c.revision == revision && (c.at[0] - at[0]).abs() < CYCLE_SLACK && (c.at[1] - at[1]).abs() < CYCLE_SLACK { + return Some(c.shown); + } + app.move_boundary = None; + None +} + +/// Whether `id` is one of the two boundary commands; `Some(true)` for Show Previous Layer Boundary. +pub(crate) fn boundary_command(id: &str) -> Option { + match id { + PREVIOUS_BOUNDARY => Some(true), + NEXT_BOUNDARY => Some(false), + _ => None, + } +} + +/// The boundary command the fired brush-size key `id` runs instead: with the Move tool picking +/// layers, `]` and `[` step the outline (Photoshop's Tools shortcuts share the keys). Auto-Select: +/// Group keeps the brush-size keys, as do the other tools. +pub(crate) fn bracket_command(app: &PhotocraftApp, id: &str) -> Option<&'static str> { + if app.ui.tool != Tool::Move || app.ui.tool_options.move_target == "group" { + return None; + } + match id { + "tools.increaseBrushSize" => Some(PREVIOUS_BOUNDARY), + "tools.decreaseBrushSize" => Some(NEXT_BOUNDARY), + _ => None, + } +} + +/// Runs Show Previous (`up`) or Show Next Layer Boundary with the pointer at `at` (document px): +/// the outline moves to the next layer with pixels there, or goes away when that is the active +/// layer. Changes no layer and adds no history state. `{"layer": null}` with no pointer on the +/// canvas, or after the cycle ended until the pointer moves. +pub(crate) fn step(app: &mut PhotocraftApp, at: Option<[f64; 2]>, up: bool) -> Result { + let id = if up { PREVIOUS_BOUNDARY } else { NEXT_BOUNDARY }; + let Some(at) = at.filter(|p| p[0].is_finite() && p[1].is_finite()) else { return Ok(json!({"layer": null})) }; + let Some(st) = app.session.active() else { return app.run(id, json!({"x": at[0], "y": at[1]})) }; + let (doc, revision) = (st.doc.id, st.revision); + let px = [at[0].floor() as i32, at[1].floor() as i32]; + let from = match live_cycle(app, doc, revision, px) { + Some(None) => return Ok(json!({"layer": null})), + Some(shown) => shown, + None => None, + }; + let out = app.run(id, json!({"x": at[0], "y": at[1], "from": from.map(|l| l.0)}))?; + if out["layers"].as_array().is_some_and(|l| !l.is_empty()) { + let shown = out["layer"].as_u64().map(LayerId); + // A cycle already in force keeps its pixel, so steps of a resting pointer never drift. + let at = app.move_boundary.as_ref().map_or(px, |c| c.at); + app.move_boundary = Some(Cycle { doc, revision, at, shown }); + } + Ok(out) +} + +/// The layer the boundary keys show with the pointer at `p` (document px), when it has pixels +/// there: a plain Auto-Select click picks it instead of the topmost layer. +pub(crate) fn cycled_layer(app: &mut PhotocraftApp, p: [f64; 2]) -> Option { + if !(p[0].is_finite() && p[1].is_finite()) { + return None; + } + let st = app.session.active()?; + let (doc, revision) = (st.doc.id, st.revision); + let at = [p[0].floor() as i32, p[1].floor() as i32]; + let shown = live_cycle(app, doc, revision, at)??; + let st = app.session.active()?; + photocraft_engine::pick_cmds::boundary_candidates(&st.doc, at[0], at[1]).contains(&shown).then_some(shown) +} + /// The document-space bounds to outline with the pointer at `at` (document px), or `None` when /// nothing is highlighted: the preference is off, another tool is current, the hover mode is /// inactive, the selected pixels move instead, a button is down, or a transform is under way. @@ -59,6 +155,15 @@ pub(crate) fn target(app: &mut PhotocraftApp, at: Option<[f64; 2]>, command: boo (target_layer, bounds) } }; + // The boundary keys' layer replaces the topmost one while the pointer stays (#18432). + let (target_layer, bounds) = match if group { None } else { live_cycle(app, doc, revision, at) } { + Some(shown) => { + let st = app.session.active()?; + let bounds = shown.and_then(|id| outline(&st.doc, id)); + (shown.filter(|_| bounds.is_some()), bounds) + } + None => (target_layer, bounds), + }; // The active layer is never outlined (#18433). Checked after the cache: picking another layer // doesn't change the document revision. if target_layer.is_some() && target_layer == active { @@ -139,6 +244,10 @@ mod move_hover_auto_select_off_tests; #[path = "../move_hover_active_layer_tests.rs"] mod move_hover_active_layer_tests; +#[cfg(test)] +#[path = "../move_layer_boundary_cycle_tests.rs"] +mod move_layer_boundary_cycle_tests; + #[cfg(test)] mod tests { use serde_json::json;