From d96bb50161f5551b8433e7d975b5752b35421078 Mon Sep 17 00:00:00 2001 From: Fabio Lussi Date: Sun, 11 Oct 2026 11:48:07 +0200 Subject: [PATCH 1/5] Add Anchor Point and Delete Anchor Point tools (#1044) (#2756) Paths could be reshaped after drawing since #865, but the number of anchors could not change. Two new engine commands do that, and two tools in the Pen flyout drive them on the canvas. - photocraft_vector::edit::add_anchor splits the segment at t with de Casteljau, so a curve keeps its shape and gets a smooth anchor; a straight segment gets a corner on the line. delete_anchor joins the neighbours keeping their handles, drops an emptied subpath and refuses to remove a path's only anchor. - path.addAnchor / path.deleteAnchor take the same targets as the other point edits (work path, saved path by name, shape layer path, vector mask) and record one history step each. - Tool::AddAnchorPoint / DeleteAnchorPoint join the P group after the Pen. They act on Direct Selection's paths, highlight the segment or anchor under the pointer, show a +/- cursor badge, swap with Alt and turn into Direct Selection with Cmd/Ctrl. An edit clears a Direct Selection on the same path so it never points at a shifted anchor. - Icons derived from Lucide pen-tool (ATTRIBUTION.md), hints and tool names in all 16 catalogs, README tool list, roadmap. Co-authored-by: Fabio Lussi <198260595+itrycodinganditsbad@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 Co-authored-by: Brandon Thomas --- ATTRIBUTION.md | 3 +- README.md | 4 +- assets/icons/pen-add-anchor.svg | 18 +++ assets/icons/pen-delete-anchor.svg | 17 +++ crates/automation/src/workspace.rs | 2 + crates/engine/src/path_edit_cmds.rs | 142 ++++++++++++++++++++- crates/ui-egui/src/anchor_tools.rs | 105 ++++++++++++++++ crates/ui-egui/src/anchor_tools_tests.rs | 152 +++++++++++++++++++++++ crates/ui-egui/src/canvas.rs | 4 + crates/ui-egui/src/direct_select.rs | 14 ++- crates/ui-egui/src/hold_keys.rs | 2 + crates/ui-egui/src/i18n/cs.tsv | 4 + crates/ui-egui/src/i18n/de.tsv | 4 + crates/ui-egui/src/i18n/el.tsv | 4 + crates/ui-egui/src/i18n/es.tsv | 4 + crates/ui-egui/src/i18n/fr.tsv | 4 + crates/ui-egui/src/i18n/id.tsv | 4 + crates/ui-egui/src/i18n/it.tsv | 4 + crates/ui-egui/src/i18n/ja.tsv | 4 + crates/ui-egui/src/i18n/ko.tsv | 4 + crates/ui-egui/src/i18n/nl.tsv | 4 + crates/ui-egui/src/i18n/pl.tsv | 4 + crates/ui-egui/src/i18n/pt-br.tsv | 4 + crates/ui-egui/src/i18n/ru.tsv | 4 + crates/ui-egui/src/i18n/uk.tsv | 4 + crates/ui-egui/src/i18n/zh-hans.tsv | 4 + crates/ui-egui/src/i18n/zh-hant.tsv | 4 + crates/ui-egui/src/icon_data.rs | 2 + crates/ui-egui/src/icons.rs | 2 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/panels.rs | 2 +- crates/ui-egui/src/state.rs | 15 ++- crates/ui-egui/src/tool_feedback.rs | 8 +- crates/ui-egui/src/vector_ui.rs | 14 ++- crates/vector/src/edit.rs | 133 +++++++++++++++++++- docs/target-app-parity.md | 4 +- 36 files changed, 685 insertions(+), 23 deletions(-) create mode 100644 assets/icons/pen-add-anchor.svg create mode 100644 assets/icons/pen-delete-anchor.svg create mode 100644 crates/ui-egui/src/anchor_tools.rs create mode 100644 crates/ui-egui/src/anchor_tools_tests.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 68312f1ce8..da46de9f83 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) | | 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 | | 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 | (`icons/.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 | (`icons/.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 | 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 `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 `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 `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 `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 `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 | | 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 1e550c03f0..be6e1654c4 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
-

🧰 56 tools

- 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 +

🧰 58 tools

+ 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

🖌️ A real brush engine

diff --git a/assets/icons/pen-add-anchor.svg b/assets/icons/pen-add-anchor.svg new file mode 100644 index 0000000000..a4e565736c --- /dev/null +++ b/assets/icons/pen-add-anchor.svg @@ -0,0 +1,18 @@ + + + + + + + + diff --git a/assets/icons/pen-delete-anchor.svg b/assets/icons/pen-delete-anchor.svg new file mode 100644 index 0000000000..f8cee2f97c --- /dev/null +++ b/assets/icons/pen-delete-anchor.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index 3a436aabe9..00a344f98c 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 53c4ba2528..6db84c270c 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 { edit_path(s, CMD, p, "Convert Point", |path| edit::convert_point(path, k, out)) } +fn add_anchor(s: &mut Session, p: &Value) -> Result { + 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 { + 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 { 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| CommandSpec { @@ -141,6 +174,18 @@ pub fn specs() -> Vec { 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 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 0000000000..a314db5fc9 --- /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 { + 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 = (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 0000000000..abd4b56971 --- /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::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 fa4e0611b6..b67fadbbfe 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 7cccf1dde9..96c0f148a9 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 64cda72397..5691576a56 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 b0d334b471..63a50c78bd 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 7e9b497383..3d74154144 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 1ef1066389..a15cf0f5ba 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 6d05dbbf25..8d99e362eb 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 12309df675..c256aa6d2a 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 5d4d885b08..94f6674fbf 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 60276d6de5..ca1a26ec81 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 03f54b09b6..f032d15fb5 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 2ce2a4ef97..f5d1ae64e1 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 4124691202..b836d27737 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 e7bfdf8baa..17207def99 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 ee6b314916..dc54026734 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 14bc60c930..effa80e987 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 f0bf886e8c..fb575be336 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 e794681ace..a01b0bbb6f 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 097400a97d..3258d263ef 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 9f4f2f1e23..f128ef9f4e 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 fbe93757f4..f6e760d8b9 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 90ea684402..449b34cbcc 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 eceada624a..0a4515f07a 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 52c98a628c..23bc080d4c 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 56f7444b45..bc993a7ae6 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 { + // 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 f1cd830db1..463a7f2993 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 8b6af7950c..c0ac2367e7 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 { + 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 e8ff48fefb..4be29aa691 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). From 2189a1610eea7102e55bbaf689abb2bd5bcea57a Mon Sep 17 00:00:00 2001 From: Teslak Date: Sun, 11 Oct 2026 02:54:09 -0700 Subject: [PATCH 2/5] fix(crop): stabilize resizing and apply ratio changes immediately (#3206) Compute snapped handles from press-time geometry to avoid feedback from Auto Center Preview. Paint the image and crop frame with the same camera. Apply ratio and size options immediately as centred rectangles contained in the current frame. Respect saved ratios, keep Swap and X consistent, and let Enter apply output sizes without an initial resize. Use container padding for the options bar's text allowance so right-aligned crop actions do not introduce horizontal overflow. Add regression coverage for handle snapping, rendered frames, preset/Enter and Swap/X interactions, and options-bar scrolling at multiple UI scales. Enable public GitHub profile name syncing for TheTeslak's contributor credit. Co-authored-by: Brandon Thomas Co-authored-by: Claude Opus 5.5 --- contributors/people.toml | 3 + crates/ui-egui/src/canvas.rs | 408 ++++++++++++---------- crates/ui-egui/src/crop_mode.rs | 59 +++- crates/ui-egui/src/crop_size.rs | 29 +- crates/ui-egui/src/crop_ui.rs | 112 +++++- crates/ui-egui/src/panels.rs | 72 +++- crates/ui-egui/src/snap_ui.rs | 88 ++++- crates/ui-egui/tests/crop_default_mode.rs | 66 ++++ docs/ui-parity.md | 6 +- 9 files changed, 620 insertions(+), 223 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 0adfc2f4a1..0248505ba6 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -93,3 +93,6 @@ sync_github_name = true [people.FinnNk] sync_github_name = true + +[people.TheTeslak] +sync_github_name = true diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index b67fadbbfe..2fcf73a330 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2479,214 +2479,225 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: None => paint_dots(ui, rect, app.session.prefs().interface.show_canvas_dots), } let border = app.session.prefs().interface.canvas_border; - let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow; - // Drop shadow, checkerboard, document image. - let img_rect = xf.doc_rect(doc.bounds()); - // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas - // (whose edge blends into them) and without its shadow. - let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output); - let drop_shadow = drop_shadow && !beyond; - // Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless - // Preferences › Performance › Low Resolution Previews is off. - let mut on_gpu = false; - // A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader - // has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform. - let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect); - if app.gpu.is_some() - && gpu_ok - && let Some((k, key, preview_size)) = - ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx)) - { - on_gpu = true; - let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)]; - let params = crate::gpu_canvas::ViewParams { - doc: key, - doc_size: preview_size, - zoom: view.zoom * k as f32 / ppp, - // A size-changing preview grows around the old image center; keep the view's pan. - center: [ - view.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0, - view.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0, - ], - rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, - shadow: { - let t = crate::theme::Tokens::get(&ctx); - !t.bevel && !t.pro && drop_shadow - }, - pixel_grid: false, - view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(), - display: sync_display_lut(app, &doc, key, output), - output: output.unwrap_or(0), - hdr: hdr_preview(app, &doc), - }; - crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params); - } else if gpu_ok && ensure_gpu(app, idx, visible_doc_rect(&xf)) { - on_gpu = true; - app.perf.gpu = true; - // Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs). - let params = crate::gpu_canvas::ViewParams { - doc: doc.id.0, - doc_size: [doc.size.width, doc.size.height], - zoom: point_zoom, - center: view.center, - rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, - shadow: { - let t = crate::theme::Tokens::get(&ctx); - !t.bevel && !t.pro && drop_shadow - }, - pixel_grid, - view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(), - display: sync_display_lut(app, &doc, doc.id.0, output), - output: output.unwrap_or(0), - hdr: hdr_preview(app, &doc), - }; - crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params); - } else { - if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { - painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0)); - } - let rotated = view.rotation.abs() > 0.05; - let size = [doc.size.width as f32, doc.size.height as f32]; - match app.session.prefs().transparency_and_gamut.square() { - Some(square) => { - let checker_id = checker(app, &ctx); - if rotated { - let tiles = vec2(size[0], size[1]) / (2.0 * square); - paint_mapped_image(&painter, &xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE); - } else { - let tiles = img_rect.size() / (2.0 * square); - painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + // Default-mode Crop changes its camera during input. Defer its image until the new camera + // is known; other tools keep their existing paint order and texture/outline snapshots. + let crop_camera = primary && crate::crop_mode::moves_image(app); + let paint_canvas = |app: &mut PhotocraftApp, ui: &egui::Ui, view: &View, xf: ViewXform| { + let point_zoom = view.zoom / ppp; + let drop_shadow = border == photocraft_engine::prefs::CanvasBorder::DropShadow; + // Drop shadow, checkerboard, document image. + let img_rect = xf.doc_rect(doc.bounds()); + // Crop tool: the layers' pixels past the canvas while a frame is edited, under the canvas + // (whose edge blends into them) and without its shadow. + let beyond = draw_beyond_canvas(app, &painter, &xf, idx, output); + let drop_shadow = drop_shadow && !beyond; + // Live adjustment previews on big documents use a downsampled proxy (see proxy.rs), unless + // Preferences › Performance › Low Resolution Previews is off. + let mut on_gpu = false; + // A flipped or pixel-aspect-corrected view draws through the CPU path (the GPU canvas shader + // has no mirroring or non-square pixels). Rotation stays on the GPU: it is a view uniform. + let gpu_ok = crate::gpu_canvas::gpu_view_ok(flip, view.rotation, aspect); + if app.gpu.is_some() + && gpu_ok + && let Some((k, key, preview_size)) = + ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx)) + { + on_gpu = true; + let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)]; + let params = crate::gpu_canvas::ViewParams { + doc: key, + doc_size: preview_size, + zoom: view.zoom * k as f32 / ppp, + // A size-changing preview grows around the old image center; keep the view's pan. + center: [ + view.center[0] / k as f32 + (preview_size[0] as f32 - original_size[0] as f32) / 2.0, + view.center[1] / k as f32 + (preview_size[1] as f32 - original_size[1] as f32) / 2.0, + ], + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, + shadow: { + let t = crate::theme::Tokens::get(&ctx); + !t.bevel && !t.pro && drop_shadow + }, + pixel_grid: false, + view_key: egui::Id::new(("pc-canvas-proxy", ctx.viewport_id(), idx)).value(), + display: sync_display_lut(app, &doc, key, output), + output: output.unwrap_or(0), + hdr: hdr_preview(app, &doc), + }; + crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params); + } else if gpu_ok && ensure_gpu(app, idx, visible_doc_rect(&xf)) { + on_gpu = true; + app.perf.gpu = true; + // Shadow, checkerboard, document and pixel grid in one custom shader (gpu_canvas.rs). + let params = crate::gpu_canvas::ViewParams { + doc: doc.id.0, + doc_size: [doc.size.width, doc.size.height], + zoom: point_zoom, + center: view.center, + rotation: if view.rotation.is_finite() { view.rotation.to_radians() } else { 0.0 }, + shadow: { + let t = crate::theme::Tokens::get(&ctx); + !t.bevel && !t.pro && drop_shadow + }, + pixel_grid, + view_key: egui::Id::new(("pc-canvas", ctx.viewport_id(), idx)).value(), + display: sync_display_lut(app, &doc, doc.id.0, output), + output: output.unwrap_or(0), + hdr: hdr_preview(app, &doc), + }; + crate::gpu_canvas::GpuCanvas::paint(&painter, rect, params); + } else { + if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow { + painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0)); + } + let rotated = view.rotation.abs() > 0.05; + let size = [doc.size.width as f32, doc.size.height as f32]; + match app.session.prefs().transparency_and_gamut.square() { + Some(square) => { + let checker_id = checker(app, &ctx); + if rotated { + let tiles = vec2(size[0], size[1]) / (2.0 * square); + paint_mapped_image(&painter, &xf, checker_id, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), size, Color32::WHITE); + } else { + let tiles = img_rect.size() / (2.0 * square); + painter.image(checker_id, img_rect, Rect::from_min_max(Pos2::ZERO, pos2(tiles.x, tiles.y)), Color32::WHITE); + } + } + None => { + if rotated { + paint_mapped_quad(&painter, &xf, size, Color32::WHITE); + } else { + painter.rect_filled(img_rect, 0.0, Color32::WHITE); + } } } - None => { + if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) { if rotated { - paint_mapped_quad(&painter, &xf, size, Color32::WHITE); + paint_mapped_image(&painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE); } else { - painter.rect_filled(img_rect, 0.0, Color32::WHITE); + let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; + painter.image(tex, img_rect, uv, Color32::WHITE); } } } - if let Some((tex, _scale)) = ensure_texture(app, &ctx, idx, output) { - if rotated { - paint_mapped_image(&painter, &xf, tex, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), size, Color32::WHITE); + // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). + if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) { + if view.rotation.abs() > 0.05 { + paint_mapped_image( + &painter, + &xf, + tex, + Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), + [doc.size.width as f32, doc.size.height as f32], + Color32::WHITE, + ); } else { let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; painter.image(tex, img_rect, uv, Color32::WHITE); } } - } - // Channels panel: alpha / Quick Mask overlays and single-channel views (channel_view.rs). - if let Some(tex) = crate::channel_view::ensure(app, &ctx, idx) { - if view.rotation.abs() > 0.05 { - paint_mapped_image( - &painter, - &xf, - tex, - Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), - [doc.size.width as f32, doc.size.height as f32], - Color32::WHITE, - ); - } else { - let uv = if flip { Rect::from_min_max(pos2(1.0, 0.0), pos2(0.0, 1.0)) } else { Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)) }; - painter.image(tex, img_rect, uv, Color32::WHITE); - } - } - crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); - // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). - if doc.has_artboards() { - let t = crate::theme::Tokens::get(&ctx); - let pasteboard = crate::prefs_ui::pasteboard_color(app); - let dot_tex = dots(&ctx, &t); - for r in crate::artboard_ui::pasteboard_rects(&xf, &doc) { - let r = r.intersect(rect); - if !r.is_positive() { - continue; - } - match pasteboard { - Some(c) => { - painter.rect_filled(r, 0.0, c); + crate::color_range_ui::paint_selection_preview(app, &ctx, &painter, doc.id, img_rect, flip); + // Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs). + if doc.has_artboards() { + let t = crate::theme::Tokens::get(&ctx); + let pasteboard = crate::prefs_ui::pasteboard_color(app); + let dot_tex = dots(&ctx, &t); + for r in crate::artboard_ui::pasteboard_rects(&xf, &doc) { + let r = r.intersect(rect); + if !r.is_positive() { + continue; } - None => { - painter.rect_filled(r, 0.0, t.canvas); - if let Some(id) = dot_tex { - // Same phase as the dots around the document. - let uv = Rect::from_min_max(((r.min - rect.min) / 22.0).to_pos2(), ((r.max - rect.min) / 22.0).to_pos2()); - painter.image(id, r, uv, Color32::WHITE); + match pasteboard { + Some(c) => { + painter.rect_filled(r, 0.0, c); + } + None => { + painter.rect_filled(r, 0.0, t.canvas); + if let Some(id) = dot_tex { + // Same phase as the dots around the document. + let uv = Rect::from_min_max(((r.min - rect.min) / 22.0).to_pos2(), ((r.max - rect.min) / 22.0).to_pos2()); + painter.image(id, r, uv, Color32::WHITE); + } } } } - } - if primary { - crate::artboard_ui::draw_frames(app, &painter, &xf); - } - } - - // Pixel grid at high zoom, over pixels with content only (the GPU path draws its own). - if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) { - crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf)); - } - - // View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are - // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer. - let layer_edges = painter.add(egui::Shape::Noop); - - // Selection outline: true boundary, animated marching ants (cached per revision). - if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) { - // Trace at display resolution over the visible part only; key by the mask's tile identity - // (not the document revision) so unrelated edits don't re-trace it. The step is in - // device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px - // selection still traces at 100% on a scaled display. - let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32; - let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)]; - let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])]; - let mut x0 = docs[0][0]; - let mut y0 = docs[0][1]; - let mut x1 = x0; - let mut y1 = y0; - for d in docs { - x0 = x0.min(d[0]); - y0 = y0.min(d[1]); - x1 = x1.max(d[0]); - y1 = y1.max(d[1]); - } - let q = 256 * step as i32; // quantise the region so small pans reuse the cache - // The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document - // to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there. - let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; - let vis = photocraft_geom::Rect::new( - px(x0.floor()).div_euclid(q) * q - q, - px(y0.floor()).div_euclid(q) * q - q, - (px(x1.ceil()).div_euclid(q) + 2) * q, - (px(y1.ceil()).div_euclid(q) + 2) * q, - ); - let key = crate::surface_fingerprint(sel) - ^ (step as u64) << 56 - ^ doc.id.0.rotate_left(17) - ^ (vis.x0 as u64) << 8 - ^ (vis.y0 as u64) << 24 - ^ (vis.x1 as u64) << 36 - ^ (vis.y1 as u64) << 48; - let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key); - if !fresh { - let t0 = crate::gpu_canvas::now_ms(); - let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis); - // Filters can occupy every worker in Rayon's global pool. A parallel scan here would - // block the UI thread waiting for those workers, preventing job cancellation (#1554). - let segs = if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) }; - app.perf.span("outline", crate::gpu_canvas::now_ms() - t0); - app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs))); - } - if let Some((_, _, segs)) = &app.outline_cache { - let time = ui.input(|i| i.time); - // A floating piece (and a selection being dragged) draws its ants where it is shown. - let mut shown = xf; - if let Some((dx, dy)) = selection_shown_offset(app) { - shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32]; + if primary { + crate::artboard_ui::draw_frames(app, &painter, &xf); } - marching_ants_segments(&painter, &shown, segs, time); - ctx.request_repaint_after(std::time::Duration::from_millis(100)); } - } + + // Pixel grid at high zoom, over pixels with content only (the GPU path draws its own). + if !on_gpu && pixel_grid && crate::pixel_grid::shows_at(view.zoom) { + crate::pixel_grid::paint(app, &painter, &xf, idx, output, visible_doc_rect(&xf)); + } + + // View › Show › Layer Edges: drawn at this depth, but only once this frame's tool events are + // in (`layer_edges_rect`), so a press that Auto-Selects a layer outlines that layer. + let layer_edges = painter.add(egui::Shape::Noop); + + // Selection outline: true boundary, animated marching ants (cached per revision). + if let Some(sel) = doc.selection.as_ref().filter(|_| app.ui.view.shows(app.ui.view.show.selection_edges) && !polygon_replaces_selection(app)) { + // Trace at display resolution over the visible part only; key by the mask's tile identity + // (not the document revision) so unrelated edits don't re-trace it. The step is in + // device pixels per document pixel (`View::zoom`, not the point zoom), so a 1 px + // selection still traces at 100% on a scaled display. + let step = (1.0 / view.zoom.max(1e-3)).log2().floor().exp2().clamp(1.0, 64.0) as u32; + let corners = [rect.min, pos2(rect.max.x, rect.min.y), rect.max, pos2(rect.min.x, rect.max.y)]; + let docs = [xf.to_doc(corners[0]), xf.to_doc(corners[1]), xf.to_doc(corners[2]), xf.to_doc(corners[3])]; + let mut x0 = docs[0][0]; + let mut y0 = docs[0][1]; + let mut x1 = x0; + let mut y1 = y0; + for d in docs { + x0 = x0.min(d[0]); + y0 = y0.min(d[1]); + x1 = x1.max(d[0]); + y1 = y1.max(d[1]); + } + let q = 256 * step as i32; // quantise the region so small pans reuse the cache + // The view centre can be any finite number (`ui.set`, #980). Past ±2³⁰ there is no document + // to outline, and the padding below (at most 2 · 256 · 64) can't overflow i32 from there. + let px = |v: f64| v.clamp(-f64::from(1 << 30), f64::from(1 << 30)) as i32; + let vis = photocraft_geom::Rect::new( + px(x0.floor()).div_euclid(q) * q - q, + px(y0.floor()).div_euclid(q) * q - q, + (px(x1.ceil()).div_euclid(q) + 2) * q, + (px(y1.ceil()).div_euclid(q) + 2) * q, + ); + let key = crate::surface_fingerprint(sel) + ^ (step as u64) << 56 + ^ doc.id.0.rotate_left(17) + ^ (vis.x0 as u64) << 8 + ^ (vis.y0 as u64) << 24 + ^ (vis.x1 as u64) << 36 + ^ (vis.y1 as u64) << 48; + let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key); + if !fresh { + let t0 = crate::gpu_canvas::now_ms(); + let b = app.cached_bounds(u64::MAX - doc.id.0, sel).intersect(&vis); + // Filters can occupy every worker in Rayon's global pool. A parallel scan here would + // block the UI thread waiting for those workers, preventing job cancellation (#1554). + let segs = + if app.session.has_jobs() { crate::outline::outline_scaled_serial(sel, b, step) } else { crate::outline::outline_scaled(sel, b, step) }; + app.perf.span("outline", crate::gpu_canvas::now_ms() - t0); + app.outline_cache = Some((doc.id, key, std::sync::Arc::new(segs))); + } + if let Some((_, _, segs)) = &app.outline_cache { + let time = ui.input(|i| i.time); + // A floating piece (and a selection being dragged) draws its ants where it is shown. + let mut shown = xf; + if let Some((dx, dy)) = selection_shown_offset(app) { + shown.center = [xf.center[0] - dx as f32, xf.center[1] - dy as f32]; + } + marching_ants_segments(&painter, &shown, segs, time); + ctx.request_repaint_after(std::time::Duration::from_millis(100)); + } + } + + (img_rect, beyond, layer_edges) + }; + let painted = if crop_camera { None } else { Some(paint_canvas(app, ui, &view, xf)) }; + let img_rect = xf.doc_rect(doc.bounds()); // Under an open dialog the canvas widget is inert, but the image still pans and zooms. let under_dialog = !app.ui.dialogs.is_empty(); @@ -3092,6 +3103,20 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: if tool.is_type() && response.double_clicked() && !crate::type_transform::visible(app, crate::workspace_ui::sticky_mods(app, mods)) { crate::type_tool::select_word(app); } + } + if crop_camera && let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { + if now.center != center { + view.center = now.center; + ctx.request_repaint(); + } + if now.rotation != rotation { + view.rotation = now.rotation; + ctx.request_repaint(); + } + } + let xf = if crop_camera { ViewXform { center: view.center, rotation: view.rotation, ..xf } } else { xf }; + let (img_rect, beyond, layer_edges) = painted.unwrap_or_else(|| paint_canvas(app, ui, &view, xf)); + if primary && !(hand_pan && response.dragged()) { if app.ui.extras.grid && app.ui.view.extras { crate::rulers::draw_grid(app, &painter, &xf, &doc); } @@ -3330,7 +3355,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: } crate::rotate_view::overlay(app, &ctx, &painter, &xf, &mut view, &response); if primary { - // The camera the tools set this frame wins over the copy's. + // Tool input can change the stored camera while navigation edits the local view. + // Merge changed camera values so write-back preserves tool-driven pan and rotation. if let (Some((center, rotation)), Some(now)) = (camera, app.ui.views.get(idx)) { if now.center != center { view.center = now.center; diff --git a/crates/ui-egui/src/crop_mode.rs b/crates/ui-egui/src/crop_mode.rs index 5250d1403b..e19f01334a 100644 --- a/crates/ui-egui/src/crop_mode.rs +++ b/crates/ui-egui/src/crop_mode.rs @@ -132,7 +132,8 @@ pub struct LiveResize { /// press and grows or shrinks symmetrically there, so the handle stays under the pointer, while on /// the image the opposite edge stays put (the centre with ⌥), as in a plain resize. Everything is /// computed from the press, so the view following the frame can't feed back into the drag. -pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) { +/// Returns the proposed frame and the camera's document-space offset without changing the app. +pub(crate) fn resized_frame(g: LiveResize) -> Option<([f64; 4], [f64; 2])> { let LiveResize { rect, deg, hx, hy, start, q, ratio, alt } = g; let c0 = crate::crop_ui::center(rect); let (w0, h0) = (rect[2] - rect[0], rect[3] - rect[1]); @@ -147,9 +148,12 @@ pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) { let s = crate::crop_ui::turn(shift, [0.0, 0.0], deg); let c1 = [c0[0] + s[0], c0[1] + s[1]]; let f = [c1[0] - w1 / 2.0, c1[1] - h1 / 2.0, c1[0] + w1 / 2.0, c1[1] + h1 / 2.0]; - if !f.iter().all(|v| v.is_finite()) { - return; - } + f.iter().all(|v| v.is_finite()).then_some((f, s)) +} + +/// Move the camera with the resized frame to keep the crop box's centre stationary on screen. +pub fn live_resize(app: &mut PhotocraftApp, g: LiveResize, press: PressView) { + let Some((f, s)) = resized_frame(g) else { return }; app.ui.crop_rect = Some(f); // The view follows the centre, so the box stays where it was on screen. if let Some(v) = app.session.active_index().and_then(|i| app.ui.views.get_mut(i)) { @@ -216,6 +220,14 @@ pub fn to_press(app: &PhotocraftApp, press: Option, p: [f64; 2]) -> [ } } +/// A press-view point mapped back into the current camera after snapping the crop handle. +pub(crate) fn from_press(app: &PhotocraftApp, press: PressView, p: [f64; 2]) -> [f64; 2] { + match press_view(app) { + Some(now) => remap(p, press, now, app.ui.view.flip_horizontal), + None => p, + } +} + /// The control channel's `ui.pointer` gives document points as the view showed them at the press /// (it can't know how the view turns and pans with the image): during a default-mode drag, the /// point the canvas would report for the same screen position now. @@ -337,6 +349,45 @@ mod tests { app.crop.default_frame = false; } + #[test] + fn a_live_resize_snaps_the_handle_without_feedback_from_the_camera() { + for (hx, hy) in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] { + for alt in [false, true] { + for (zoom, ppp, flip, ratio) in [(1.0, 1.0, false, false), (0.5, 1.0, false, true), (3.0, 2.0, false, false), (3.0, 2.0, true, true)] { + let mut app = app(); + app.ppp = ppp; + app.ui.views[0].zoom = zoom; + app.ui.view.flip_horizontal = flip; + if ratio { + app.ui.tool_options.crop_ratio = "original".into(); + } + app.ui.extras.snap = true; + crate::crop_ui::ensure_frame(&mut app); + let box0 = screen_box(&app); + let c = mid_of(box0); + let from = xf(&app).to_screen(100.0 + hx as f32 * 100.0, 50.0 + hy as f32 * 50.0); + let direction = (from - c).normalized(); + let mods = if alt { Modifiers::ALT } else { NONE }; + let d = xf(&app).to_doc(from); + tool_event(&mut app, ToolEvent::Down { x: d[0], y: d[1], pressure: 1.0 }, mods); + // Leave the snap radius, then return just inside it. A still pointer must + // settle on the canvas edge instead of alternating on opposite sides of it. + for offset in [20.0, -2.0, -2.0, -2.0, -2.0, -2.0] { + let p = from + direction * offset; + let d = xf(&app).to_doc(p); + tool_event(&mut app, ToolEvent::Move { x: d[0], y: d[1], pressure: 1.0 }, mods); + if offset == -2.0 { + assert!(close(screen_box(&app), box0), "handle ({hx}, {hy}), Alt {alt}: {:?}", app.ui.crop_rect); + } + } + let d = xf(&app).to_doc(from + direction * -2.0); + tool_event(&mut app, ToolEvent::Up { x: d[0], y: d[1] }, mods); + assert!(close(screen_box(&app), box0), "release: {:?}", app.ui.crop_rect); + } + } + } + } + #[test] fn dragging_outside_turns_the_image_and_the_box_stays_upright() { let mut app = app(); diff --git a/crates/ui-egui/src/crop_size.rs b/crates/ui-egui/src/crop_size.rs index 42b9675a58..2e58647432 100644 --- a/crates/ui-egui/src/crop_size.rs +++ b/crates/ui-egui/src/crop_size.rs @@ -156,8 +156,8 @@ pub fn ratio(o: &ToolOptions, doc_dpi: f64) -> Option { /// Editable W and H shown for a custom aspect ratio. An existing valid ratio is authoritative; /// when either side is zero, use the in-progress values retained in ToolOptions. -pub fn custom_ratio_fields(o: &ToolOptions) -> (f32, f32) { - crate::chrome_ui::crop_ratio(&o.crop_ratio, 0.0, 0.0) +pub fn custom_ratio_fields(o: &ToolOptions, doc_size: (f64, f64)) -> (f32, f32) { + crate::chrome_ui::crop_ratio(&o.crop_ratio, doc_size.0, doc_size.1) .filter(|(w, h)| w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0 && *w <= 99_999.0 && *h <= 99_999.0) .map(|(w, h)| (w as f32, h as f32)) .unwrap_or((o.crop_custom_ratio_width, o.crop_custom_ratio_height)) @@ -247,6 +247,7 @@ pub fn chosen(app: &mut PhotocraftApp) { o.crop_resolution = (*r).into(); o.crop_resolution_unit = PX_PER_IN.into(); } + crate::crop_ui::apply_ratio(app); } /// I with the Crop tool (no text field focused, which the caller checks): Front Image. Returns @@ -257,6 +258,7 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } if ctx.input_mut(|i| i.consume_key(Modifiers::NONE, egui::Key::I)) { front_image(app); + crate::crop_ui::apply_ratio(app); return true; } false @@ -343,12 +345,12 @@ mod tests { set_custom_ratio_fields(&mut options, 4.0, 0.0); assert_eq!(options.crop_ratio, "", "an incomplete ratio stays unconstrained"); - assert_eq!(custom_ratio_fields(&options), (4.0, 0.0), "first entry survives the next frame"); + assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (4.0, 0.0), "first entry survives the next frame"); - let (width, _) = custom_ratio_fields(&options); + let (width, _) = custom_ratio_fields(&options, (0.0, 0.0)); set_custom_ratio_fields(&mut options, width, 3.0); assert_eq!(options.crop_ratio, "4:3"); - assert_eq!(custom_ratio_fields(&options), (4.0, 3.0)); + assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (4.0, 3.0)); let (width, height) = crate::chrome_ui::crop_ratio(&options.crop_ratio, 0.0, 0.0).unwrap_or_default(); assert_eq!(width / height, 4.0 / 3.0); } @@ -357,11 +359,11 @@ mod tests { fn selecting_free_ratio_clears_previous_custom_dimensions() { let mut options = ToolOptions { crop_ratio: "16:9".into(), ..ToolOptions::default() }; select_custom_ratio(&mut options); - assert_eq!(custom_ratio_fields(&options), (16.0, 9.0)); + assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (16.0, 9.0)); options.crop_ratio.clear(); select_custom_ratio(&mut options); - assert_eq!(custom_ratio_fields(&options), (0.0, 0.0)); + assert_eq!(custom_ratio_fields(&options, (0.0, 0.0)), (0.0, 0.0)); } #[test] @@ -469,6 +471,19 @@ mod tests { /// Committing a W x H x Resolution crop resamples the frame's area to exactly W x H px and sets /// the resolution, in one undo step, at 8 and 16 bits. + #[test] + fn choosing_a_size_with_the_canvas_ratio_commits_without_a_resize() { + let mut app = app(SampleType::U8); + crate::crop_ui::ensure_frame(&mut app); + app.ui.tool_options = whr("800 px", "600 px", "92", PX_PER_IN); + chosen(&mut app); + assert_eq!(app.ui.crop_rect, Some([0.0, 0.0, 400.0, 300.0])); + assert!(!app.crop.default_frame, "an output size is a pending crop even when the frame fits"); + crate::canvas::commit_crop(&mut app); + let doc = &app.session.active().unwrap().doc; + assert_eq!((doc.size, doc.resolution_dpi), (Size::new(800, 600), 92.0)); + } + #[test] fn commit_resamples_to_the_target_size_and_resolution() { for depth in [SampleType::U8, SampleType::U16] { diff --git a/crates/ui-egui/src/crop_ui.rs b/crates/ui-egui/src/crop_ui.rs index 1c8d3db827..194cf60476 100644 --- a/crates/ui-egui/src/crop_ui.rs +++ b/crates/ui-egui/src/crop_ui.rs @@ -200,7 +200,7 @@ fn size_ok(r: [f64; 4]) -> bool { } /// The options-bar ratio preset as width / height (W : H in W x H x Resolution mode). -fn preset_ratio(app: &PhotocraftApp) -> Option { +pub(crate) fn preset_ratio(app: &PhotocraftApp) -> Option { if app.ui.tool_options.crop_ratio == crate::crop_size::WHR { let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi)); return crate::crop_size::ratio(&app.ui.tool_options, dpi); @@ -209,6 +209,43 @@ fn preset_ratio(app: &PhotocraftApp) -> Option { crate::chrome_ui::crop_ratio(&app.ui.tool_options.crop_ratio, size.0, size.1).map(|(w, h)| w / h).filter(|k| k.is_finite() && *k > 0.0) } +/// Largest centred rectangle of `ratio` contained in the current frame; never adds area. +fn fitted_ratio(r: [f64; 4], ratio: f64) -> Option<[f64; 4]> { + let (w, h) = (r[2] - r[0], r[3] - r[1]); + if !r.iter().all(|v| v.is_finite()) || !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 || !ratio.is_finite() || ratio <= 0.0 { + return None; + } + if ((w / h) / ratio - 1.0).abs() < 1e-12 { + return Some(r); + } + let c = [r[0] + w / 2.0, r[1] + h / 2.0]; + let (w, h) = if w / h > ratio { (h * ratio, h) } else { (w, w / ratio) }; + let fitted = [c[0] - w / 2.0, c[1] - h / 2.0, c[0] + w / 2.0, c[1] + h / 2.0]; + (fitted.iter().all(|v| v.is_finite()) && fitted[2] > fitted[0] && fitted[3] > fitted[1]).then_some(fitted) +} + +/// Apply committed options to the preview now, before a resize or confirmation is needed. +pub(crate) fn apply_ratio(app: &mut PhotocraftApp) { + if app.ui.tool != Tool::Crop || app.crop.drag.is_some() { + return; + } + frame(app); + fit_frame(app); + crate::crop_mode::sync_frame(app); +} + +fn fit_frame(app: &mut PhotocraftApp) { + let dpi = app.session.active().map_or(72.0, |s| f64::from(s.doc.resolution_dpi)); + if let Some(r) = app.ui.crop_rect + && let Some(ratio) = preset_ratio(app) + && let Some(fitted) = fitted_ratio(r, ratio) + // W x H x Resolution can change output size even when the frame already fits. + && (fitted != r || crate::crop_size::target(&app.ui.tool_options, dpi).is_some()) + { + keyed(app, fitted); + } +} + /// A new frame drawn from `anchor` to `cur`: ⇧ square, ⌥ from the centre, `ratio` held. pub fn drawn(anchor: [f64; 2], cur: [f64; 2], ratio: Option, mods: Modifiers) -> [f64; 4] { let e = match ratio { @@ -308,6 +345,7 @@ fn frame(app: &mut PhotocraftApp) { app.crop.frame_for = key; app.crop.editing = false; claim(app); + fit_frame(app); } /// A crop gesture is in progress: Space repositions the frame rather than panning. @@ -408,7 +446,7 @@ pub fn press(app: &mut PhotocraftApp) -> bool { new } -fn tolerance(app: &PhotocraftApp) -> f64 { +pub(crate) fn tolerance(app: &PhotocraftApp) -> f64 { HANDLE_PX / (app.point_zoom() as f64).max(0.01) } @@ -522,9 +560,13 @@ pub fn swap_orientation(app: &mut PhotocraftApp) -> bool { { app.ui.tool_options.crop_ratio = k; } - keyed(app, swapped(r)); - crate::crop_mode::sync_frame(app); - crate::crop_mode::auto_center(app); + if preset_ratio(app).is_some() { + apply_ratio(app); + } else { + keyed(app, swapped(r)); + crate::crop_mode::sync_frame(app); + crate::crop_mode::auto_center(app); + } true } @@ -668,8 +710,7 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { // Auto Center Preview: the box stays centred where it was while the handle follows // the pointer. let q = crate::crop_mode::to_press(app, Some(view), p); - let keep = (rect[2] - rect[0] > 0.0 && rect[3] - rect[1] > 0.0).then(|| (rect[2] - rect[0]) / (rect[3] - rect[1])); - let ratio = ratio.or(if mods.shift { keep } else { None }); + let ratio = resize_ratio(app, rect, mods); crate::crop_mode::live_resize(app, crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio, alt: mods.alt }, view); return; } @@ -709,6 +750,12 @@ fn update(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers) { app.ui.crop_rect = Some(rect); } +/// Geometry and snapping must use the same ratio so constrained handles stay aligned. +pub(crate) fn resize_ratio(app: &PhotocraftApp, rect: [f64; 4], mods: Modifiers) -> Option { + let keep = (rect[2] - rect[0] > 0.0 && rect[3] - rect[1] > 0.0).then(|| (rect[2] - rect[0]) / (rect[3] - rect[1])); + preset_ratio(app).or(if mods.shift { keep } else { None }) +} + /// Cursor over the canvas at document point `p`: resize arrows on the edges, move inside. pub fn cursor(app: &PhotocraftApp, p: [f64; 2]) -> Option { if app.ui.tool != Tool::Crop { @@ -835,6 +882,57 @@ mod tests { tool_event(app, ToolEvent::Up { x: last[0], y: last[1] }, mods); } + #[test] + fn fitting_a_ratio_keeps_the_centre_angle_and_area() { + let mut app = app(SampleType::U8); + app.ui.crop_rect = Some([20.0, 10.0, 180.0, 90.0]); + app.ui.crop_angle = 25.0; + for key in ["1:1", "16:9", "9:16", "", "0:0"] { + let before = app.ui.crop_rect.unwrap(); + app.ui.tool_options.crop_ratio = key.into(); + crate::crop_size::chosen(&mut app); + let after = app.ui.crop_rect.unwrap(); + assert_eq!(center(after), center(before)); + assert_eq!(app.ui.crop_angle, 25.0); + assert!(after[0] >= before[0] && after[1] >= before[1] && after[2] <= before[2] && after[3] <= before[3]); + if let Some(ratio) = preset_ratio(&app) { + assert!(((after[2] - after[0]) / (after[3] - after[1]) - ratio).abs() < 1e-10); + } else { + assert_eq!(after, before); + } + } + for ratio in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(fitted_ratio([0.0, 0.0, 200.0, 100.0], ratio).is_none()); + } + assert!(fitted_ratio([-f64::MAX, 0.0, f64::MAX, 100.0], 1.0).is_none()); + } + + #[test] + fn choosing_a_ratio_fits_and_commits_without_a_resize() { + for classic in [false, true] { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_shield.classic_mode = classic; + ensure_frame(&mut app); + app.ui.tool_options.crop_ratio = "1:1".into(); + crate::crop_size::chosen(&mut app); + assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); + crate::canvas::commit_crop(&mut app); + assert_eq!(app.session.active().unwrap().doc.size, Size::new(100, 100)); + } + } + + #[test] + fn entering_crop_with_a_saved_ratio_fits_the_selection_or_canvas() { + let mut app = app(SampleType::U8); + app.ui.tool_options.crop_ratio = "1:1".into(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([50.0, 0.0, 150.0, 100.0])); + cancel(&mut app); + app.run("select.rect", json!({"x": 20, "y": 10, "width": 80, "height": 40})).unwrap(); + ensure_frame(&mut app); + assert_eq!(app.ui.crop_rect, Some([40.0, 10.0, 80.0, 50.0])); + } + #[test] fn picking_the_tool_frames_the_canvas_or_the_selection() { // #668: the Crop tool started with no frame. diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 0a4515f07a..e0b963e7e9 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -826,6 +826,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator)); ui.style_mut().spacing.scroll = egui::style::ScrollStyle { bar_width: 4.0, ..egui::style::ScrollStyle::floating() }; egui::ScrollArea::horizontal().id_salt("tool-options").auto_shrink([false, false]).show(ui, |ui| { + // Font ink can extend beyond its advance width at fractional positions. + // Include its gutter in the container layout, including right-aligned actions. + egui::Frame::NONE.inner_margin(egui::Margin { right: 2, ..Default::default() }).show(ui, |ui| { ui.horizontal_centered(|ui| { if t.pro { crate::chrome_ui::home_button(app, ui); @@ -1148,14 +1151,17 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::gradient_ui::options_changed(app, &before); } Tool::Crop if t.pro => { + let before_ratio = crate::crop_ui::preset_ratio(app); + let doc_size = app.session.active().map_or((0.0, 0.0), |s| (f64::from(s.doc.size.width), f64::from(s.doc.size.height))); // Ratios, sizes, saved presets, New / Delete Crop Preset… (#2443, #1919). crate::crop_presets::dropdown(app, ui); let o = &mut app.ui.tool_options; if o.crop_ratio == crate::crop_size::WHR { crate::crop_size::fields(o, ui); } else { - // Keep partial edits in ToolOptions so the first side survives a frame. - let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o); + // Keep partial edits in ToolOptions so the first side survives a frame; + // Original Ratio shows the document's numbers, as Photoshop does. + let (mut rw, mut rh) = crate::crop_size::custom_ratio_fields(o, doc_size); let cw = widgets::value_field(ui, &mut rw, 0.0..=99_999.0, "", 54.0).changed(); let swap = icons::button(ui, "arrow-left-right", 22.0, false, tl!("Swaps height and width")).clicked(); let ch = widgets::value_field(ui, &mut rh, 0.0..=99_999.0, "", 54.0).changed(); @@ -1178,6 +1184,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { crate::crop_overlay::options_button(o, ui); let pick_shield_color = crate::crop_shield::options_button(&mut o.crop_shield, ui); widgets::checkbox(ui, &mut o.crop_delete, tl!("Delete Cropped Pixels")); + if crate::crop_ui::preset_ratio(app) != before_ratio { + crate::crop_ui::apply_ratio(app); + } if pick_shield_color { crate::crop_shield::pick_custom_color(app); } @@ -1362,10 +1371,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { } crate::brush_panel::commit_gesture(app, ui.ctx(), &brush_before, &brush); }); - // Font ink can extend beyond its advance width at fractional positions. - ui.expand_to_include_x(ui.min_rect().right() + 2.0); reveal_focused_control(ui); }); + }); }); } @@ -4904,6 +4912,62 @@ mod compact_visual_regressions { } } + #[test] + fn a_wide_crop_options_bar_does_not_scroll() { + for kind in crate::theme::ThemeKind::ALL { + for scale in [1.0, 1.5, 2.0] { + for mode in ["", crate::crop_size::WHR] { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, kind); + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + if !Tokens::get(&ctx).pro { + continue; + } + app.ui.tool = Tool::Crop; + app.ui.tool_options.crop_ratio = mode.into(); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(1600.0, 120.0)); + let clear_x = |output: &egui::FullOutput| { + output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.job.text == "Clear" => Some(t.pos.x), + _ => None, + }) + .unwrap() + }; + let mut before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); + before.textures_delta.clear(); + for _ in 0..3 { + before = ctx.run_ui(input_at_scale(screen, scale), |ui| options_bar(&mut app, ui)); + before.textures_delta.clear(); + } + let mut after = before.clone(); + for _ in 0..6 { + after = ctx.run_ui( + egui::RawInput { + events: vec![ + egui::Event::PointerMoved(pos2(800.0, 20.0)), + egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(-100.0, 0.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + }, + ], + ..input_at_scale(screen, scale) + }, + |ui| options_bar(&mut app, ui), + ); + after.textures_delta.clear(); + } + assert_eq!(clear_x(&before), clear_x(&after), "a roomy bar must not have horizontal overflow"); + } + } + } + } + #[test] fn narrow_tool_options_can_scroll_to_the_last_control() { for kind in crate::theme::ThemeKind::ALL { diff --git a/crates/ui-egui/src/snap_ui.rs b/crates/ui-egui/src/snap_ui.rs index 99dc614ed9..a1cdf8e366 100644 --- a/crates/ui-egui/src/snap_ui.rs +++ b/crates/ui-egui/src/snap_ui.rs @@ -169,7 +169,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { // outside the selection moves the layer as the Move tool does (#2681). let tool = crate::canvas::event_tool(app, mods); let moves_layer = crate::canvas::command_moves_layer(app, tool, p, mods); - let tol = tolerance(app); + let crop_tol = crate::crop_ui::tolerance(app); let gesture = if let Some(t) = &app.ui.transform { if t.mode == crate::state::TransformMode::Distort { // Distort is freehand corner placement (fitting an image onto a screen, say): guides @@ -189,7 +189,8 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { moving_rect(app, tool).map(|rect| (Gesture::Move { rect }, exclude)) } else if tool == Tool::Crop && (crate::crop_mode::classic(app) || app.crop.default_frame) - && let Some(rect) = app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, tol) == crate::crop_ui::Hit::Inside) + && let Some(rect) = + app.ui.crop_rect.filter(|r| crate::crop_ui::angle(app) == 0.0 && crate::crop_ui::hit(*r, p, crop_tol) == crate::crop_ui::Hit::Inside) { // Inside the untouched default frame draws a new crop (in both modes): snap its corner, not // the old canvas-sized frame's bounds. An edited Classic Mode frame still moves and snaps @@ -198,7 +199,7 @@ fn begin(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) { Some((gesture, Vec::new())) } else if tool == Tool::Crop && (crate::crop_ui::turns_at(app, p) - || app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, tol) == crate::crop_ui::Hit::Inside)) + || app.ui.crop_rect.is_some_and(|r| crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), p, crop_tol) == crate::crop_ui::Hit::Inside)) { // Turning the frame, moving a turned one (its edges don't line up with anything), or in // the default mode moving or turning the image under the box: no snapping. @@ -249,7 +250,7 @@ fn pixel_round(app: &PhotocraftApp, p: [f64; 2]) -> [f64; 2] { } /// Snap one pointer position for the active gesture; records the alignment lines. -fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] { +fn apply(app: &mut PhotocraftApp, p: [f64; 2], mods: egui::Modifiers) -> [f64; 2] { let tol = tolerance(app); let Some(snap) = app.prefs_rt.snap.as_ref() else { return p }; if snap.disabled { @@ -257,7 +258,8 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] { return p; } let (out, lines) = match &snap.gesture { - Gesture::Point | Gesture::Guide => snap.targets.snap_point(p, tol), + Gesture::Point => live_crop_handle(app, p, mods, &snap.targets, tol).unwrap_or_else(|| snap.targets.snap_point(p, tol)), + Gesture::Guide => snap.targets.snap_point(p, tol), Gesture::Move { rect } | Gesture::TransformMove { rect } | Gesture::SelectionMove { rect } => { let d = [p[0] - snap.start[0], p[1] - snap.start[1]]; let moved = [rect[0] + d[0], rect[1] + d[1], rect[2] + d[0], rect[3] + d[1]]; @@ -270,6 +272,66 @@ fn apply(app: &mut PhotocraftApp, p: [f64; 2]) -> [f64; 2] { out } +/// Snap the proposed handle on the image, calculated from the original camera. Snapping the +/// pointer in the moving camera feeds the previous frame's pan back into the resize and makes +/// a stationary pointer oscillate near the canvas edges. +fn live_crop_handle(app: &PhotocraftApp, p: [f64; 2], mods: egui::Modifiers, targets: &SnapTargets, tol: f64) -> Option<([f64; 2], Vec)> { + if app.ui.tool != Tool::Crop { + return None; + } + let crate::crop_ui::CropDrag::Resize { hx, hy, start, rect, view: Some(view) } = app.crop.drag? else { return None }; + let deg = crate::crop_ui::angle(app); + let q = crate::crop_mode::to_press(app, Some(view), p); + let g = crate::crop_mode::LiveResize { rect, deg, hx, hy, start, q, ratio: crate::crop_ui::resize_ratio(app, rect, mods), alt: mods.alt }; + let (frame, _) = crate::crop_mode::resized_frame(g)?; + let at = |r: [f64; 4]| { + let c = crate::crop_ui::center(r); + crate::crop_ui::turn([c[0] + f64::from(hx) * (r[2] - r[0]) / 2.0, c[1] + f64::from(hy) * (r[3] - r[1]) / 2.0], c, deg) + }; + let handle = at(frame); + let (snapped, mut lines) = targets.snap_point(handle, tol); + let mut d = crate::crop_ui::turn([snapped[0] - handle[0], snapped[1] - handle[1]], [0.0, 0.0], -deg); + // An edge handle controls only its own axis, not the midpoint along the other one. + if hx == 0 { + d[0] = 0.0; + } + if hy == 0 { + d[1] = 0.0; + } + if deg == 0.0 { + lines.retain(|line| if line.vertical { hx != 0 } else { hy != 0 }); + } + // Auto Center Preview moves both screen edges. On the image the opposite edge stays put, + // so the grabbed edge travels twice as far as the pointer (once with Alt). + let scale = if mods.alt { 1.0 } else { 2.0 }; + if lines.is_empty() { + return Some((p, lines)); + } + let original = at(rect); + let travel = crate::crop_ui::turn([handle[0] - original[0], handle[1] - original[1]], [0.0, 0.0], -deg); + let mut local = [(travel[0] + d[0]) / scale, (travel[1] + d[1]) / scale]; + if deg == 0.0 + && hx != 0 + && hy != 0 + && let Some(k) = g.ratio + { + // A corner with a ratio has one degree of freedom. Put the other axis on the same + // ratio, rather than letting the raw pointer's unused axis override the snapped edge. + if lines.iter().any(|line| line.vertical) { + local[1] = f64::from(hy) * ((rect[2] - rect[0] + 2.0 * f64::from(hx) * local[0]) / k - (rect[3] - rect[1])) / 2.0; + } else { + local[0] = f64::from(hx) * ((rect[3] - rect[1] + 2.0 * f64::from(hy) * local[1]) * k - (rect[2] - rect[0])) / 2.0; + } + } + let d = crate::crop_ui::turn(local, [0.0, 0.0], deg); + let q = [start[0] + d[0], start[1] + d[1]]; + if let Some((snapped_frame, _)) = crate::crop_mode::resized_frame(crate::crop_mode::LiveResize { q, ..g }) { + let h = at(snapped_frame); + lines.retain(|line| (if line.vertical { h[0] } else { h[1] } - line.pos).abs() < 1e-3); + } + Some((crate::crop_mode::from_press(app, view, q), lines)) +} + /// Snap a tool event's coordinates (called by `canvas::tool_event` before the tools see it). pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> ToolEvent { match ev { @@ -277,8 +339,16 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier begin(app, [x, y], mods); // Moves snap their delta, which is zero at the start: keep the press point. let p = match app.prefs_rt.snap.as_ref().map(|s| &s.gesture) { - Some(Gesture::Point) => { - let q = apply(app, [x, y]); + Some(Gesture::Point) + if !(app.ui.tool == Tool::Crop + && app.ui.crop_rect.is_some_and(|r| { + matches!( + crate::crop_ui::hit_turned(r, crate::crop_ui::angle(app), [x, y], crate::crop_ui::tolerance(app)), + crate::crop_ui::Hit::Handle(..) + ) + })) => + { + let q = apply(app, [x, y], mods); pixel_round(app, q) } _ => [x, y], @@ -292,7 +362,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if let Some(s) = app.prefs_rt.snap.as_mut() { s.disabled = override_held(mods); } - let q = apply(app, [x, y]); + let q = apply(app, [x, y], mods); let p = pixel_round(app, q); ToolEvent::Move { x: p[0], y: p[1], pressure } } @@ -303,7 +373,7 @@ pub fn filter_event(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifier if let Some(s) = app.prefs_rt.snap.as_mut() { s.disabled = override_held(mods); } - let q = apply(app, [x, y]); + let q = apply(app, [x, y], mods); let p = pixel_round(app, q); app.prefs_rt.snap = None; app.prefs_rt.snap_lines.clear(); diff --git a/crates/ui-egui/tests/crop_default_mode.rs b/crates/ui-egui/tests/crop_default_mode.rs index 7792c68b7c..d7867c945c 100644 --- a/crates/ui-egui/tests/crop_default_mode.rs +++ b/crates/ui-egui/tests/crop_default_mode.rs @@ -11,6 +11,7 @@ //! adapter exists (like `crop_beyond_canvas.rs`). use egui::{Key, Modifiers, PointerButton, Pos2, pos2, vec2}; +use egui_kittest::kittest::Queryable; use photocraft_ui_egui::PhotocraftApp; use photocraft_ui_egui::canvas::ViewXform; use photocraft_ui_egui::control::{ControlRequest, handle}; @@ -101,6 +102,71 @@ fn setup() -> Option { Some(h) } +#[test] +fn a_ratio_dropdown_updates_the_preview_and_enter_without_touching_a_handle() { + let Some(mut h) = setup() else { return }; + h.get_by_value("Ratio").click(); + h.run_steps(3); + h.get_by_label("1 : 1 (Square)").click(); + h.run_steps(3); + assert_eq!(h.state().ui.crop_rect, Some([50.0, 0.0, 250.0, 200.0])); + if let Some(dir) = std::env::var_os("CRAFT_UI_VISUAL_FIXTURES") { + let dir = std::path::PathBuf::from(dir); + std::fs::create_dir_all(&dir).unwrap(); + h.render().unwrap().save(dir.join("photocraft-crop-square.png")).unwrap(); + } + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.size, photocraft_doc::Size::new(200, 200)); +} + +#[test] +fn the_swap_button_and_x_apply_the_same_inscribed_ratio() { + let Some(mut h) = setup() else { return }; + let original = [30.0, 20.0, 270.0, 180.0]; + h.state_mut().ui.crop_rect = Some(original); + h.state_mut().ui.tool_options.crop_ratio = "3:2".into(); + h.run_steps(3); + let before = mid(screen_box(&h)); + h.get_by_label("Swaps height and width").click(); + h.run_steps(3); + let button = h.state().ui.crop_rect.unwrap(); + assert_eq!(h.state().ui.tool_options.crop_ratio, "2:3"); + assert!(((button[2] - button[0]) / (button[3] - button[1]) - 2.0 / 3.0).abs() < 1e-10); + assert!(button[0] >= original[0] && button[2] <= original[2] && button[1] >= original[1] && button[3] <= original[3]); + assert!(mid(screen_box(&h)).distance(before) < 0.01); + h.state_mut().ui.crop_rect = Some(original); + h.state_mut().ui.tool_options.crop_ratio = "3:2".into(); + h.run_steps(3); + h.key_press(Key::X); + h.run_steps(3); + assert_eq!(h.state().ui.crop_rect, Some(button)); + assert!(mid(screen_box(&h)).distance(before) < 0.01); +} + +#[test] +fn a_resize_renders_the_frame_and_image_with_the_same_camera() { + let Some(mut h) = setup() else { return }; + let box0 = screen_box(&h); + let c = mid(box0); + let right = pos2(box0[1].x, c.y); + drag(&mut h, right, right - vec2(48.0, 0.0), 6, |h, i| { + let img = h.render().expect("render"); + let b = screen_box(h); + // The left edge also moves inward with Auto Center Preview. Sample either side + // away from the handles and the red patch: white inside, dimmed white outside. + let y = c.y + 70.0; + for x in [b[0].x - 5.0, b[1].x + 5.0] { + let px = img.get_pixel(x.round() as u32, y.round() as u32); + assert!(px[0] < 230 && px[1] < 230 && px[2] < 230, "frame {i}, outside at {x}: {px:?}"); + } + for x in [b[0].x + 5.0, b[1].x - 5.0] { + let px = img.get_pixel(x.round() as u32, y.round() as u32); + assert!(px[0] > 245 && px[1] > 245 && px[2] > 245, "frame {i}, inside at {x}: {px:?}"); + } + }); +} + #[test] fn dragging_inside_moves_the_image_and_the_box_stays_centred() { let Some(mut h) = setup() else { return }; diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 27fe0bf318..b078fd3f86 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity: tools, handles, modifiers and feel -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (first version: tools, transform, nudging, snapping, modifiers, navigation, shortcuts, panels audited from source and open issues) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Crop resize stability, immediate ratio previews, and options-bar overflow regression coverage) · **Target:** Adobe Photoshop 2026 How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation, @@ -129,6 +129,9 @@ Triangle and Curvature Pen (minus legacy Rounded Rectangle and Targeted Adjustme |---|---|---| | Drag outside rotates (⇧ 15°), angle readout; ↵ rotates and crops in one undo step | done | TOOL-214-18 | | Straighten button and ⌘-drag line | done | TOOL-214-21 | +| Default-mode resize snaps handles without camera feedback; image and frame use the same camera in each rendered frame | done | `crop_mode.rs::a_live_resize_snaps_the_handle_without_feedback_from_the_camera`, `tests/crop_default_mode.rs::a_resize_renders_the_frame_and_image_with_the_same_camera` (2026-10-10) | +| Ratio presets and W × H changes immediately fit the current frame around its centre; Swap button and X share the fitted ratio, Enter needs no resize | done | `crop_ui.rs::choosing_a_ratio_fits_and_commits_without_a_resize`, `crop_size.rs::choosing_a_size_with_the_canvas_ratio_commits_without_a_resize`, `tests/crop_default_mode.rs` (2026-10-10) | +| Roomy Crop options bar does not scroll; narrow tool bars retain horizontal scrolling | done | `panels.rs::a_wide_crop_options_bar_does_not_scroll`, `panels.rs::narrow_tool_options_can_scroll_to_the_last_control` (2026-10-10) | | Overlays (thirds, grid, diagonal, triangle, golden ratio/spiral), O / ⇧O | done | TOOL-214-20 | | Crop shield, Show Cropped Area (H) | done | TOOL-214-22 | | Default mode: the image turns and moves behind an upright box; Auto Center Preview; Use Classic Mode | done | TOOL-214-23 | @@ -204,3 +207,4 @@ Paragraph; the rest open as in-app floating windows. | Date | Change | Summary | |---|---|---| | 2026-10-10 | major | First version, from a source audit against Photoshop 2026 27.11.0's shortcuts file and the open issues | +| 2026-10-10 | minor | Fixed Crop live resize snapping feedback and outdated-camera rendering, applied ratios immediately to centred inscribed previews, and removed two-point options-bar overflow; added pointer, rendering, dropdown/Enter, Swap/X and scrolling regressions | From aa509ca9666aec0420a883e4efaf17c219c2d218 Mon Sep 17 00:00:00 2001 From: Fabio Lussi Date: Sun, 11 Oct 2026 11:55:39 +0200 Subject: [PATCH 3/5] UI fonts: lazy fallback for Thai, Arabic, Indic and other scripts (#2275) (#2758) Layer names (and any other UI text) in scripts the bundled Inter lacks showed missing-glyph boxes even when the canvas found a fallback font. The lazy UI loader only knew CJK plus a short hard-coded list of Thai font paths, so any other script, or a Thai font at another path, never got a fallback. photocraft_text::scripts classifies 20 scripts and picks candidate files by name (Noto, Windows, macOS and common Linux families) from a listing of the platform font directories, made once per process on first need. The UI loader tries a script once when one of its characters is missing, reads at most a few candidates, and registers the first face whose cmap really maps the character. Latin text loads nothing; the web build has no candidates and does nothing. Co-authored-by: Fabio Lussi <198260595+itrycodinganditsbad@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- crates/text/src/fonts.rs | 4 +- crates/text/src/lib.rs | 1 + crates/text/src/scripts.rs | 366 +++++++++++++++++++++++++++++ crates/ui-egui/src/cjk_fonts.rs | 392 +++++++++++++++++++++++--------- crates/ui-egui/src/theme.rs | 4 +- 5 files changed, 654 insertions(+), 113 deletions(-) create mode 100644 crates/text/src/scripts.rs diff --git a/crates/text/src/fonts.rs b/crates/text/src/fonts.rs index 0db728017e..0323533074 100644 --- a/crates/text/src/fonts.rs +++ b/crates/text/src/fonts.rs @@ -499,7 +499,7 @@ pub fn guess_from_postscript(ps: &str) -> ResolvedFont { } #[cfg(not(target_arch = "wasm32"))] -fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec) { +pub(crate) fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec) { let Ok(rd) = std::fs::read_dir(dir) else { return; }; @@ -516,7 +516,7 @@ fn collect_font_files(dir: &std::path::Path, depth: u32, out: &mut Vec Vec { +pub(crate) fn system_font_dirs() -> Vec { use std::path::PathBuf; let home = std::env::var_os("HOME").map(PathBuf::from); let mut v = Vec::new(); diff --git a/crates/text/src/lib.rs b/crates/text/src/lib.rs index a63b3d9c06..173b1c84c1 100644 --- a/crates/text/src/lib.rs +++ b/crates/text/src/lib.rs @@ -26,6 +26,7 @@ pub mod psd; pub mod psd_styles; pub mod raster; pub mod render; +pub mod scripts; pub mod served; pub mod spell; pub mod warp; diff --git a/crates/text/src/scripts.rs b/crates/text/src/scripts.rs new file mode 100644 index 0000000000..b6e0aae74f --- /dev/null +++ b/crates/text/src/scripts.rs @@ -0,0 +1,366 @@ +//! UI fallback fonts for the non-CJK scripts the bundled Inter / JetBrains Mono don't draw +//! (Thai, Arabic, Hebrew, the Indic scripts, ...): which characters belong to which script, and +//! which installed font files to try for it. +//! +//! Candidates come from the file names in the platform font directories (the same directories +//! [`crate::fonts::FontDb`] scans), listed once per process and only when first asked for, so +//! nothing is read at startup and no path is hard-coded per distribution. Noto fonts are matched +//! by their family-derived file names (`NotoSansThai-Regular.ttf`, `NotoSansThai[wght].ttf`), +//! platform fonts by their known file names (Leelawadee UI, Nirmala UI, Segoe UI, Geeza Pro, +//! Kohinoor, DejaVu Sans, Lohit, ...). A file name is only a hint: callers check that a face +//! really maps the character ([`covering_face`]) before using it. CJK has its own, +//! locale-ordered lists ([`crate::cjk`]). + +/// A script that needs a UI fallback font. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Script { + Thai, + Lao, + Khmer, + Myanmar, + Tibetan, + Arabic, + Hebrew, + Armenian, + Georgian, + Ethiopic, + Devanagari, + Bengali, + Gurmukhi, + Gujarati, + Oriya, + Tamil, + Telugu, + Kannada, + Malayalam, + Sinhala, +} + +impl Script { + pub const ALL: [Script; 20] = [ + Script::Thai, + Script::Lao, + Script::Khmer, + Script::Myanmar, + Script::Tibetan, + Script::Arabic, + Script::Hebrew, + Script::Armenian, + Script::Georgian, + Script::Ethiopic, + Script::Devanagari, + Script::Bengali, + Script::Gurmukhi, + Script::Gujarati, + Script::Oriya, + Script::Tamil, + Script::Telugu, + Script::Kannada, + Script::Malayalam, + Script::Sinhala, + ]; + + /// Font file names for this script, most preferred first: lowercase, without extension, + /// spaces, underscores or style suffix (`NotoSansThai-Bold.ttf` and `NotoSansThai[wght].ttf` + /// are both `notosansthai`). Noto first (the usual Linux font), then Windows, macOS and + /// other Linux families. + fn file_names(self) -> &'static [&'static str] { + use Script::*; + match self { + Thai => &[ + "notosansthai", + "notosansthailooped", + "notosansthaiui", + "notoserifthai", + "leelawui", + "leelawad", + "tahoma", + "thonburi", + "sukhumvitset", + "ayuthaya", + "loma", + "garuda", + "waree", + "kinnari", + "norasi", + ], + Lao => &["notosanslao", "notosanslaoui", "notoseriflao", "leelawui", "laosangammn", "laomn", "phetsarathot", "saysetthaot"], + Khmer => &["notosanskhmer", "notosanskhmerui", "notoserifkhmer", "leelawui", "daunpenh", "khmersangammn", "khmermn", "khmeros", "khmerossys"], + Myanmar => &["notosansmyanmar", "notosansmyanmarui", "notoserifmyanmar", "mmrtext", "myanmarsangammn", "myanmarmn", "padauk"], + Tibetan => &["notoseriftibetan", "himalaya", "kailasa", "jomolhari", "tibetanmachineuni"], + Arabic => &[ + "notosansarabic", + "notosansarabicui", + "notonaskharabic", + "notonaskharabicui", + "notokufiarabic", + "segoeui", + "tahoma", + "geezapro", + "sfarabic", + "dejavusans", + "kacstone", + "kacstbook", + "amiri", + "arial", + ], + Hebrew => &["notosanshebrew", "notoserifhebrew", "segoeui", "arialhb", "sfhebrew", "dejavusans", "arial", "freesans", "culmus"], + Armenian => &["notosansarmenian", "notoserifarmenian", "segoeui", "sylfaen", "mshtakan", "dejavusans", "freesans"], + Georgian => &["notosansgeorgian", "notoserifgeorgian", "segoeui", "sylfaen", "dejavusans", "freesans"], + Ethiopic => &["notosansethiopic", "notoserifethiopic", "ebrima", "kefa", "abyssinicasil"], + Devanagari => &[ + "notosansdevanagari", + "notosansdevanagariui", + "notoserifdevanagari", + "nirmala", + "mangal", + "kohinoor", + "kohinoordevanagari", + "itfdevanagari", + "devanagarimt", + "devanagarisangammn", + "lohitdevanagari", + "lohit-devanagari", + "gargi", + "freesans", + ], + Bengali => &[ + "notosansbengali", + "notosansbengaliui", + "notoserifbengali", + "nirmala", + "vrinda", + "kohinoorbangla", + "banglasangammn", + "banglamn", + "lohitbengali", + "lohit-bengali", + "lohit-assamese", + ], + Gurmukhi => &[ + "notosansgurmukhi", + "notosansgurmukhiui", + "notoserifgurmukhi", + "nirmala", + "raavi", + "gurmukhisangammn", + "gurmukhimn", + "lohit-gurmukhi", + "lohit-punjabi", + ], + Gujarati => &[ + "notosansgujarati", + "notosansgujaratiui", + "notoserifgujarati", + "nirmala", + "shruti", + "kohinoorgujarati", + "gujaratisangammn", + "gujaratimt", + "lohit-gujarati", + ], + Oriya => &["notosansoriya", "notosansoriyaui", "notoseriforiya", "nirmala", "kalinga", "oriyasangammn", "oriyamn", "lohit-odia", "lohit-oriya"], + Tamil => &["notosanstamil", "notosanstamilui", "notoseriftamil", "nirmala", "latha", "tamilsangammn", "tamilmn", "lohit-tamil"], + Telugu => { + &["notosanstelugu", "notosansteluguui", "notoseriftelugu", "nirmala", "gautami", "kohinoortelugu", "telugusangammn", "telugumn", "lohit-telugu"] + } + Kannada => &["notosanskannada", "notosanskannadaui", "notoserifkannada", "nirmala", "tunga", "kannadasangammn", "kannadamn", "lohit-kannada"], + Malayalam => { + &["notosansmalayalam", "notosansmalayalamui", "notoserifmalayalam", "nirmala", "kartika", "malayalamsangammn", "malayalammn", "lohit-malayalam"] + } + Sinhala => &["notosanssinhala", "notosanssinhalaui", "notoserifsinhala", "nirmala", "iskpota", "sinhalasangammn", "sinhalamn", "lklug"], + } + } +} + +/// The script of a character that needs a non-CJK fallback font, or `None`. +pub fn classify(c: char) -> Option