From 18602e6a2e391a4e96ded85dcab86c2429c2bd47 Mon Sep 17 00:00:00 2001 From: RickiNano <81099017+RickiNano@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:00:33 +0100 Subject: [PATCH] Direct Selection: Delete removes the selected anchor, segment or targeted path, not the layer (#13203) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Direct Selection, Delete / Backspace fell through to Edit › Clear and deleted the active layer. Now, as measured in the reference: - one selected anchor goes with its two segments (path.deleteAnchor segments:true, as for the anchor tools, #12703): History "Delete Anchor Point"; - a selected segment goes on its own: the anchors stay, a closed subpath opens starting at the segment's end (new path.deleteSegment, History "Delete Anchor Point"); - with nothing selected, the targeted saved path or Work Path is deleted (path.delete, "Delete Path"), and a targeted vector mask goes as the Paths panel's trash deletes it. Several selected anchors and a shape layer's path with nothing selected were not measured and keep today's route. --- crates/engine/src/cmd/path_edit_cmds.rs | 35 ++++ crates/ui-egui/src/input/shortcuts.rs | 25 ++- crates/ui-egui/src/tools/direct_select.rs | 3 + .../tools/direct_select/delete_key_tests.rs | 183 ++++++++++++++++++ crates/ui-egui/src/tools/vector_ui.rs | 6 +- .../ui-egui/src/tools/vector_ui/path_ops.rs | 65 ++++++- crates/vector/src/edit.rs | 50 +++++ 7 files changed, 346 insertions(+), 21 deletions(-) create mode 100644 crates/ui-egui/src/tools/direct_select/delete_key_tests.rs diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index 4e8b89f56e..a42f9b8efb 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -206,6 +206,14 @@ fn delete_anchor(s: &mut Session, p: &Value) -> Result { Ok(r) } +/// ⌫ / Delete on a segment selected with Direct Selection: the segment goes, its anchors stay. +/// Photoshop names the step Delete Anchor Point (#13203). +fn delete_segment(s: &mut Session, p: &Value) -> Result { + const CMD: &str = "path.deleteSegment"; + let k = knot(CMD, p)?; + edit_path(s, CMD, p, "Delete Anchor Point", |path| edit::delete_segment(path, k)) +} + /// Merge Shape Components on a path (the Pen's and Path Selection's Path Operations menu): the /// components' operations are baked into plain combined outlines, as for a shape layer. fn merge_components(s: &mut Session, p: &Value) -> Result { @@ -314,6 +322,12 @@ pub fn specs() -> Vec { r#""subpath":i,"knot":j,"segments":bool=false (its neighbours are joined, keeping their handles; segments = ⌫/Delete on a selected anchor: its two segments go too, so a closed subpath opens there and an open one splits; a subpath's last anchor removes the subpath; the path's only anchor empties a saved path and is refused elsewhere) (the result also has subpathRemoved:bool)"#.into(), delete_anchor, ), + spec( + "path.deleteSegment", + "Delete Segment", + r#""subpath":i,"knot":j (the segment leaving it) (⌫/Delete on a segment selected with Direct Selection: the anchors stay; a closed subpath opens there, starting at the segment's end; an open one splits in two) (History: Delete Anchor Point)"#.into(), + delete_segment, + ), spec( "path.mergeShapeComponents", "Merge Shape Components", @@ -503,6 +517,27 @@ mod tests { assert_eq!(work(&s), before); } + #[test] + fn deleting_a_segment_opens_the_subpath_in_one_step_and_refuses_bad_params() { + let mut s = session(); + s.execute("path.set", json!({"path": square()})).unwrap(); + let (before, steps) = (work(&s), s.active().unwrap().history.entries().len()); + s.execute("path.deleteSegment", json!({"subpath": 0, "knot": 1})).unwrap(); + let sp = &work(&s).subpaths[0]; + assert_eq!((sp.knots.len(), sp.closed), (4, false), "every anchor stays"); + assert_eq!(sp.knots[0].anchor, before.subpaths[0].knots[2].anchor, "it starts at the segment's end"); + assert_eq!(s.active().unwrap().history.entries().len(), steps + 1); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); + assert!(s.undo()); + assert_eq!(work(&s), before); + for p in + [json!({}), json!({"subpath": 0}), json!({"subpath": 0, "knot": 9}), json!({"subpath": -1, "knot": 0}), json!({"name": 3, "subpath": 0, "knot": 0})] + { + assert!(s.execute("path.deleteSegment", p.clone()).is_err(), "{p}"); + } + assert_eq!(work(&s), before, "refusals change nothing"); + } + #[test] fn anchor_tools_edit_saved_paths_shapes_and_vector_masks() { let mut s = session(); diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 158079ddf0..62f2303657 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -722,19 +722,23 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f crate::shape_bounds_box::cancel(app); return true; } - // An anchor selected with the Add Anchor Point tool: ⌫/Delete removes it and its two segments, - // as in Photoshop (#12703), never the active layer. + // An anchor selected with Direct Selection or the Add / Delete Anchor Point tool: ⌫/Delete + // removes it and its two segments (#12703, #13203); a segment selected with Direct Selection + // goes on its own (#13203). As in Photoshop, never the active layer. if focus != crate::shortcut_dispatch::Focus::DeletingWidget - && let Some((target, [s, k])) = crate::vector_ui::delete_key_deletes_anchor(app) + && let Some((target, cmd, mut params)) = crate::vector_ui::delete_key_deletes_anchor(app) + .map(|(target, [s, k])| (target, "path.deleteAnchor", json!({"subpath": s, "knot": k, "segments": true}))) + .or_else(|| { + crate::vector_ui::delete_key_deletes_segment(app).map(|(target, [s, k])| (target, "path.deleteSegment", json!({"subpath": s, "knot": k}))) + }) { let mods = ctx.input(|i| i.modifiers); if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { - let mut params = json!({"subpath": s, "knot": k, "segments": true}); if let (Some(p), Some(t)) = (params.as_object_mut(), target.params(app).as_object()) { p.extend(t.clone()); } - match app.run("path.deleteAnchor", params) { + match app.run(cmd, params) { // The anchors shift: the selection would point at the wrong ones. Ok(_) => app.ui.direct_selection = crate::direct_select::DirectSelection::default(), Err(e) => { @@ -745,13 +749,16 @@ fn handle_pen_and_work_path_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f return true; } } - // A finished work path shown by the Pen or Path Selection: ⌫/Delete deletes it, as in - // Photoshop (#5702), never Edit › Clear on the pixels under it. - if focus != crate::shortcut_dispatch::Focus::DeletingWidget && crate::vector_ui::delete_key_deletes_work_path(app) { + // A finished work path shown by the Pen or Path Selection (#5702), or the path Direct + // Selection targets with nothing selected on it (#13203): ⌫/Delete deletes it, as in + // Photoshop, never Edit › Clear on the pixels under it or the active layer. + if focus != crate::shortcut_dispatch::Focus::DeletingWidget + && let Some((cmd, params)) = crate::vector_ui::delete_key_deletes_path(app) + { let mods = ctx.input(|i| i.modifiers); if !mods.command && !mods.ctrl && !mods.shift && !mods.alt && ctx.input_mut(|i| i.consume_key(mods, Key::Backspace) || i.consume_key(mods, Key::Delete)) { - if let Err(e) = app.run("path.delete", json!({"name": "work"})) { + if let Err(e) = app.run(cmd, params) { app.ui.status = e; app.ui.status_error = true; } diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 9272d570fc..dca0c67707 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -927,6 +927,9 @@ mod convert_point_history_tests; #[cfg(test)] mod convert_point_targeted_path_tests; +#[cfg(test)] +mod delete_key_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select/delete_key_tests.rs b/crates/ui-egui/src/tools/direct_select/delete_key_tests.rs new file mode 100644 index 0000000000..270cedbd50 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/delete_key_tests.rs @@ -0,0 +1,183 @@ +//! #13203: with Direct Selection, Delete / Backspace edits the targeted path, never the active +//! layer. A selected anchor goes with its two segments, a selected segment on its own (History: +//! Delete Anchor Point), and with nothing selected the targeted path is deleted (Delete Path). + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// 800 x 600 on white, pixel layer Red active, saved path Path 1 (a closed corner square and the +/// open line (400,300)-(700,300)) targeted in the Paths panel, Direct Selection on. +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600, "background": "white"})).unwrap(); + app.sync_views(); + app.run("layer.new.layer", json!({"name": "Red"})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"closed": false, "knots": [[400, 300], [700, 300]]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.ui.tool = Tool::DirectSelection; + app +} + +fn path1(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().doc.paths.iter().find(|p| p.name == "Path 1").map(|p| p.path.clone()) +} + +fn layers(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.layers.len() +} + +fn steps(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().history.past_len() +} + +fn last_step(app: &PhotocraftApp) -> Option { + app.session.active().unwrap().history.undo_label().map(str::to_string) +} + +fn click(app: &mut PhotocraftApp, at: [f64; 2]) { + tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, Modifiers::NONE); + tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, Modifiers::NONE); +} + +/// A key through the app's shortcut handling, as the canvas gets it. +fn press(app: &mut PhotocraftApp, key: egui::Key) { + let ctx = egui::Context::default(); + let m = Modifiers::NONE; + let raw = egui::RawInput { + events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }], + ..Default::default() + }; + ctx.begin_pass(raw); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn anchors(path: &Path, s: usize) -> (Vec<[f64; 2]>, bool) { + let sp = &path.subpaths[s]; + (sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(), sp.closed) +} + +#[test] +fn delete_on_a_selected_anchor_of_a_saved_path_keeps_every_layer() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let (before, n, count) = (path1(&app), steps(&app), layers(&app)); + click(&mut app, [300.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "{key:?}: the click selects the corner"); + assert_eq!(steps(&app), n, "{key:?}: a click moves nothing"); + press(&mut app, key); + assert_eq!(layers(&app), count, "{key:?}: every layer is still there"); + let p = path1(&app).unwrap(); + assert_eq!(anchors(&p, 0), (vec![[300.0, 500.0], [100.0, 500.0], [100.0, 300.0]], false), "{key:?}: the square opens at the next anchor"); + assert_eq!(anchors(&p, 1).0.len(), 2, "{key:?}: the line is untouched"); + assert_eq!((steps(&app), last_step(&app).as_deref()), (n + 1, Some("Delete Anchor Point")), "{key:?}"); + assert!(app.session.undo()); + assert_eq!(path1(&app), before, "{key:?}: Undo restores the closed square"); + } +} + +#[test] +fn delete_on_a_selected_segment_removes_only_that_segment() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let (before, n, count) = (path1(&app), steps(&app), layers(&app)); + click(&mut app, [100.0, 400.0]); + assert_eq!((app.ui.direct_selection.segment, app.ui.direct_selection.anchors.len()), (Some([0, 3]), 0), "{key:?}: the left edge"); + press(&mut app, key); + assert_eq!(layers(&app), count, "{key:?}: every layer is still there"); + let p = path1(&app).unwrap(); + assert_eq!( + anchors(&p, 0), + (vec![[100.0, 300.0], [300.0, 300.0], [300.0, 500.0], [100.0, 500.0]], false), + "{key:?}: open, all four anchors, from (100,300) to (100,500)" + ); + assert_eq!((steps(&app), last_step(&app).as_deref()), (n + 1, Some("Delete Anchor Point")), "{key:?}"); + assert!(app.session.undo()); + assert_eq!(path1(&app), before, "{key:?}"); + } +} + +#[test] +fn delete_on_an_open_lines_start_leaves_its_end() { + let mut app = app(); + let count = layers(&app); + click(&mut app, [400.0, 300.0]); + assert_eq!(app.ui.direct_selection.anchors, vec![[1, 0]]); + press(&mut app, egui::Key::Delete); + assert_eq!(layers(&app), count); + assert_eq!(anchors(&path1(&app).unwrap(), 1), (vec![[700.0, 300.0]], false)); + assert_eq!(last_step(&app).as_deref(), Some("Delete Anchor Point")); +} + +#[test] +fn delete_with_nothing_selected_deletes_the_targeted_saved_path() { + for key in [egui::Key::Delete, egui::Key::Backspace] { + let mut app = app(); + let count = layers(&app); + press(&mut app, key); + assert_eq!(layers(&app), count, "{key:?}: every layer is still there"); + assert!(path1(&app).is_none(), "{key:?}: Path 1 is deleted"); + assert_eq!(last_step(&app).as_deref(), Some("Delete Path"), "{key:?}"); + assert!(app.session.undo()); + assert!(path1(&app).is_some(), "{key:?}: Undo brings it back"); + } +} + +#[test] +fn delete_with_nothing_selected_deletes_the_targeted_work_path() { + let mut app = app(); + app.run("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": [[10, 10], [90, 90]]}]}})).unwrap(); + app.ui.selected_path = Some("work".into()); + let count = layers(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(layers(&app), count); + let st = app.session.active().unwrap(); + assert!(st.doc.work_path.is_none() && path1(&app).is_some(), "only the Work Path goes"); + assert_eq!(last_step(&app).as_deref(), Some("Delete Path")); +} + +#[test] +fn delete_with_nothing_selected_deletes_the_targeted_vector_mask() { + let mut app = app(); + app.run("layer.vectorMask.fromPath", json!({"name": "Path 1"})).unwrap(); + app.ui.selected_path = None; + app.ui.vector_mask_target = true; + let (count, red) = (layers(&app), app.session.active().unwrap().active_layer.unwrap()); + press(&mut app, egui::Key::Delete); + let st = app.session.active().unwrap(); + assert_eq!(layers(&app), count, "every layer is still there"); + assert!(st.doc.layer(red).unwrap().vector_mask.is_none(), "the vector mask is deleted"); + assert!(path1(&app).is_some(), "the saved path stays"); +} + +#[test] +fn without_a_targeted_path_delete_keeps_its_usual_route() { + let mut app = app(); + app.ui.selected_path = None; + app.run("path.delete", json!({"name": "Path 1"})).unwrap(); + let count = layers(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(layers(&app), count - 1, "no path: Delete still deletes the active layer"); +} + +#[test] +fn several_selected_anchors_keep_todays_route() { + // Not measured in the reference: the path is left alone. + let mut app = app(); + click(&mut app, [300.0, 300.0]); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::SHIFT); + tool_event(&mut app, ToolEvent::Up { x: 300.0, y: 500.0 }, Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1], [0, 2]]); + let before = path1(&app); + press(&mut app, egui::Key::Delete); + assert_eq!(path1(&app), before, "the path is unchanged"); +} diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 54fe6527ce..74eaebbe80 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -40,13 +40,15 @@ use overlay::{MAX_CURVE_PIECES, bezier}; pub(crate) use overlay::{curve_points, path_lines, selected_saved_path, shows_anchors}; pub(crate) use overlay::{draw_anchor, draw_handle, draw_outline}; #[cfg(test)] +use path_ops::delete_key_deletes_work_path; +#[cfg(test)] use path_ops::target_path; pub use path_ops::{ active_path_name, make_shape, path_selection_finish, path_to_selection, pick_shape_at, selected_document_path, takes_path_mask, with_active_path, }; pub(crate) use path_ops::{ - active_shape_path, active_type_path, delete_key_deletes_anchor, delete_key_deletes_work_path, deselect_loaded_path, free_transform_path, - targeted_vector_mask, work_path_shown, + active_shape_path, active_type_path, delete_key_deletes_anchor, delete_key_deletes_path, delete_key_deletes_segment, deselect_loaded_path, + free_transform_path, targeted_vector_mask, work_path_shown, }; #[cfg(test)] use paths_panel::path_context_actions; diff --git a/crates/ui-egui/src/tools/vector_ui/path_ops.rs b/crates/ui-egui/src/tools/vector_ui/path_ops.rs index 6c86c1d287..62385a2ff1 100644 --- a/crates/ui-egui/src/tools/vector_ui/path_ops.rs +++ b/crates/ui-egui/src/tools/vector_ui/path_ops.rs @@ -216,25 +216,70 @@ pub(crate) fn delete_key_deletes_work_path(app: &PhotocraftApp) -> bool { && matches!(target_path(app), Some((PathTarget::Work, _))) } -/// The anchor ⌫ / Delete removes, with its two segments: with the Add or Delete Anchor Point tool, the one -/// anchor selected on it (⌘/Ctrl+click) while that selection still holds and its path is shown, -/// as in Photoshop (#12703). The key reached Edit › Clear and deleted the active layer. Several -/// selected anchors weren't measured and keep the key's other routes. -pub(crate) fn delete_key_deletes_anchor(app: &PhotocraftApp) -> Option<(crate::direct_select::PathRef, [usize; 2])> { +/// Does ⌫ / Delete act on what Direct Selection or the anchor tools selected on `target`: the +/// selection still holds, nothing is being drawn or dragged, and the path is shown and writable. +fn delete_key_edits_selection(app: &PhotocraftApp, target: &crate::direct_select::PathRef) -> bool { let ds = &app.ui.direct_selection; - let ([[s, k]], Some(target)) = (ds.anchors.as_slice(), ds.target) else { return None }; - let usable = matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) - && app.ui.pen.is_none() + app.ui.pen.is_none() && ds.drag.is_none() && app.ui.view.shows(app.ui.view.show.target_path) && crate::direct_select::still_valid(app, ds) - && crate::direct_select::writable(app, &target); - usable.then_some(())?; + && crate::direct_select::writable(app, target) +} + +/// The anchor ⌫ / Delete removes, with its two segments: with Direct Selection or the Add or +/// Delete Anchor Point tool, the one anchor selected on it while that selection still holds and +/// its path is shown, as in Photoshop (#12703, #13203). The key reached Edit › Clear and deleted +/// the active layer. Several selected anchors weren't measured and keep the key's other routes. +pub(crate) fn delete_key_deletes_anchor(app: &PhotocraftApp) -> Option<(crate::direct_select::PathRef, [usize; 2])> { + let ds = &app.ui.direct_selection; + let ([[s, k]], Some(target)) = (ds.anchors.as_slice(), ds.target) else { return None }; + let tool = matches!(app.ui.tool, Tool::DirectSelection | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint); + (tool && delete_key_edits_selection(app, &target)).then_some(())?; let (_, path) = crate::direct_select::candidates(app).into_iter().find(|(r, _)| *r == target)?; path.subpaths.get(*s)?.knots.get(*k)?; Some((target, [*s, *k])) } +/// The segment ⌫ / Delete removes (`[subpath, knot]` it leaves): with Direct Selection, a clicked +/// segment and no selected anchor. Its anchors stay and the subpath opens there, as in Photoshop +/// (#13203). +pub(crate) fn delete_key_deletes_segment(app: &PhotocraftApp) -> Option<(crate::direct_select::PathRef, [usize; 2])> { + let ds = &app.ui.direct_selection; + let (Some([s, k]), Some(target)) = (ds.segment, ds.target) else { return None }; + let usable = app.ui.tool == Tool::DirectSelection && ds.anchors.is_empty() && delete_key_edits_selection(app, &target); + usable.then_some(())?; + let (_, path) = crate::direct_select::candidates(app).into_iter().find(|(r, _)| *r == target)?; + path.subpaths.get(s)?.knots.get(k)?; + Some((target, [s, k])) +} + +/// The path ⌫ / Delete deletes, as the command and its params: the work path with the Pen, +/// Freeform Pen or Path Selection ([`delete_key_deletes_work_path`]); with Direct Selection and +/// no anchor or segment selected, the targeted saved path, work path or vector mask, as in +/// Photoshop (#13203). A shape layer's path wasn't measured: the key keeps deleting the layer. +pub(crate) fn delete_key_deletes_path(app: &PhotocraftApp) -> Option<(&'static str, Value)> { + if delete_key_deletes_work_path(app) { + return Some(("path.delete", json!({"name": "work"}))); + } + let ds = &app.ui.direct_selection; + let selected = crate::direct_select::still_valid(app, ds) && (!ds.anchors.is_empty() || ds.segment.is_some()); + let usable = app.ui.tool == Tool::DirectSelection + && !selected + && app.ui.pen.is_none() + && app.ui.transform.is_none() + && ds.drag.is_none() + && app.ui.view.shows(app.ui.view.show.target_path); + usable.then_some(())?; + match target_path(app)?.0 { + PathTarget::Work => Some(("path.delete", json!({"name": "work"}))), + PathTarget::Saved(name) => Some(("path.delete", json!({"name": name}))), + // As the Paths panel's trash does with a vector mask's row. + PathTarget::VectorMask(id) => Some(("layer.vectorMask.delete", json!({"layer": id}))), + PathTarget::Shape(_) => None, + } +} + /// The path Path Selection edits: the targeted vector mask, the active shape layer's path, the /// saved path selected in the Paths panel (#8478), else the work path. pub(super) fn target_path(app: &PhotocraftApp) -> Option<(PathTarget, Path)> { diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs index 30b200216b..d84c1642a7 100644 --- a/crates/vector/src/edit.rs +++ b/crates/vector/src/edit.rs @@ -295,6 +295,25 @@ pub fn delete_anchor_and_segments(path: &mut Path, [s, k]: [usize; 2]) -> Result Ok(false) } +/// ⌫ / Delete on a segment selected with Direct Selection: removes the segment that leaves +/// `[s, k]` and keeps every anchor. A closed subpath opens there, starting at the segment's end +/// and ending at `k`; an open subpath splits in two. The knots keep their handles. +pub fn delete_segment(path: &mut Path, [s, k]: [usize; 2]) -> Result<(), String> { + let [_, end] = segment_end(path, [s, k])?; + let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?; + if sp.closed { + // `end` is `k + 1`, or 0 when the closing segment goes. + sp.knots.rotate_left(end); + sp.closed = false; + return Ok(()); + } + // Open: `end` = `k + 1` < len. + let rest = Subpath { closed: false, knots: sp.knots.split_off(end), op: sp.op }; + let at = s.checked_add(1).ok_or_else(|| format!("no subpath after {s}"))?; + path.subpaths.insert(at, rest); + Ok(()) +} + /// Every anchor of subpath `s` (⌥-click with Direct Selection selects the whole subpath). pub fn subpath_anchors(path: &Path, s: usize) -> Vec<[usize; 2]> { path.subpaths.get(s).map_or_else(Vec::new, |sp| (0..sp.knots.len()).map(|k| [s, k]).collect()) @@ -700,6 +719,37 @@ mod tests { } } + #[test] + fn deleting_a_segment_opens_a_closed_subpath_or_splits_an_open_one() { + let square = || Path::new(vec![Subpath::polygon(&[(100.0, 300.0), (300.0, 300.0), (300.0, 500.0), (100.0, 500.0)])]); + // The left edge (the closing segment): all four anchors, from (100,300) to (100,500). + let mut p = square(); + delete_segment(&mut p, [0, 3]).unwrap(); + assert_eq!(p, Path::new(vec![Subpath::polyline(&[(100.0, 300.0), (300.0, 300.0), (300.0, 500.0), (100.0, 500.0)])])); + let mut p = square(); + delete_segment(&mut p, [0, 1]).unwrap(); + assert_eq!(p, Path::new(vec![Subpath::polyline(&[(300.0, 500.0), (100.0, 500.0), (100.0, 300.0), (300.0, 300.0)])])); + let line = || Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)])]); + let mut p = line(); + delete_segment(&mut p, [0, 0]).unwrap(); + assert_eq!(p, Path::new(vec![Subpath::polyline(&[(0.0, 0.0)]), Subpath::polyline(&[(10.0, 0.0), (20.0, 0.0)])])); + let mut p = line(); + delete_segment(&mut p, [0, 1]).unwrap(); + assert_eq!(p, Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (10.0, 0.0)]), Subpath::polyline(&[(20.0, 0.0)])])); + } + + #[test] + fn deleting_a_segment_refuses_one_that_does_not_exist() { + for k in [[0, 2], [0, 3], [1, 0], [usize::MAX, usize::MAX]] { + let mut p = Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0)])]); + let before = p.clone(); + assert!(delete_segment(&mut p, k).is_err(), "{k:?}"); + assert_eq!(p, before, "{k:?}: unchanged"); + } + let mut lone = Path::new(vec![Subpath { closed: true, knots: vec![Knot::corner(1.0, 1.0)], op: PathOp::Combine }]); + assert!(delete_segment(&mut lone, [0, 0]).is_err(), "a closed single anchor has no segment"); + } + #[test] fn deleting_with_segments_trims_or_splits_an_open_subpath() { let line = || Path::new(vec![Subpath::polyline(&[(0.0, 0.0), (10.0, 0.0), (20.0, 0.0), (30.0, 0.0)])]);