Skip to content

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

Add Anchor Point and Delete Anchor Point tools (#1044) (#2756)

Fabio Lussid96bb50161f5
diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md
index 68312f1ce..da46de9f8 100644
--- a/ATTRIBUTION.md
+++ b/ATTRIBUTION.md
@@ -20,7 +20,7 @@ next to them.
| `crates/ui-egui/src/i18n/uk.tsv` | Ukrainian UI translations | PhotoCraft contributors | Original translations of PhotoCraft's English labels | MIT OR Apache-2.0, [`LICENSE-translations.txt`](crates/ui-egui/src/i18n/LICENSE-translations.txt) |
| `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | <https://github.com/rsms/inter> | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) |
| `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | <https://github.com/JetBrains/JetBrainsMono> | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) |
-| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+| `assets/icons/*.svg` except `slice-knife.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg` and `marquee-{row,column}.svg` (112 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | <https://github.com/lucide-icons/lucide> (`icons/<name>.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/{check,chevron-down,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | <https://github.com/feathericons/feather> via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
| `assets/icons/marquee-row.svg`, `assets/icons/marquee-column.svg` | Single Row and Single Column Marquee tool glyphs: a dashed row (column) between two edge bars, drawn on Lucide's 24 px grid and stroke | PhotoCraft contributors | Original work | MIT OR Apache-2.0 |
@@ -30,6 +30,7 @@ next to them.
| `assets/icons/brush-replace.svg` | Color Replacement tool glyph: Lucide `brush` plus two swap arrows | Lucide Icons and Contributors; arrows by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/brush.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/bandage-sparkle.svg` | Remove tool glyph: Lucide `bandage` moved down, plus a sparkle mark | Lucide Icons and Contributors; mark by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/bandage.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/direct-select.svg` | Direct Selection tool glyph: Lucide `mouse-pointer-2` plus an anchor square | Lucide Icons and Contributors; square by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/mouse-pointer-2.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
+| `assets/icons/pen-add-anchor.svg`, `assets/icons/pen-delete-anchor.svg` | Add Anchor Point and Delete Anchor Point tool glyphs: Lucide `pen-tool` plus a + or − mark | Lucide Icons and Contributors; marks by PhotoCraft contributors | Derived from <https://github.com/lucide-icons/lucide> `icons/pen-tool.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/painting-symmetry.svg` | Painting symmetry glyph: Lucide `heart` with a central axis | Lucide Icons and Contributors; adapted by @shorbank | Derived from <https://github.com/lucide-icons/lucide> `icons/heart.svg` | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) |
| `assets/icons/symmetry-{vertical,horizontal,dual,diagonal}.svg` | Painting symmetry axis glyphs | @shorbank | Original work; supplied SVG line geometry centred on a common square canvas, stroke adjusted to match the painting-symmetry glyph | MIT OR Apache-2.0, [`assets/icons/LICENSE-symmetry-axes.txt`](assets/icons/LICENSE-symmetry-axes.txt) |
| `assets/icons/lasso-magnetic.svg` | Magnetic Lasso tool glyph, adapted from "Magnetic Lasso Tool" (redrawn on the 24 px toolbar grid) | Lil' Seal (Noun Project); adapted by PhotoCraft contributors | <https://thenounproject.com/icon/magnetic-lasso-tool-177513/> | CC BY 3.0, [`assets/icons/LICENSE-noun-magnetic-lasso.txt`](assets/icons/LICENSE-noun-magnetic-lasso.txt) |
diff --git a/README.md b/README.md
index 1e550c03f..be6e1654c 100644
--- a/README.md
+++ b/README.md
@@ -178,8 +178,8 @@ Every screenshot here is the real app at work on public-domain art, rendered off
<table>
<tr>
<td width="33%" valign="top">
- <h4>🧰 56 tools</h4>
- Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
+ <h4>🧰 58 tools</h4>
+ Move · Rectangular and Elliptical Marquee · Single Row Marquee · Single Column Marquee · Lasso · Polygonal Lasso · Magnetic Lasso · Object Selection · Quick Selection · Magic Wand · Crop · Slice · Slice Select · Eyedropper · Ruler · Note · Count · Remove · Spot Healing Brush · Healing Brush · Patch · Content-Aware Move · Red Eye · Brush · Pencil · Mixer Brush · Color Replacement · Clone Stamp · Pattern Stamp · History Brush · Eraser · Background Eraser · Magic Eraser · Gradient · Paint Bucket · Blur · Sharpen · Smudge · Dodge · Burn · Sponge · Pen · Add Anchor Point · Delete Anchor Point · Horizontal and Vertical Type · Path Selection · Direct Selection · Rectangle · Ellipse · Triangle · Polygon · Line · Custom Shape · Hand · Rotate View · Zoom
</td>
<td width="33%" valign="top">
<h4>🖌️ A real brush engine</h4>
diff --git a/assets/icons/pen-add-anchor.svg b/assets/icons/pen-add-anchor.svg
new file mode 100644
index 000000000..a4e565736
--- /dev/null
+++ b/assets/icons/pen-add-anchor.svg
@@ -0,0 +1,18 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
+ <path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
+ <path d="m2.3 2.3 7.286 7.286" />
+ <circle cx="11" cy="11" r="2" />
+ <path d="M18 3.5h5" />
+ <path d="M20.5 1v5" />
+</svg>
diff --git a/assets/icons/pen-delete-anchor.svg b/assets/icons/pen-delete-anchor.svg
new file mode 100644
index 000000000..f8cee2f97
--- /dev/null
+++ b/assets/icons/pen-delete-anchor.svg
@@ -0,0 +1,17 @@
+<svg
+ xmlns="http://www.w3.org/2000/svg"
+ width="24"
+ height="24"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+>
+ <path d="M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z" />
+ <path d="m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18" />
+ <path d="m2.3 2.3 7.286 7.286" />
+ <circle cx="11" cy="11" r="2" />
+ <path d="M18 3.5h5" />
+</svg>
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 3a436aabe..00a344f98 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -729,6 +729,8 @@ mod tests {
| "path.moveHandle"
| "path.bendSegment"
| "path.convertPoint"
+ | "path.addAnchor"
+ | "path.deleteAnchor"
| "path.clippingPath.set"
| "path.rename"
| "select.toWorkPath"
diff --git a/crates/engine/src/path_edit_cmds.rs b/crates/engine/src/path_edit_cmds.rs
index 53c4ba252..6db84c270 100644
--- a/crates/engine/src/path_edit_cmds.rs
+++ b/crates/engine/src/path_edit_cmds.rs
@@ -1,5 +1,6 @@
-//! Point-level path edits, what Photoshop's Direct Selection (A) and Convert Point tools do on
-//! the canvas: move anchors, drag direction handles, bend segments and convert points. The
+//! Point-level path edits, what Photoshop's Direct Selection (A), Convert Point and Add / Delete
+//! Anchor Point tools do on the canvas: move anchors, drag direction handles, bend segments,
+//! convert points, and insert or remove anchors. The
//! geometry is `photocraft_vector::edit`; the canvas previews a drag with it and commits the
//! whole drag as one command (one history step).
//!
@@ -109,6 +110,38 @@ fn convert_point(s: &mut Session, p: &Value) -> Result<Value> {
edit_path(s, CMD, p, "Convert Point", |path| edit::convert_point(path, k, out))
}
+fn add_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "path.addAnchor";
+ let k = knot(CMD, p)?;
+ let t = match p.get("t") {
+ Some(v) => v.as_f64().filter(|t| *t > 0.0 && *t < 1.0).ok_or_else(|| bad(CMD, "`t` must be strictly between 0 and 1"))?,
+ None => 0.5,
+ };
+ let mut added = None;
+ let mut r = edit_path(s, CMD, p, "Add Anchor Point", |path| {
+ added = Some(edit::add_anchor(path, k, t)?);
+ Ok(())
+ })?;
+ if let (Some(o), Some([sp, kn])) = (r.as_object_mut(), added) {
+ o.insert("anchor".into(), json!({"subpath": sp, "knot": kn}));
+ }
+ Ok(r)
+}
+
+fn delete_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "path.deleteAnchor";
+ let k = knot(CMD, p)?;
+ let mut removed = false;
+ let mut r = edit_path(s, CMD, p, "Delete Anchor Point", |path| {
+ removed = edit::delete_anchor(path, k)?;
+ Ok(())
+ })?;
+ if let Some(o) = r.as_object_mut() {
+ o.insert("subpathRemoved".into(), json!(removed));
+ }
+ Ok(r)
+}
+
pub fn specs() -> Vec<CommandSpec> {
const TARGET: &str = r#""name":str|"work"|"layer"="work","layer":id? (with "layer": a shape layer's path or a vector mask)"#;
let spec = |id: &'static str, label: &'static str, params: String, run: fn(&mut Session, &Value) -> Result<Value>| CommandSpec {
@@ -141,6 +174,18 @@ pub fn specs() -> Vec<CommandSpec> {
r#""subpath":i,"knot":j,"out":[x,y]? (none: corner with retracted handles; given: smooth with this out handle and its mirror)"#.into(),
convert_point,
),
+ spec(
+ "path.addAnchor",
+ "Add Anchor Point",
+ r#""subpath":i,"knot":j (the segment leaving it),"t":0<t<1=0.5 (where on the segment) (a curve is split there without changing its shape and gets a smooth anchor; a straight segment gets a corner) (the result also has anchor:{subpath,knot})"#.into(),
+ add_anchor,
+ ),
+ spec(
+ "path.deleteAnchor",
+ "Delete Anchor Point",
+ r#""subpath":i,"knot":j (its neighbours are joined, keeping their handles; a subpath's last anchor removes the subpath; the path's only anchor is refused) (the result also has subpathRemoved:bool)"#.into(),
+ delete_anchor,
+ ),
]
}
@@ -233,6 +278,87 @@ mod tests {
assert_eq!(vm.path.subpaths[0].knots[0].anchor, photocraft_geom::Point::new(5.0, 5.0));
}
+ fn curve() -> serde_json::Value {
+ json!({"subpaths": [{"closed": false, "knots": [
+ {"anchor": [10, 80], "in": [10, 80], "out": [10, 20]},
+ {"anchor": [60, 50], "in": [40, 20], "out": [80, 80], "smooth": true},
+ {"anchor": [110, 80], "in": [110, 20], "out": [110, 80]}
+ ]}]})
+ }
+
+ fn knots(s: &Session) -> usize {
+ work(s).subpaths.iter().map(|sp| sp.knots.len()).sum()
+ }
+
+ #[test]
+ fn anchors_are_added_and_deleted_in_one_undoable_step_each() {
+ let mut s = session();
+ s.execute("path.set", json!({"path": curve()})).unwrap();
+ let before = work(&s);
+ let steps = s.active().unwrap().history.entries().len();
+ let r = s.execute("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0.5})).unwrap();
+ assert_eq!(r["anchor"], json!({"subpath": 0, "knot": 1}));
+ assert_eq!((knots(&s), s.active().unwrap().history.entries().len()), (4, steps + 1));
+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
+ assert!(work(&s).subpaths[0].knots[1].smooth);
+ let added = work(&s);
+ assert!(s.undo());
+ assert_eq!(work(&s), before, "one undo restores the path exactly");
+ assert!(s.redo());
+ assert_eq!(work(&s), added);
+ let r = s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap();
+ assert_eq!(r["subpathRemoved"], json!(false));
+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
+ assert_eq!(knots(&s), 3);
+ // Deleting the middle anchor of the original curve joins the ends with their own handles.
+ s.execute("path.set", json!({"path": curve()})).unwrap();
+ s.execute("path.deleteAnchor", json!({"subpath": 0, "knot": 1})).unwrap();
+ let k = &work(&s).subpaths[0].knots;
+ assert_eq!((k.len(), k[0].out_ctrl, k[1].in_ctrl), (2, before.subpaths[0].knots[0].out_ctrl, before.subpaths[0].knots[2].in_ctrl));
+ }
+
+ #[test]
+ fn anchor_tools_edit_saved_paths_shapes_and_vector_masks() {
+ let mut s = session();
+ s.execute("path.set", json!({"name": "Outline", "path": square()})).unwrap();
+ let r = s.execute("path.deleteAnchor", json!({"name": "Outline", "subpath": 0, "knot": 0})).unwrap();
+ assert_eq!((r["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), r["path"]["subpaths"][0]["closed"].clone()), (3, json!(true)));
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 120, "height": 100, "depth": depth})).unwrap();
+ let id = s.execute("shape.create", json!({"kind": "rect", "rect": [10, 10, 40, 40], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
+ // Top edge, then pull the new midpoint up: the layer re-renders from the edited path.
+ let r = s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0, "t": 0.5})).unwrap();
+ assert_eq!(anchor(&r, 1), [30.0, 10.0]);
+ s.execute("path.moveAnchors", json!({"name": "layer", "layer": id, "anchors": [[0, 1]], "move": [0, -8]})).unwrap();
+ let st = s.active().unwrap();
+ let photocraft_doc::LayerContent::Shape(ShapeLayer { live, cache, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") };
+ assert!(live.is_none());
+ assert_eq!(cache.as_ref().unwrap().content_bounds().y0, 2, "depth {depth}: re-rendered");
+ s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 1})).unwrap();
+ let st = s.active().unwrap();
+ let photocraft_doc::LayerContent::Shape(ShapeLayer { cache, path, .. }) = &st.doc.layer(LayerId(id)).unwrap().content else { panic!("shape") };
+ assert_eq!((path.subpaths[0].knots.len(), cache.as_ref().unwrap().content_bounds().y0), (4, 10), "depth {depth}");
+ }
+ let id = s.active().unwrap().active_layer.unwrap().0;
+ s.execute("layer.vectorMask.add", json!({"layer": id, "path": square()})).unwrap();
+ s.execute("path.addAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 3, "t": 0.5})).unwrap();
+ let vm = s.active().unwrap().doc.layer(LayerId(id)).unwrap().vector_mask.clone().unwrap();
+ assert_eq!(vm.path.subpaths[0].knots[4].anchor, photocraft_geom::Point::new(10.0, 35.0), "the closing segment's midpoint");
+ }
+
+ #[test]
+ fn the_last_anchor_of_a_shape_is_refused() {
+ let mut s = session();
+ let one = json!({"subpaths": [{"closed": false, "knots": [[10, 10], [50, 10]]}]});
+ let id = s.execute("shape.create", json!({"kind": "path", "path": one, "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap();
+ let steps = s.active().unwrap().history.entries().len();
+ let e = s.execute("path.deleteAnchor", json!({"name": "layer", "layer": id, "subpath": 0, "knot": 0})).unwrap_err();
+ assert!(e.to_string().contains("only anchor"), "{e}");
+ assert_eq!(s.active().unwrap().history.entries().len(), steps);
+ }
+
#[test]
fn bad_params_fail_without_an_edit() {
let mut s = session();
@@ -254,6 +380,18 @@ mod tests {
("path.convertPoint", json!({"subpath": 0, "knot": 0, "out": "x"})),
("path.convertPoint", json!({"name": "nope", "subpath": 0, "knot": 0})),
("path.convertPoint", json!({"name": "layer", "subpath": 0, "knot": 0})),
+ ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 0})),
+ ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": 1})),
+ ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": -0.5})),
+ ("path.addAnchor", json!({"subpath": 0, "knot": 0, "t": "half"})),
+ ("path.addAnchor", json!({"subpath": 0, "knot": 4})),
+ ("path.addAnchor", json!({"subpath": 1, "knot": 0})),
+ ("path.addAnchor", json!({"knot": 0})),
+ ("path.addAnchor", json!({"name": "nope", "subpath": 0, "knot": 0})),
+ ("path.deleteAnchor", json!({"subpath": 0, "knot": 4})),
+ ("path.deleteAnchor", json!({"subpath": 0, "knot": -1})),
+ ("path.deleteAnchor", json!({"subpath": 0})),
+ ("path.deleteAnchor", json!({"name": "layer", "subpath": 0, "knot": 0})),
] {
assert!(s.execute(id, p.clone()).is_err(), "{id} {p}");
}
diff --git a/crates/ui-egui/src/anchor_tools.rs b/crates/ui-egui/src/anchor_tools.rs
new file mode 100644
index 000000000..a314db5fc
--- /dev/null
+++ b/crates/ui-egui/src/anchor_tools.rs
@@ -0,0 +1,105 @@
+//! Add Anchor Point and Delete Anchor Point tools (P group with the Pen, #1044), as in Photoshop.
+//! They edit the paths Direct Selection edits, front first: the targeted vector mask or the active
+//! shape layer's path, then the work path.
+//!
+//! * Add Anchor Point: hovering a segment highlights it and shows where the anchor would go; a
+//! click inserts it there (`path.addAnchor`). A curve is split without changing its shape.
+//! * Delete Anchor Point: hovering an anchor highlights it; a click removes it
+//! (`path.deleteAnchor`), joining its neighbours.
+//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held.
+//!
+//! Each click is one command and one history step; a click on nothing it can edit does nothing.
+
+use egui::{Color32, Modifiers, Pos2, Stroke};
+use photocraft_doc::vector::Path;
+use photocraft_geom::Point;
+use photocraft_vector::edit::{self, Hit};
+
+use crate::PhotocraftApp;
+use crate::canvas::ToolEvent;
+use crate::direct_select::{DirectSelection, PathRef};
+use crate::state::Tool;
+
+/// The anchor tool in effect, if the current tool is one: ⌥ swaps Add and Delete.
+pub fn effective(tool: Tool, mods: Modifiers) -> Option<Tool> {
+ let (add, delete) = (Tool::AddAnchorPoint, Tool::DeleteAnchorPoint);
+ match tool {
+ Tool::AddAnchorPoint => Some(if mods.alt { delete } else { add }),
+ Tool::DeleteAnchorPoint => Some(if mods.alt { add } else { delete }),
+ _ => None,
+ }
+}
+
+/// What a click at `p` would edit with `tool`: the frontmost path under the pointer and the
+/// segment (Add) or anchor (Delete) hit on it. An anchor hit with Add, or a segment with Delete,
+/// edits nothing.
+fn target(app: &PhotocraftApp, tool: Tool, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> {
+ let tol = 6.0 / f64::from(app.point_zoom().max(0.01));
+ let (r, path, hit) =
+ crate::direct_select::candidates(app).into_iter().find_map(|(r, path)| edit::hit(&path, Point::new(p[0], p[1]), tol, &[]).map(|h| (r, path, h)))?;
+ match (tool, hit) {
+ (Tool::AddAnchorPoint, Hit::Segment(..)) | (Tool::DeleteAnchorPoint, Hit::Anchor(_)) => Some((r, path, hit)),
+ _ => None,
+ }
+}
+
+/// Canvas pointer events for the anchor tools; false when the current tool isn't one.
+pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool {
+ let Some(tool) = effective(app.ui.tool, mods) else { return false };
+ if let ToolEvent::Down { x, y, .. } = ev {
+ click(app, tool, [x, y]);
+ }
+ true
+}
+
+fn click(app: &mut PhotocraftApp, tool: Tool, p: [f64; 2]) {
+ let Some((r, _, hit)) = target(app, tool, p) else { return };
+ let (id, mut params) = match hit {
+ Hit::Segment([s, k], t) => ("path.addAnchor", serde_json::json!({"subpath": s, "knot": k, "t": t})),
+ Hit::Anchor([s, k]) => ("path.deleteAnchor", serde_json::json!({"subpath": s, "knot": k})),
+ Hit::Handle(..) => return,
+ };
+ // A hit right at a segment's end is an anchor (anchors win the hit test), so `t` is inside.
+ if let (Some(o), Some(t)) = (params.as_object_mut(), r.params().as_object()) {
+ o.extend(t.clone());
+ }
+ match app.run(id, params) {
+ // The anchors shift: a Direct Selection on this path would point at the wrong ones.
+ Ok(_) if app.ui.direct_selection.target == Some(r) => app.ui.direct_selection = DirectSelection { target: Some(r), ..Default::default() },
+ Ok(_) => {}
+ Err(e) => {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ }
+}
+
+/// The hover feedback over the Direct Selection overlay: Add highlights the segment under the
+/// pointer and shows the anchor a click would add; Delete highlights the anchor it would remove.
+pub fn draw_hover(app: &PhotocraftApp, painter: &egui::Painter, to_scr: &dyn Fn([f64; 2]) -> Pos2, accent: Color32, mods: Modifiers) {
+ let (Some(tool), Some(p)) = (effective(app.ui.tool, mods), app.hover_doc) else { return };
+ if mods.command {
+ return;
+ }
+ let Some((_, path, hit)) = target(app, tool, p) else { return };
+ match hit {
+ Hit::Segment([s, k], t) => {
+ let Some(seg) = path.subpaths.get(s).and_then(|sp| sp.segments().get(k).copied()) else { return };
+ let pts: Vec<Pos2> = (0..=48).map(|i| edit::eval(&seg, f64::from(i) / 48.0)).map(|q| to_scr([q.x, q.y])).collect();
+ painter.add(egui::Shape::line(pts, Stroke::new(2.5, accent)));
+ let q = edit::eval(&seg, t);
+ crate::vector_ui::draw_anchor(painter, to_scr([q.x, q.y]), false, accent);
+ }
+ Hit::Anchor([s, k]) => {
+ let Some(kn) = path.subpaths.get(s).and_then(|sp| sp.knots.get(k)) else { return };
+ let c = to_scr([kn.anchor.x, kn.anchor.y]);
+ painter.rect_stroke(egui::Rect::from_center_size(c, egui::vec2(11.0, 11.0)), 0.0, Stroke::new(1.5, accent), egui::StrokeKind::Inside);
+ crate::vector_ui::draw_anchor(painter, c, true, accent);
+ }
+ Hit::Handle(..) => {}
+ }
+}
+
+#[cfg(test)]
+#[path = "anchor_tools_tests.rs"]
+mod tests;
diff --git a/crates/ui-egui/src/anchor_tools_tests.rs b/crates/ui-egui/src/anchor_tools_tests.rs
new file mode 100644
index 000000000..abd4b5697
--- /dev/null
+++ b/crates/ui-egui/src/anchor_tools_tests.rs
@@ -0,0 +1,152 @@
+//! #1044: the Add Anchor Point and Delete Anchor Point tools insert and remove anchors on the
+//! paths Direct Selection edits, one history step per click.
+
+use egui::Modifiers;
+use photocraft_doc::vector::Path;
+use photocraft_geom::Point;
+use serde_json::json;
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, tool_event};
+use crate::direct_select::PathRef;
+use crate::state::Tool;
+
+fn app(tool: Tool) -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap();
+ app.sync_views();
+ app.ui.tool = tool;
+ app
+}
+
+/// A square work path; knot 1 at (120, 40) is smooth, so the top edge (0 → 1) is a curve.
+fn with_path(app: &mut PhotocraftApp) {
+ let path = json!({"subpaths": [{"closed": true, "knots": [
+ [40, 40],
+ {"anchor": [120, 40], "in": [100, 20], "out": [140, 60], "smooth": true},
+ [120, 120],
+ [40, 120],
+ ]}]});
+ app.run("path.set", json!({"name": "work", "path": path})).unwrap();
+}
+
+fn work(app: &PhotocraftApp) -> Path {
+ app.session.active().unwrap().doc.work_path.clone().unwrap()
+}
+
+fn steps(app: &PhotocraftApp) -> usize {
+ app.session.active().unwrap().history.entries().len()
+}
+
+fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) {
+ tool_event(app, ToolEvent::Down { x: at[0], y: at[1], pressure: 1.0 }, mods);
+ tool_event(app, ToolEvent::Up { x: at[0], y: at[1] }, mods);
+}
+
+#[test]
+fn both_tools_join_the_pen_group() {
+ let group: Vec<Tool> = Tool::ALL.iter().copied().filter(|t| t.key() == 'P').collect();
+ assert_eq!(group, vec![Tool::Pen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint], "P cycles Pen → Add → Delete");
+ let mut app = app(Tool::Brush);
+ app.ui.tool = Tool::from_name("addAnchorPoint").unwrap();
+ assert_eq!(app.ui.tool, Tool::AddAnchorPoint);
+}
+
+#[test]
+fn add_on_a_straight_segment_inserts_a_corner_in_one_step() {
+ let mut app = app(Tool::AddAnchorPoint);
+ with_path(&mut app);
+ let (before, n) = (work(&app), steps(&app));
+ click(&mut app, [80.0, 121.0], Modifiers::NONE);
+ let p = work(&app);
+ assert_eq!(p.subpaths[0].knots.len(), 5);
+ let k = p.subpaths[0].knots[3];
+ assert!(!k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a corner on the bottom edge: {k:?}");
+ assert_eq!(steps(&app), n + 1);
+ assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point"));
+ assert!(app.session.undo());
+ assert_eq!(work(&app), before);
+}
+
+#[test]
+fn add_on_a_curve_splits_it_where_clicked() {
+ let mut app = app(Tool::AddAnchorPoint);
+ with_path(&mut app);
+ let seg = work(&app).subpaths[0].segments()[0];
+ let on = photocraft_vector::edit::eval(&seg, 0.5);
+ click(&mut app, [on.x, on.y], Modifiers::NONE);
+ let p = work(&app);
+ let k = p.subpaths[0].knots[1];
+ assert!(k.smooth && (k.anchor.x - on.x).hypot(k.anchor.y - on.y) < 0.2, "a smooth anchor where clicked: {k:?}");
+ // The two halves still pass through the old curve's quarter points.
+ let halves = &p.subpaths[0].segments()[..2];
+ for t in [0.25, 0.75] {
+ let old = photocraft_vector::edit::eval(&seg, t);
+ let near = halves
+ .iter()
+ .flat_map(|s| (0..=400).map(move |i| photocraft_vector::edit::eval(s, f64::from(i) / 400.0)))
+ .fold(f64::MAX, |d, q| d.min((q.x - old.x).hypot(q.y - old.y)));
+ assert!(near < 0.1, "t={t}: {near}");
+ }
+}
+
+#[test]
+fn delete_removes_the_clicked_anchor_and_alt_swaps_the_tools() {
+ let mut app = app(Tool::DeleteAnchorPoint);
+ with_path(&mut app);
+ let n = steps(&app);
+ click(&mut app, [120.0, 120.0], Modifiers::NONE);
+ let p = work(&app);
+ assert_eq!((p.subpaths[0].knots.len(), p.subpaths[0].closed), (3, true));
+ assert_eq!(p.subpaths[0].knots[2].anchor, Point::new(40.0, 120.0));
+ assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point"));
+ // ⌥ with Delete adds; ⌥ with Add deletes.
+ click(&mut app, [80.0, 120.0], Modifiers::ALT);
+ assert_eq!(work(&app).subpaths[0].knots.len(), 3, "the bottom edge is gone; ⌥ on empty canvas adds nothing");
+ click(&mut app, [40.0, 80.0], Modifiers::ALT);
+ assert_eq!(work(&app).subpaths[0].knots.len(), 4);
+ app.ui.tool = Tool::AddAnchorPoint;
+ click(&mut app, [40.0, 80.0], Modifiers::ALT);
+ assert_eq!(work(&app).subpaths[0].knots.len(), 3);
+ assert_eq!(steps(&app), n + 3);
+}
+
+#[test]
+fn clicks_on_nothing_editable_change_nothing() {
+ let mut app = app(Tool::AddAnchorPoint);
+ with_path(&mut app);
+ let (before, n) = (work(&app), steps(&app));
+ click(&mut app, [80.0, 80.0], Modifiers::NONE);
+ click(&mut app, [40.0, 40.0], Modifiers::NONE);
+ app.ui.tool = Tool::DeleteAnchorPoint;
+ click(&mut app, [80.0, 80.0], Modifiers::NONE);
+ click(&mut app, [40.0, 80.0], Modifiers::NONE);
+ assert_eq!((work(&app), steps(&app)), (before, n), "empty canvas, an anchor with Add, a segment with Delete");
+}
+
+#[test]
+fn shape_layer_paths_are_edited_and_a_direct_selection_is_cleared() {
+ let mut app = app(Tool::DirectSelection);
+ let id = app.run("shape.create", json!({"kind": "rect", "rect": [20, 20, 60, 60], "fill": "#3070c0"})).unwrap()["layer"].as_u64().unwrap();
+ click(&mut app, [80.0, 80.0], Modifiers::NONE);
+ assert_eq!((app.ui.direct_selection.target, app.ui.direct_selection.anchors.clone()), (Some(PathRef::Layer(id)), vec![[0, 2]]));
+ app.ui.tool = Tool::AddAnchorPoint;
+ click(&mut app, [50.0, 20.0], Modifiers::NONE);
+ let info = app.run("shape.info", json!({"layer": id})).unwrap();
+ assert_eq!(info["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), 5);
+ assert!(app.ui.direct_selection.anchors.is_empty(), "the selection no longer points at a shifted anchor");
+ app.ui.tool = Tool::DeleteAnchorPoint;
+ click(&mut app, [20.0, 80.0], Modifiers::NONE);
+ let info = app.run("shape.info", json!({"layer": id})).unwrap();
+ assert_eq!(info["path"]["subpaths"][0]["knots"].as_array().unwrap().len(), 4);
+}
+
+#[test]
+fn the_cursor_shows_plus_or_minus() {
+ use crate::tool_feedback::{Badge, badge};
+ let app = app(Tool::AddAnchorPoint);
+ assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::NONE), Some(Badge::Add));
+ assert_eq!(badge(&app, Tool::AddAnchorPoint, Modifiers::ALT), Some(Badge::Subtract));
+ assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::NONE), Some(Badge::Subtract));
+ assert_eq!(badge(&app, Tool::DeleteAnchorPoint, Modifiers::COMMAND), None, "⌘ is Direct Selection");
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index fa4e0611b..b67fadbbf 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -4075,6 +4075,10 @@ pub fn tool_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers)
if crate::direct_select::pointer(app, ev, mods) {
return;
}
+ // Add / Delete Anchor Point tools (#1044).
+ if crate::anchor_tools::pointer(app, ev, mods) {
+ return;
+ }
// Ruler, Count and Note tools.
if crate::analysis_ui::pointer(app, ev, mods) {
return;
diff --git a/crates/ui-egui/src/direct_select.rs b/crates/ui-egui/src/direct_select.rs
index 7cccf1dde..96c0f148a 100644
--- a/crates/ui-egui/src/direct_select.rs
+++ b/crates/ui-egui/src/direct_select.rs
@@ -35,7 +35,7 @@ pub enum PathRef {
impl PathRef {
/// The engine's target params for this path.
- fn params(self) -> Value {
+ pub(crate) fn params(self) -> Value {
match self {
PathRef::Work => json!({"name": "work"}),
PathRef::Layer(id) => json!({"name": "layer", "layer": id}),
@@ -104,19 +104,21 @@ impl Edit {
}
}
-/// Is Direct Selection what the pointer does now: its own tool, or the Pen with ⌘/Ctrl held.
+/// Is Direct Selection what the pointer does now: its own tool, or the Pen or an anchor point
+/// tool with ⌘/Ctrl held.
fn direct(tool: Tool, mods: Modifiers) -> bool {
- tool == Tool::DirectSelection || (tool == Tool::Pen && mods.command)
+ tool == Tool::DirectSelection || (matches!(tool, Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) && mods.command)
}
-/// Does the canvas draw Direct Selection's overlay instead of the plain path outlines?
+/// Does the canvas draw Direct Selection's overlay instead of the plain path outlines? The Add /
+/// Delete Anchor Point tools show it too: they edit the same paths.
pub fn shows(app: &PhotocraftApp, mods: Modifiers) -> bool {
- direct(app.ui.tool, mods) || app.ui.direct_selection.drag.is_some()
+ direct(app.ui.tool, mods) || app.ui.direct_selection.drag.is_some() || matches!(app.ui.tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint)
}
/// The paths Direct Selection edits, front first: the targeted vector mask or the active shape
/// layer's path, then the work path.
-fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> {
+pub(crate) fn candidates(app: &PhotocraftApp) -> Vec<(PathRef, Path)> {
let layer = crate::vector_ui::targeted_vector_mask(app).or_else(|| crate::vector_ui::active_shape_path(app));
let work = app.session.active().and_then(|st| st.doc.work_path.clone());
layer.map(|(id, p)| (PathRef::Layer(id), p)).into_iter().chain(work.map(|p| (PathRef::Work, p))).collect()
diff --git a/crates/ui-egui/src/hold_keys.rs b/crates/ui-egui/src/hold_keys.rs
index 64cda7239..5691576a5 100644
--- a/crates/ui-egui/src/hold_keys.rs
+++ b/crates/ui-egui/src/hold_keys.rs
@@ -82,6 +82,8 @@ pub fn cmd_moves(t: Tool) -> bool {
| Tool::PathSelection
| Tool::DirectSelection
| Tool::Pen
+ | Tool::AddAnchorPoint
+ | Tool::DeleteAnchorPoint
| Tool::RectMarquee
| Tool::EllipseMarquee
| Tool::Lasso
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index b0d334b47..63a50c78b 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -1683,6 +1683,10 @@
Paints from the document's opening state Maluje ze stavu dokumentu při otevření
Path Selection Tool Nástroj výběr cesty
Direct Selection Tool Nástroj přímý výběr
+ Add Anchor Point Tool Nástroj přidat kotevní bod
+ Delete Anchor Point Tool Nástroj odstranit kotevní bod
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Klepnutím na segment přidáte kotevní bod · {alt}+klik na kotevní bod jej odstraní
+ Click an anchor point to delete it · {alt}-click a segment to add one Klepnutím na kotevní bod jej odstraníte · {alt}+klik na segment přidá nový bod
Pattern Overlay Překrytí vzorkem
Pen Pressure Přítlak pera
Pen Tilt Náklon pera
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 7e9b49738..3d7415414 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -1658,6 +1658,10 @@
Paints from the document's opening state Malt aus dem Zustand beim Öffnen des Dokuments
Path Selection Tool Pfadauswahl-Werkzeug
Direct Selection Tool Direktauswahl-Werkzeug
+ Add Anchor Point Tool Ankerpunkt-hinzufügen-Werkzeug
+ Delete Anchor Point Tool Ankerpunkt-löschen-Werkzeug
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Klicke auf ein Segment, um einen Ankerpunkt hinzuzufügen · {alt}-Klick auf einen Ankerpunkt löscht ihn
+ Click an anchor point to delete it · {alt}-click a segment to add one Klicke auf einen Ankerpunkt, um ihn zu löschen · {alt}-Klick auf ein Segment fügt einen hinzu
Pattern Overlay Musterüberlagerung
Pen Pressure Stiftdruck
Pen Tilt Stiftneigung
diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv
index 1ef106638..a15cf0f5b 100644
--- a/crates/ui-egui/src/i18n/el.tsv
+++ b/crates/ui-egui/src/i18n/el.tsv
@@ -3249,6 +3249,10 @@ cameraRaw Yellow Κίτρινο
Paint Bucket Tool Κουβάς γεμίσματος (Paint Bucket Tool)
Path Selection Tool Επιλογή διαδρομής (Path Selection Tool)
Direct Selection Tool Άμεση επιλογή (Direct Selection Tool)
+ Add Anchor Point Tool Εργαλείο προσθήκης σημείου αγκύρωσης
+ Delete Anchor Point Tool Εργαλείο διαγραφής σημείου αγκύρωσης
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Κάντε κλικ σε ένα τμήμα για να προσθέσετε σημείο αγκύρωσης · {alt}-κλικ σε σημείο αγκύρωσης για διαγραφή
+ Click an anchor point to delete it · {alt}-click a segment to add one Κάντε κλικ σε ένα σημείο αγκύρωσης για να το διαγράψετε · {alt}-κλικ σε τμήμα για προσθήκη
Pen Tool Πένα (Pen Tool)
Polygon Tool Πολύγωνο (Polygon Tool)
Polygonal Lasso Tool Πολυγωνικό λάσο (Polygonal Lasso Tool)
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 6d05dbbf2..8d99e362e 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -1666,6 +1666,10 @@
Paints from the document's opening state Pinta a partir del estado en que se abrió el documento.
Path Selection Tool Herramienta Selección de trazado
Direct Selection Tool Herramienta Selección directa
+ Add Anchor Point Tool Herramienta Añadir punto de ancla
+ Delete Anchor Point Tool Herramienta Eliminar punto de ancla
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Haz clic en un segmento para añadir un punto de ancla · {alt}-clic en un punto de ancla para eliminarlo
+ Click an anchor point to delete it · {alt}-click a segment to add one Haz clic en un punto de ancla para eliminarlo · {alt}-clic en un segmento para añadir uno
Pattern Overlay Superposición de patrón
Pen Pressure Presión del lápiz
Pen Tilt Inclinación del lápiz
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 12309df67..c256aa6d2 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -1644,6 +1644,10 @@
Paints from the document's opening state Peint à partir de l'état d'ouverture du document
Path Selection Tool Outil Sélection de tracé
Direct Selection Tool Outil Sélection directe
+ Add Anchor Point Tool Outil Ajout de point d'ancrage
+ Delete Anchor Point Tool Outil Suppression de point d'ancrage
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Cliquez sur un segment pour ajouter un point d'ancrage · {alt}-clic sur un point d'ancrage pour le supprimer
+ Click an anchor point to delete it · {alt}-click a segment to add one Cliquez sur un point d'ancrage pour le supprimer · {alt}-clic sur un segment pour en ajouter un
Pattern Overlay Superposition de motif
Pen Pressure Pression du stylet
Pen Tilt Inclinaison du stylet
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 5d4d885b0..94f6674fb 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -1638,6 +1638,10 @@
Paints from the document's opening state Melukis dari kondisi awal dokumen saat dibuka
Path Selection Tool Alat Path Selection
Direct Selection Tool Alat Direct Selection
+ Add Anchor Point Tool Alat Tambah Titik Jangkar
+ Delete Anchor Point Tool Alat Hapus Titik Jangkar
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Klik segmen untuk menambah titik jangkar · {alt}-klik titik jangkar untuk menghapusnya
+ Click an anchor point to delete it · {alt}-click a segment to add one Klik titik jangkar untuk menghapusnya · {alt}-klik segmen untuk menambah titik
Pattern Overlay Overlay Pola
Pen Pressure Tekanan Pena
Pen Tilt Kemiringan Pena
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 60276d6de..ca1a26ec8 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -1664,6 +1664,10 @@
Paints from the document's opening state Dipinge dallo stato di apertura del documento
Path Selection Tool Strumento Selezione tracciato
Direct Selection Tool Strumento Selezione diretta
+ Add Anchor Point Tool Strumento Aggiungi punto di ancoraggio
+ Delete Anchor Point Tool Strumento Elimina punto di ancoraggio
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Fai clic su un segmento per aggiungere un punto di ancoraggio · {alt}-clic su un punto di ancoraggio per eliminarlo
+ Click an anchor point to delete it · {alt}-click a segment to add one Fai clic su un punto di ancoraggio per eliminarlo · {alt}-clic su un segmento per aggiungerne uno
Pattern Overlay Sovrapposizione pattern
Pen Pressure Pressione penna
Pen Tilt Inclinazione penna
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 03f54b09b..f032d15fb 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -1669,6 +1669,10 @@
Paints from the document's opening state ドキュメントを開いた時点の状態から描画します
Path Selection Tool パスコンポーネント選択ツール
Direct Selection Tool パス選択ツール
+ Add Anchor Point Tool アンカーポイントの追加ツール
+ Delete Anchor Point Tool アンカーポイントの削除ツール
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it セグメントをクリックしてアンカーポイントを追加 · {alt}+クリック: アンカーポイントを削除
+ Click an anchor point to delete it · {alt}-click a segment to add one アンカーポイントをクリックして削除 · {alt}+クリック: セグメントにアンカーポイントを追加
Pattern Overlay パターンオーバーレイ
Pen Pressure ペンの筆圧
Pen Tilt ペンの傾き
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 2ce2a4ef9..f5d1ae64e 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -1637,6 +1637,10 @@
Paints from the document's opening state 문서를 열었을 때의 상태로 칠하기
Path Selection Tool 패스 선택 도구
Direct Selection Tool 직접 선택 도구
+ Add Anchor Point Tool 기준점 추가 도구
+ Delete Anchor Point Tool 기준점 삭제 도구
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it 세그먼트를 클릭하여 기준점 추가 · {alt}-클릭: 기준점 삭제
+ Click an anchor point to delete it · {alt}-click a segment to add one 기준점을 클릭하여 삭제 · {alt}-클릭: 세그먼트에 기준점 추가
Pattern Overlay 패턴 오버레이
Pen Pressure 펜 압력
Pen Tilt 펜 기울기
diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv
index 412469120..b836d2773 100644
--- a/crates/ui-egui/src/i18n/nl.tsv
+++ b/crates/ui-egui/src/i18n/nl.tsv
@@ -1648,6 +1648,10 @@
Paints from the document's opening state Schildert vanuit de staat waarin het document werd geopend
Path Selection Tool Padselectiegereedschap
Direct Selection Tool Direct-selectiegereedschap
+ Add Anchor Point Tool Gereedschap Ankerpunt toevoegen
+ Delete Anchor Point Tool Gereedschap Ankerpunt verwijderen
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Klik op een segment om een ankerpunt toe te voegen · {alt}-klik op een ankerpunt om het te verwijderen
+ Click an anchor point to delete it · {alt}-click a segment to add one Klik op een ankerpunt om het te verwijderen · {alt}-klik op een segment om er een toe te voegen
Pattern Overlay Patroonbedekking
Pen Pressure Pendruk
Pen Tilt Penkanteling
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index e7bfdf8ba..17207def9 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1662,6 +1662,10 @@
Paints from the document's opening state Maluje na podstawie stanu dokumentu z chwili otwarcia
Path Selection Tool Narzędzie Zaznaczanie ścieżki
Direct Selection Tool Narzędzie Zaznaczanie bezpośrednie
+ Add Anchor Point Tool Narzędzie Dodaj punkt kontrolny
+ Delete Anchor Point Tool Narzędzie Usuń punkt kontrolny
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Kliknij segment, aby dodać punkt kontrolny · {alt}-klik na punkcie kontrolnym usuwa go
+ Click an anchor point to delete it · {alt}-click a segment to add one Kliknij punkt kontrolny, aby go usunąć · {alt}-klik na segmencie dodaje punkt
Pattern Overlay Nakładka wzoru
Pen Pressure Nacisk pióra
Pen Tilt Nachylenie pióra
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index ee6b31491..dc5402673 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -1643,6 +1643,10 @@
Paints from the document's opening state Pinta a partir do estado de abertura do documento
Path Selection Tool Ferramenta Seleção de demarcador
Direct Selection Tool Ferramenta Seleção direta
+ Add Anchor Point Tool Ferramenta Adicionar ponto de ancoragem
+ Delete Anchor Point Tool Ferramenta Excluir ponto de ancoragem
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Clique em um segmento para adicionar um ponto de ancoragem · {alt}-clique em um ponto de ancoragem para excluí-lo
+ Click an anchor point to delete it · {alt}-click a segment to add one Clique em um ponto de ancoragem para excluí-lo · {alt}-clique em um segmento para adicionar um
Pattern Overlay Sobreposição de padrão
Pen Pressure Pressão da caneta
Pen Tilt Inclinação da caneta
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index 14bc60c93..effa80e98 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -1564,6 +1564,10 @@
Pen Tool Перо
Path Selection Tool Выделение контура
Direct Selection Tool Выделение узла
+ Add Anchor Point Tool Добавить узел
+ Delete Anchor Point Tool Удалить узел
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Щёлкните сегмент, чтобы добавить узел · {alt}-щелчок по узлу удаляет его
+ Click an anchor point to delete it · {alt}-click a segment to add one Щёлкните узел, чтобы удалить его · {alt}-щелчок по сегменту добавляет узел
Rectangle Tool Прямоугольник
Ellipse Tool Овал
Triangle Tool Треугольник
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index f0bf886e8..fb575be33 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -1546,6 +1546,10 @@
Pen Tool Інструмент «Перо»
Path Selection Tool Інструмент «Виділення контуру»
Direct Selection Tool Інструмент «Пряме виділення»
+ Add Anchor Point Tool Інструмент «Додати вузол»
+ Delete Anchor Point Tool Інструмент «Видалити вузол»
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it Клацніть сегмент, щоб додати вузол · {alt}+клацання по вузлу видаляє його
+ Click an anchor point to delete it · {alt}-click a segment to add one Клацніть вузол, щоб видалити його · {alt}+клацання по сегменту додає вузол
Rectangle Tool Інструмент «Прямокутник»
Ellipse Tool Інструмент «Еліпс»
Triangle Tool Інструмент «Трикутник»
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index e794681ac..a01b0bbb6 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -1681,6 +1681,10 @@
Paints from the document's opening state 从文档打开时的状态绘制
Path Selection Tool 路径选择工具
Direct Selection Tool 直接选择工具
+ Add Anchor Point Tool 添加锚点工具
+ Delete Anchor Point Tool 删除锚点工具
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it 单击线段以添加锚点 · {alt}-单击锚点:删除锚点
+ Click an anchor point to delete it · {alt}-click a segment to add one 单击锚点将其删除 · {alt}-单击线段:添加锚点
Pattern Overlay 图案叠加
Pen Pressure 钢笔压力
Pen Tilt 钢笔倾斜
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 097400a97..3258d263e 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -1673,6 +1673,10 @@
Paints from the document's opening state 從文件開啟時的狀態繪製
Path Selection Tool 路徑選取工具
Direct Selection Tool 直接選取工具
+ Add Anchor Point Tool 增加錨點工具
+ Delete Anchor Point Tool 刪除錨點工具
+ Click a segment to add an anchor point · {alt}-click an anchor to delete it 按一下線段以增加錨點 · {alt}-按一下錨點:刪除錨點
+ Click an anchor point to delete it · {alt}-click a segment to add one 按一下錨點將其刪除 · {alt}-按一下線段:增加錨點
Pattern Overlay 圖樣覆蓋
Pen Pressure 筆壓
Pen Tilt 筆傾斜
diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs
index 9f4f2f1e2..f128ef9f4 100644
--- a/crates/ui-egui/src/icon_data.rs
+++ b/crates/ui-egui/src/icon_data.rs
@@ -81,6 +81,8 @@ pub static ICONS: &[(&str, &[u8])] = &[
("palette", include_bytes!("../../../assets/icons/palette.svg")),
("panel-right", include_bytes!("../../../assets/icons/panel-right.svg")),
("panels-top-left", include_bytes!("../../../assets/icons/panels-top-left.svg")),
+ ("pen-add-anchor", include_bytes!("../../../assets/icons/pen-add-anchor.svg")),
+ ("pen-delete-anchor", include_bytes!("../../../assets/icons/pen-delete-anchor.svg")),
("pen-tool", include_bytes!("../../../assets/icons/pen-tool.svg")),
("pencil", include_bytes!("../../../assets/icons/pencil.svg")),
("pentagon", include_bytes!("../../../assets/icons/pentagon.svg")),
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index fbe93757f..f6e760d8b 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -130,6 +130,8 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::QuickSelection => "circle-dashed",
Tool::ObjectSelection => "square-dashed-mouse-pointer",
Tool::Pen => "pen-tool",
+ Tool::AddAnchorPoint => "pen-add-anchor",
+ Tool::DeleteAnchorPoint => "pen-delete-anchor",
Tool::PathSelection => "mouse-pointer-2",
Tool::DirectSelection => "direct-select",
Tool::Rectangle => "rectangle-horizontal",
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 90ea68440..449b34cbc 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -21,6 +21,7 @@ pub mod adjust_preview;
pub mod adjust_ui;
mod alt_grab;
pub mod analysis_ui;
+pub mod anchor_tools;
pub mod artboard_ui;
pub(crate) mod blend_preview;
mod brand;
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index eceada624..0a4515f07 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -34,7 +34,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[
&[Tool::Dodge, Tool::Burn, Tool::Sponge],
],
&[
- &[Tool::Pen],
+ &[Tool::Pen, Tool::AddAnchorPoint, Tool::DeleteAnchorPoint],
&[Tool::Type, Tool::VerticalType],
&[Tool::PathSelection, Tool::DirectSelection],
&[Tool::Rectangle, Tool::EllipseShape, Tool::Triangle, Tool::Polygon, Tool::Line, Tool::CustomShape],
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 52c98a628..23bc080d4 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -111,6 +111,8 @@ pub enum Tool {
QuickSelection,
ObjectSelection,
Pen,
+ AddAnchorPoint,
+ DeleteAnchorPoint,
PathSelection,
DirectSelection,
Rectangle,
@@ -124,7 +126,7 @@ pub enum Tool {
}
impl Tool {
- pub const ALL: [Tool; 56] = [
+ pub const ALL: [Tool; 58] = [
Tool::Move,
Tool::RectMarquee,
Tool::EllipseMarquee,
@@ -171,6 +173,8 @@ impl Tool {
Tool::QuickSelection,
Tool::ObjectSelection,
Tool::Pen,
+ Tool::AddAnchorPoint,
+ Tool::DeleteAnchorPoint,
Tool::PathSelection,
Tool::DirectSelection,
Tool::Rectangle,
@@ -233,6 +237,8 @@ impl Tool {
Tool::QuickSelection => "Quick Selection Tool",
Tool::ObjectSelection => "Object Selection Tool",
Tool::Pen => "Pen Tool",
+ Tool::AddAnchorPoint => "Add Anchor Point Tool",
+ Tool::DeleteAnchorPoint => "Delete Anchor Point Tool",
Tool::PathSelection => "Path Selection Tool",
Tool::DirectSelection => "Direct Selection Tool",
Tool::Rectangle => "Rectangle Tool",
@@ -295,7 +301,7 @@ impl Tool {
Tool::SingleRowMarquee | Tool::SingleColumnMarquee => '\0',
Tool::Dodge | Tool::Burn | Tool::Sponge => 'O',
Tool::QuickSelection | Tool::ObjectSelection => 'W',
- Tool::Pen => 'P',
+ Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint => 'P',
Tool::PathSelection | Tool::DirectSelection => 'A',
Tool::Rectangle | Tool::EllipseShape | Tool::Triangle | Tool::Polygon | Tool::Line | Tool::CustomShape => 'U',
}
@@ -1237,7 +1243,10 @@ mod tests {
assert!(!Tool::RedEye.is_brushlike());
assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp));
assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp));
- assert_eq!(Tool::ALL.len(), 56);
+ assert_eq!(Tool::ALL.len(), 58);
+ assert_eq!(Tool::from_name("addAnchorPoint"), Some(Tool::AddAnchorPoint));
+ assert_eq!(Tool::from_name("Delete Anchor Point Tool"), Some(Tool::DeleteAnchorPoint));
+ assert_eq!(Tool::DeleteAnchorPoint.key(), 'P');
assert_eq!(Tool::from_name("Remove Tool"), Some(Tool::Remove));
assert_eq!(Tool::Remove.key(), 'J');
assert!(Tool::Remove.is_brushlike());
diff --git a/crates/ui-egui/src/tool_feedback.rs b/crates/ui-egui/src/tool_feedback.rs
index 56f7444b4..bc993a7ae 100644
--- a/crates/ui-egui/src/tool_feedback.rs
+++ b/crates/ui-egui/src/tool_feedback.rs
@@ -97,8 +97,14 @@ pub fn document_selection_mode(app: &PhotocraftApp, tool: Tool, m: egui::Modifie
}
}
-/// The badge the cursor of `tool` shows with modifiers `m` (None for non-selection tools or New).
+/// The badge the cursor of `tool` shows with modifiers `m` (None for non-selection tools or New;
+/// the anchor point tools show theirs).
pub fn badge(app: &PhotocraftApp, tool: Tool, m: egui::Modifiers) -> Option<Badge> {
+ // Add / Delete Anchor Point: + or − beside the crosshair, as on Photoshop's pen cursors (⌥
+ // swaps them; ⌘ is Direct Selection, which shows none).
+ if let Some(t) = crate::anchor_tools::effective(tool, m) {
+ return (!m.command).then_some(if t == Tool::AddAnchorPoint { Badge::Add } else { Badge::Subtract });
+ }
if !is_selection_tool(tool) {
return None;
}
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index f1cd830db..463a7f299 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -486,6 +486,9 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
if crate::direct_select::shows(app, painter.ctx().input(|i| i.modifiers)) {
// Direct Selection (or the Pen with ⌘/Ctrl held) draws the paths it edits (#790).
crate::direct_select::draw_overlay(app, painter, &to_scr, accent, paths);
+ if paths {
+ crate::anchor_tools::draw_hover(app, painter, &to_scr, accent, painter.ctx().input(|i| i.modifiers));
+ }
} else if paths {
if vector_tool {
if let Some(wp) = &doc.work_path {
@@ -535,7 +538,7 @@ pub fn draw_overlay(app: &PhotocraftApp, painter: &egui::Painter, xf: &ViewXform
/// Options bar for vector tools; false for other tools.
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bool {
- if !(is_shape_tool(tool) || matches!(tool, Tool::Pen | Tool::PathSelection | Tool::DirectSelection)) {
+ if !(is_shape_tool(tool) || matches!(tool, Tool::Pen | Tool::AddAnchorPoint | Tool::DeleteAnchorPoint | Tool::PathSelection | Tool::DirectSelection)) {
return false;
}
let t = Tokens::get(ui.ctx());
@@ -558,6 +561,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
);
return true;
}
+ if matches!(tool, Tool::AddAnchorPoint | Tool::DeleteAnchorPoint) {
+ let hint = if tool == Tool::AddAnchorPoint {
+ tl!("Click a segment to add an anchor point · {alt}-click an anchor to delete it")
+ } else {
+ tl!("Click an anchor point to delete it · {alt}-click a segment to add one")
+ };
+ lbl(ui, &crate::i18n::fmt(hint, &[("alt", &crate::shortcuts::pretty("Alt"))]));
+ return true;
+ }
if tool == Tool::Pen {
let opts = [("path".to_string(), tl!("Path")), ("shape".to_string(), tl!("Shape"))];
crate::widgets::dropdown(ui, "pen-mode", &mut o.vector_mode, &opts, 80.0);
diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs
index 8b6af7950..c0ac2367e 100644
--- a/crates/vector/src/edit.rs
+++ b/crates/vector/src/edit.rs
@@ -1,6 +1,6 @@
-//! Point-level path editing, Photoshop's Direct Selection and Convert Point tools: move anchors,
-//! drag direction handles, reshape a segment by dragging it, convert between smooth and corner
-//! points, and hit-test a path's parts. Pure geometry on [`Path`]; the engine's `path.*` edit
+//! Point-level path editing, Photoshop's Direct Selection, Convert Point and Add / Delete Anchor
+//! Point tools: move anchors, drag direction handles, reshape a segment by dragging it, convert
+//! between smooth and corner points, insert and remove anchors, and hit-test a path's parts. Pure geometry on [`Path`]; the engine's `path.*` edit
//! commands and the canvas previews share it, so a preview is exactly what the command commits.
//!
//! Knots are addressed as `[subpath, knot]`. Every edit validates its indices and returns an
@@ -167,6 +167,59 @@ pub fn bend_segment(path: &mut Path, knot: [usize; 2], t: f64, d: [f64; 2]) -> R
Ok(())
}
+fn lerp(a: Point, b: Point, t: f64) -> Point {
+ Point::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
+}
+
+/// Add Anchor Point: inserts an anchor into the segment leaving `knot` at curve parameter `t`
+/// (strictly between 0 and 1) and returns the new knot's `[subpath, knot]`. A curve is split at
+/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth; on a straight
+/// segment (both handles retracted) the new anchor is a corner on the line.
+pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2], String> {
+ if !(t.is_finite() && t > 0.0 && t < 1.0) {
+ return Err("`t` must be strictly between 0 and 1".into());
+ }
+ let end = segment_end(path, knot)?;
+ let retracted = |k: &Knot, h: Handle| dist(handle(k, h), k.anchor) < 1e-9;
+ let a = *knot_mut(path, knot)?;
+ let b = *knot_mut(path, end)?;
+ let new = if retracted(&a, Handle::Out) && retracted(&b, Handle::In) {
+ let p = lerp(a.anchor, b.anchor, t);
+ Knot::corner(p.x, p.y)
+ } else {
+ let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t));
+ let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t));
+ knot_mut(path, knot)?.out_ctrl = p01;
+ knot_mut(path, end)?.in_ctrl = p23;
+ Knot::smooth(lerp(p012, p123, t), p012, p123)
+ };
+ let [s, k] = knot;
+ let at = k.checked_add(1).ok_or_else(|| format!("no segment leaves knot {k} of subpath {s}"))?;
+ let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?;
+ // `at` ≤ len: the segment leaving `k` exists, so `k` < len.
+ sp.knots.insert(at.min(sp.knots.len()), new);
+ Ok([s, at])
+}
+
+/// Delete Anchor Point: removes a knot. Its neighbours are joined by one segment that keeps the
+/// previous anchor's out handle and the next anchor's in handle; a closed subpath stays closed.
+/// Removing a subpath's last anchor removes the subpath. Refused (unchanged) when it would leave
+/// the path with no anchors at all. Returns whether the subpath was removed.
+pub fn delete_anchor(path: &mut Path, [s, k]: [usize; 2]) -> Result<bool, String> {
+ knot_mut(path, [s, k])?;
+ let total: usize = path.subpaths.iter().map(|sp| sp.knots.len()).fold(0, usize::saturating_add);
+ if total <= 1 {
+ return Err("can't delete the path's only anchor point; delete the path instead".into());
+ }
+ let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?;
+ if sp.knots.len() <= 1 {
+ path.subpaths.remove(s);
+ return Ok(true);
+ }
+ sp.knots.remove(k);
+ Ok(false)
+}
+
/// 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())
@@ -186,7 +239,8 @@ pub fn anchors_in(path: &Path, [x0, y0, x1, y1]: [f64; 4]) -> Vec<[usize; 2]> {
out
}
-fn eval(seg: &[Point; 4], t: f64) -> Point {
+/// The point at parameter `t` of the cubic segment `[anchor, out, in, anchor]`.
+pub fn eval(seg: &[Point; 4], t: f64) -> Point {
let u = 1.0 - t;
let (a, b, c, d) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
Point::new(a * seg[0].x + b * seg[1].x + c * seg[2].x + d * seg[3].x, a * seg[0].y + b * seg[1].y + c * seg[2].y + d * seg[3].y)
@@ -331,6 +385,77 @@ mod tests {
assert_eq!(hit(&tri(), Point::new(50.0, 40.0), 3.0, &[]), None);
}
+ #[test]
+ fn adding_to_a_curve_splits_it_without_changing_its_shape() {
+ for t in [0.5, 0.13, 0.9] {
+ let mut p = curve();
+ let seg = curve().subpaths[0].segments()[0];
+ let r = add_anchor(&mut p, [0, 0], t).unwrap();
+ assert_eq!((r, p.subpaths[0].knots.len()), ([0, 1], 4));
+ let k = at(&p, 0, 1);
+ assert!(k.smooth, "a split curve gets a smooth anchor");
+ assert!(dist(k.anchor, eval(&seg, t)) < 1e-9, "the new anchor is where it was clicked");
+ // 100 evenly spaced parameters of the old segment land on the two halves.
+ let halves = p.subpaths[0].segments();
+ for i in 0..=100 {
+ let u = i as f64 / 100.0;
+ let q = if u <= t { eval(&halves[0], u / t) } else { eval(&halves[1], (u - t) / (1.0 - t)) };
+ assert!(dist(q, eval(&seg, u)) < 0.01, "t={t} u={u}");
+ }
+ assert_eq!(halves[2], curve().subpaths[0].segments()[1], "the next segment is untouched");
+ }
+ }
+
+ #[test]
+ fn adding_to_a_straight_segment_makes_a_corner_on_the_line() {
+ let mut p = tri();
+ // The closing segment (2 → 0) wraps: the new anchor goes last.
+ assert_eq!(add_anchor(&mut p, [0, 2], 0.5).unwrap(), [0, 3]);
+ assert_eq!(at(&p, 0, 3), Knot::corner(25.0, 40.0));
+ assert_eq!(add_anchor(&mut p, [0, 0], 0.25).unwrap(), [0, 1]);
+ assert_eq!(at(&p, 0, 1), Knot::corner(25.0, 0.0));
+ assert_eq!(p.subpaths[0].knots.len(), 5);
+ assert!(p.subpaths[0].closed);
+ }
+
+ #[test]
+ fn deleting_joins_the_neighbours_with_their_handles() {
+ let mut sq = Path::new(vec![Subpath::polygon(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])]);
+ assert!(!delete_anchor(&mut sq, [0, 2]).unwrap());
+ assert_eq!((sq.subpaths[0].knots.len(), sq.subpaths[0].closed), (3, true));
+ let mut c = Path::new(vec![Subpath::polyline(&[(0.0, 50.0), (50.0, 0.0), (100.0, 50.0)])]);
+ c.subpaths[0].knots[0].out_ctrl = Point::new(10.0, 20.0);
+ c.subpaths[0].knots[2].in_ctrl = Point::new(90.0, 20.0);
+ delete_anchor(&mut c, [0, 1]).unwrap();
+ assert_eq!(c.subpaths[0].segments(), vec![[Point::new(0.0, 50.0), Point::new(10.0, 20.0), Point::new(90.0, 20.0), Point::new(100.0, 50.0)]]);
+ }
+
+ #[test]
+ fn deleting_a_subpaths_last_anchor_removes_it_but_never_the_last_anchor() {
+ let mut p = tri();
+ p.subpaths.push(Subpath::polyline(&[(5.0, 5.0)]));
+ assert!(delete_anchor(&mut p, [1, 0]).unwrap());
+ assert_eq!(p, tri());
+ let mut one = Path::new(vec![Subpath::polyline(&[(5.0, 5.0)])]);
+ let before = one.clone();
+ assert!(delete_anchor(&mut one, [0, 0]).is_err());
+ assert_eq!(one, before);
+ }
+
+ #[test]
+ fn bad_anchor_edits_are_errors_and_change_nothing() {
+ let mut p = curve();
+ for t in [0.0, 1.0, -0.5, 2.0, f64::NAN, f64::INFINITY] {
+ assert!(add_anchor(&mut p, [0, 0], t).is_err(), "t={t}");
+ }
+ assert!(add_anchor(&mut p, [0, 2], 0.5).is_err(), "an open subpath's last knot starts no segment");
+ assert!(add_anchor(&mut p, [0, usize::MAX], 0.5).is_err());
+ assert!(add_anchor(&mut p, [usize::MAX, 0], 0.5).is_err());
+ assert!(delete_anchor(&mut p, [0, 3]).is_err());
+ assert!(delete_anchor(&mut p, [1, 0]).is_err());
+ assert_eq!(p, curve());
+ }
+
#[test]
fn marquee_and_subpath_selections() {
let p = tri();
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index e8ff48fef..4be29aa69 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -431,7 +431,7 @@ filled bar. This extends UI reachability and does not claim Photoshop-authored s
| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. |
| Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. |
| UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418). 2026-10-09: canvas zoom is physical at any display scale — 100% is one document pixel per physical display pixel, and every screen-space overlay, cursor, scrollbar, navigator and fit follows it (#1943) | low–medium | Needs recurring visual QA with realistic documents. |
-| Tools | 2026-10-10: Pencil, Mixer Brush, Color Replacement, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. Crop rotation (2026-10-09, #1792): dragging outside the crop frame turns it (⇧ 15° steps, angle readout), and ↵ rotates the document and crops in one undo step (`image.crop` `angle`); the frame turns over the image as in Photoshop's Classic Mode, and the options-bar Straighten is still missing. |
+| Tools | 2026-10-10: Pencil, Mixer Brush, Color Replacement, Patch, Content-Aware Move, Vertical Type, Pattern Stamp and Rotate View are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Color Sampler, Perspective Crop, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). Rotate View (2026-10-09) turns the canvas camera around its centre without rewriting pixels; Reset View and Match Rotation copy the angle. Crop rotation (2026-10-09, #1792): dragging outside the crop frame turns it (⇧ 15° steps, angle readout), and ↵ rotates the document and crops in one undo step (`image.crop` `angle`); the frame turns over the image as in Photoshop's Classic Mode, and the options-bar Straighten is still missing. |
| Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. |
| Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. |
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
@@ -524,7 +524,7 @@ See [method and results](octagonal-mask-performance.md).
effects, composite with masks and adjustment layers, CMYK print prep…) scripted end to end and
checked against Photoshop's output on every build. Their pass rate becomes the headline parity
number.
-4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790) and
+4. **Tool coverage and workflow depth:** Pen variants (Direct Selection landed, #790; Add/Delete Anchor Point, #1044) and
Perspective Crop; finish Content-Aware Move's Transform On Drop and live result preview.
Pencil, Mixer Brush, Patch, Vertical Type, Pattern Stamp and Rotate View are already available on the toolbar.
5. **Complex-document performance** (#125/#128) and GPU tiling beyond the texture limit (#49).