From 1be942d7fc435d6a517724f8dc62aabc54018044 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 16:16:42 -0800 Subject: [PATCH 01/19] Dimension tool: a drag from a dimension already drawn moves it With no points or lines picked, a press within 8 pixels of what a visible, unlocked dimension draws (its lines, arrowheads and label), where it is the topmost object that can be edited, followed by a drag moves that dimension as one undo step. A segment of the art as near the press as the dimension's lines and label, or nearer, takes the press instead, and a click there without a drag still picks a point. The part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center as the pointer turns, or toward the pointer when grabbed at the center. The dimension keeps what it measures and its link to the art. With Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line, as when it is placed, and of two lines on one level the one nearer the pointer along it wins. Isolation mode, clipping masks and locked artboards apply as they do to a click; with a part of a dimension isolated, the dimension is not dragged. A dimension that a geometry effect on it, on one of its parts or on a group around it draws elsewhere is not dragged, except in Outline view and on a layer whose Preview is off. dimension.update takes `at: [x,y]`, which puts a linear dimension's line through the point, gives an angular arc a radius of the point's distance from the vertex (at least 12 pt), or turns a radius or diameter line toward it. With Real-time Drawing off, a dimension.update preview that names its dimensions outlines only those dimensions. A dimension pasted into a document that had none now marks the document as holding dimensions (Document::insert), so the Dimension tool drags it like one drawn there and edits refresh it. Opening a native file sets the flag from the objects it holds, which covers files saved after such a paste. Docs: docs/dimensions.md, docs/target-app-parity.md. --- crates/doc/src/document.rs | 8 +- crates/engine/src/cmd/dimension.rs | 7 +- crates/engine/src/tooling.rs | 22 ++- crates/engine/tests/it/dimensions.rs | 278 +++++++++++++++++++++++++++ crates/format/src/lib.rs | 5 + crates/tools/src/dimension.rs | 194 ++++++++++++++++++- docs/dimensions.md | 26 ++- docs/target-app-parity.md | 1 + 8 files changed, 520 insertions(+), 21 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 608902756b..388c51abfb 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -551,13 +551,19 @@ impl Document { } /// Insert `node` into `parent` at `index` (clamped; `usize::MAX` = top). In a layer, art goes - /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). + /// below the layer's ruler guides and a ruler guide among them ([`Node::insert_index`]). A + /// node that is or holds a dimension (a pasted one) sets [`Document::dimensions`]. pub fn insert(&mut self, parent: Option, index: usize, node: Node) -> Result { + fn holds_dimension(n: &Node) -> bool { + n.extras().dimension.is_some() || n.children().into_iter().flatten().any(|c| holds_dimension(c)) + } let id = node.id; self.check_ruler_guide_place(&node, parent)?; + let dimension = !self.dimensions && holds_dimension(&node); let ch = self.children_mut(parent)?; let i = Node::insert_index(ch, index, &node); ch.insert(i, Arc::new(node)); + self.dimensions |= dimension; Ok(id) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index e38f8f99bb..9f631aafd2 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Update Dimensions", [], None, - "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create)} restyle, turn or move existing dimensions → {ids}", + "{ids?: [dimension ids] (default selection), options?: dimension options, orientation?: aligned|horizontal|vertical (linear dimensions only; the line stays on the side of the points it was on), offset?: pt (as in dimension.create), at?: [x,y] (after offset: puts a linear dimension's line through this point, gives an angular dimension's arc a radius of the point's distance from the vertex, at least 12 pt, or turns a radius or diameter line toward it; what the dimension measures does not change)} restyle, turn or move existing dimensions → {ids}", has_doc, update ), @@ -159,6 +159,7 @@ fn update(s: &mut Session, p: &Value) -> Result { return Err(error("Select dimensions to update")); } let o = if p.get("options").is_some() { Some(options(s, p)?) } else { None }; + let at = if p.get("at").is_some() { Some(point(p, "at")?) } else { None }; // Every dimension is checked before anything changes, and an update that changes none of // them records no undo step. let mut next = Vec::with_capacity(ids.len()); @@ -178,6 +179,10 @@ fn update(s: &mut Session, p: &Value) -> Result { } dim.offset = distance(p, dim.offset)?; dim.resolve(doc).map_err(error)?; + if let Some(at) = at { + dim.place(at); + dim.resolve(doc).map_err(error)?; + } if dim != old { next.push((*id, dim)); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..9edfa98661 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1,7 +1,7 @@ //! Hosting the active tool: pointer/key events → actions → commands. use serde_json::{Map, Value}; -use vectorcraft_doc::Selection; +use vectorcraft_doc::{NodeId, Selection}; use vectorcraft_geom::Point; use vectorcraft_tools::distort::perspective::widget::WidgetPlace; use vectorcraft_tools::draw2::FEEDBACK; @@ -1754,7 +1754,7 @@ impl Session { (st.doc.clone(), st.selection.clone(), st.revision, self.pending_paint.clone(), interaction_fields) }; let (overlays, transform_box) = if self.preview(cmd, p).is_ok() { - let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection)).unwrap_or_default(); + let overlays = self.active().map(|st| outlines_for_selection(&st.doc, &st.selection, cmd, p)).unwrap_or_default(); let (objects, color) = self .active() .map(|st| (st.selection.objects.clone(), st.selection.objects.first().map(|id| st.doc.layer_color(*id)))) @@ -1795,11 +1795,17 @@ const FEEDBACK_MAX_POINTS: usize = 100_000; /// The outlines of every selected object, a group's members each with their own, or the selection's /// bounds when the outlines' points and the objects evaluated to make them come to more than -/// [`FEEDBACK_MAX_POINTS`]. -fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection) -> Vec { - let nodes = selection.objects.iter().filter_map(|&id| doc.node(id)); - let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS).unwrap_or_else(|| { - doc.bounds_of(&selection.objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect() - }); +/// [`FEEDBACK_MAX_POINTS`]. A `dimension.update` preview (`cmd`, `p`) that names its dimensions, +/// as the Dimension tool sends for a dimension it drags, outlines those dimensions instead. +fn outlines_for_selection(doc: &vectorcraft_doc::Document, selection: &Selection, cmd: &str, p: &Value) -> Vec { + let named: Vec = if cmd == "dimension.update" { + p.get("ids").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).map(NodeId).collect() + } else { + vec![] + }; + let objects = if named.is_empty() { &selection.objects } else { &named }; + let nodes = objects.iter().filter_map(|&id| doc.node(id)); + let outlines = vectorcraft_render::drawn_outlines(doc, nodes, FEEDBACK_MAX_POINTS) + .unwrap_or_else(|| doc.bounds_of(objects, true).map(|b| vectorcraft_geom::shapes::rectangle(b).to_bezpath()).into_iter().collect()); outlines.into_iter().map(|path| Overlay::Path { path, color: FEEDBACK, width: 1.0, dashed: false }).collect() } diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 30f3ce2665..c92390feec 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2115,6 +2115,284 @@ fn a_dimension_line_on_another_level_shows_one_guide_across_both() { assert_eq!(recipe(&s, id).line_ends(), (pt(200.0, 170.0), pt(300.0, 170.0))); } +/// A drag with the Dimension tool from a dimension already drawn moves its line as far across as +/// the pointer moved, keeps what it measures and its link to the art, and is one undo step. A +/// click on its line does not move it, and neither does Escape during the drag. +#[test] +fn dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let (count, label) = (s.doc().unwrap().doc.node_count(), text(&s, first)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Dragged up and to the side: the line goes up as far as the pointer, and stays over the + // points it measures. + drag(&mut s, (150.0, 170.0), (180.0, 130.0)); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + assert_eq!((recipe(&s, first).a, recipe(&s, first).b), (pt(100.0, 200.0), pt(200.0, 200.0))); + assert_eq!((s.doc().unwrap().doc.node_count(), text(&s, first)), (count, label)); + // One undo step puts it back. + run(&mut s, "edit.undo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + run(&mut s, "edit.redo", json!({})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Still linked: moving the art moves its points, and the line keeps its distance from them. + let art = s.doc().unwrap().doc.layers[0].children().unwrap()[0].id.0; + run(&mut s, "select.set", json!({"ids":[art]})); + run(&mut s, "object.move", json!({"dx":0,"dy":10})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 140.0), pt(200.0, 140.0))); + run(&mut s, "object.move", json!({"dx":0,"dy":-10})); + run(&mut s, "select.none", json!({})); + run(&mut s, "dimension.update", json!({"ids":[first],"at":[150,170]})); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A click on the line picks a point there and leaves the dimension where it is. + linear_click(&mut s, plain, 150.0, 170.0); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // Escape during the drag leaves it where it was. + ev(&mut s, PointerKind::Down, 150.0, 170.0); + ev(&mut s, PointerKind::Drag, 150.0, 120.0); + assert!(s.in_interaction()); + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + ev(&mut s, PointerKind::Up, 150.0, 120.0); + assert!(!s.in_interaction()); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + // A locked dimension is not moved: the drag from its line drags out nothing either. + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "object.lock", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + assert_eq!(s.doc().unwrap().doc.node_count(), count); +} + +/// A dimension moved with the Dimension tool lands on the level of a parallel dimension line +/// within the Smart Guides snapping tolerance, and its own line before the drag is not a level. +#[test] +fn a_dimension_moved_beside_another_lands_on_its_level() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + linear_click(&mut s, plain, 200.0, 200.0); + linear_click(&mut s, plain, 300.0, 200.0); + linear_click(&mut s, plain, 250.0, 150.0); + let second = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 150.0), pt(300.0, 150.0))); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // 3.5 points off its own level, with no other level there: where the pointer puts it. + drag(&mut s, (150.0, 170.0), (150.0, 166.5)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 166.5), pt(200.0, 166.5))); + // 2.5 points below the first line's new level: on it. + drag(&mut s, (250.0, 150.0), (250.0, 169.0)); + assert_eq!(recipe(&s, second).line_ends(), (pt(200.0, 166.5), pt(300.0, 166.5))); +} + +/// `dimension.update` with `at` puts a linear dimension's line, an angular dimension's arc or a +/// radius line through the point, and keeps what each measures; a bad `at` changes nothing. +#[test] +fn dimension_update_at_moves_the_line_through_the_point() { + let mut s = session(); + let line = edge(&mut s); + let linear = dim(&mut s, line); + let label = text(&s, linear); + run(&mut s, "dimension.update", json!({"ids":[linear],"at":[130,50]})); + let d = recipe(&s, linear); + assert!((d.line_ends().0.y - 50.0).abs() < 1e-9 && (d.line_ends().1.y - 50.0).abs() < 1e-9, "{:?}", d.line_ends()); + assert_eq!(text(&s, linear), label); + let angular = run(&mut s, "dimension.create", json!({"mode":"angular","a":[100,0],"vertex":[0,0],"b":[0,100]}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[angular],"at":[60,0]})); + assert!((recipe(&s, angular).offset - 60.0).abs() < 1e-9); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let radius = run(&mut s, "dimension.create", json!({"mode":"radius","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[radius],"at":[172,400]})); + let d = recipe(&s, radius); + assert!(d.b.distance(vectorcraft_geom::Point::new(172.0, 244.0)) < 1e-6, "turned toward the point: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + let before = recipe(&s, linear); + for bad in [json!([1]), json!("x"), json!([0, 1e12])] { + assert!(s.execute("dimension.update", &json!({"ids":[linear],"at":bad})).is_err(), "{bad}"); + assert_eq!(recipe(&s, linear), before); + } +} + +/// A dimension dragged with the Dimension tool follows the part grabbed: a diameter grabbed on its +/// far half turns that half toward the pointer, and an angular arc grabbed away from its middle +/// grows by as much as the pointer moved away from the vertex. +#[test] +fn a_dragged_dimension_follows_the_part_grabbed() { + let plain = ViewInfo::default(); + let mut s = session(); + let circle = run(&mut s, "shape.ellipse", json!({"x":100,"y":100,"width":144,"height":144}))["id"].as_u64().unwrap(); + let diameter = run(&mut s, "dimension.create", json!({"mode":"diameter","source":{"kind":"circle","node":circle}}))["id"].as_u64().unwrap(); + run(&mut s, "dimension.update", json!({"ids":[diameter],"at":[244,172]})); + let angular = + run(&mut s, "dimension.create", json!({"mode":"angular","a":[500,400],"vertex":[400,400],"b":[400,500],"offset":60}))["id"].as_u64().unwrap(); + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // Grabbed left of the center and dragged up: the left half goes up, the right half down. + drag(&mut s, (120.0, 172.0), (120.0, 152.0)); + let d = recipe(&s, diameter); + assert!(d.b.y > 172.0 + 1.0, "the half not grabbed turns away from the pointer: {:?}", d.b); + assert!((d.a.distance(d.b) - 72.0).abs() < 1e-6, "the radius stays"); + // Grabbed at the center: it turns toward the pointer. + drag(&mut s, (172.0, 172.0), (172.0, 100.0)); + assert!(recipe(&s, diameter).b.distance(vectorcraft_geom::Point::new(172.0, 100.0)) < 1e-6, "{:?}", recipe(&s, diameter).b); + // Grabbed 10° from the arc's start and dragged 20 points straight away from the vertex. + let (sin, cos) = 10f64.to_radians().sin_cos(); + drag(&mut s, (400.0 + 60.0 * cos, 400.0 + 60.0 * sin), (400.0 + 80.0 * cos, 400.0 + 80.0 * sin)); + assert!((recipe(&s, angular).offset - 80.0).abs() < 1e-6, "the arc's radius: {}", recipe(&s, angular).offset); +} + +/// The Dimension tool takes a drag only from a dimension the canvas hits: one painted wider than +/// the reach is taken by its stroke, while one outside isolation mode, around an isolated part of +/// it, clipped away where the press is or drawn elsewhere by a geometry effect stays put. With +/// Real-time Drawing off the dimension being dragged is outlined. +#[test] +fn a_dimension_is_dragged_only_where_the_canvas_hits_it() { + use vectorcraft_engine::tools::Overlay; + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let at_170 = (pt(100.0, 170.0), pt(200.0, 170.0)); + let drag = |s: &mut Session, from: (f64, f64), to: (f64, f64)| { + for (kind, (x, y)) in [(PointerKind::Move, from), (PointerKind::Down, from), (PointerKind::Drag, to), (PointerKind::Up, to)] { + s.pointer(&PointerEvent::new(kind, x, y), plain).unwrap(); + } + }; + // A 30-point line: a press 13 points from its middle is on its stroke. + let (mut s, first) = level_start(plain); + run(&mut s, "dimension.update", json!({"ids":[first],"options":{"lineWeight":30}})); + drag(&mut s, (115.0, 183.0), (115.0, 143.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // Outside the isolated group: not moved. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":50,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[rect]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In a clipping mask that leaves its right half out: not taken there, taken on its left half. + let (mut s, first) = level_start(plain); + let mask = run(&mut s, "shape.rectangle", json!({"x":90,"y":140,"width":50,"height":90}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, mask]})); + run(&mut s, "object.clippingMask.make", json!({})); + run(&mut s, "select.none", json!({})); + let count = s.doc().unwrap().doc.node_count(); + drag(&mut s, (180.0, 170.0), (180.0, 130.0)); + assert_eq!((recipe(&s, first).line_ends(), s.doc().unwrap().doc.node_count()), (at_170, count)); + // That press picked a point, as a click there does: Escape drops it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + drag(&mut s, (120.0, 170.0), (120.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // In a group whose Transform effect draws it 50 points lower: not taken where it is drawn. + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[group],"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // In Outline view the canvas draws no effects: taken where its recipe puts it. + s.tool_key(ToolKey::Escape, Mods::default(), plain).unwrap(); + let outline = ViewInfo { outline: true, ..plain }; + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), outline).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); + // A Transform effect on its parts draws them 50 points lower: not taken where they are drawn. + let (mut s, first) = level_start(plain); + let parts: Vec = s.doc().unwrap().doc.node(NodeId(first)).unwrap().children().unwrap().iter().map(|c| c.id.0).collect(); + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":parts,"params":{"moveV":50}})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 220.0), (150.0, 260.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // With one of its parts isolated, the dimension around it is outside the editing scope. + let (mut s, first) = level_start(plain); + let part = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The dimension line, which the press below lands on. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x0 < 150.0 && r.x1 > 150.0 && r.y0 < 171.0 && r.y1 > 169.0)); + line.unwrap().id.0 + }; + run(&mut s, "object.isolate", json!({"id": part})); + run(&mut s, "select.none", json!({})); + drag(&mut s, (150.0, 170.0), (150.0, 130.0)); + assert_eq!(recipe(&s, first).line_ends(), at_170); + // Real-time Drawing off: the dimension is outlined where the drag puts it, and other selected + // art, which the drag does not move, is not. + let (mut s, first) = level_start(plain); + let rect = run(&mut s, "shape.rectangle", json!({"x":400,"y":400,"width":50,"height":50}))["id"].as_u64().unwrap(); + run(&mut s, "select.set", json!({"ids":[first, rect]})); + run(&mut s, "prefs.set", json!({"key": "realTimeDrawing", "value": false})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 110.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + let boxes: Vec = s + .overlays(plain) + .into_iter() + .filter_map(|o| if let Overlay::Path { path, .. } = o { Some(vectorcraft_geom::kurbo::Shape::bounding_box(&path)) } else { None }) + .collect(); + assert!(boxes.iter().any(|r| r.y0 < 111.0 && r.y1 > 109.0 && r.width() >= 99.0), "the dragged dimension is outlined at its new place"); + assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}"); +} + +/// A dimension pasted into a document that had none is dragged with the Dimension tool like one +/// drawn there. +#[test] +fn a_dimension_pasted_into_another_document_is_dragged() { + let plain = ViewInfo::default(); + let (mut s, first) = level_start(plain); + run(&mut s, "select.set", json!({"ids":[first]})); + run(&mut s, "edit.copy", json!({})); + run(&mut s, "file.new", json!({"width": 612, "height": 792})); + run(&mut s, "edit.paste", json!({})); + let pasted = s.doc().unwrap().selection.objects[0].0; + run(&mut s, "select.none", json!({})); + s.select_tool("dimension", plain).unwrap(); + let (a, b) = recipe(&s, pasted).line_ends(); + let mid = a.midpoint(b); + for (kind, y) in [(PointerKind::Move, mid.y), (PointerKind::Down, mid.y), (PointerKind::Drag, mid.y - 40.0), (PointerKind::Up, mid.y - 40.0)] { + s.pointer(&PointerEvent::new(kind, mid.x, y), plain).unwrap(); + } + let (a2, b2) = recipe(&s, pasted).line_ends(); + assert!((a2.y - (a.y - 40.0)).abs() < 1e-6 && (b2.y - (b.y - 40.0)).abs() < 1e-6, "{:?} → {:?}", (a, b), (a2, b2)); +} + +/// A file that holds a dimension but was saved without the document's dimension flag (as one saved +/// after a dimension was pasted into a document that had none) opens with its dimension dragged +/// by the Dimension tool. +#[test] +fn a_dimension_in_a_file_saved_without_the_flag_is_dragged() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (s, first) = level_start(plain); + let mut doc = s.doc().unwrap().doc.as_ref().clone(); + doc.dimensions = false; + let mut reopened = Session::new(); + reopened.add_document(vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(), None); + reopened.select_tool("dimension", plain).unwrap(); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + reopened.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&reopened, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + /// A second dimension of the same two points as a dimension already drawn lands on its level too. /// Off every level, a pointer moved in small steps while it is placed puts the line at each step, /// with no pull from the preview of the dimension itself. diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index a8c7358aa7..430769069d 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -637,6 +637,11 @@ fn load_unpacked(file: unpack::Unpacked<'_>, max_nodes: usize, max_values: usize // Untrusted: the type's sizes, leading, baseline shifts and scales, its indents and paragraph // spacing, and its tab stops, each within its range (after the depth limit: the walk recurses). doc.keep_type_values_in_range(); + // Untrusted, and unset in a file saved after a dimension was pasted into a document that had + // none: the flag is set when some object is a dimension (after the depth limit too). + let mut dimensions = false; + doc.walk(|n| dimensions |= n.extras().dimension.is_some()); + doc.dimensions = dimensions; // Untrusted: ruby ranges over the type's text, clamped to it (after the depth limit too). doc.fix_ruby(); // Untrusted: the raster effects resolution, within 1 to 2400 ppi (72 when it isn't finite). diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index dffe13a378..081703bb13 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -106,6 +106,12 @@ pub struct DimensionTool { /// The document's next object id at the dimension's first preview: the id its preview takes /// (`dimension.create` gives the dimension the next id). The preview is not a level. preview_id: u64, + /// The dimension drawn already under the press under way, when a drag from there moves it + /// ([`dimension_under`]). + grab: Option, + /// While a dimension drawn already is dragged: its id, where the press was and its recipe + /// then. `pending` holds it where the pointer puts it. + moving: Option<(NodeId, Point, Dimension)>, } /// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is @@ -536,6 +542,107 @@ fn on_dimensions(cx: &ToolContext, p: Point) -> Option<(Point, bool)> { best.end.map(|(_, q)| (q, true)).or_else(|| best.line.map(|(_, q)| (q, false))) } +/// The dimension drawn already that a drag from `p` moves, and how far `p` lies from its lines +/// and label (0 inside the label's bounds): the dimension holding the topmost object the canvas +/// hits within 8 pixels of `p`, when it can be edited. The hit takes in what the dimension paints +/// (stroke widths and arrowheads), the clipping masks over it and isolation mode. A dimension that +/// a geometry effect on it, on a part of it or on a group around it draws elsewhere is not taken +/// where effects are drawn. +fn dimension_under(cx: &ToolContext, p: Point) -> Option<(NodeId, f64)> { + use vectorcraft_geom::kurbo::ParamCurveNearest; + fn art(n: &Node, p: Point, budget: &mut usize, near: &mut f64) { + if *budget == 0 || !n.visible { + return; + } + *budget -= 1; + if let NodeKind::Text(_) = &n.kind + && let Some(r) = n.geometric_bounds() + { + let (dx, dy) = ((r.x0 - p.x).max(p.x - r.x1).max(0.0), (r.y0 - p.y).max(p.y - r.y1).max(0.0)); + *near = near.min(dx.hypot(dy)); + } + if let Some(path) = n.path_data() { + for sp in &path.subpaths { + for i in 0..sp.segment_count() { + if *budget == 0 { + return; + } + *budget -= 1; + let d = sp.segment(i).nearest(p, 1e-4).distance_sq.sqrt(); + if d.is_finite() { + *near = near.min(d); + } + } + } + } + for c in n.children().into_iter().flatten() { + art(c, p, budget, near); + } + } + if !cx.doc.dimensions { + return None; + } + let opt = vectorcraft_doc::hit::HitOptions { tol: cx.tol(8.0), ..cx.hit_options() }; + let hit = vectorcraft_doc::hit::hit_test(cx.doc, p, opt)?; + let chain: Vec = hit.ancestry.iter().copied().chain([hit.leaf]).collect(); + // The innermost dimension holding the object hit: the one that draws it. + let at = chain.iter().rposition(|id| cx.doc.node(*id).is_some_and(|n| n.extras().dimension.is_some()))?; + let id = *chain.get(at)?; + // In isolation mode only a dimension at or inside the isolated object is moved: one around an + // isolated part of it is outside the editing scope. + let scope_at = opt.scope.and_then(|s| chain.iter().position(|a| *a == s)); + if scope_at.is_some_and(|i| i > at) { + return None; + } + // Where a geometry effect on the dimension, on a part of it or on a group around it draws it is + // not where its recipe puts it, so a drag there could not follow the pointer. In outline, and + // below a layer whose Preview is off, the canvas draws no effects and the recipe is what it + // hits. + let nodes: Vec<&Node> = chain.iter().filter_map(|id| cx.doc.node(*id)).collect(); + let below = scope_at.map_or(0, |i| i + 1); + let outline = opt.outline || nodes.iter().skip(below).any(|n| matches!(n.kind, NodeKind::Layer { preview: false, .. })); + let displaced = nodes.iter().enumerate().any(|(i, n)| { + vectorcraft_effects::has_geometry(&n.appearance.effects) + || (i >= at && n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects()))) + }); + if !outline && displaced { + return None; + } + let n = cx.doc.node(id).filter(|_| cx.doc.is_editable(id))?; + let (mut budget, mut near) = (20_000usize, f64::INFINITY); + art(n, p, &mut budget, &mut near); + Some((id, near)) +} + +/// Where [`Dimension::place`] puts dimension `d`, grabbed at `start`, for the pointer at `p`: the +/// line of a linear dimension moves as far across as the pointer moved, the arc of an angular one +/// grows or shrinks by as much as the pointer moved away from or toward the vertex, and a radius +/// or diameter line turns about the center by the angle the pointer turned through, so the part +/// grabbed stays under the pointer wherever it was grabbed. +fn grabbed_to(d: &Dimension, start: Point, p: Point) -> Point { + let handle = d.handle(); + match d.mode { + DimensionMode::Linear => handle + (p - start), + DimensionMode::Angular => { + let out = handle - d.vertex; + let r = out.hypot() + p.distance(d.vertex) - start.distance(d.vertex); + if out.hypot() > 1e-9 { d.vertex + out / out.hypot() * r.max(12.0) } else { handle } + } + DimensionMode::Radius | DimensionMode::Diameter => { + let (from, to) = (start - d.a, p - d.a); + if to.hypot() <= 1e-9 { + return handle; + } + // Grabbed at the center: the line turns toward the pointer. + if from.hypot() <= 1e-9 { + return p; + } + let v = handle - d.a; + d.a + Vec2::from_angle(v.atan2() + to.atan2() - from.atan2()) * v.hypot() + } + } +} + /// The line of a linear dimension already drawn: its ends and its direction. type DimensionLine = ((Point, Point), Vec2); @@ -816,6 +923,9 @@ impl DimensionTool { p } fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec { + if self.moving.is_some() { + return self.reposition(cx, p); + } self.level_guide = None; let Some(d) = &mut self.pending else { return vec![] }; if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) @@ -856,15 +966,10 @@ impl DimensionTool { if !self.began { self.preview_id = cx.doc.peek_next_id(); } - let (from, at) = match cx.interaction_doc { - Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), - None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), - }; - if !self.began || (cx.smart_guides && self.levels_at != at) { - self.levels = dimension_lines(from, (self.preview_id, [d.a, d.b])); - self.levels_at = at; - } + let points = [d.a, d.b]; + self.read_levels(cx, (self.preview_id, points)); } + let Some(d) = &mut self.pending else { return vec![] }; let level = if cx.smart_guides { line_level(&self.levels, d, p, cx.snap_tol()) } else { None }; d.place(level.map_or(p, |(on_level, _)| on_level)); if d.validate().is_err() { @@ -879,6 +984,51 @@ impl DimensionTool { actions.push(Action::Preview("dimension.create".into(), Self::params(d))); actions } + /// Reads `levels` at the first preview and, with Smart Guides on, again when the document they + /// come from has changed since: while an interaction is in progress, the document as it began. + /// `skip` names the dimension being placed or moved, which is not a level: its id and the + /// points it measures. + fn read_levels(&mut self, cx: &ToolContext, skip: (u64, [Point; 2])) { + let (from, at) = match cx.interaction_doc { + Some(began) => (began, (cx.revision.0, 0, std::ptr::from_ref(began).addr())), + None => (cx.doc, (cx.revision.0, cx.revision.1, 0)), + }; + if !self.began || (cx.smart_guides && self.levels_at != at) { + self.levels = dimension_lines(from, skip); + self.levels_at = at; + } + } + /// Moves the dimension drawn already that a drag picked up ([`Self::moving`]) as + /// [`grabbed_to`] says, and what it measures stays. With Smart Guides on, a linear + /// dimension's line lands on the level of a parallel dimension line, as when it is placed. + fn reposition(&mut self, cx: &ToolContext, p: Point) -> Vec { + self.level_guide = None; + let Some((id, start, from)) = self.moving.clone() else { return vec![] }; + let at = grabbed_to(&from, start, p); + if from.mode == DimensionMode::Linear { + self.read_levels(cx, (id.0, [from.a, from.b])); + } + // The levels are measured across from the line through `at` and, along it, from the + // pointer, which may be far from the line's middle. + let dir = from.direction(); + let along = at + dir * (p - at).dot(dir); + let level = if cx.smart_guides { line_level(&self.levels, &from, along, cx.snap_tol()) } else { None }; + let at = level.map_or(at, |(on_level, _)| on_level); + let mut d = from; + d.place(at); + if d.validate().is_err() { + return vec![]; + } + self.pending = Some(d); + self.level_guide = level.map(|(_, ends)| ends); + let mut actions = vec![]; + if !self.began { + actions.push(Action::Begin("Update Dimensions".into())); + self.began = true; + } + actions.push(Action::Preview("dimension.update".into(), json!({"ids":[id.0],"at":[at.x,at.y]}))); + actions + } /// Places the pending dimension at `p` and commits it. fn place(&mut self, cx: &ToolContext, p: Point) -> Vec { let mut out = self.preview(cx, p); @@ -906,6 +1056,8 @@ impl DimensionTool { self.second = None; self.level_guide = None; self.levels.clear(); + self.grab = None; + self.moving = None; } /// A plain click: picks a point or a line, or measures a circle's radius. fn click(&mut self, cx: &ToolContext, p: Point, target: Option, mods: Mods) -> Vec { @@ -1038,13 +1190,37 @@ impl Tool for DimensionTool { && (anchor_under(cx, ev.pos).is_some() || preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end)); - self.press = Some((ev.pos, self.target(cx, ev.pos))); + let target = self.target(cx, ev.pos); + // A press on a dimension drawn already, nearer to its lines and label than to any + // segment of the art, moves that dimension when it drags. A click there still + // picks a point. + self.grab = None; + if self.points.is_empty() + && self.lines.is_empty() + && let Some((id, d)) = dimension_under(cx, ev.pos) + { + let art = pick(cx, ev.pos).and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); + if art.is_none_or(|a| d < a) { + self.grab = Some(id); + } + } + self.press = Some((ev.pos, target)); vec![] } PointerKind::Drag => { if self.pending.is_some() && !self.dragging && self.press.is_some() { return self.preview(cx, ev.pos); } + if self.pending.is_none() + && let (Some((start, _)), Some(id)) = (self.press.as_ref(), self.grab) + && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) + && let Some(d) = cx.doc.node(id).and_then(|n| n.extras().dimension.as_deref()) + { + self.moving = Some((id, *start, d.clone())); + self.pending = Some(d.clone()); + self.dragging = true; + self.grab = None; + } if self.pending.is_none() && let Some((start, Some(target))) = self.press.clone() && start.distance(ev.pos) > cx.tol(if self.press_on_anchor { ANCHOR_REACH } else { 3.0 }) diff --git a/docs/dimensions.md b/docs/dimensions.md index bf6cf78653..1e5b52886a 100644 --- a/docs/dimensions.md +++ b/docs/dimensions.md @@ -86,7 +86,26 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers straight lines that meet (or would, extended), then click to place. - **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its radius, inwards its diameter. Clicking it gives its radius. Ellipses have no single radius. -- **Escape** or switching tools cancels a dimension being placed. +- **Moving a dimension:** the + [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) + describes repositioning a dimension by dragging it with the Dimension tool. With no points or + lines picked, a press within 8 pixels of what a dimension draws (its lines, arrowheads and + label), where it is the topmost object that can be edited, followed by a drag of more than 3 + pixels (8 pixels when the Linear tool finds an anchor, a corner of preview bounds or the end of a + dimension line within reach of the press) moves that dimension, as one undo step. A segment of the art + as near the press as the dimension's lines and label, or nearer, takes the press instead. The + line of a linear dimension moves as far across as the pointer moves; the arc of an angular one + moves as far as the pointer moves away from or toward the vertex, to no less than 12 points from + it; a radius or diameter line turns about the center as far as the pointer turns, or toward the + pointer when it was grabbed at the center. The dimension keeps what it measures and its link to + the art. Isolation mode applies as it does to a click: with a part of a dimension isolated, the + dimension is not dragged. A dimension that a geometry effect on it, on one of its parts or on a + group around it moves or distorts is not dragged, except in Outline view and on a layer whose + Preview is off, where effects are not drawn. With Smart Guides on, a linear dimension's line + lands on the level of a parallel dimension line, as when it is placed; when two such lines lie + on one level, the one nearer the pointer along it wins. A click there without a drag still picks a point. + How far the dimension moves is VectorCraft's own rule. +- **Escape** or switching tools cancels a dimension being placed or moved. **Tool Options** set the style of new dimensions: units (inches, millimetres, points, picas, pixels, centimetres, metres, feet, yards), precision (0–6 decimals), scale, the dimension and @@ -156,7 +175,10 @@ another document. line from the first point: along the left normal of a → b for an aligned dimension, downward for a horizontal one and leftward for a vertical one. A negative offset goes the other way. - `dimension.update`: restyle or move existing dimensions, or change the orientation of linear - ones. A new orientation keeps the line on the side of the points it was on. An update that + ones. A new orientation keeps the line on the side of the points it was on. `at: [x,y]`, applied + after `offset`, puts a linear dimension's line through the point, gives an angular dimension's + arc a radius of the point's distance from the vertex (at least 12 points), or turns a radius or + diameter line toward it, keeping what the dimension measures. An update that changes nothing records no undo step. - `dimension.applyToAll`: every dimension takes one dimension's style, in one undo step. - `tool.select {"tool":"dimension"}` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..eac5e220fe 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -690,6 +690,7 @@ since 2026-10-01. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool points on preview bounds corners (#8537):** With Use Preview Bounds on, a Linear point can land on a corner of the preview bounds of a path or compound path with a stroke or effects; the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes measuring a stroked segment by snapping onto its preview bounds. By VectorCraft's own rule, only the four corners are snapped to: a click within 8 pixels of a corner lands on it instead of on the anchor at the same corner of the object's geometric bounds, and any other anchor nearer the pointer takes the point; for an object that is not rotated, a horizontal or vertical dimension between two such corners measures, when it is drawn, the size that W and H show. The edges of the preview bounds, a group's own strokes or effects, type and paths made into guides are not snapped to. `with_preview_bounds_points_land_on_the_corners_of_the_stroke`, `preview_bounds_corners_take_picks_as_anchors_do`, `a_corner_takes_only_the_anchor_it_stands_for`, `a_point_is_held_for_a_corner_only_when_picked_on_it` and `hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring` cover it. **Drawing tools, Dimension tool lines line up with dimensions already drawn (#8063, #5590):** By VectorCraft's own rule, with Smart Guides on, a linear dimension placed with its line within the Smart Guides snapping tolerance of the level of a parallel line of a visible, unlocked linear dimension already drawn has its line on that level, and with Alignment Guides on a guide runs along the level across both lines while it is placed. `a_dimension_line_placed_beside_another_lands_on_its_level`, `a_dimension_line_on_another_level_shows_one_guide_across_both`, `a_dimension_of_the_same_points_lines_up_and_the_line_follows_the_pointer`, `a_dimension_dragged_out_beside_another_lands_on_its_level` and `a_line_the_pointer_lies_across_wins_on_one_level` cover it. +**Drawing tools, Dimension tool moves a dimension already drawn:** As the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes, a drag with the Dimension tool from a dimension already drawn repositions it, as one undo step, keeping what it measures and its link to the art. By VectorCraft's own rule, the part grabbed follows the pointer: a linear dimension's line moves as far across as the pointer moves, an angular arc moves as far as the pointer moves away from or toward the vertex, and a radius or diameter line turns about the center; the press must be where the canvas hits the dimension, within 8 pixels; with Smart Guides on, a linear dimension's line lands on the level of a parallel dimension line. `dimension.update` takes `at`. `dragging_a_placed_dimension_with_the_dimension_tool_moves_its_line`, `a_dimension_moved_beside_another_lands_on_its_level`, `a_dragged_dimension_follows_the_part_grabbed`, `a_dimension_is_dragged_only_where_the_canvas_hits_it` and `dimension_update_at_moves_the_line_through_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. **Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Dimension tool Arrow Style offers every stroke arrowhead (#8049, #3222):** By VectorCraft's own rule, Arrow Style lists Filled, Open, Tick and None, then the other 38 built-in Stroke panel arrowheads, each with its drawn preview. The options save the head in `arrowHead` (`Barbed`) and keep `arrowStyle` at `filled`, so versions that have the stroke arrowhead but not `arrowHead` keep the saved arrows until they draw the dimension again and then draw Filled arrows (versions without the stroke arrowhead do not open the file); documents and tool settings saved before open unchanged. `every_stroke_arrowhead_draws_as_a_dimension_arrowhead`, `arrow_style_shows_a_stroke_arrowhead`, `arrow_style_list_names_each_style_once` and `built_in_arrowhead_names_are_in_complete_catalogs` cover it. From 7f3888c59d165fde691acf4e170ce6246e7db89a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:07:47 -0800 Subject: [PATCH 02/19] Fonts: a rescan clears the version record after it publishes its catalog A rescan of the font folders cleared the record of families whose other versions had been looked for before it walked the folders. A version lookup made during the walk read the old catalog and recorded its family again, so a version the rescan found stayed hidden until the next scan. The record is now cleared after the new catalog is written. - The font gate used by tests: a thread's first SteadyFonts no longer waits for a font change that is itself waiting for guards other threads hold, so a guarded test does not hang when another test queues a change. It still waits for a change under way and for a waiting change that can start. - Tests that check a change waits for a guard now read the gate's own decision, recorded under its lock, instead of the request to change. --- crates/text/src/fontdb/db.rs | 5 ++- crates/text/src/test_fonts.rs | 30 +++++++++++-- crates/text/src/tests/sysfonts.rs | 72 +++++++++++++++++++++++++++---- 3 files changed, 94 insertions(+), 13 deletions(-) diff --git a/crates/text/src/fontdb/db.rs b/crates/text/src/fontdb/db.rs index 046db94dfd..1b8d9cd04d 100644 --- a/crates/text/src/fontdb/db.rs +++ b/crates/text/src/fontdb/db.rs @@ -374,8 +374,6 @@ impl FontDb { #[cfg(not(target_arch = "wasm32"))] fn scan_font_dirs(&self) -> usize { - // Files may have been installed since: other versions are looked for again. - self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); let mut catalog = Catalog::new(); let mut aliases: HashMap> = HashMap::new(); let mut postscript = PostScriptNames::new(); @@ -455,6 +453,9 @@ impl FontDb { let _change = self.cataloged.get().is_some().then(crate::test_fonts::font_change); *self.stamp.lock().unwrap_or_else(|e| e.into_inner()) = Some(ScanStamp { paths, modified: modified_at }); *self.catalog.write().unwrap_or_else(|e| e.into_inner()) = catalog; + // Files may have been installed since: other versions are looked for again, in this + // catalog. A version lookup made during the scan read the previous one. + self.version_scanned.write().unwrap_or_else(|e| e.into_inner()).clear(); *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = aliases; *self.postscript.write().unwrap_or_else(|e| e.into_inner()) = postscript; // Faces loaded from a file this scan did not catalog (the font was removed, or its folder diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index d8f91f8d50..6dd0ba0449 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -105,12 +105,17 @@ impl Drop for SteadyFonts { /// [`SteadyFonts`] for `db`. Catalogs `db`'s installed fonts first: a first scan does not wait for /// any guard, so this thread can wait for one running on another thread while it holds a guard. A -/// thread's first guard waits for the font changes under way or waiting. +/// thread's first guard waits for a font change under way, and for a waiting change that can start +/// now. It does not wait for a change that is waiting for guards other threads hold: the thread +/// waiting for this guard may hold one of them. pub fn steady_fonts(db: &crate::FontDb) -> SteadyFonts { db.ensure_catalog(); if STEADY.with(std::cell::Cell::get) == 0 { let mut s = steadiness(); - while !CHANGING.with(std::cell::Cell::get) && (s.changing || s.waiting > 0) { + let waits = |s: &Steadiness| !CHANGING.with(std::cell::Cell::get) && (s.changing || (s.waiting > 0 && s.holders == s.holders_waiting)); + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Guard, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.holders += 1; @@ -150,7 +155,10 @@ pub(crate) fn font_change() -> FontChange { font_changers().push(std::thread::current().id()); s.waiting += 1; s.holders_waiting += usize::from(holder); - while s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 } { + let waits = |s: &Steadiness| s.changing || if holder { s.holders > s.holders_waiting } else { s.holders > 0 }; + #[cfg(test)] + gate_decisions().push((std::thread::current().id(), GateAsk::Change, waits(&s))); + while waits(&s) { s = await_steadiness(s); } s.waiting -= 1; @@ -175,6 +183,22 @@ pub(crate) fn font_changers() -> std::sync::MutexGuard<'static, Vec std::sync::MutexGuard<'static, Vec<(std::thread::ThreadId, GateAsk, bool)>> { + static DECISIONS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + DECISIONS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The family of [`variable_font`]. pub const VARIABLE_FAMILY: &str = "Varitest Sans"; diff --git a/crates/text/src/tests/sysfonts.rs b/crates/text/src/tests/sysfonts.rs index 08f6584186..b6a1e8c1aa 100644 --- a/crates/text/src/tests/sysfonts.rs +++ b/crates/text/src/tests/sysfonts.rs @@ -4,6 +4,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::fontdb::fonts_outside; +use crate::test_fonts::GateAsk; use crate::*; const FAMILY: &str = "Sysfont Sans3"; @@ -83,10 +84,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let _steady = guarded.then(|| crate::test_fonts::steady_fonts(&db)); db.add_font(font) }); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "guarded {guarded}: the other thread's change waits for the guard"); assert_eq!(db.generation(), before, "guarded {guarded}: the other thread's change waits for the guard"); let listed = db.families().iter().any(|f| f == crate::test_fonts::VARIABLE_FAMILY); assert!(!listed, "guarded {guarded}: the other thread publishes the font only once the guard is dropped"); @@ -99,10 +98,8 @@ fn steady_fonts_hold_back_other_threads_font_changes() { let steady = crate::test_fonts::steady_fonts(&db); std::thread::scope(|scope| { let adding = scope.spawn(|| db.add_font(crate::test_fonts::two_axis_font().unwrap())); - let id = adding.thread().id(); - while !adding.is_finished() && !crate::test_fonts::font_changers().contains(&id) { - std::thread::yield_now(); - } + let waits = first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()); + assert_eq!(waits, Some(true), "the other thread's change waits for the guard"); let before = db.generation(); assert!(db.add_font(crate::test_fonts::variable_font().unwrap()) > 0); let after = db.generation(); @@ -114,6 +111,65 @@ fn steady_fonts_hold_back_other_threads_font_changes() { }); } +/// Whether the first `ask` that the thread `id` made of the font gate waited, once the thread has +/// made it; `None` when `finished` says the thread ended without making it. +fn first_decision(id: std::thread::ThreadId, ask: GateAsk, finished: impl Fn() -> bool) -> Option { + loop { + let done = finished(); + let waits = crate::test_fonts::gate_decisions().iter().find(|(t, a, _)| *t == id && *a == ask).map(|(_, _, waits)| *waits); + if waits.is_some() || done { + return waits; + } + std::thread::yield_now(); + } +} + +/// While a thread holds [`test_fonts::steady_fonts`] and a font change on another thread waits for +/// it, a third thread's first guard does not wait for that change, which cannot start before the +/// first guard is dropped. +#[test] +fn a_first_guard_does_not_wait_for_a_change_that_waits_for_other_guards() { + let db = FontDb::with_font_dirs(vec![]); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let adding = scope.spawn(|| db.add_font(crate::test_fonts::variable_font().unwrap())); + assert_eq!(first_decision(adding.thread().id(), GateAsk::Change, || adding.is_finished()), Some(true), "the change waits for the guard"); + let guarding = scope.spawn(|| drop(crate::test_fonts::steady_fonts(&db))); + let waits = first_decision(guarding.thread().id(), GateAsk::Guard, || guarding.is_finished()); + assert_eq!(waits, Some(false), "the new guard does not wait for the change that waits for this thread's guard"); + guarding.join().unwrap(); + drop(steady); + assert!(adding.join().unwrap() > 0, "the font is new to this database"); + }); +} + +/// A version of a family looked up while a rescan of the font folders is under way, before the +/// rescan publishes what it found, does not hide a version of that family the rescan found. +#[test] +fn a_version_looked_up_during_a_rescan_is_found_after_it() { + use crate::test_fonts::{TWIN_FAMILY, TWIN_VERSIONS, twin_font}; + let dir = std::env::temp_dir().join(format!("vc-sysfonts-{}-rescan-versions", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Older.ttf"), twin_font(false).unwrap()).unwrap(); + let db = FontDb::with_font_dirs(vec![dir.clone()]); + assert_eq!(db.load_system_fonts(), 1); + let face = db.face(TWIN_FAMILY, "Regular").expect("the installed face"); + assert_eq!(face.version, TWIN_VERSIONS[0]); + std::fs::write(dir.join("Newer.ttf"), twin_font(true).unwrap()).unwrap(); + let versions = |db: &FontDb| db.versions(&face).iter().map(|f| f.version.clone()).collect::>(); + std::thread::scope(|scope| { + let steady = crate::test_fonts::steady_fonts(&db); + let rescanning = scope.spawn(|| db.load_system_fonts()); + let waits = first_decision(rescanning.thread().id(), GateAsk::Change, || rescanning.is_finished()); + assert_eq!(waits, Some(true), "the rescan waits for the guard before it publishes"); + assert_eq!(versions(&db), [TWIN_VERSIONS[0]], "before the rescan publishes, only the older file is cataloged"); + drop(steady); + assert_eq!(rescanning.join().unwrap(), 2); + }); + assert_eq!(versions(&db), TWIN_VERSIONS, "the version the rescan found is loaded"); + std::fs::remove_dir_all(dir).unwrap(); +} + /// The first scan of a database's installed fonts does not wait for [`test_fonts::steady_fonts`] /// held for another database, so a thread holding one can catalog a database that another thread /// is scanning. From 32afba75ae22ba3c79886042a8edec15d490b2a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:15:40 -0800 Subject: [PATCH 03/19] Live Paint: a Cmd-drag cut short keeps the bucket's colors With the Live Paint Bucket active, Cmd lends the Selection tool for a drag. When the bucket was chosen again during a drag of a corner, pie, blend or similar widget, the lent tool canceled the drag as it went back, after the session had already stopped treating the bucket as the lender. With New Art Has Basic Appearance off, the cancel then gave the selected object's appearance to the colors the bucket paints with. The lent tool's last actions now run while the session still counts them as the bucket's, as the Eyedropper's sample for the bucket does. --- crates/engine/src/cmd/paint.rs | 13 +++++++++++-- crates/engine/src/lib.rs | 5 +++-- crates/engine/src/tests/build.rs | 28 ++++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 6 ++++++ 4 files changed, 48 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index b94a45e4f5..6666a1d7a3 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -373,16 +373,25 @@ impl DocState { } } +/// Is `t` the Live Paint Bucket, or a tool armed to switch back to it after its pick? +fn works_for_bucket(t: &dyn vectorcraft_tools::Tool) -> bool { + t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET) +} + impl Session { + /// Did the Live Paint Bucket, or the Eyedropper armed for it, lend the active tool (a Cmd+click)? + pub(crate) fn lent_by_bucket(&self) -> bool { + self.lender.as_deref().is_some_and(works_for_bucket) + } + /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the /// sample its click takes before it switches back to the bucket. pub fn bucket_paints(&self) -> bool { - let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET); // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. - self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket) + self.back_to_bucket || works_for_bucket(self.tool.as_ref()) || self.lent_by_bucket() } /// The tool the active tool's armed one-shot pick switches back to after its click diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..68067dc697 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -75,8 +75,9 @@ pub struct Session { /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the - /// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the - /// colors the bucket paints with ([`Session::bucket_paints`]). + /// Eyedropper's sample into a stop of the bucket's gradient), and while a tool the bucket lent + /// is deactivated as it goes back: their paint commands change the colors the bucket paints + /// with ([`Session::bucket_paints`]). pub(crate) back_to_bucket: bool, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index b37550d5c5..32a9db4b21 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3493,6 +3493,34 @@ fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_clic assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample"); } +/// A Cmd-drag of a corner widget with the Live Paint Bucket that is cut short by choosing the +/// bucket again (the Selection tool it lent cancels the drag as it goes back) leaves the bucket's +/// colors as they were, with New Art Has Basic Appearance off: the selected object's appearance +/// does not replace them. +#[test] +fn live_paint_bucket_keeps_its_colors_when_a_lent_drag_is_cut_short() { + let v = ViewInfo::default(); + let mut s = session(); + let rect = rect(&mut s, 300.0, 300.0, 100.0, 100.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.select_tool("livePaintBucket", v).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let fill = s.paint.fill.clone(); + let st = s.doc().unwrap(); + let w = vectorcraft_tools::corners::CornerWidgets::showing(&st.doc, &st.selection, v.zoom, false, true, 180.0).expect("corner widgets show"); + let at = w.visible().next().expect("a widget"); + let cmd = Mods { cmd: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, at.x + 8.0, at.y + 8.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.tool_id(), "selection", "the bucket lent the Selection tool for the drag"); + assert!(s.in_interaction(), "the corner widget drag is in progress"); + s.select_tool("livePaintBucket", v).unwrap(); + assert_eq!(s.tool_id(), "livePaintBucket"); + assert_eq!(s.paint.fill, fill, "the bucket's fill stays"); +} + /// A gradient stop selected on the selection's gradient is not selected once the Live Paint /// Bucket is active (its proxies show the default paint), and one selected on the bucket's /// gradient is not selected once another tool is chosen. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 7c1af811ed..4323323e22 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -319,6 +319,7 @@ impl Session { /// Pen goes on drawing its path), less the work the gesture ended as a command would: a /// Cmd+click that takes the type being edited out of the selection ends its edit (#3779). pub(crate) fn give_back_tool(&mut self, view: ViewInfo) -> Result<()> { + let lent_by_bucket = self.lent_by_bucket(); let Some(lender) = self.lender.take() else { return Ok(()) }; // The points the lent tool left picked go back to the tool it was lent to when that tool // picks mesh points, none when it unpicked them all (#8090). Group Selection and the @@ -328,7 +329,12 @@ impl Session { .then(|| self.tool.options().get("meshPoints").cloned()) .flatten() .filter(|p| lender.options().get("meshPoints") != Some(p)); + // The lent tool's last actions (a drag it cancels or keeps) still count as the Live Paint + // Bucket's when the bucket lent it ([`Session::bucket_paints`]). + let outer_bucket = self.back_to_bucket; + self.back_to_bucket |= lent_by_bucket; let r = self.deactivate_tool(view); + self.back_to_bucket = outer_bucket; self.keep_tool_settings(); self.tool = lender; if let Some(points) = mesh_points { From 6d264b28905a2d0102ae38e0cdb22aa1787a5d05 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 19:27:37 -0800 Subject: [PATCH 04/19] Expand Appearance: Safe Mode skips symbol art of a hidden instance in a group's image The image a group's or layer's raster effect makes leaves out hidden objects and everything in them, as the renderer does. The Safe Mode plug-in check looked into every object of such a group, so a hidden plain symbol instance whose symbol art holds a plug-in effect stopped Expand Appearance of the group. The check now skips hidden objects inside the group's image. The group itself still counts when it, or a group around it, is hidden, since expansion still makes its image. --- crates/engine/src/cmd/effectcmd.rs | 50 +++++++++++++++++++----- crates/engine/tests/plugin_safe_mode.rs | 52 +++++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index cb399eca1c..2b28cd64ff 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -1611,33 +1611,63 @@ fn expanded_node( /// Does `n`, an object in it, or the art of a symbol placed in it hold a plug-in effect that /// expanding it draws: a visible one, the object's own or a visible fill's or stroke's, on an -/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does, and so does -/// every object in a group or layer with a raster effect, whose image draws all of it). A symbol's +/// object that expands ([`expandable`]; in a symbol's art, `in_art`, every object does), or that the +/// image of a group or layer with a raster effect draws ([`rasterizes_plugin_effect`]). A symbol's /// art counts where an instance of it expands. `seen` holds the symbols already looked into. fn holds_plugin_effect(d: &Document, n: &Node, in_art: bool, seen: &mut std::collections::HashSet) -> bool { - let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); let mut symbols = vec![]; - let mut drawn = vec![]; let mut holds = false; n.walk(&mut |c| { - if !in_art && is_container(c) && !rasterfx::raster_fx(c).is_empty() { - drawn.push(c); - } if !in_art && !expandable(c) { return; } - holds |= c.appearance.effects.iter().any(plugin) || c.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)); + holds |= has_own_plugin_effect(c); if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { symbols.push(symbol.clone()); } }); holds - || drawn.into_iter().any(|g| holds_plugin_effect(d, g, true, seen)) + || (!in_art && rasterizes_plugin_effect(d, n, &mut std::collections::HashSet::new())) || symbols.into_iter().any(|name| { seen.insert(name.clone()) && d.symbols.iter().find(|s| s.name == name).is_some_and(|s| holds_plugin_effect(d, &s.art, true, seen)) }) } +/// Does `n` have a visible plug-in effect of its own, or on a visible fill or stroke? +fn has_own_plugin_effect(n: &Node) -> bool { + let plugin = |e: &Effect| e.visible && vectorcraft_plugins::effect::plugin_id(&e.id).is_some(); + n.appearance.effects.iter().any(plugin) || n.appearance.items.iter().any(|i| i.visible() && i.effects().iter().any(plugin)) +} + +/// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect +/// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or +/// a group around it, is hidden. +fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + let mut drawn = vec![]; + n.walk(&mut |c| { + if is_container(c) && !rasterfx::raster_fx(c).is_empty() { + drawn.push(c); + } + }); + drawn.into_iter().any(|g| draws_plugin_effect(d, g, seen)) +} + +/// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, +/// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object +/// in `n`, and everything in it, as the renderer does. `seen` holds the symbols already looked into. +fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { + if has_own_plugin_effect(n) { + return true; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && seen.insert(symbol.clone()) + && d.symbols.iter().find(|s| s.name == *symbol).is_some_and(|s| draws_plugin_effect(d, &s.art, seen)) + { + return true; + } + n.children().into_iter().flatten().any(|c| c.visible && draws_plugin_effect(d, c, seen)) +} + fn expand_appearance(s: &mut Session, p: &Value) -> Result { let roots = edit_targets(s, p, "effect.expandAppearance")?; // In Safe Mode a plug-in effect draws nothing: expanding it would drop the effect and keep the diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index a469e68f20..98047a2d86 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -506,6 +506,58 @@ fn expand_appearance_in_safe_mode_checks_symbol_art_a_group_image_draws() { refused(&mut s, &json!(outer)); } +/// In Safe Mode, a hidden plain instance draws nothing in the image a group's raster effect makes, +/// so its symbol art's plug-in effect doesn't stop Expand Appearance of the group; shown, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.hid", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.hid"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let hide = |s: &mut Session, id: u64| { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(vectorcraft_engine::doc::NodeId(id)).unwrap().visible = false; + }; + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + // A blurred group of a visible rectangle and an instance, then one of a visible rectangle and a + // group around an instance; the instance, or the group around it, is shown and then hidden. + for wrap in [false, true] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let mut hidden = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + if wrap { + hidden = s.execute("object.group", &json!({"ids": [hidden]})).unwrap()["id"].clone(); + } + let group = s.execute("object.group", &json!({"ids": [rect, hidden]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [group], "params": {"radius": 2}})).unwrap(); + let (hidden, group) = (hidden.as_u64().unwrap(), group.as_u64().unwrap()); + let err = expand(&mut s, group).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + hide(&mut s, hidden); + expand(&mut s, group).unwrap(); + } + // Expansion still makes the image of a hidden blurred group, or of one in a hidden group, so + // a shown instance in it still stops it. + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 20})).unwrap()["id"].clone(); + let blurred = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [blurred], "params": {"radius": 2}})).unwrap(); + let parent = s.execute("object.group", &json!({"ids": [blurred]})).unwrap()["id"].as_u64().unwrap(); + hide(&mut s, parent); + let err = expand(&mut s, parent).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + let blurred = blurred.as_u64().unwrap(); + hide(&mut s, blurred); + let err = expand(&mut s, blurred).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..a6af3a0d23 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13275,7 +13275,8 @@ runs: `plugin.install`, `plugin.run`, `plugin.reload` and exporters return an er object's geometry unchanged while the object keeps the effect: `effect.list` gives that effect `skipped: true`, and the Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a -plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. `vectorcraft` rejects an option it does not know (such as +visible plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. A +hidden instance draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From a84a398a3f7e29e7a84c5a766ae6cde563284c6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 20:06:07 -0800 Subject: [PATCH 05/19] Expand Appearance: Safe Mode skips symbol art in a template layer of a group's image The image a group's or layer's raster effect makes is drawn with templates skipped, so it leaves out template layers, guides and ruler guides with everything in them. The Safe Mode plug-in check still looked into a template sublayer, so a plain symbol instance there whose symbol art holds a plug-in effect stopped Expand Appearance of the layer. The check now skips them as the renderer does. --- crates/engine/src/cmd/effectcmd.rs | 9 ++++--- crates/engine/tests/plugin_safe_mode.rs | 35 +++++++++++++++++++++++++ docs/mcp.md | 2 +- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 2b28cd64ff..c33ebb61d7 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -97,7 +97,7 @@ fn effect_specs() -> Vec { "Expand Appearance", ["Object"], None, - "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", + "{ids?|id?: [..], target?} turn each object's appearance into objects: every fill and stroke becomes an object of its own (a stroke stays a stroke, with its weight, dashes, arrowheads and width profile, on its own copy of the path, which object.expand or object.path.outlineStroke outline; brushed strokes become their brush art) grouped in paint order under the object's id and transparency, geometry effects are baked, raster effects become an embedded image (shadows and outer glows below the art; blur, feather and inner glow replace it; an object whose only raster effect is its own Rasterize becomes the image object.rasterize makes with the effect's options), type with effects or fills of its own is outlined; Crop Marks become a group of the object and its marks; Vector Halftone (addon.color.halftone) becomes a group of its dot paths, one per ink; a group's or layer's own fills and strokes become objects among its members, which are expanded too; a symbol instance whose topmost fill or stroke is visible, has an opacity above 0 and has a geometry or raster effect becomes a group of its art, that fill's effects reshaping the art's filled shapes and that stroke's effects reshaping its stroked shapes, as the canvas draws them, its raster effects an image as for other objects; a symbol instance in that art whose topmost fill or stroke has such an effect (its own or one the outer instance passes on) becomes its art and image in turn. An outlined frame of threaded text leaves its thread with the text it shows, and a frame kept as type in a group stays in its thread. A dimension whose art it changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked. Hidden fills, strokes and effects are dropped. One expansion makes at most 1,024 images of raster effects, 256 megapixels in all (VectorCraft's own limits): an object or symbol instance whose image would go past them stays as it is, with its effects, and when nothing else expands that is an error. In Safe Mode, an object with a visible plug-in effect (in it, or in a symbol it places, a visible plain instance outside template layers in a group or layer whose raster effect makes an image of it included) is an error and nothing changes. Enabled when a selected or targeted object's appearance isn't basic (`ids` then pick which objects) → {ids, warning? (an image in the art couldn't be decoded, as object.rasterize says; or raster effects were left past the limits), rasterLeft? (how many objects were left so)}", can_expand, expand_appearance ), @@ -1654,7 +1654,8 @@ fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections: /// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, /// have a visible plug-in effect ([`has_own_plugin_effect`])? The image leaves out a hidden object -/// in `n`, and everything in it, as the renderer does. `seen` holds the symbols already looked into. +/// in `n`, a template layer, a guide or a ruler guide, and everything in it, as the renderer does +/// with templates skipped. `seen` holds the symbols already looked into. fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { if has_own_plugin_effect(n) { return true; @@ -1665,7 +1666,9 @@ fn draws_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::Hash { return true; } - n.children().into_iter().flatten().any(|c| c.visible && draws_plugin_effect(d, c, seen)) + let drawn = + |c: &Node| c.visible && !c.is_ruler_guide() && !matches!(c.kind, NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. }); + n.children().into_iter().flatten().any(|c| drawn(c) && draws_plugin_effect(d, c, seen)) } fn expand_appearance(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index 98047a2d86..c2213a930a 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -558,6 +558,41 @@ fn expand_appearance_in_safe_mode_skips_symbol_art_of_a_hidden_instance_a_group_ assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); } +/// In Safe Mode, the image a layer's raster effect makes leaves out a template sublayer, so the symbol +/// art of a plain instance in it doesn't stop Expand Appearance of the layer; in a plain sublayer, it does. +#[test] +fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_layer_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.tpl", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.tpl"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let layer = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setCurrent", &json!({"id": layer})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap(); + let instance = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].as_u64().unwrap(); + let sub = s.execute("layer.newSublayer", &json!({"parent": layer})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.move", &json!({"ids": [instance], "target": sub})).unwrap(); + s.execute("layer.target", &json!({"id": layer})).unwrap(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [layer], "item": null, "params": {"radius": 2}})).unwrap(); + let blurred = |s: &Session| s.doc().unwrap().doc.node(vectorcraft_engine::doc::NodeId(layer)).unwrap().appearance.effects.len(); + assert_eq!(blurred(&s), 1, "the layer has its own Gaussian Blur"); + let expand = |s: &mut Session| { + s.execute("layer.target", &json!({"id": layer})).unwrap(); + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({})); + safe_mode::set_active(None); + r + }; + let err = expand(&mut s).unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{err}"); + s.execute("layer.setProps", &json!({"id": sub, "template": true})).unwrap(); + expand(&mut s).unwrap(); +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index a6af3a0d23..11e8bb47f4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13276,7 +13276,7 @@ object's geometry unchanged while the object keeps the effect: `effect.list` giv Appearance panel shows "(Safe Mode)" after its name and the plug-in's id in its tooltip. `effect.expandAppearance` returns an error and changes nothing when an object it would expand holds such an effect, in it or in a symbol it places. That includes a visible plain symbol instance in a group or layer with a raster effect, since the group's image draws the symbol's art. A -hidden instance draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as +hidden instance, or one in a template sublayer, draws nothing in that image, so its symbol's art does not count. `vectorcraft` rejects an option it does not know (such as `--safe-mod`) instead of opening it as a file; `--` before a file name that starts with `-` opens it. The web build keeps no installed plug-ins from one page load to the next and has no launch marker, so it never offers the choice. `plugin.safeMode` returns `{active, source, disabled, pendingItem}`; a command does not turn Safe Mode on or off. `plugin.setEnabled {id | file, enabled}` turns a plug-in on or From 92c63bb8cf0ae10101da593c47b577e51c8dd470 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:03:29 -0800 Subject: [PATCH 06/19] Expand Appearance: Safe Mode skips raster groups inside a blurred group's image A group or layer whose raster effects are not all shadows and outer glows (a blur, feather or inner glow) becomes one image of what it draws, and the groups and layers in it make no images of their own. The Safe Mode plug-in check still looked into every group with a raster effect inside it, so a hidden blurred group there holding a plain symbol instance with a plug-in effect in its art stopped the expansion. The check now stops at such a group. Under shadows and outer glows the members still expand on their own, so their groups are still checked. --- crates/engine/src/cmd/effectcmd.rs | 20 +++++++----- crates/engine/tests/plugin_safe_mode.rs | 41 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index c33ebb61d7..90176831a4 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -1641,15 +1641,21 @@ fn has_own_plugin_effect(n: &Node) -> bool { /// Does a group or layer in `n` with a raster effect make an image of a visible plug-in effect /// ([`draws_plugin_effect`])? Expansion makes the image of such a group or layer even when it, or -/// a group around it, is hidden. +/// a group around it, is hidden. A group or layer that paints something and whose raster effects +/// are not all shadows and outer glows becomes one image of what it draws, so the groups and layers +/// in it make no images of their own; one that paints nothing makes no image, and its members +/// expand on their own. fn rasterizes_plugin_effect(d: &Document, n: &Node, seen: &mut std::collections::HashSet) -> bool { - let mut drawn = vec![]; - n.walk(&mut |c| { - if is_container(c) && !rasterfx::raster_fx(c).is_empty() { - drawn.push(c); + let fx = if is_container(n) { rasterfx::raster_fx(n) } else { vec![] }; + if !fx.is_empty() { + if draws_plugin_effect(d, n, seen) { + return true; } - }); - drawn.into_iter().any(|g| draws_plugin_effect(d, g, seen)) + if !fx.iter().all(effects::RasterFx::is_below) && vectorcraft_render::painted_bounds(d, n).is_some() { + return false; + } + } + n.children().into_iter().flatten().any(|c| rasterizes_plugin_effect(d, c, seen)) } /// Does `n`, an object the image of `n` draws in it, or the art of a symbol such an instance places, diff --git a/crates/engine/tests/plugin_safe_mode.rs b/crates/engine/tests/plugin_safe_mode.rs index c2213a930a..6cb261dd0f 100644 --- a/crates/engine/tests/plugin_safe_mode.rs +++ b/crates/engine/tests/plugin_safe_mode.rs @@ -593,6 +593,47 @@ fn expand_appearance_in_safe_mode_skips_symbol_art_in_a_template_sublayer_a_laye expand(&mut s).unwrap(); } +/// In Safe Mode, a group whose Gaussian Blur makes it one image leaves out a hidden blurred group in +/// it, which makes no image of its own, so the symbol art of a plain instance there doesn't stop +/// Expand Appearance. Under a Drop Shadow, whose members expand on their own, the hidden group still +/// makes its image, so it does. +#[test] +fn expand_appearance_in_safe_mode_skips_a_hidden_blurred_group_that_a_blurred_group_image_leaves_out() { + let _f = fresh(); + let mut s = Session::new(); + let fx = wat::parse_str(tpl::returning(&tpl::manifest("test.sm.nest", "effect", "{}"), r#"{"objects":[]}"#)).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&fx)})).unwrap(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s.execute("effect.apply", &json!({"effect": "plugin.test.sm.nest"})).unwrap(); + s.execute("symbol.new", &json!({"name": "fx"})).unwrap(); + let expand = |s: &mut Session, group: u64| { + safe_mode::set_active(Some(safe_mode::Source::Flag)); + let r = s.execute("effect.expandAppearance", &json!({"ids": [group]})); + safe_mode::set_active(None); + r + }; + for (outer, allowed) in [("blur.gaussian", true), ("stylize.dropShadow", false)] { + let rect = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 20, "height": 20})).unwrap()["id"].clone(); + let plain = s.execute("symbol.place", &json!({"name": "fx", "x": 150, "y": 150})).unwrap()["id"].clone(); + let inner = s.execute("object.group", &json!({"ids": [plain]})).unwrap()["id"].clone(); + s.execute("effect.apply", &json!({"effect": "blur.gaussian", "ids": [inner], "params": {"radius": 2}})).unwrap(); + let group = s.execute("object.group", &json!({"ids": [rect, inner]})).unwrap()["id"].as_u64().unwrap(); + s.execute("effect.apply", &json!({"effect": outer, "ids": [group]})).unwrap(); + let inner = vectorcraft_engine::doc::NodeId(inner.as_u64().unwrap()); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(inner).unwrap().visible = false; + let r = expand(&mut s, group); + if allowed { + r.unwrap(); + // The blurred group became its image: the hidden group in it was not expanded on its own. + assert!(s.doc().unwrap().doc.node(inner).is_none(), "the hidden group went into the image"); + } else { + let err = r.unwrap_err().to_string(); + assert!(err.contains("a plug-in effect in the selection can't be expanded in Safe Mode"), "{outer}: {err}"); + } + } +} + /// In Safe Mode, a plug-in effect in the art of a graph design in a series stops Expand Appearance of the graph only /// when an effect of the series group draws that art with the group. #[test] From a93cd03c35add317bf072785d97bc87425696d01 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 21:44:34 -0800 Subject: [PATCH 07/19] Type: text commands refuse a parameter of the wrong type text.editRange's insert, text.setText's text and text.createInPath's mode and text must be strings, text.createInPath's at must be two numbers, and start in text.touchType, text.glyphAlternates and text.setGlyphAlternate must be a whole number of at least 0. A wrong value was read as left out (an edit inserting nothing, area type, no start point) or reported as a missing start; it is now an error naming the parameter, and the document and undo history do not change. Null still reads as the parameter left out. Pathfinder precision no longer reads the leading number of a string such as "1abc"; a number, a string that is all one number and a length with a unit ("10 pt") still read. --- crates/engine/src/cmd/pathops.rs | 7 ++--- crates/engine/src/cmd/textedit.rs | 34 ++++++++++++++--------- crates/engine/src/cmd/typecmd.rs | 4 +-- crates/engine/src/tests/pathops.rs | 6 +++++ crates/engine/src/tests/textedit.rs | 42 +++++++++++++++++++++++++++++ docs/mcp.md | 13 ++++++--- docs/target-app-parity.md | 1 + 7 files changed, 83 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index 96b9e51f99..1793f17d5c 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -199,14 +199,11 @@ pub fn specs() -> Vec { // ---------- helpers ---------- -/// Number param that also accepts strings like `"10 pt"`. +/// Number param that also accepts a string when all of it is a number (`"10"`, not `"10abc"`). pub(crate) fn num_param(p: &Value, key: &str) -> Option { match p.get(key)? { Value::Number(n) => n.as_f64(), - Value::String(s) => { - let t: String = s.trim().chars().take_while(|c| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).collect(); - t.parse().ok() - } + Value::String(s) => whole_number(s), _ => None, } .filter(|v: &f64| v.is_finite()) diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 0d75061bee..3af85a8265 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -11,8 +11,8 @@ use super::menucmds::whole_or; use super::stroke::StrokeChange; use super::typecmd::refresh_bounds; use super::{ - CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index, - number_or, object_param, point_param, str_param, switch_or, targets, text_param, + CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, finite_numbers, has_doc, has_selection, + index, number_or, object_param, str_param, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point; anything but two numbers: an error), size?: pt 0.1..1296 (outside it: an error), font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -255,9 +255,15 @@ fn byte_param(p: &Value, k: &str) -> Option { /// The byte offset that `p` gives for `k`, or `default` when `p` leaves it out or gives null. Any /// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. fn offset_or(p: &Value, k: &str, default: usize, cmd: &str) -> Result { + Ok(offset_given(p, k, cmd)?.unwrap_or(default)) +} + +/// The byte offset that `p` gives for `k`, or `None` when `p` leaves it out or gives null. Any +/// other value that is not a whole number of at least 0, such as `"2"`, `-1` or `1.5`, is an error. +fn offset_given(p: &Value, k: &str, cmd: &str) -> Result> { match p.get(k) { - None | Some(Value::Null) => Ok(default), - Some(_) => Ok(index(whole_or(p, k, 0, cmd)?)), + None | Some(Value::Null) => Ok(None), + Some(_) => Ok(Some(index(whole_or(p, k, 0, cmd)?))), } } @@ -280,7 +286,7 @@ pub(crate) fn edit_range(s: &mut Session, p: &Value) -> Result { None | Some(Value::Null) => None, Some(v) => Some(serde_json::from_value(v.clone()).map_err(|e| bad(C, format!("bad `runs`: {e}")))?), }; - let insert = str_param(p, "insert").unwrap_or("").to_string(); + let insert = text_param(p, "insert", C)?.unwrap_or("").to_string(); let clear = clear_param(s, p, id, C)?; let caret = s.edit("Typing", |d, _| { for other in &clear { @@ -1313,8 +1319,7 @@ pub fn effective_kerning(db: &vectorcraft_text::FontDb, t: &TextObject, lay: &ve /// The character at byte `start` of `p` in text object `t`, its bytes and its font's face. An error /// when there is no character there, it is an inline graphic, or its font is not available. fn glyph_target(t: &TextObject, p: &Value, c: &str) -> Result<(char, std::ops::Range, std::sync::Arc)> { - check_numbers(p, &["start"], c)?; - let start = byte_param(p, "start").ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", c)?.ok_or_else(|| bad(c, "missing `start` (the byte offset of a character)"))?; let mut at = 0; for run in &t.runs { let end = at + run.text.len(); @@ -1558,8 +1563,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result { fn touch_type(s: &mut Session, p: &Value) -> Result { const C: &str = "text.touchType"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?; - check_numbers(p, &["start"], C)?; - let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; + let start = offset_given(p, "start", C)?.ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?; if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) { return Err(bad(C, "nothing to change: give dx, dy, hScale, vScale or rotation")); } @@ -1797,7 +1801,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result { fn create_in_path(s: &mut Session, p: &Value) -> Result { const C: &str = "text.createInPath"; let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?; - let on_path = match str_param(p, "mode").unwrap_or("area") { + let on_path = match text_param(p, "mode", C)?.unwrap_or("area") { "area" => false, "onPath" | "path" => true, o => return Err(bad(C, format!("mode must be area|onPath, got {o}"))), @@ -1815,8 +1819,12 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { check_switches(p, &["vertical", "placeholder"], C)?; super::color_param(p, "color", C)?; let style = super::create::new_type_style(s, p, C)?; - let text = str_param(p, "text").unwrap_or("").to_string(); - let start = match point_param(p, "at") { + let text = text_param(p, "text", C)?.unwrap_or("").to_string(); + let at = match p.get("at").filter(|v| !v.is_null()) { + None => None, + Some(v) => Some(finite_numbers::<2>(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad(C, "`at` must be a point: [x, y]"))?), + }; + let start = match at { Some(at) if on_path => vectorcraft_geom::ArcPath::new(path).fraction_at(at).unwrap_or(0.0), _ => 0.0, }; diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 185baf734f..2a62a46374 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -13,7 +13,7 @@ use super::edit::selected_roots; use super::pathops::{length_given, number_given, shape_node}; use super::{ CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, index_opt, number_or, - object_param, ok, str_param, switch_or, targets, text_param, + object_param, ok, switch_or, targets, text_param, }; pub fn specs() -> Vec { @@ -873,7 +873,7 @@ pub(crate) fn style_chars(t: &mut TextObject, range: Option, mut f: i } fn set_text(s: &mut Session, p: &Value) -> Result { - let text = str_param(p, "text").ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); + let text = text_param(p, "text", "text.setText")?.ok_or_else(|| bad("text.setText", "missing `text`"))?.to_string(); let ids = text_targets(s, p, "text.setText")?; // The text the type already has is no undo step. edit_if_nodes_changed(s, "Typing", &ids, |d| { diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index feb71e40ad..6bd92225db 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1736,11 +1736,17 @@ fn pathfinder_options_round_trip_and_refuse_bad_values() { assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set); let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap(); assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}"); + for (given, want) in [("10 pt", 10.0), ("0.25", 0.25)] { + let r = s.execute("object.pathfinder.options", &json!({"precision": given})).unwrap(); + assert_eq!(r["precision"], json!(want), "{given}"); + } s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap(); for bad in [ json!({"precision": 0}), json!({"precision": 11}), json!({"precision": "x"}), + json!({"precision": "1abc"}), + json!({"precision": "0.5 extra"}), json!({"precision": -1}), json!({"removeRedundantPoints": "yes"}), json!({"removeUnpainted": 1}), diff --git a/crates/engine/src/tests/textedit.rs b/crates/engine/src/tests/textedit.rs index 8857378855..d49b18b031 100644 --- a/crates/engine/src/tests/textedit.rs +++ b/crates/engine/src/tests/textedit.rs @@ -671,6 +671,48 @@ fn character_ruby_and_path_handle_refuse_a_param_of_the_wrong_type() { s.execute("text.setPathHandle", &handle(Value::Null)).unwrap(); } +/// Range edits, Set Text, area and on-path type and the glyph commands refuse a param of the wrong +/// type with an error naming the param, and leave the document and the undo history as they were: +/// text that is not a string, a byte offset that is fractional or negative, and a point that is not +/// two numbers. Null counts as a param left out, which keeps its default. +#[test] +fn text_edits_refuse_a_param_of_the_wrong_type() { + use crate::tests::not_refused; + let mut s = session(); + let id = text(&mut s, "abc"); + let frame = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 100, "height": 50})).unwrap()["id"].clone(); + let line = s.execute("path.create", &json!({"anchors": [{"x": 100, "y": 400}, {"x": 400, "y": 400}]})).unwrap()["id"].clone(); + let string = |k: &str| format!("`{k}` must be a string"); + let whole = "`start` must be a whole number".to_string(); + let point = "`at` must be a point: [x, y]".to_string(); + let calls: Vec<(String, Value, String)> = [ + ("text.editRange", json!({"id": id.0, "start": 0, "end": 1, "insert": 5}), string("insert")), + ("text.editRange", json!({"id": id.0, "start": 0, "end": 3, "insert": ["x"]}), string("insert")), + ("text.setText", json!({"ids": [id.0], "text": true}), string("text")), + ("text.createInPath", json!({"path": frame, "mode": 1}), string("mode")), + ("text.createInPath", json!({"path": frame, "text": true}), string("text")), + ("text.createInPath", json!({"path": line, "mode": "onPath", "text": "a", "at": [1, "y"]}), point.clone()), + ("text.createInPath", json!({"path": line, "mode": "onPath", "at": [100]}), point.clone()), + ("text.createInPath", json!({"path": frame, "text": "a", "at": "start"}), point), + ("text.touchType", json!({"id": id.0, "start": 1.5, "dy": 2}), whole.clone()), + ("text.touchType", json!({"id": id.0, "start": -1, "dy": 2}), whole.clone()), + ("text.glyphAlternates", json!({"id": id.0, "start": 1.5}), whole.clone()), + ("text.setGlyphAlternate", json!({"id": id.0, "start": -1, "gid": null}), whole), + ] + .into_iter() + .map(|(cmd, p, msg)| (cmd.to_string(), p, msg)) + .collect(); + let wrong = not_refused(&mut s, &calls); + assert!(wrong.is_empty(), "not refused: {wrong:#?}"); + // Null keeps each default: nothing inserted, area type with no text, no start point. + s.execute("text.editRange", &json!({"id": id.0, "start": 0, "end": 1, "insert": null})).unwrap(); + assert_eq!(obj(&s, id).plain_text(), "bc"); + let r = s.execute("text.createInPath", &json!({"path": frame, "mode": null, "text": null, "at": null})).unwrap(); + let t = obj(&s, NodeId(r["id"].as_u64().unwrap())); + assert!(matches!(t.kind, TextKind::Area { .. }) && t.plain_text().is_empty(), "{:?}", t.kind); + s.execute("text.createInPath", &json!({"path": line, "mode": "onPath", "text": "a", "at": [100, 400]})).unwrap(); +} + /// Where each glyph of type object `id` is drawn from (its origin in font units), document space. fn glyph_pens(s: &Session, id: NodeId) -> Vec<(usize, Point)> { let t = obj(s, id); diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..6848635a23 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2430,11 +2430,15 @@ with `` `font` must be a string ``, and a `features` list with an entry that is `text.setStyle` and `text.setRangeStyle` refuse a `size` outside 0.1 to 1,296 pt with `` `size` must be from 0.1 to 1296 `` and change nothing. `type.ruby` refuses a `text`, `position` or `align` that is not a string, and `text.setPathHandle` refuses a `which` other than `in` or `out` with -`` `which` must be one of in, out ``. Each leaves the document, the selection and the undo history as they were, also -when the call gives another param it could apply. A null is read as a key left out. +`` `which` must be one of in, out ``. `text.editRange` refuses an `insert` that is not a string, `text.setText` a `text` +that is not a string, and `text.createInPath` a `mode` or `text` that is not a string, each with +`` `insert` must be a string ``, naming the key; `text.createInPath` refuses an `at` that is not two numbers with +`` `at` must be a point: [x, y] ``, in area mode too. Each leaves the document, the selection and the undo history as +they were, also when the call gives another param it could apply. A null is read as a key left out. A byte offset must be a whole number of at least 0. `at` in `text.startList`, and `start` and `end` in -`text.editRange`, `text.getRange` and `text.setRangeStyle`, and in `type.step` and `addon.type.textTweaker` given an `id`, +`text.editRange`, `text.getRange` and `text.setRangeStyle`, `start` in `text.touchType`, `text.glyphAlternates` and +`text.setGlyphAlternate`, and `start` and `end` in `type.step` and `addon.type.textTweaker` given an `id`, refuse a negative or fractional number with `` `at` must be a whole number ``, naming the key, and change nothing. `2.0` is read as `2`, and a null as the key left out. @@ -6207,7 +6211,8 @@ editing the pattern first". While a mask is edited, `object.pattern.edit` and `o Pathfinder Options: `object.pathfinder.options {precision?, removeRedundantPoints?, removeUnpainted?}` (or `prefs.get`/`prefs.set` with key `pathfinder`) reads and sets the options every later Shape Mode and Pathfinder -operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit also reads) is how closely results follow +operation uses: `precision` (0.001–10 pt, default 0.01; a string with a unit or a string that is all one number also reads, and +any other string, such as `"1abc"`, is an error) is how closely results follow the paths (they are refit to within it and pieces thinner than it are dropped), `removeRedundantPoints` takes the anchors that don't change a result's shape off it, and `removeUnpainted` makes Divide and Outline leave out the pieces of objects with no fill (or only hidden fills). Both default to false; `{}` reads the options. Each Shape Mode and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c4508481b3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -946,6 +946,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. - **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. +- **Text command parameter errors:** `text.editRange`'s `insert`, `text.setText`'s `text` and `text.createInPath`'s `mode` and `text` must be strings, `text.createInPath`'s `at` must be two numbers, and `start` in `text.touchType`, `text.glyphAlternates` and `text.setGlyphAlternate` must be a whole number of at least 0. A wrong value is an error naming the parameter, and the document and undo history do not change; null is read as the parameter left out. Pathfinder `precision` takes a number, a string that is all one number or a length with a unit, and refuses a string such as `"1abc"`. This is VectorCraft's own rule; no score changes. Tests: `tests::textedit::text_edits_refuse_a_param_of_the_wrong_type` and `tests::pathops::pathfinder_options_round_trip_and_refuse_bad_values` in `vectorcraft-engine`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. From 342341a55f230235436f1fb83aac347b826ff936 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:42:48 -0800 Subject: [PATCH 08/19] Smooth: path.smoothRegion and path.joinScrub refuse a radius, fidelity or tolerance outside its range path.smoothRegion read a radius below 0 as 0 and moved a fidelity into its range, and path.joinScrub read a tolerance below 0 as 0. Each now refuses a value outside its range with an error naming the key, and the document, the selection and the undo history do not change: radius and tolerance 0.001 to 1000 pt (the Path Eraser's width range), fidelity 0.000078125 to about 3195 pt (the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom). A key left out or null keeps its default. The Smooth, Join and Path Eraser tools, and an Alt smoothing drag with the Pencil, Paintbrush or Blob Brush, keep what they send within these ranges at any zoom, also when the interface zoom puts the tool's zoom past the view's range. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/draw2/commands.rs | 4 +- crates/engine/src/cmd/draw2/smooth.rs | 16 ++++--- crates/engine/src/tests/draw2.rs | 60 +++++++++++++++++++++++++ crates/tools/src/draw2.rs | 5 +++ crates/tools/src/draw2/gesture.rs | 24 +++++++--- crates/tools/src/draw2/gesture/tests.rs | 39 ++++++++++++++++ docs/mcp.md | 8 ++++ docs/target-app-parity.md | 1 + 8 files changed, 144 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index e4846367b5..9c3dcbd47a 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Smooth", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12), fidelity?: pt (2.5; kept within 0.000078125 and about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the smoothing), radius?: pt (12; from 0.001 to 1000), fidelity?: pt (2.5; from 0.000078125 to about 3195, the Smooth tool's 0.05 to 100 px at the highest and the lowest zoom: the tool sends its Fidelity in screen pixels divided by the zoom, kept within the range)} smooth selected paths near the drag, keeping a corner where the path turns by more than 57.5° at the anchor and over radius and twice radius on either side → {ids, before, after}. A radius or fidelity outside its range is refused with an error, and nothing changes", has_selection, smooth_region ), @@ -129,7 +129,7 @@ pub fn specs() -> Vec { "Join", [], None, - "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}", + "{points: [[x,y]…] (pen values after x and y are checked as path.freehand checks them and do not change the join), tolerance?: pt (12; from 0.001 to 1000)} join the open-path endpoints scrubbed over, or trim two crossing open paths whose overhanging ends are scrubbed and join them at the crossing → {id}. A tolerance outside 0.001 to 1000 is refused with an error, and nothing changes", has_doc, join_scrub ), diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..52b18c3a31 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,9 +1,9 @@ use vectorcraft_pathops::addons::pathtools as pt; -use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; +use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, ranged, subpath_len, target_paths}; use super::{ - Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, json, - number_or, po, + Anchor, BezPath, CubicBez, NodeId, ParamCurve, ParamCurveNearest, PathData, Point, Rect, Result, Session, SimplifyOptions, SubPath, Value, bad, + json, number_or, po, }; // ---------- Smooth ---------- @@ -733,8 +733,12 @@ fn smooth_open(anchors: &[Anchor], marked: &[bool], near: &dyn Fn(Point) -> bool pub(super) fn smooth_region(s: &mut Session, p: &Value) -> Result { const C: &str = "path.smoothRegion"; let pts = points_param(p, "points", C)?; - let radius = number_or(p, "radius", 12.0, C)?.max(0.0); - let tol = number_or(p, "fidelity", 2.5, C)?.clamp(vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let radius = ranged(p, "radius", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; + let tol = number_or(p, "fidelity", 2.5, C)?; + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + if !(lo..=hi).contains(&tol) { + return Err(bad(C, format!("`fidelity` must be from {lo} to {hi} pt"))); + } let sigma = radius * SMOOTH_SPREAD; let st = s.doc()?; let mut plan = vec![]; @@ -882,7 +886,7 @@ fn trim_join(d: &vectorcraft_doc::Document, ids: &[NodeId], pts: &[Point], tol: pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { const C: &str = "path.joinScrub"; let pts = points_param(p, "points", C)?; - let tol = number_or(p, "tolerance", 12.0, C)?.max(0.0); + let tol = ranged(p, "tolerance", 12.0, vectorcraft_tools::draw2::REACH_RANGE, C)?; let st = s.doc()?; let targets = target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)); // Paths that cross with their ends scrubbed are trimmed there and joined (#5844). diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 75d7d081d9..fe151dd7bb 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3313,6 +3313,66 @@ fn path_eraser_width_outside_its_range_is_refused() { } } +/// `path.smoothRegion` refuses a `radius` outside 0.001 to 1000 pt and a `fidelity` outside the +/// Smooth tool's tolerance range, and `path.joinScrub` a `tolerance` outside 0.001 to 1000 pt: the +/// document, the selection and the undo history do not change. The ends of each range are taken, +/// and null is read as the key left out, which smooths or joins in one undo step. +#[test] +fn smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range() { + let mut s = session(); + let anchors: Vec<_> = (0..=40).map(|i| json!({"x": 100.0 + i as f64 * 5.0, "y": if i % 2 == 0 { 200.0 } else { 203.0 }})).collect(); + let r = s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let drag = json!({"points": [[90, 200], [200, 200], [310, 200]]}); + let (lo, hi) = (vectorcraft_tools::draw2::SMOOTH_MIN_TOLERANCE, vectorcraft_tools::draw2::SMOOTH_MAX_TOLERANCE); + let reaches = [json!(0), json!(-1), json!(0.0009), json!(1e-300), json!(1000.01), json!(1e300)]; + let fidelities = [json!(0), json!(-1), json!(lo / 2.0), json!(hi * 1.01), json!(1e300)]; + let refused = reaches + .iter() + .map(|x| ("radius", x, "`radius` must be from 0.001 to 1000".to_string())) + .chain(fidelities.iter().map(|x| ("fidelity", x, format!("`fidelity` must be from {lo} to {hi} pt")))); + for (key, x, want) in refused { + let sel = s.doc().unwrap().selection.clone(); + refuses_with(&mut s, "path.smoothRegion", &with(&drag, json!({ key: x })), &want); + assert_eq!(s.doc().unwrap().selection, sel, "{key} {x} changed the selection"); + } + for extra in [json!({"radius": 0.001}), json!({"radius": 1000}), json!({"fidelity": lo}), json!({"fidelity": hi})] { + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, extra.clone())).unwrap_or_else(|e| panic!("{extra}: {e}")); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + } + let before = path(&s, id); + let undo = undo_steps(&s); + s.execute("path.smoothRegion", &with(&drag, json!({"radius": null, "fidelity": null}))).unwrap(); + assert!(path(&s, id) != before, "the default radius and fidelity smoothed nothing"); + assert_eq!(undo_steps(&s), undo + 1); + + let mut s = session(); + line(&mut s, 100.0, 100.0, 200.0, 100.0); + line(&mut s, 205.0, 100.0, 300.0, 150.0); + s.execute("select.none", &json!({})).unwrap(); + let scrub = json!({"points": [[202, 90], [202, 110]]}); + for x in &reaches { + refuses_with(&mut s, "path.joinScrub", &with(&scrub, json!({"tolerance": x})), "`tolerance` must be from 0.001 to 1000"); + assert_eq!(paths(&s).len(), 2, "tolerance {x}"); + } + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 0.001}))).unwrap(); + assert_eq!(paths(&s).len(), 2, "0.001 pt reaches neither end"); + let undo = undo_steps(&s); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": 1000}))).unwrap(); + while undo_steps(&s) > undo { + s.execute("edit.undo", &json!({})).unwrap(); + } + s.execute("select.none", &json!({})).unwrap(); + s.execute("path.joinScrub", &with(&scrub, json!({"tolerance": null}))).unwrap(); + assert_eq!(paths(&s).len(), 1, "the default tolerance joined nothing"); + assert_eq!(undo_steps(&s), undo + 1); +} + /// The Eraser, Path Eraser, Smooth, Join and Blob Brush commands refuse a size, angle, roundness, /// width, radius, fidelity or tolerance given as text or as another value that is not a number, and change /// nothing; null is read as the key left out. diff --git a/crates/tools/src/draw2.rs b/crates/tools/src/draw2.rs index 3c663006e5..800cda5d94 100644 --- a/crates/tools/src/draw2.rs +++ b/crates/tools/src/draw2.rs @@ -50,6 +50,11 @@ pub const SMOOTH_MIN_TOLERANCE: f64 = SMOOTH_MIN_FIDELITY / 640.0; /// pixels) at the lowest zoom (3.13 %). pub const SMOOTH_MAX_TOLERANCE: f64 = 100.0 / 0.0313; +/// The range (points) of `path.smoothRegion`'s `radius`, `path.joinScrub`'s `tolerance` and +/// `path.eraseSegments`' `width`, which the tools send as screen pixels divided by the zoom. +/// VectorCraft's own range. +pub const REACH_RANGE: (f64, f64) = (0.001, 1000.0); + /// Whether segment `i` of `sp` is straight, so the Smooth tool leaves it as it is: its handles lie /// on the line through its ends, and the segment runs from one end to the other without turning back. pub fn segment_is_straight(sp: &SubPath, i: usize) -> bool { diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index dc123e6cc1..ab88d16436 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -96,6 +96,20 @@ fn fit_tolerance(cx: &ToolContext, px: f64) -> f64 { cx.tol(px).clamp(super::MIN_FIT_TOLERANCE, super::MAX_FIT_TOLERANCE) } +/// The `fidelity` (points) the Smooth tool, and an Alt smoothing drag, send `path.smoothRegion` for +/// `px` screen pixels at the current zoom, within the range the command takes +/// ([`super::SMOOTH_MIN_TOLERANCE`]..[`super::SMOOTH_MAX_TOLERANCE`]). +fn smooth_tolerance(cx: &ToolContext, px: f64) -> f64 { + cx.tol(px).clamp(super::SMOOTH_MIN_TOLERANCE, super::SMOOTH_MAX_TOLERANCE) +} + +/// The distance (points) the Smooth, Join and Path Eraser tools send for `px` screen pixels at the +/// current zoom, within [`super::REACH_RANGE`]. +fn reach(cx: &ToolContext, px: f64) -> f64 { + let (lo, hi) = super::REACH_RANGE; + cx.tol(px).clamp(lo, hi) +} + pub struct GestureTool { /// How many points the last preview of the stroke had ([`crate::previews_at`]); 0 when it was /// fitted coarser than the stroke kept ([`PREVIEW_FIDELITY_PX`]). @@ -1550,13 +1564,13 @@ impl GestureTool { fn finish(&mut self, cx: &ToolContext, m: Mods) -> Vec { let pts = &self.points; let has_sel = !cx.selection.is_empty(); - let tol = cx.tol(self.edit_within); - let radius = cx.tol(SMOOTH_RADIUS); + let tol = reach(cx, self.edit_within); + let radius = reach(cx, SMOOTH_RADIUS); if self.smoothing { if pts.len() >= 2 && has_selected_smooth_path(cx) { return vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.smooth_fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.smooth_fidelity)}), )]; } return vec![]; @@ -1621,10 +1635,10 @@ impl GestureTool { "smooth" if pts.len() >= 2 && has_selected_smooth_path(cx) => { vec![Action::Exec( "path.smoothRegion".into(), - json!({"points": points_json(pts), "radius": radius, "fidelity": cx.tol(self.fidelity)}), + json!({"points": points_json(pts), "radius": radius, "fidelity": smooth_tolerance(cx, self.fidelity)}), )] } - "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": cx.tol(8.0)}))], + "pathEraser" if has_sel => vec![Action::Exec("path.eraseSegments".into(), json!({"points": points_json(pts), "width": reach(cx, 8.0)}))], "join" if pts.len() >= 2 => vec![Action::Exec("path.joinScrub".into(), json!({"points": points_json(pts), "tolerance": tol}))], _ => vec![], } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 1ffcf1c37b..dbbbb53a78 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -309,6 +309,45 @@ fn fidelity_sent_stays_within_what_path_freehand_takes() { } } +/// `path.smoothRegion`, `path.joinScrub` and `path.eraseSegments` refuse a radius, Fidelity, +/// tolerance or width outside their ranges, so at a zoom beyond the view's range the Smooth, Join +/// and Path Eraser tools, and an Alt smoothing drag, send the nearer end of each. +#[test] +fn smooth_join_and_path_eraser_send_values_their_commands_take() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + let (reach_lo, reach_hi) = crate::draw2::REACH_RANGE; + let (tol_lo, tol_hi) = (crate::draw2::SMOOTH_MIN_TOLERANCE, crate::draw2::SMOOTH_MAX_TOLERANCE); + let alt = Mods { alt: true, ..Default::default() }; + for (zoom, fidelity, reach, tol) in [(0.001, 100.0, reach_hi, tol_hi), (100_000.0, 0.05, reach_lo, tol_lo)] { + cx.zoom = zoom; + // The same drag on screen at each zoom. + let pts: Vec<_> = [(50.0, 150.0), (150.0, 150.0), (250.0, 160.0)].iter().map(|&(x, y)| (x / zoom, y / zoom)).collect(); + let sent = |acts: &[Vec]| match acts.last().and_then(|a| a.first()) { + Some(Action::Exec(c, v)) => (c.clone(), v.clone()), + a => panic!("expected a command at {zoom}x, got: {a:?} in {acts:?}"), + }; + let mut smooth = GestureTool::new("smooth"); + smooth.set_option("fidelity", &json!(fidelity)); + let mut pencil = GestureTool::new("pencil"); + pencil.set_option("altSmooth", &json!(true)); + pencil.set_option("smoothFidelity", &json!(fidelity)); + for (what, acts) in [("smooth", drag(&mut smooth, &cx, &pts, Mods::default())), ("pencil", drag_held(&mut pencil, &cx, &pts, alt))] { + let (c, v) = sent(&acts); + assert_eq!(c, "path.smoothRegion", "{what} at {zoom}x"); + assert_eq!((v["radius"].as_f64(), v["fidelity"].as_f64()), (Some(reach), Some(tol)), "{what} at {zoom}x: {v}"); + } + let (c, v) = sent(&drag(&mut GestureTool::new("join"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["tolerance"].as_f64()), ("path.joinScrub", Some(reach)), "join at {zoom}x: {v}"); + let (c, v) = sent(&drag(&mut GestureTool::new("pathEraser"), &cx, &pts, Mods::default())); + assert_eq!((c.as_str(), v["width"].as_f64()), ("path.eraseSegments", Some(reach)), "path eraser at {zoom}x: {v}"); + } +} + /// The Blob Brush's Fidelity stays in points (#5729 is the Pencil's and the Paintbrush's): its /// stroke, and another tool chosen while it is drawn, send it as set at any zoom. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..612bfb775a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7062,6 +7062,14 @@ VectorCraft's own values. `` `width` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is recorded. Left out or null, `width` is 8 pt. The range is VectorCraft's own value. +`path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt with +`` `radius` must be from 0.001 to 1000 `` and a `fidelity` outside 0.000078125 to about 3195 pt (the Smooth tool's +0.05 to 100 px at the highest and the lowest zoom) with `` `fidelity` must be from 0.000078125 to 3194.8881789137376 pt ``. +`path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt with +`` `tolerance` must be from 0.001 to 1000 ``. The document and the selection do not change and no undo step is +recorded. Left out or null, `radius` is 12 pt, `fidelity` is 2.5 pt and `tolerance` is 12 pt. The tools send these in screen +pixels divided by the zoom, kept within the ranges. The `radius` and `tolerance` ranges are VectorCraft's own values. + These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: `independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..c513bfcca8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1461,6 +1461,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Eraser Tool Options has Angle and Roundness besides Size, as [Erase paths using the Eraser tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-paths-using-eraser-tool.html) describes: the Eraser's tip is an ellipse Size across, its long axis at Angle and its short axis Roundness percent of the long one, and a drag with a tip that is not round shows the outline of the area it erases (`path.eraseRegion` `angle` and `roundness`). `path.eraseRegion` refuses an Angle outside −180° to 180° and a Roundness outside 1% to 100% with an error and leaves the document unchanged; a key left out or null takes its default (0° and 100%). The help page gives no range for the two options, so the ranges are VectorCraft's own values. `path.split` refuses a `t` outside 0 to 1 in the same way. `path.eraseSegments` (the Path Eraser) refuses a `width` outside 0.001 to 1000 pt with an error and leaves the document unchanged; left out or null, the width is 8 pt. The help page gives the Path Eraser no width option, so the range is VectorCraft's own value. + `path.smoothRegion` (the Smooth tool) refuses a `radius` outside 0.001 to 1000 pt or a `fidelity` outside 0.000078125 to about 3195 pt with an error naming the key, and `path.joinScrub` (the Join tool) refuses a `tolerance` outside 0.001 to 1000 pt the same way; the document does not change; before, a radius or tolerance below 0 was read as 0 and a fidelity was moved into its range. Left out or null, the defaults stay (12 pt, 2.5 pt and 12 pt), and the tools keep what they send within the ranges at any zoom. The radius and tolerance ranges are VectorCraft's own values (engine `smooth_and_join_refuse_a_reach_or_fidelity_outside_its_range`). Eraser Tool Options gives Angle, Roundness and Size each a menu of Fixed, Random, Pressure, Tilt, Bearing and Rotation with a Variation field, as the same page describes: the tip varies by up to the Variation either way, Random once per drag and the others with what the pen reads at each point of the drag, and the tip outline at the pointer follows the pen while it erases. The outline of the area a drag shows takes, at each step, the tip the pen's readings give halfway along it, with a Random value shown as the value itself, and a mouse drag erases at the set values (`path.eraseRegion` `angleMode`, `roundnessMode`, `sizeMode` and their variations). Eraser Tool Options show the Blob Brush's tip preview under the Roundness rows. A drag on the arrowhead turns the Angle, and a drag that starts on a black dot moves it toward the center for a flatter tip or away from it for a rounder one, as the Eraser tool options section of the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=133) describes; the fields show the new values, and OK keeps them. The drag's mapping and the Angle and Roundness sliders are the Blob Brush preview's, which are VectorCraft's own, with the Eraser's Roundness range of 1% to 100% for the drag and the keys. The preview shows the set Angle and Roundness, not a Random or pen-driven variation of them. Regression tests: `dialogs::tests::the_eraser_tip_preview_sets_the_angle_and_roundness_by_dragging`, `dialogs::freehand::tests::a_roundness_dot_keeps_the_eraser_at_one_percent_or_more`. The outline a Blob Brush or Eraser drag shows is built a bounded amount per frame, so a long stroke does not slow the canvas: each frame takes at most 256 new points of the drag and outlines again only the pieces of up to 32 segments they change, and the parts of a piece's outline inside the rest of the area are removed a limited amount at a time. While work is left, the canvas draws again with the pointer still, the points not outlined yet show as a thin line, and the tip shows at the pointer. When the tip varies with the pen (Size set to Pressure, or an Eraser mode that follows the pen), each step is its own piece and the outline also shows only the edge of the whole area. The release sends the whole stroke as before (`path.blob`, `path.eraseRegion`). From 49fd8652b13adf31eea13819a5ffa4162a8d6312 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 23:49:54 -0800 Subject: [PATCH 09/19] Dimension tool: a geometry effect on any part keeps a dimension in place A press on one part of a dimension now also checks its other parts for a geometry effect, so an effect on an extension line keeps the drag from moving the dimension (and from drawing the parts again without the effect). In isolation mode, only art inside the isolated object is compared with the dimension when the press decides between them. --- crates/engine/tests/it/dimensions.rs | 44 ++++++++++++++++++++++++++++ crates/tools/src/dimension.rs | 32 ++++++++++++++++---- 2 files changed, 70 insertions(+), 6 deletions(-) diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index c92390feec..9d9446fa90 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -2352,6 +2352,50 @@ fn a_dimension_is_dragged_only_where_the_canvas_hits_it() { assert!(!boxes.iter().any(|r| r.x1 > 399.0), "the rectangle is not outlined: {boxes:?}"); } +/// A geometry effect on a part of a dimension other than the one pressed keeps the Dimension tool +/// from dragging it, and the effect stays on that part. +#[test] +fn a_geometry_effect_on_another_part_keeps_the_dimension_in_place() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + let extension = { + let doc = &s.doc().unwrap().doc; + let parts = doc.node(NodeId(first)).unwrap().children().unwrap(); + // The extension line at x = 100, which the press below on the dimension line misses. + let line = parts.iter().find(|c| c.geometric_bounds().is_some_and(|r| r.x1 < 101.0 && r.height() > 10.0)); + line.unwrap().id.0 + }; + run(&mut s, "effect.apply", json!({"effect":"distort.transform","ids":[extension],"params":{"moveH":-60}})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 170.0), (PointerKind::Down, 170.0), (PointerKind::Drag, 130.0), (PointerKind::Up, 130.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 170.0), pt(200.0, 170.0))); + let kept = s.doc().unwrap().doc.node(NodeId(extension)).is_some_and(|n| !n.appearance.effects.is_empty()); + assert!(kept, "the extension line keeps its effect"); +} + +/// In isolation mode, art outside the isolated group does not take a press on a dimension inside +/// it: the drag moves the dimension. +#[test] +fn art_outside_isolation_does_not_take_the_press_on_a_dimension() { + let plain = ViewInfo::default(); + let pt = vectorcraft_geom::Point::new; + let (mut s, first) = level_start(plain); + // A line across the dimension line, outside the group isolated below. The press, a point below + // the dimension line, is nearer to it than to the dimension line. + run(&mut s, "path.create", json!({"d": "M150 100 L150 250"})); + run(&mut s, "select.set", json!({"ids":[first]})); + let group = run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap(); + run(&mut s, "object.isolate", json!({"id": group})); + run(&mut s, "select.none", json!({})); + for (kind, y) in [(PointerKind::Move, 171.0), (PointerKind::Down, 171.0), (PointerKind::Drag, 131.0), (PointerKind::Up, 131.0)] { + s.pointer(&PointerEvent::new(kind, 150.0, y), plain).unwrap(); + } + assert_eq!(recipe(&s, first).line_ends(), (pt(100.0, 130.0), pt(200.0, 130.0))); +} + /// A dimension pasted into a document that had none is dragged with the Dimension tool like one /// drawn there. #[test] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 081703bb13..9e770fbe68 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -157,6 +157,11 @@ fn constrained(cx: &ToolContext, last: Point, at: Point) -> Point { /// Nearest editable segment, with bounded work and no snapping to dimension artwork itself. pub fn pick(cx: &ToolContext, p: Point) -> Option { + pick_among(cx, p, cx.doc.layers.iter().rev().map(|n| n.as_ref())) +} + +/// [`pick`] among `roots`, topmost first, and what they hold. +fn pick_among<'a>(cx: &ToolContext, p: Point, roots: impl Iterator) -> Option { let mut best = None; let mut dist = cx.tol(8.0); let mut budget = 20_000usize; @@ -186,7 +191,7 @@ pub fn pick(cx: &ToolContext, p: Point) -> Option { } } } - for n in cx.doc.layers.iter().rev() { + for n in roots { visit(n, p, &mut budget, &mut dist, &mut best); } best @@ -601,11 +606,21 @@ fn dimension_under(cx: &ToolContext, p: Point) -> Option<(NodeId, f64)> { let nodes: Vec<&Node> = chain.iter().filter_map(|id| cx.doc.node(*id)).collect(); let below = scope_at.map_or(0, |i| i + 1); let outline = opt.outline || nodes.iter().skip(below).any(|n| matches!(n.kind, NodeKind::Layer { preview: false, .. })); - let displaced = nodes.iter().enumerate().any(|(i, n)| { - vectorcraft_effects::has_geometry(&n.appearance.effects) - || (i >= at && n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects()))) + let item_geometry = |n: &Node| n.appearance.items.iter().any(|item| item.visible() && vectorcraft_effects::has_geometry(item.effects())); + let displaced = nodes.iter().enumerate().any(|(i, n)| vectorcraft_effects::has_geometry(&n.appearance.effects) || (i >= at && item_geometry(n))); + // The parts of the dimension the press did not land on count too: a geometry effect on any of + // them is drawn elsewhere as well. + let parts_displaced = cx.doc.node(id).is_some_and(|d| { + d.try_walk(&mut |n| { + if vectorcraft_effects::has_geometry(&n.appearance.effects) || item_geometry(n) { + std::ops::ControlFlow::Break(()) + } else { + std::ops::ControlFlow::Continue(()) + } + }) + .is_break() }); - if !outline && displaced { + if !outline && (displaced || parts_displaced) { return None; } let n = cx.doc.node(id).filter(|_| cx.doc.is_editable(id))?; @@ -1199,7 +1214,12 @@ impl Tool for DimensionTool { && self.lines.is_empty() && let Some((id, d)) = dimension_under(cx, ev.pos) { - let art = pick(cx, ev.pos).and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); + // In isolation mode only art inside the isolated object competes for the press. + let edge = match cx.hit_options().scope.and_then(|s| cx.doc.node(s)) { + Some(isolated) => pick_among(cx, ev.pos, std::iter::once(isolated)), + None => pick(cx, ev.pos), + }; + let art = edge.and_then(|e| nearest_on(cx, &e, ev.pos)).map(|q| q.distance(ev.pos)); if art.is_none_or(|a| d < a) { self.grab = Some(id); } From 239a7d61d0fa337f1023e8640fe651d4dbf7dfe4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:15:55 -0800 Subject: [PATCH 10/19] Smooth: the dashed band shows the radius its release sends at the lowest zooms The band a smoothing drag shows took the Smooth radius in points without the 1,000 pt bound the release applies, so below 1.2% zoom it drew wider than the region path.smoothRegion smooths. It now uses the same bound. --- crates/tools/src/draw2/gesture.rs | 2 +- crates/tools/src/draw2/gesture/tests.rs | 32 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index ab88d16436..a34c819761 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1920,7 +1920,7 @@ impl Tool for GestureTool { // release smooths. if (self.id == "smooth" || self.smoothing) && has_selected_smooth_path(cx) - && let Some(path) = self.smooth_band(cx.tol(SMOOTH_RADIUS)) + && let Some(path) = self.smooth_band(reach(cx, SMOOTH_RADIUS)) { o.push(Overlay::SharedPath { path, color: FEEDBACK, width: 1.0, dash: Some(0.0) }); } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index dbbbb53a78..00f0ebc93e 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -1641,6 +1641,38 @@ fn smoothing_band_shows_no_seam_where_it_turns_across_a_square_side() { } } +/// Zoomed out far enough that the Smooth tool's radius in points passes the top of +/// [`crate::draw2::REACH_RANGE`], the band a smoothing drag shows has the radius its release sends. +#[test] +fn smoothing_band_at_the_lowest_zoom_has_the_radius_the_release_sends() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.set([id]); + let p = paint(); + let mut cx = cx(&d, &s, &p); + cx.smart_guides = false; + cx.zoom = 0.005; + let r = crate::draw2::REACH_RANGE.1; + assert!(cx.tol(SMOOTH_RADIUS) > r, "the radius on screen is past the range at {}x", cx.zoom); + let ends = [Point::new(1000.0, 1000.0), Point::new(5000.0, 1000.0)]; + let mut t = GestureTool::new("smooth"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, ends[0].x, ends[0].y)); + for i in 1..=20 { + let q = ends[0].lerp(ends[1], f64::from(i) / 20.0); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, q.x, q.y)); + } + let mut frames = 0; + while t.overlays_pending() { + assert!(frames < 10_000, "the band reaches the whole drag"); + bands(&t, &cx); + frames += 1; + } + check_band(&t, &cx, r); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, ends[1].x, ends[1].y)); + let Some(Action::Exec(c, v)) = acts.first() else { panic!("expected a command, got {acts:?}") }; + assert_eq!((c.as_str(), v["radius"].as_f64()), ("path.smoothRegion", Some(r)), "{v}"); +} + /// One straight piece of a square's outline along a side, where the band goes on across only part /// of it, shows only the part with nothing across. #[test] From 38e36aeb819c32de4cde8d3f90c7900b2a180931 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 00:53:49 -0800 Subject: [PATCH 11/19] Paths: Object > Path > Simplify and Smooth keep a closed path's start Simplify and Smooth refit a closed path from its first corner and kept that order, so the path's first anchor moved and its dashes started somewhere else. A refit now starts at the old first anchor when it keeps one there, otherwise at a new anchor where the refit passes nearest that point while the result still has fewer anchors than the path had, and otherwise at the refit's nearest anchor. Its direction stays the same. A direct-selected run across the start follows the same rule; before, the path started at the run's end anchor. The Smooth tool's start_nearest moves into vectorcraft-pathops, and both commands call it with the limit on anchor count above. --- crates/engine/src/cmd/draw2/smooth.rs | 81 +------------ crates/engine/src/tests/simplify_part.rs | 81 ++++++++++--- crates/pathops/src/edit.rs | 147 +++++++++++++++++++++-- crates/pathops/src/lib.rs | 6 +- crates/pathops/tests/it/ops.rs | 68 +++++++++++ docs/mcp.md | 10 +- docs/target-app-parity.md | 1 + 7 files changed, 287 insertions(+), 107 deletions(-) diff --git a/crates/engine/src/cmd/draw2/smooth.rs b/crates/engine/src/cmd/draw2/smooth.rs index d0f480d132..e730401b60 100644 --- a/crates/engine/src/cmd/draw2/smooth.rs +++ b/crates/engine/src/cmd/draw2/smooth.rs @@ -1,4 +1,5 @@ use vectorcraft_pathops::addons::pathtools as pt; +use vectorcraft_pathops::start_nearest; use super::common::{dist_to_polyline, ids_json, path_mut, path_of, points_param, poly_bounds, subpath_len, target_paths}; use super::{ @@ -323,84 +324,6 @@ fn refit_run(anchors: &[Anchor], tol: f64, sigma: f64, free: [bool; 2]) -> Vec (usize, f64) { - let mut best: Option<(f64, usize, f64)> = None; - for j in 0..orig.anchors.len() { - let hit = orig.segment(j).nearest(p, 1e-9); - if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { - best = Some((hit.distance_sq, j, hit.t)); - } - } - best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) -} - -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before smoothing) from its first anchor is used, -/// then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest point, -/// is returned as it is. -fn start_nearest(mut sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - let n = sp.anchors.len(); - if !sp.closed || n < 2 { - return sp; - } - // (distance, place along `orig` once a tie needs it, segment of `sp`, parameter) - type Best = (f64, Option<(usize, f64)>, usize, f64); - let mut best: Option = None; - for i in 0..n { - let c = sp.segment(i); - let hit = c.nearest(start, 1e-9); - if !hit.distance_sq.is_finite() || !hit.t.is_finite() { - continue; - } - let d = hit.distance_sq.sqrt(); - match &mut best { - None => best = Some((d, None, i, hit.t)), - Some((bd, bplace, bi, bt)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, sp.segment(*bi).eval(*bt))); - let place = place_along(orig, c.eval(hit.t)); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), i, hit.t)); - } - } - Some((bd, ..)) if d < *bd => best = Some((d, None, i, hit.t)), - Some(_) => {} - } - } - let Some((_, _, i, t)) = best else { return sp }; - let c = sp.segment(i); - let at = c.eval(t); - let first = if at.distance(c.p0) <= START_SNAP { - i - } else if at.distance(c.p3) <= START_SNAP { - (i + 1) % n - } else { - let mid = if sp.segment_is_line(i) { - Anchor::corner(at) - } else { - let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); - sp.anchors[i].h_out = l.p1; - sp.anchors[(i + 1) % n].h_in = r.p2; - Anchor::with_handles(at, l.p2, r.p1) - }; - sp.anchors.insert(i + 1, mid); - i + 1 - }; - sp.anchors.rotate_left(first); - sp -} - /// Pieces of curve that one Smooth drag measures against the drag while it searches the segments /// under it ([`reach_samples`]), shared equally by the curved segments that come within its reach, /// each of which gets at least one: enough to search 300,000 pt of curve within the default reach @@ -1009,6 +932,8 @@ pub(super) fn join_scrub(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod tests { + use vectorcraft_pathops::START_SNAP; + use super::*; /// A closed ring of four smooth anchors round (100, 100) with radius 50. diff --git a/crates/engine/src/tests/simplify_part.rs b/crates/engine/src/tests/simplify_part.rs index f3ab93f274..82f6cdc628 100644 --- a/crates/engine/src/tests/simplify_part.rs +++ b/crates/engine/src/tests/simplify_part.rs @@ -122,34 +122,87 @@ fn separate_runs_on_one_path_simplify_independently_in_one_step() { assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// The points of a closed 80-gon of radius 100 round (300, 300), starting at (400, 300). +fn eighty_gon() -> Vec<(f64, f64)> { + (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect() +} + /// On a closed 80-gon, a run from anchor 70 through the start point to anchor 10 simplifies as one -/// run: anchor 0 goes, anchors 11–69 stay exactly as they were (the path now starts at anchor 10), -/// anchors 10 and 70 stay where they were with their outer handles, and the path stays closed. +/// run: anchor 0 goes, and the path starts at a new anchor where the refitted run passes nearest +/// it; anchors 11–69 stay exactly as they were, anchors 10 and 70 stay where they were with their +/// outer handles, the path stays closed, and the refitted run stays direct-selected. #[test] fn a_run_across_the_start_of_a_closed_path_simplifies_as_one() { let mut s = session(); - let pts: Vec<(f64, f64)> = - (0..80).map(|i| (f64::from(i) * std::f64::consts::TAU / 80.0).sin_cos()).map(|(y, x)| (300.0 + 100.0 * x, 300.0 + 100.0 * y)).collect(); - let id = polyline(&mut s, &pts, true); + let id = polyline(&mut s, &eighty_gon(), true); let original = path_of(&s, id).subpaths[0].clone(); select_anchors(&mut s, id, &[(70, 79), (0, 10)]); s.execute("object.path.simplify", &json!({"tolerance": 1})).unwrap(); let sp = path_of(&s, id).subpaths[0].clone(); assert!(sp.closed); assert!(sp.anchors.len() < 80 - 10, "{}", sp.anchors.len()); - assert!(!sp.anchors.iter().any(|a| a.p == original.anchors[0].p), "anchor 0 was inside the run"); - assert_eq!(sp.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); - assert_eq!((sp.anchors[0].p, sp.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); - assert_eq!((sp.anchors[60].p, sp.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); - for i in 0..60 { - assert_eq!(sp.segment(i), original.segment(10 + i)); - } + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt"); let n = sp.anchors.len(); - assert!(worst_offset(&original, (70..80).chain(0..10), &sp, 60..n) <= 1.0 + 1e-6); - let sel: BTreeSet<_> = std::iter::once((0, 0)).chain((60..n).map(|i| (0, i))).collect(); + let k = sp.anchors.iter().position(|a| a.p == original.anchors[10].p).unwrap(); + let mut turned = sp.clone(); + turned.anchors.rotate_left(k); + assert_eq!(turned.anchors.to_vec()[1..60], original.anchors.to_vec()[11..70]); + assert_eq!((turned.anchors[0].p, turned.anchors[0].h_out), (original.anchors[10].p, original.anchors[10].h_out)); + assert_eq!((turned.anchors[60].p, turned.anchors[60].h_in), (original.anchors[70].p, original.anchors[70].h_in)); + for i in 0..60 { + assert_eq!(turned.segment(i), original.segment(10 + i)); + } + assert!(worst_offset(&original, (70..80).chain(0..10), &turned, 60..n) <= 1.0 + 1e-6); + let sel: BTreeSet<_> = (0..=k).chain(k + 60..n).map(|i| (0, i)).collect(); assert_eq!(s.doc().unwrap().selection.anchors.get(&id), Some(&sel)); } +/// Smooth of a direct-selected run across the start of a closed 80-gon starts the path near where it +/// started too, with fewer anchors. +#[test] +fn smoothing_a_run_across_the_start_keeps_the_start() { + let mut s = session(); + let id = polyline(&mut s, &eighty_gon(), true); + let original = path_of(&s, id).subpaths[0].clone(); + select_anchors(&mut s, id, &[(70, 79), (0, 10)]); + s.execute("object.path.smooth", &json!({"level": 50})).unwrap(); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < 80, "{}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", sp.anchors[0].p); +} + +/// A dashed closed path keeps its start, where its dashes begin, through Simplify and through +/// Smooth: a loop of radius 50 round (300, 300) with a needle out to (550, 300), starting on the far +/// side of the loop at (250, 300). Its stroke stays as it was, and each command is one undo step. +#[test] +fn a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth() { + let mut s = session(); + let at = |deg: f64| (300.0 + 50.0 * deg.to_radians().cos(), 300.0 + 50.0 * deg.to_radians().sin()); + let pts: Vec<(f64, f64)> = + (0..=20).map(|i| at(180.0 + 8.95 * f64::from(i))).chain([(550.0, 300.0)]).chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))).collect(); + let id = polyline(&mut s, &pts, true); + s.execute("stroke.set", &json!({"ids": [id.0], "weight": 2, "dash": [10, 5]})).unwrap(); + let stroke = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().appearance.clone(); + let style = stroke(&s); + let original = path_of(&s, id).subpaths[0].clone(); + // (command, params, how far the start may move: Simplify's tolerance, or Smooth's smoothing and tolerance) + let commands = [("object.path.simplify", json!({"tolerance": 1}), 1.0 + 1e-9), ("object.path.smooth", json!({"level": 50}), 5.0)]; + for (command, params, limit) in commands { + let steps = undo_len(&s); + s.execute(command, ¶ms).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "{command}"); + let sp = path_of(&s, id).subpaths[0].clone(); + assert!(sp.closed && sp.anchors.len() < original.anchors.len(), "{command}: {}", sp.anchors.len()); + let moved = sp.anchors[0].p.distance(original.anchors[0].p); + assert!(moved <= limit, "{command}: the start moved {moved} pt, to {:?}", sp.anchors[0].p); + assert_eq!(stroke(&s), style, "{command}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id).subpaths[0], original, "{command}"); + } +} + /// Segments picked with the Direct Selection tool simplify the same way, and stay picked as /// segments. #[test] diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 3ad1281eb2..a26da95828 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -97,7 +97,10 @@ fn turn_deg(a: &Seg, b: &Seg) -> f64 { d.acos().to_degrees() } -/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. +/// Least-squares Bézier refit of every subpath, keeping corners sharper than the threshold. A closed +/// subpath starts where it did: at its first anchor when the refit keeps an anchor there, otherwise +/// at a new anchor split into the refit at its point nearest there when the refit still has fewer +/// anchors than the subpath with that one, and otherwise at the refit's anchor nearest there. pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { let mut out = Vec::new(); for sp in &path.subpaths { @@ -108,15 +111,132 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { PathData::new(out) } -/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed subpath -/// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the -/// point farthest from its start, or in three when two still give that. When three parts still give -/// no area, straight lines follow the subpath within the tolerance, and without straight lines it +/// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit +/// starts where the subpath started ([`keep_start`]). +fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { + refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) +} + +/// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] +/// starts at that anchor instead of at a new one split in beside it. +pub const START_SNAP: f64 = 1e-3; + +/// Distance (points) within which two points of a closed path count as equally near its old start. +const START_TIE: f64 = 1e-6; + +/// Where `p` lies along the closed `orig` from its first anchor: the segment index and parameter of +/// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place +/// when there is none. +fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + let mut best: Option<(f64, usize, f64)> = None; + for j in 0..orig.anchors.len() { + let hit = orig.segment(j).nearest(p, 1e-9); + if hit.distance_sq.is_finite() && hit.t.is_finite() && best.is_none_or(|(d, ..)| hit.distance_sq < d) { + best = Some((hit.distance_sq, j, hit.t)); + } + } + best.map_or((usize::MAX, f64::INFINITY), |(_, j, t)| (j, t)) +} + +/// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: +/// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from +/// its first anchor, then the first given. +fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { + // (distance, place along `orig` once a tie needs it, point, value) + type Best = (f64, Option<(usize, f64)>, Point, T); + let mut best: Option> = None; + for (d, p, x) in candidates { + if !d.is_finite() { + continue; + } + match &mut best { + None => best = Some((d, None, p, x)), + Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { + let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); + let place = place_along(orig, p); + if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { + best = Some((d, Some(place), p, x)); + } + } + Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), + Some(_) => {} + } + } + best.map(|(.., x)| x) +} + +/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new +/// anchor split into the segment there, which leaves the outline as it is. Of points equally near +/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is +/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// point, is returned as it is. +pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { + start_near(sp, start, orig, true).0 +} + +/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies +/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → +/// (the path, the segment split when one was, where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { + let n = sp.anchors.len(); + if !sp.closed || n < 2 { + return (sp, None, 0); + } + let hits = (0..n).map(|i| { + let c = sp.segment(i); + let hit = c.nearest(start, 1e-9); + let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; + (d, c.eval(hit.t), (i, hit.t)) + }); + let Some((i, t)) = earliest_nearest(hits, orig) else { return (sp, None, 0) }; + let c = sp.segment(i); + let at = c.eval(t); + let (first, cut) = if at.distance(c.p0) <= START_SNAP { + (i, None) + } else if at.distance(c.p3) <= START_SNAP { + ((i + 1) % n, None) + } else if split { + let mid = if sp.segment_is_line(i) { + Anchor::corner(at) + } else { + let (l, r) = (c.subsegment(0.0..t), c.subsegment(t..1.0)); + sp.anchors[i].h_out = l.p1; + sp.anchors[(i + 1) % n].h_in = r.p2; + Anchor::with_handles(at, l.p2, r.p1) + }; + sp.anchors.insert(i + 1, mid); + (i + 1, Some(i)) + } else { + let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + (earliest_nearest(near, orig).unwrap_or(0), None) + }; + sp.anchors.rotate_left(first); + (sp, cut, first) +} + +/// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at +/// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An +/// open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { + match orig.anchors.first() { + Some(a) if orig.closed => { + let split = fit.anchors.len() + 1 < orig.anchors.len(); + start_near(fit, a.p, orig, split) + } + _ => (fit, None, 0), + } +} + +/// [`simplify_subpath`] before the start is put back: a closed subpath whose refit is one segment, +/// or lines that enclose no area, is refitted in two parts, cut at the point farthest from its +/// start, or in three when two still give that. When three parts still give no area, straight lines +/// follow the subpath within the tolerance, and without straight lines it /// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose /// an area, it stays as it is, or with straight lines follows the lines between samples of each /// curved segment when the limits leave room for lines within the tolerance; one that is all in line /// keeps the refit. -fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { +fn refit_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); if n == 0 || sp.closed && n < 2 { @@ -694,7 +814,8 @@ pub struct SimplifiedPart { /// two end anchors, which stay where they are with their handles on the side away from the run. /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more -/// segments than it had is left as it is (except with Convert to Straight Lines). +/// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -782,7 +903,17 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - (SubPath::new(anchors, sp.closed), runs, kept) + // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + let len = out.anchors.len(); + if (cut, first) == (None, 0) || len == 0 { + return (out, runs, kept); + } + let turned = |i: usize| (i + len - first) % len; + let after_cut = |i: usize| i + usize::from(cut.is_some_and(|c| i > c)); + let runs = runs.into_iter().flat_map(|s| if cut == Some(s) { vec![s, s + 1] } else { vec![after_cut(s)] }).map(turned).collect(); + let kept = kept.into_iter().map(|(old, new)| (old, turned(after_cut(new)))).collect(); + (out, runs, kept) } /// `a` with its out (`out`) or in handle at `h` and the other as it is: still smooth when it was diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d500182401..0ff1b82594 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -22,9 +22,9 @@ pub use boolean::{ try_unite_all_with, unite_all, unite_all_with, }; pub use edit::{ - AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, - remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, smooth_level, - smooth_options, split_into_grid, + AverageAxis, SIMPLIFY_LEVEL, SMOOTH_AUTO_LEVEL, START_SNAP, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, + join, remove_anchor, remove_anchors, remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, + smooth_level, smooth_options, split_into_grid, start_nearest, }; pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index a31c9af2e4..60410a0d5d 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -742,6 +742,74 @@ fn smooth_level_0_keeps_a_closed_paths_start_corner_within_tolerance() { assert!(moved <= limit, "level 0 moved the path by {moved} pt, more than {limit} pt: {:?}", s.subpaths[0].anchors[0]); } +/// Twice the area `sp` encloses, from 16 points along each segment: positive when it runs +/// counterclockwise in y-up terms. +fn signed_area(sp: &SubPath) -> f64 { + let pts: Vec = (0..sp.segment_count()).flat_map(|i| (0..16).map(move |k| sp.segment(i).eval(f64::from(k) / 16.0))).collect(); + (0..pts.len()).map(|i| pts[i].to_vec2().cross(pts[(i + 1) % pts.len()].to_vec2())).sum() +} + +/// A D of 41 corner points round (0, 0): the arc of radius 100 from (100, 0) up to (0, 100), the +/// straight side down to (0, -100), and the arc back. It starts in the middle of its arc, and its +/// first corner is at the top. +fn d_shape() -> SubPath { + let at = |deg: f64| Point::new(100.0 * deg.to_radians().cos(), 100.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20).map(|i| at(4.5 * f64::from(i))).chain((0..20).map(|i| at(-90.0 + 4.5 * f64::from(i)))).collect(); + SubPath::polyline(&pts, true) +} + +/// Object › Path › Simplify starts a closed path where it started, though the refit runs from the +/// first corner: on the D, the refit starts within the tolerance of the old start, runs the same way +/// round, and has fewer anchors. +#[test] +fn simplify_keeps_a_closed_paths_start() { + let sp = d_shape(); + let path = PathData::single(sp.clone()); + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, ..Default::default() }); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 1.0 + 1e-9, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); + assert!(one_way_distance(&path, &s).max(one_way_distance(&s, &path)) <= 1.0 + 1e-6); +} + +/// Object › Path › Smooth starts a closed path near where it started, though the refit runs from the +/// point where the path turns back: a round loop of radius 50 with a needle out to (250, 0), which +/// starts on the far side of the loop at (-50, 0). +#[test] +fn smooth_keeps_a_closed_paths_start() { + let at = |deg: f64| Point::new(50.0 * deg.to_radians().cos(), 50.0 * deg.to_radians().sin()); + let pts: Vec = (0..=20) + .map(|i| at(180.0 + 8.95 * f64::from(i))) + .chain([Point::new(250.0, 0.0)]) + .chain((0..20).map(|i| at(1.0 + 8.95 * f64::from(i)))) + .collect(); + let sp = SubPath::polyline(&pts, true); + let path = PathData::single(sp.clone()); + let s = smooth_level(&path, SMOOTH_AUTO_LEVEL); + let out = &s.subpaths[0]; + assert!(out.closed && out.anchors.len() < sp.anchors.len(), "{out:?}"); + let moved = out.anchors[0].p.distance(sp.anchors[0].p); + assert!(moved <= 5.0, "the start moved {moved} pt, to {:?}", out.anchors[0].p); + assert!(signed_area(out) * signed_area(&sp) > 0.0, "the direction stays"); +} + +/// A refit with only one anchor fewer than the closed path gets no anchor split in to keep its +/// start: it starts at its anchor nearest the old start. A rectangle with a straight point at +/// (30, 0) simplifies to its four corners, starting at (0, 0). +#[test] +fn simplify_starts_at_the_nearest_anchor_rather_than_add_one_back() { + let pts = [(30.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0), (0.0, 0.0)].map(|(x, y)| Point::new(x, y)); + let path = PathData::single(SubPath::polyline(&pts, true)); + let want = [(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)].map(|(x, y)| Point::new(x, y)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 1.0, straight_lines, ..Default::default() }); + let got: Vec = s.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(got, want, "straight_lines {straight_lines}"); + } +} + #[test] fn remove_redundant_collinear_and_curve() { let p = PathData::single(SubPath::polyline( diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..9ca5ab7c48 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7113,8 +7113,10 @@ result and the original path stay within `tolerance` of each other, except that is dropped, so a small circle in a compound path can be removed at a large `tolerance`. A segment that would need more than 65,536 samples at that tolerance stays as it is, and so does a segment after a run's first 16,777,216 samples or 2,097,152 result segments. With `straightLines`, such a segment becomes evenly spaced lines, up to 65,536, and past those -limits the lines can be farther than `tolerance` from the segment. With `level` or `auto`, the reply also has the `level` -used: +limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes +begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit +passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at +the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} @@ -7123,7 +7125,7 @@ used: With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then starts at the run's end anchor. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: @@ -7151,7 +7153,7 @@ side) to 100 (maximum smoothing); `auto: true` (Auto-Smooth) uses level 50, the its length (by up to 5% of its longer side; none at level 0) and refitted with curves within 0.1% to 2.5% of it, keeping a corner only where it turns back on itself, so bumps, jags and kinks become one curve; with anchor points or segments of a path direct-selected (and no `ids`), only the sections between them are smoothed, as Simplify does. A refit never has more anchor points than the path had, so a shape whose corners the tolerance can't -round, such as a rectangle, stays as it is. Closed paths stay closed and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: +round, such as a rectangle, stays as it is. Closed paths stay closed and keep their start as Simplify keeps it, and open paths keep their end points. The reply has the anchor counts `before` and `after` and the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.smooth","params":{"level":80}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..3af61d620e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,6 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From 956a76baa65af79fc6212a7cb89023cc4a812a8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:36:06 -0800 Subject: [PATCH 12/19] Paths: tied start candidates at one point search the old path once When several refit points tie for nearest to a closed path's old start, the earliest-along-the-path tie rule now places each distinct point on the old path once, so many segments meeting at one point no longer search every old segment once each. The tie rule is unchanged. Also "the same way around" in the docs. --- crates/pathops/src/edit.rs | 42 ++++++++++++++++++++++++++++++++------ docs/mcp.md | 2 +- docs/target-app-parity.md | 2 +- 3 files changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index a26da95828..d95a6c9037 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -1,7 +1,7 @@ //! Object → Path commands: Simplify, Smooth, Remove redundant points, Add Anchor Points, Average, //! Join, Split Into Grid. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -128,6 +128,8 @@ const START_TIE: f64 = 1e-6; /// the point of `orig` nearest `p`, the first such point in its order. Sorts after every finite place /// when there is none. fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { + #[cfg(test)] + tests::count_places(); let mut best: Option<(f64, usize, f64)> = None; for j in 0..orig.anchors.len() { let hit = orig.segment(j).nearest(p, 1e-9); @@ -140,11 +142,14 @@ fn place_along(orig: &SubPath, p: Point) -> (usize, f64) { /// Of the candidates (distance, point, value), the value of the nearest, with a finite distance: /// of those within [`START_TIE`] of each other, the one whose point is earliest along `orig` from -/// its first anchor, then the first given. +/// its first anchor, then the first given. Each distinct point is placed along `orig` once. fn earliest_nearest(candidates: impl IntoIterator, orig: &SubPath) -> Option { // (distance, place along `orig` once a tie needs it, point, value) type Best = (f64, Option<(usize, f64)>, Point, T); let mut best: Option> = None; + // Places along `orig` by the bits of the point, so many ties at one point search `orig` once. + let mut placed: HashMap<[u64; 2], (usize, f64)> = HashMap::new(); + let mut place = |p: Point| *placed.entry([p.x.to_bits(), p.y.to_bits()]).or_insert_with(|| place_along(orig, p)); for (d, p, x) in candidates { if !d.is_finite() { continue; @@ -152,10 +157,10 @@ fn earliest_nearest(candidates: impl IntoIterator, or match &mut best { None => best = Some((d, None, p, x)), Some((bd, bplace, bp, _)) if (d - *bd).abs() <= START_TIE => { - let held = *bplace.get_or_insert_with(|| place_along(orig, *bp)); - let place = place_along(orig, p); - if place.0 < held.0 || (place.0 == held.0 && place.1 < held.1) { - best = Some((d, Some(place), p, x)); + let held = *bplace.get_or_insert_with(|| place(*bp)); + let at = place(p); + if at.0 < held.0 || (at.0 == held.0 && at.1 < held.1) { + best = Some((d, Some(at), p, x)); } } Some((bd, ..)) if d < *bd => best = Some((d, None, p, x)), @@ -1533,6 +1538,31 @@ mod tests { MOVES.set(MOVES.get() + n); } + std::thread_local! { + /// Calls of [`place_along`], each a search of every segment of the path before the refit. + static PLACES: std::cell::Cell = const { std::cell::Cell::new(0) }; + } + + pub(super) fn count_places() { + PLACES.set(PLACES.get() + 1); + } + + /// Candidates tied at one point are placed along the old path once, not once each, and the first + /// given still wins the tie. + #[test] + fn tied_candidates_at_one_point_are_placed_once() { + let orig = SubPath::new( + vec![Anchor::corner(Point::new(0.0, 0.0)), Anchor::corner(Point::new(100.0, 0.0)), Anchor::corner(Point::new(100.0, 100.0))], + true, + ); + let candidates = (0..1000).map(|i| (0.0, Point::new(0.0, 0.0), i)); + PLACES.set(0); + let got = earliest_nearest(candidates, &orig); + let places = PLACES.get(); + assert_eq!(got, Some(0)); + assert_eq!(places, 1, "searches of the old path for 1000 candidates at one point"); + } + /// A subpath of `n` anchors from `seed`: corners, smooth points and points with one handle. fn random_subpath(seed: &mut u64, n: usize, closed: bool) -> SubPath { let mut rnd = || { diff --git a/docs/mcp.md b/docs/mcp.md index 9ca5ab7c48..e3043ece27 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7116,7 +7116,7 @@ than 65,536 samples at that tolerance stays as it is, and so does a segment afte limits the lines can be farther than `tolerance` from the segment. A closed path keeps its start, where its dashes begin: it starts at its old first anchor when the refit keeps an anchor there, otherwise at a new anchor where the refit passes nearest that point when the result with that anchor still has fewer anchors than the path had, and otherwise at -the refit's anchor nearest that point. It runs the same way round as before. With `level` or `auto`, the reply also has the `level` used: +the refit's anchor nearest that point. It runs the same way around as before. With `level` or `auto`, the reply also has the `level` used: ```json {"name":"run_command","arguments":{"command":"object.path.simplify","params":{"auto":true}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3af61d620e..677cc05923 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,7 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Simplify dialog also has Corner Point Angle Threshold, Convert to Straight Lines and Show Original Path. The threshold is a slider from 0° to 180° and opens at 150°: an anchor whose corner is sharper than the threshold stays a corner, so moving the slider right keeps more corners, and the dialog sends `cornerAngle` as 180° less the threshold. While Preview is on, Show Original Path draws the paths as they were before the preview in a wide, faint band of their layer's color under the selection's outlines. Object › Path › Simplify opens a slider under the selection ([Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html), [Auto simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/auto-simplify-paths.html)) with Auto-Simplify, a rail from the fewest anchor points to the closest fit, and More Options, which opens the dialog at the slider's tolerance. The rail's levels are VectorCraft's own scale (`object.path.simplify {level}`): level 50 is 1 pt, and every 10 levels halve or double the tolerance, from 32 pt at 0 to 1/32 pt at 100. Auto-Simplify picks the lowest level whose tolerance is at most 1/400 of the selection's longer side, or level 100 when that side is under 12.5 pt; the slider opens at that level, with its result previewed, as the manual-simplify page describes. The dialog's "Open this dialog with these settings next time" makes the menu item open the dialog on the settings of its last OK. With anchors or segments of a path selected with Direct Selection, Simplify acts on just that part of the path, as the [Manually simplify paths](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/manually-simplify-paths.html) page puts it: the slider, Auto-Simplify and the dialog refit only each run of selected segments, between its end anchors, which keep their place and their handles on the side away from the run. The anchors and segments outside the runs stay exactly as they were, a closed path's run may cross its start point, separate runs on one path are refitted independently in one undo step, and the runs stay selected. A path with only lone anchors selected is still simplified whole, and `object.path.simplify {wholePaths: true}` simplifies partly selected paths whole. Tests: `crates/engine/src/tests/simplify_part.rs` and `simplify_slider_and_dialog_simplify_only_the_direct_selected_part_of_a_path`. - Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way round. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. + Object › Path › Simplify and Smooth keep a closed path's start, where its dashes begin, whole or with a run across the start selected: the path starts at its old first anchor when the refit keeps one there, otherwise at a new anchor where the refit passes nearest it while the result still has fewer anchors, and otherwise at the refit's nearest anchor, running the same way around. This is VectorCraft's own rule. Tests: `ops.rs` tests `simplify_keeps_a_closed_paths_start`, `smooth_keeps_a_closed_paths_start` and `simplify_starts_at_the_nearest_anchor_rather_than_add_one_back`, and `simplify_part.rs` tests `a_run_across_the_start_of_a_closed_path_simplifies_as_one`, `smoothing_a_run_across_the_start_keeps_the_start` and `a_dashed_closed_path_keeps_its_start_through_simplify_and_smooth`. Object › Path › Smooth… (#4115) opens a slider under the selection from Minimum to Maximum smoothing with an Auto-Smooth button, as the [Smooth slider](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/refine-path-segments-with-the-smooth-slider.html) page describes; the canvas previews it and Enter or a click outside keeps it as one undo step (`object.path.smooth {level, auto, ids}`). The page names only the ends, so the rest is VectorCraft's own rule: each selected path, compound path members included, is smoothed along its length (by up to 5% of its longer side, so a shaky line comes out as one curve at Auto-Smooth) and refitted with curves within 0.1% (level 0) to 2.5% (level 100) of it, corners kept only where it turns back and never with more anchors (a rectangle stays as it is); Auto-Smooth is level 50. With anchor points of a path direct-selected, only the section between them is smoothed. Closed paths stay closed and open ones keep their end points. Tests: `crates/engine/src/tests/smooth_path.rs` and `smooth_slider_previews_auto_smooth_and_keeps_the_result`. - **Devanagari shaping:** with an OpenType Devanagari font, Ka, virama and Ssa (क्ष) form one conjunct glyph, Ra and virama before a consonant (र्क) become a reph drawn after it, the i matra (कि) is drawn before its consonant, and Ka with a nukta is drawn like the precomposed क़ (U+0958), as [Microsoft's Devanagari shaping specification](https://learn.microsoft.com/en-us/typography/script-development/devanagari) describes. Each syllable is one cluster of its source bytes, and the arrow keys stop at its ends. A click inside a syllable drawn with several glyphs puts the caret at the syllable's nearer end, in point, area and path type. Tests: `crates/text/src/tests/devanagari.rs`; they print SKIPPED when no such font is installed. - **Vertical type spacing shortcuts:** The [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page gives Alt+Down/Up for kerning at a caret or tracking of selected text, Alt+Left/Right for leading, and Alt+Shift+Right/Left for baseline shift. Alt+Shift+Down/Up also steps kerning or tracking. Down increases kerning or tracking, Left increases leading, and Shift+Right increases baseline shift; the opposite arrows decrease them. Cmd/Ctrl makes five steps. Horizontal type keeps its existing mapping; mixed horizontal and vertical text-object selections take the horizontal mapping for both objects in one undo step. Selected vertical point, area and path type use the same directions. Tests: `spacing_arrows_follow_each_text_objects_orientation`, `alt_arrows_rotate_for_selected_vertical_type`, `mixed_type_objects_take_horizontal_spacing_chords_in_both_orders`, and `selected_vertical_area_and_path_type_use_vertical_spacing_chords`. From 263718ffd24f5dc41b5c60d6fda529fdfb41a5b1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:58:10 -0800 Subject: [PATCH 13/19] Paths: a run across a closed path's start keeps the new start on that run When a direct-selected run holds a closed path's first anchor, Simplify and Smooth now look for the new start on that run alone, so an unselected segment that passes through the old start is not split. When the first anchor stays, the path already starts there and is left as it is. --- crates/pathops/src/edit.rs | 85 +++++++++++++++++++++++++++++++------- docs/mcp.md | 3 +- 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index d95a6c9037..dd5d84ebe7 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -2,6 +2,7 @@ //! Join, Split Into Grid. use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::ops::Range; use kurbo::{CubicBez, Line, ParamCurve, ParamCurveNearest, PathSeg, Point, Rect, Vec2}; use vectorcraft_geom::path::measured_arclen; @@ -114,7 +115,10 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// [`simplify_with`] for one subpath; `None` when the refit leaves nothing of it. A closed refit /// starts where the subpath started ([`keep_start`]). fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { - refit_subpath(sp, opts).map(|fit| keep_start(fit, sp).0) + refit_subpath(sp, opts).map(|fit| { + let n = fit.anchors.len(); + keep_start(fit, sp, 0..n).0 + }) } /// Distance (points) from an anchor within which a closed path restarted by [`start_nearest`] @@ -176,18 +180,21 @@ fn earliest_nearest(candidates: impl IntoIterator, or /// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { - start_near(sp, start, orig, true).0 + let n = sp.anchors.len(); + start_near(sp, start, orig, true, 0..n).0 } -/// [`start_nearest`], splitting a segment only when `split` is set; otherwise, when no anchor lies -/// at the nearest point, the path starts at its anchor nearest `start`, with the same tie rule. → -/// (the path, the segment split when one was, where the new start was before the anchors turned). -fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (SubPath, Option, usize) { +/// [`start_nearest`] on the segments `within` alone, splitting a segment only when `split` is set; +/// otherwise, when no anchor lies at the nearest point, the path starts at the anchor of those +/// segments nearest `start`, with the same tie rule. → (the path, the segment split when one was, +/// where the new start was before the anchors turned). +fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within: Range) -> (SubPath, Option, usize) { let n = sp.anchors.len(); if !sp.closed || n < 2 { return (sp, None, 0); } - let hits = (0..n).map(|i| { + let within = within.start.min(n)..within.end.min(n); + let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); let d = if hit.distance_sq.is_finite() && hit.t.is_finite() { hit.distance_sq.sqrt() } else { f64::NAN }; @@ -212,7 +219,8 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - let near = sp.anchors.iter().enumerate().map(|(j, a)| (a.p.distance(start), a.p, j)); + // The anchors of the segments `within`: each one's first, and the last one's end. + let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); (earliest_nearest(near, orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); @@ -221,13 +229,13 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool) -> (Su /// The closed refit `fit` of the closed `orig` started where `orig` starts: at its anchor at /// `orig`'s first anchor, or at a new anchor split in at its point nearest there when it still has -/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]). An -/// open `orig` keeps `fit` as it is. -fn keep_start(fit: SubPath, orig: &SubPath) -> (SubPath, Option, usize) { +/// fewer anchors than `orig` with that one, or else at its anchor nearest there ([`start_near`]), +/// looking only at the segments `within`. An open `orig` keeps `fit` as it is. +fn keep_start(fit: SubPath, orig: &SubPath, within: Range) -> (SubPath, Option, usize) { match orig.anchors.first() { Some(a) if orig.closed => { let split = fit.anchors.len() + 1 < orig.anchors.len(); - start_near(fit, a.p, orig, split) + start_near(fit, a.p, orig, split, within) } _ => (fit, None, 0), } @@ -820,7 +828,8 @@ pub struct SimplifiedPart { /// The other segments and anchors stay exactly as they are. A subpath whose every segment is in /// `segments` is simplified whole, as [`simplify_with`] does. A run whose refit would have more /// segments than it had is left as it is (except with Convert to Straight Lines). A closed subpath -/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]). +/// starts where it did, as [`simplify_with`] starts one ([`keep_start`]), on the run that held its +/// first anchor when that anchor goes. pub fn simplify_part(path: &PathData, segments: &BTreeSet<(usize, usize)>, opts: &SimplifyOptions) -> SimplifiedPart { let opts = &SimplifyOptions { free_start: false, free_end: false, ..*opts }; let (mut runs, mut anchors) = (BTreeSet::new(), BTreeMap::new()); @@ -859,6 +868,7 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP let mut anchors = vec![sp.anchors[start]]; let mut kept = vec![(start, 0)]; let mut runs = vec![]; + let mut start_run = None; let mut k = 0; while k < n { let j = (start + k) % n; @@ -891,7 +901,12 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } // The run's segments, from its first anchor on: a run back to the walk's start ends with // the closing segment, the last index. - runs.extend(first..first + if keep_original { run.len() } else { fitted.len() }); + let segs = first..first + if keep_original { run.len() } else { fitted.len() }; + if sp.closed && (k + 1..k + len).any(|i| (start + i) % m == 0) { + // The run that held the old first anchor. + start_run = Some(segs.clone()); + } + runs.extend(segs); let end_seg = fitted.last().filter(|_| !keep_original); if sp.closed && k + len == n { // The run ends where the walk started. @@ -908,8 +923,11 @@ fn simplify_runs(sp: &SubPath, picked: &[bool], opts: &SimplifyOptions) -> (SubP } k += len; } - // A closed subpath starts where it did ([`keep_start`]), with the runs and anchors kept renumbered. - let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp); + // A closed subpath starts where it did: the walk already starts at its first anchor when that + // stays, and otherwise the run that held it starts the path ([`keep_start`] on that run's + // segments alone, so no other segment changes), with the runs and anchors kept renumbered. + let Some(within) = start_run else { return (SubPath::new(anchors, sp.closed), runs, kept) }; + let (out, cut, first) = keep_start(SubPath::new(anchors, sp.closed), sp, within); let len = out.anchors.len(); if (cut, first) == (None, 0) || len == 0 { return (out, runs, kept); @@ -1547,6 +1565,41 @@ mod tests { PLACES.set(PLACES.get() + 1); } + /// A refitted run across the start of a closed path that crosses itself at its start keeps the + /// start on the run: the unselected segment through the old start is not split. + #[test] + fn a_run_across_the_start_keeps_the_start_on_the_run() { + let pts = [ + (0.0, 0.0), + (10.0, 0.3), + (20.0, -0.3), + (30.0, 0.3), + (40.0, 0.6), + (40.0, 50.0), + (0.0, 50.0), + (0.0, -50.0), + (-40.0, -50.0), + (-40.0, 0.6), + (-30.0, 0.3), + (-20.0, -0.3), + (-10.0, 0.3), + ]; + let sp = SubPath::new(pts.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true); + let path = PathData::new(vec![sp]); + let picked: BTreeSet<(usize, usize)> = [9, 10, 11, 12, 0, 1, 2, 3].into_iter().map(|s| (0, s)).collect(); + let out = simplify_part(&path, &picked, &SimplifyOptions { tolerance: 1.0, ..SimplifyOptions::default() }); + let got = &out.path.subpaths[0]; + let n = got.anchors.len(); + assert!(n < pts.len(), "{n} anchors"); + let (top, bottom) = (Point::new(0.0, 50.0), Point::new(0.0, -50.0)); + assert!( + (0..n).any(|i| got.anchors[i].p == top && got.anchors[(i + 1) % n].p == bottom), + "the segment through the old start was split: {:?}", + got.anchors.iter().map(|a| a.p).collect::>() + ); + assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index e3043ece27..8f907cea87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7125,7 +7125,8 @@ the refit's anchor nearest that point. It runs the same way around as before. Wi With segments of a path direct-selected (`select.segments`, or `select.anchors` with both anchors of a segment), Simplify refits only each run of consecutive selected segments, between the run's end anchors: they stay where they are, with their handles on the side away from the run, and every other anchor and segment of the path stays exactly as it was. A -closed path's run may cross its start point; the path then keeps its start as a whole path does. Separate runs on one path +closed path's run may cross its start point; the path then keeps its start as a whole path does, with the new start on +that run. Separate runs on one path simplify independently, in one undo step, and the runs stay direct-selected (as segments when segments were picked). A path with only lone anchors selected, and every path with `wholePaths: true`, simplifies whole: From c8d02b0dbd7d8d7b287e72864290b2a45af2cc3d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 01:58:33 -0800 Subject: [PATCH 14/19] Retype: a glyph in an even-odd compound matches with only some of its contours reversed An even-odd compound paints the same whichever way each contour runs, so an o's counter may run the same way as its outer contour. Such a part matched neither as it is nor with all its contours reversed, and stayed an outline at tolerance 0. A part of a split compound is now also read with each contour turned the way its depth gives (outer contours one way, their counters the other), both ways round. In a nonzero compound those contours paint the counter, and the painted-area check still keeps the part an outline. The containment test that splits a compound into glyphs moves into its own function, `containers`, which the new reading also calls. Docs: docs/mcp.md, docs/type-parity.md. --- crates/engine/src/cmd/retype.rs | 2 +- crates/engine/src/cmd/retype_tests.rs | 28 ++++ crates/text/src/retype.rs | 209 +++++++++++++++++++++----- docs/mcp.md | 5 +- docs/type-parity.md | 2 +- 5 files changed, 207 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index b0d37a1d61..81972395e2 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them, and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", + "{fonts?: [family…], tolerance?: 0..0.05 (default 0: exact matches only)} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation; with a tolerance above 0, a shape that is no glyph exactly may nearly be one (an outline simplified, a curve split in two, contours in another order, start or direction) when its leftover distance from the glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (VectorCraft's own measure; shapes of at most 8 contours); a compound path holding several glyphs (a word outlined as one path, at most 256 contour groups, 512 contours and 65,536 path elements, and 16,384 contours per command) is split into them (a part matching exactly also with its contours the other way round, or with only some of them so, as an o's counter alone in an even-odd compound), and becomes type only when every one of them matches; matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more exactly matched glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions; with a tolerance, within it), and before a near-matched glyph the line's size and turn would draw further from its shape than the tolerance; a glyph must also paint the area the shape paints under its fill rule (a nonzero compound whose inner contour runs the same way as its outer one paints its center, so a ring glyph does not replace it; a counter narrower than three times the outline tolerance across in some direction, an outline too large to check, or parts of a split compound that overlap where its fill rule leaves the overlap unpainted, or that overlap at all when the compound has an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke, also keep the shape an outline); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool), score (how closely the line's least close glyph fits, 1 for exact, 0 at a leftover distance of 0.05)}], unmatched: [id…] (shapes that stayed as they are when another shape became type), truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error, with no unmatched list, when no shape becomes type, or when tolerance is not a number from 0 to 0.05", has_selected_path, retype )] diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index 2727dd4432..7151ba0a23 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -1385,6 +1385,34 @@ fn glyphs_side_by_side_in_an_even_odd_compound_still_become_type() { assert_eq!(r["texts"], json!(["oo"]), "{r}"); } +#[test] +fn a_glyph_with_only_some_contours_turned_in_an_even_odd_compound_still_becomes_type() { + // An even-odd compound paints the same whichever way its contours run, so an o's counter may + // run the same way as its outer contour: neither the part as it is nor all its contours turned + // is the glyph. Filled by the nonzero rule, the same contours paint the o's counter, and the + // compound stays an outline. + for turned in [1usize, 2] { + let mut s = session(); + let c = one_compound(&mut s, "do"); + // One path per contour: the d's two, then the o's two. + let paths = children_of(&s, c); + assert_eq!(paths.len(), 4, "a d and an o are two contours each"); + let p = paths[paths.len() - turned]; + s.edit("test", |d, _| { + let data = d.node_mut(NodeId(p)).unwrap().path_data_mut().unwrap(); + *data = vectorcraft_geom::PathData::from_bezpath(&data.to_bezpath().reverse_subpaths()); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [c]})).unwrap(); + assert!(s.execute("type.retype", &json!({})).is_err(), "nonzero, contour {turned} turned paints the counter"); + s.execute("path.setFillRule", &json!({"rule": "evenOdd", "ids": [c]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["do"]), "contour {turned} turned: {r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + } +} + #[test] fn a_compound_whose_glyph_stays_an_outline_keeps_its_other_glyphs_too() { let mut s = session(); diff --git a/crates/text/src/retype.rs b/crates/text/src/retype.rs index 0a991c669f..aed9d29679 100644 --- a/crates/text/src/retype.rs +++ b/crates/text/src/retype.rs @@ -360,13 +360,25 @@ impl RetypeIndex { /// [`Self::all_matches`], and when the shape fits no glyph as it is, its contours read the /// other way round: for a part of a compound path, which Make Compound Path may have turned so - /// it cuts a hole in the paths behind it. + /// it cuts a hole in the paths behind it. When neither reading fits, the contours are read the + /// way their depth gives, outer contours one way and their counters the other, both ways round: + /// an even-odd compound paints the same whichever way each contour runs, so an o's counter may + /// run the same way as its outer contour. pub fn matches_either_way(&self, shape: &BezPath) -> Vec { let found = self.matches_read(shape, shape); if !found.is_empty() { return found; } - self.matches_read(shape, &shape.reverse_subpaths()) + let found = self.matches_read(shape, &shape.reverse_subpaths()); + if !found.is_empty() { + return found; + } + let Some(nested) = nested_reading(shape) else { return vec![] }; + let found = self.matches_read(shape, &nested); + if !found.is_empty() { + return found; + } + self.matches_read(shape, &nested.reverse_subpaths()) } /// [`Self::all_matches`] of `shape`, its contours read as in `reading` (the same outline). @@ -880,39 +892,7 @@ pub fn clusters(path: &BezPath) -> Vec { }, } } - let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); - // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in - // another only when every one of them does. - let probes: Vec> = subs - .iter() - .map(|s| { - let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); - let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); - anchors.into_iter().step_by(step).collect() - }) - .collect(); - // Each contour's container: the smallest contour around it. - let parent: Vec> = (0..subs.len()) - .map(|i| { - let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; - if pi.is_empty() { - return None; - } - (0..subs.len()) - .filter(|&j| j != i) - .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) - .filter(|(_, bj, sj)| { - bj.area() > bi.area() - && bj.x0 <= bi.x0 - && bj.y0 <= bi.y0 - && bj.x1 >= bi.x1 - && bj.y1 >= bi.y1 - && pi.iter().all(|p| sj.winding(*p) != 0) - }) - .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) - .map(|(j, _, _)| j) - }) - .collect(); + let parent = containers(&subs); let root = |mut i: usize| { // Containers are strictly larger, so the chain ends; the bound keeps it so. for _ in 0..subs.len() { @@ -935,6 +915,90 @@ pub fn clusters(path: &BezPath) -> Vec { groups.into_iter().map(|(_, p)| p).collect() } +/// Each contour's container among `subs` (one contour each): the smallest other contour that holds +/// it, `None` for an outer contour. +fn containers(subs: &[BezPath]) -> Vec> { + let boxes: Vec = subs.iter().map(Shape::bounding_box).collect(); + // Up to MAX_CONTAINMENT_PROBES of each contour's anchor points, evenly spread: a contour lies in + // another only when every one of them does. + let probes: Vec> = subs + .iter() + .map(|s| { + let anchors: Vec = s.elements().iter().filter_map(|e| e.end_point()).collect(); + let step = anchors.len().div_ceil(MAX_CONTAINMENT_PROBES).max(1); + anchors.into_iter().step_by(step).collect() + }) + .collect(); + // Each contour's container: the smallest contour around it. + (0..subs.len()) + .map(|i| { + let (Some(bi), Some(pi)) = (boxes.get(i), probes.get(i)) else { return None }; + if pi.is_empty() { + return None; + } + (0..subs.len()) + .filter(|&j| j != i) + .filter_map(|j| Some((j, boxes.get(j)?, subs.get(j)?))) + .filter(|(_, bj, sj)| { + bj.area() > bi.area() + && bj.x0 <= bi.x0 + && bj.y0 <= bi.y0 + && bj.x1 >= bi.x1 + && bj.y1 >= bi.y1 + && pi.iter().all(|p| sj.winding(*p) != 0) + }) + .min_by(|a, b| a.1.area().total_cmp(&b.1.area())) + .map(|(j, _, _)| j) + }) + .collect() +} + +/// `path` with each contour turned to run the way its depth gives (an outer contour one way, its +/// counters the other, what lies in those the first way again), the outer contours keeping the way +/// the first of them runs. `None` when that turns no contour (the path read as it is), for a +/// contour that encloses no area, and for more than [`MAX_CONTOURS`] contours. +fn nested_reading(path: &BezPath) -> Option { + let mut subs: Vec = vec![]; + for el in path.elements() { + if matches!(el, PathEl::MoveTo(_)) { + if subs.len() >= MAX_CONTOURS { + return None; + } + subs.push(BezPath::new()); + } + subs.last_mut()?.push(*el); + } + let parent = containers(&subs); + let depth = |mut i: usize| { + let mut d = 0usize; + // Containers are strictly larger, so the chain ends; the bound keeps it so. + for _ in 0..subs.len() { + match parent.get(i).copied().flatten() { + Some(p) => { + i = p; + d += 1; + } + None => break, + } + } + d + }; + let areas: Vec = subs.iter().map(Shape::area).collect(); + if areas.iter().any(|a| !a.is_normal()) { + return None; + } + let outer = (0..subs.len()).find(|&i| depth(i) == 0).and_then(|i| areas.get(i)).map(|a| a.signum())?; + let turned: Vec = areas.iter().enumerate().map(|(i, a)| a.signum() != if depth(i) % 2 == 0 { outer } else { -outer }).collect(); + if turned.iter().all(|t| !*t) { + return None; + } + let mut out = BezPath::new(); + for (s, t) in subs.iter().zip(&turned) { + out.extend(if *t { s.reverse_subpaths() } else { s.clone() }.iter()); + } + Some(out) +} + /// `a` wrapped into −π..π. fn wrapped(a: f64) -> f64 { (a + std::f64::consts::PI).rem_euclid(std::f64::consts::TAU) - std::f64::consts::PI @@ -2271,6 +2335,81 @@ mod tests { assert!(clusters(&BezPath::new()).is_empty()); } + #[test] + fn the_nested_reading_turns_counters_against_their_outer_contour() { + let split = |p: &BezPath| -> Vec { + let mut out: Vec = vec![]; + for el in p.elements() { + if matches!(el, PathEl::MoveTo(_)) { + out.push(BezPath::new()); + } + out.last_mut().unwrap().push(*el); + } + out + }; + let join = |cs: &[BezPath]| { + let mut p = BezPath::new(); + for c in cs { + p.extend(c.iter()); + } + p + }; + let cs = split(&letter()); + let (outer, counter) = (cs[0].clone(), cs[1].clone()); + let (same, opposite) = if outer.area().signum() == counter.area().signum() { + (counter.clone(), counter.reverse_subpaths()) + } else { + (counter.reverse_subpaths(), counter.clone()) + }; + // A counter running the same way as its outer contour is turned; the outer one is kept. + let read = nested_reading(&join(&[outer.clone(), same.clone()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[0], outer); + assert_eq!(rs[1].area().signum(), opposite.area().signum()); + // So is the outer contour's way when it comes second. + let read = nested_reading(&join(&[opposite.clone(), outer.reverse_subpaths()])).unwrap(); + let rs = split(&read); + assert_eq!(rs[1], outer.reverse_subpaths()); + assert_eq!(rs[0].area().signum(), outer.area().signum()); + // Already nested so: nothing to turn. + assert!(nested_reading(&join(&[outer.clone(), opposite])).is_none()); + // A contour enclosing no area gives none. + let mut flat = BezPath::new(); + flat.move_to((0.0, 0.0)); + flat.line_to((10.0, 0.0)); + flat.close_path(); + assert!(nested_reading(&join(&[outer, flat])).is_none()); + } + + #[test] + fn a_part_with_some_contours_turned_still_matches_exactly() { + let db = FontDb::with_font_dirs(vec![]); + assert_eq!(db.add_font(crate::test_fonts::named_copy(false, ("Turntest", "Regular", "Version 1.000", "Turntest-Regular")).unwrap()), 1); + let face = db.face("Turntest", "Regular").unwrap(); + let o = Affine::translate((40.0, 90.0)) * Affine::scale(0.03) * db.outline_uncached(&face, face.glyph_for('o')); + let mut cs: Vec = vec![]; + for el in o.elements() { + if matches!(el, PathEl::MoveTo(_)) { + cs.push(BezPath::new()); + } + cs.last_mut().unwrap().push(*el); + } + assert_eq!(cs.len(), 2, "an o is two contours"); + let keys = std::iter::once(shape_key(&o).unwrap()).collect(); + let index = RetypeIndex::build(&db, vec![face], &keys); + assert!(!index.all_matches(&o).is_empty()); + for turned in 0..2 { + let mut shape = BezPath::new(); + for (i, c) in cs.iter().enumerate() { + shape.extend(if i == turned { c.reverse_subpaths() } else { c.clone() }.iter()); + } + assert!(index.all_matches(&shape).is_empty(), "contour {turned} turned is no glyph as it is"); + assert!(index.all_matches(&shape.reverse_subpaths()).is_empty(), "nor read the other way round"); + let found = index.matches_either_way(&shape); + assert!(found.iter().any(|m| m.ch == 'o'), "contour {turned} turned still matches the o"); + } + } + #[test] fn the_same_corners_joined_another_way_are_another_outline() { let poly = |pts: &[(f64, f64)]| { diff --git a/docs/mcp.md b/docs/mcp.md index 5032690fc6..41b31464d7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11456,8 +11456,9 @@ at a leftover distance of 0.05. A compound path that holds several glyphs, such as a word made into one compound path, is split into groups of contours (a contour with the contours inside it) in path order, and runs of up to three groups are matched, the longest first among those after which the remaining groups can still all be matched, so an i's stem and dot become one i. A group whose contours run the other -way round, as Make Compound Path leaves some of them, still matches exactly. Exact matches of the whole shape come -first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The +way round, as Make Compound Path leaves some of them, still matches exactly, and so does one where only some of its +contours run the other way round (in an even-odd compound, an o's counter and not its outer contour). Exact matches +of the whole shape come first, then exact matches of its groups, then near matches of the whole shape, then near matches of its groups. The compound becomes type only when every one of its glyphs does; otherwise it stays as it is and is reported once in `unmatched` when another shape of the selection becomes type, and the command returns an error when no shape does. A glyph also has to paint the area the shape paints under the shape's fill rule: a compound filled by the nonzero rule diff --git a/docs/type-parity.md b/docs/type-parity.md index 868b944bcd..94993affe1 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match. A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Near matches: with `tolerance` (0 to 0.05), shapes of up to 8 contours whose leftover distance from a glyph, relative to the shape's outline spread (the root mean square distance of its sampled outline points from their center), is at most the tolerance (simplified outlines, curves split in two, contours in another order or direction) match too, and each line reports a `score`; a compound path holding several glyphs is split into them and becomes type only when all of them match, a part still matching exactly when some of its contours run the other way round (an o's counter alone in an even-odd compound). A line of three or more exactly matched glyphs keeps the spacing most of its gaps share as tracking (gaps one space wide stay word spaces when type draws them). A line of two glyphs that untracked type does not draw in place takes the tracking of the nearest tracked line in the same font, size and turn, and keeps it only when type at that tracking draws both glyphs in place; a line of one or two glyphs that joins tracked lines in one object takes their tracking. Other lines are set untracked, each glyph at its own position, and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): glyphs fused into one contour, near matches and compound paths of several glyphs in the panel's list, opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | From d8db9eda83f7919b621fa70d08d3709b79571759 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:42:10 -0800 Subject: [PATCH 15/19] Symbols: Direct Selection picks a dynamic instance's part where its fill and stroke effects draw it A geometry effect on a dynamic symbol instance's fill or stroke moves or reshapes the art the canvas draws, and a click there already selects the instance. Direct Selection still picked a part of the art at its plain shape and outlined that shape, so a click on the drawn result picked nothing and a click where the part no longer paints picked it. symbol_part_at and symbol_part_outline_in_view now test and outline the instance's art with the effects of its active fill and stroke added, as the canvas adds them. Live objects in the art keep their place, so the child-index path still leads to the part. A nested instance is picked and outlined where its reshaped art is drawn, type with a fill or stroke of its own where its reshaped glyphs are drawn (Type Object Selection by Path Only still takes the type path), and an image's outline includes the shapes its own fills and strokes paint. A clipping path is still picked and outlined by its own geometry. Outline view and layers with Preview off keep the plain shapes; blends, envelopes and repeats in the art are picked without the instance's effects. --- crates/doc/src/hit.rs | 179 +++++++++++++++++++-- crates/effects/src/lib.rs | 6 +- crates/effects/src/reshape.rs | 28 +++- crates/engine/src/session/documents.rs | 3 + crates/engine/src/tests/dynamic_symbols.rs | 154 ++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 347 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 7c0de44cab..6286597882 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -115,6 +115,22 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } +/// Adds the geometry and raster effects of a symbol instance's active fill and stroke to the fills +/// and strokes that paint in the art it is given, the instance's art in the symbol's coordinates, +/// as the canvas adds them to the art it draws. Every object keeps its place in the art, so the +/// child indices of [`symbol_part_at`] still lead to it. Effects are evaluated above this crate, so +/// the engine registers one with [`set_instance_row_art`]. +pub type InstanceRowArt = fn(Option<&Document>, &Node, &mut Node); + +static INSTANCE_ROW_ART: OnceLock = OnceLock::new(); + +/// Register how a symbol instance's art takes the effects of the instance's fill and stroke, for +/// Direct Selection's parts (the first registration stays). +pub fn set_instance_row_art(f: InstanceRowArt) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_ROW_ART.set(f); +} + /// The shapes that [`ImagePaint`] gives for one object. type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; @@ -1575,12 +1591,45 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio /// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a /// stroke along its shape, a fill inside it except with Selection by Path Only. fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + painted_hit(&image_paint(Some(symbols.document()), n), p, opt) +} + +/// What a click at `p` hits among `painted`, the shapes [`image_paint`] gives, as [`hit_painted`] +/// tests them. +fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option { + painted.iter().rev().find_map(|(bp, rule, item)| match item { AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), }) } +/// Is `n` a symbol instance whose active fill or stroke has geometry effects that reshape the art +/// it draws ([`image_paint`])? Callers ask [`own_effects_art`] first, which takes an instance whose +/// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow) +/// is tested here. Never with `outline`, where the canvas draws no effects, nor while a +/// [`DrawnOff`] guard lives. +fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { + !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && !image_paint(Some(symbols.document()), n).is_empty() +} + +/// The art that symbol instance `n` draws with a visible effect of its own, the effects of its +/// fills and strokes and those of its symbol's art all applied, or that type `n` draws with the +/// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]). +/// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or +/// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect +/// changes what it draws. +fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option { + let has = match n.kind { + NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible), + NodeKind::Text(_) => has_own_effects(n), + _ => false, + }; + if outline || DRAWN_OFF.get() || !has { + return None; + } + DRAWN_ART.get()?(symbols, n) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. @@ -1690,6 +1739,17 @@ impl<'a> InstanceArt<'a> { Some(Self { art, map, xf: *xf, boxes }) } + /// [`Self::of`] with the effects of the instance's active fill and stroke added to the fills and + /// strokes in the art ([`set_instance_row_art`]), so that each object of it is tested and + /// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects. + fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option { + let mut art = Self::of(doc, inst)?; + if !outline && let Some(f) = INSTANCE_ROW_ART.get() { + f(Some(doc), inst, &mut art.art); + } + Some(art) + } + /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides @@ -1751,15 +1811,18 @@ fn moved(n: &Node, xf: vectorcraft_geom::Affine) -> Node { /// [`HitOptions::skip_guides`]. Nothing is picked in art that placing through the symbol's 9-slice /// guides could make more than [`crate::MAX_SYMBOL_NODES`] objects of, which the canvas does not /// draw. Art in a layer of the symbol whose Preview is off, and the art of an instance below such a -/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. `None` when `inst` is not a symbol instance or -/// no editable object of its art is under `p`. +/// layer, is tested in outline ([`HitOptions::outline`]), as the canvas draws it. Elsewhere each +/// object is tested where the geometry effects of the instance's active fill and stroke draw it +/// ([`InstanceArt::drawn`]), and not where its own shape no longer paints. Live objects in the art +/// (blends, envelopes, repeats) are tested without those effects. `None` when `inst` is not a +/// symbol instance or no editable object of its art is under `p`. pub fn symbol_part_at(doc: &Document, inst: &Node, p: Point, opt: HitOptions) -> Option> { let _walk = ArtWalk::open(); - let art = InstanceArt::of(doc, inst)?; + let outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; let symbols = doc.kept_symbol_boxes(); let mut path = vec![]; - let outline = opt.outline || below_preview_off(doc, inst, opt.scope); - let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false }; + let find = FindPart { art: &art, p, opt, symbols: &symbols, whole_instance: false, drawn: true }; find.find(&art.art, &mut path, None, outline).map(|_| path) } @@ -1772,14 +1835,35 @@ struct FindPart<'a> { /// For [`instance_art_hit`]: locked and template objects of the art count, as the canvas draws /// them, and clipping paths are not picked by their outline. whole_instance: bool, + /// For [`symbol_part_at`] and [`drawn_instance_hit`]: the art carries the effects of the + /// instance's active fill and stroke ([`InstanceArt::drawn`]). + drawn: bool, } impl FindPart<'_> { /// What a click at `p` hits on object `n` of the art, placed. [`hit_any`] takes `n` and each - /// object it visits inside `n` from the [`ArtWalk`] limit. + /// object it visits inside `n` from the [`ArtWalk`] limit. In drawn art, a symbol instance with + /// geometry effects of its own, and type whose own effects or fill and stroke effects (its own, + /// or those the outer instance adds) reshape it, are hit only where the art they draw is + /// ([`own_effects_art`]), and an instance whose fill or stroke has geometry effects that reshape + /// its art (its own, or those the outer instance passes on) only where its art is drawn with + /// them ([`drawn_instance_hit`]); not anywhere in their bounds. With Type Object Selection by + /// Path Only ([`HitOptions::type_path_only`]), type is still picked by its type path. fn hit(&self, n: &Node, whole: Option, opt: HitOptions) -> Option { let placed = self.art.place(n, whole)?; let _charged = ArtWalk::charge(); + // Type Object Selection by Path Only picks type by its type path, whatever its effects draw. + let type_path = opt.type_path_only && matches!(placed.kind, NodeKind::Text(_)); + if self.drawn && !type_path { + if let Some(art) = own_effects_art(&placed, self.symbols, opt.outline) { + let _off = DrawnOff::set(); + let _art_only = ArtOnly::set(); + return hit_any(&art, self.p, opt, self.symbols); + } + if reshapes_instance_art(&placed, self.symbols, opt.outline) { + return drawn_instance_hit(&placed, self.p, opt, self.symbols); + } + } hit_any(&placed, self.p, opt, self.symbols) } @@ -1858,7 +1942,26 @@ fn instance_art_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) ARTS_WALKED.with(|c| c.set(c.get() + 1)); let opt = HitOptions { clip_outlines: false, ..opt }; let _art_only = ArtOnly::set(); - FindPart { art: &art, p, opt, symbols, whole_instance: true }.find(&art.art, &mut vec![], None, false) + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: false }.find(&art.art, &mut vec![], None, false) +} + +/// What a click at `p` hits of symbol instance `n`, an object of another instance's drawn art, +/// where the canvas draws `n`'s art with the geometry effects of `n`'s active fill and stroke +/// ([`InstanceArt::drawn`]): each object of that art where it is drawn, paths, images and type +/// alike, and not anywhere in `n`'s box. Locked and template objects of the art count, as in +/// [`instance_art_hit`]. `None` for an instance of a missing symbol, of a symbol that holds an +/// instance of itself or nests too deep ([`SymbolBoxes::art`]), of art past the 9-slice object +/// limit ([`InstanceArt::of`]), and once the click has visited as many objects of symbol art as +/// [`ArtWalk`] allows. +fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return None }; + if symbols.art(symbol).is_none() || ArtWalk::used_up() { + return None; + } + let art = InstanceArt::drawn(symbols.document(), n, false)?; + let opt = HitOptions { clip_outlines: false, ..opt }; + let _art_only = ArtOnly::set(); + FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false) } thread_local! { @@ -2008,15 +2111,18 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< /// instance (the isolated container [`HitOptions::scope`] and the layers around it apart), the /// outlines are cut to the bounds of the plain clipping paths, without their live effects, as /// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around -/// the object leave no region. +/// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's +/// active fill and stroke, as [`symbol_part_at`] does. pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { - let art = InstanceArt::of(doc, inst)?; - let part = crate::symbol_overrides::part(&art.art, path)?; let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); + let art = InstanceArt::drawn(doc, inst, outline)?; + let part = crate::symbol_overrides::part(&art.art, path)?; + let symbols = doc.kept_symbol_boxes(); let mut out = BezPath::new(); let mut limit = None; let mut whole = None; let mut n = &art.art; + let mut mask = false; for &i in path { let children = n.children()?; whole = art.whole(n, whole); @@ -2028,9 +2134,12 @@ pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], op let Some(within) = limit_within(&art.place_unclipped(first, whole)?, limit, outline) else { return Some(out) }; limit = within; } + mask = i == 0 && n.clips(); n = children.get(usize::try_from(i).ok()?)?; } - outline_within(&art.place(part, whole)?, limit, outline, &mut out); + // A clipping path is picked by its own geometry ([`FindPart::find`]), and outlined so. + let placed = art.place(part, whole)?; + plain(mask, || outline_within(&placed, &symbols, limit, outline, &mut out)); Some(out) } @@ -2052,9 +2161,37 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option, outline: bool, out: &mut BezPath) { +/// [`symbol_part_outline_in_view`] for placed object `n`, cut to `limit` when there is one. A path +/// or compound path whose geometry effects reshape it is outlined as the art they draw +/// ([`drawn_art`]), a symbol instance with geometry effects of its own and type whose effects +/// reshape it as the art they draw ([`own_effects_art`]), and a symbol instance whose fill or stroke effects reshape its art as that +/// art drawn with them ([`InstanceArt::drawn`]), as [`FindPart`] tests them, except with `outline` +/// and while a [`DrawnOff`] guard lives. +fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; + if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) + && let Some(art) = drawn_art(symbols, n, outline) + { + let _off = DrawnOff::set(); + art.iter().for_each(|a| outline_within(a, symbols, limit, outline, out)); + return; + } + if let Some(art) = own_effects_art(n, symbols, outline) { + let _off = DrawnOff::set(); + outline_within(&art, symbols, limit, outline, out); + return; + } + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && reshapes_instance_art(n, symbols, outline) + { + if symbols.art(symbol).is_some() + && let Some(art) = InstanceArt::drawn(symbols.document(), n, false) + && let Some(placed) = art.place(&art.art, None) + { + outline_within(&placed, symbols, limit, outline, out); + } + return; + } if let Some(pd) = n.path_data() { match limit { Some(r) => push_cut(out, &pd.to_bezpath(), r), @@ -2066,16 +2203,26 @@ fn outline_within(n: &Node, limit: Option, outline: bool, out: &mut BezPat { out.extend(b.to_path(0.1)); } + // An image is also outlined where its own fills and strokes paint with their effects, as + // [`hit_leaf`] picks it there ([`image_paint`]). + if !outline && matches!(n.kind, NodeKind::Image(_)) { + for (bp, ..) in image_paint(Some(symbols.document()), n).iter() { + match limit { + Some(r) => push_cut(out, bp, r), + None => out.extend(bp.iter()), + } + } + } let Some(children) = n.children() else { return }; let outline = outline || previews_off(n); if n.clips() && let Some((first, rest)) = children.split_first() { let Some(inner) = limit_within(first, limit, outline) else { return }; - rest.iter().for_each(|c| outline_within(c, inner, outline, out)); + rest.iter().for_each(|c| outline_within(c, symbols, inner, outline, out)); return; } - children.iter().for_each(|c| outline_within(c, limit, outline, out)); + children.iter().for_each(|c| outline_within(c, symbols, limit, outline, out)); } /// The overlap of `a` and `b` (`a` alone without `b`), `None` when they do not overlap. diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index c46ab0c76e..46fd9344e2 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -89,9 +89,9 @@ pub use raster::{ without_geometry, }; pub use reshape::{ - SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies, - has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, - instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, + SYMBOL_ART_MAX_NODES, add_instance_row_effects_to_parts, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, + has_gradient_copies, has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, + has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape, }; pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index a57c2085f6..c7ab85e7a8 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -388,11 +388,23 @@ fn row_effects_of(fx: &[Effect]) -> Vec { /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, true); +} + +/// [`add_instance_row_effects`] for Direct Selection's parts of a symbol instance's art: live +/// objects (blends, envelopes, repeats) are left as they are, without the effects, so that every +/// object keeps its place in the art and the child indices that pick a part still lead to it. +pub fn add_instance_row_effects_to_parts(doc: Option<&Document>, n: &Node, art: &mut Node) { + add_instance_rows(doc, n, art, false); +} + +/// [`add_instance_row_effects`], evaluating live objects in the art only with `live`. +fn add_instance_rows(doc: Option<&Document>, n: &Node, art: &mut Node, live: bool) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| row_effects_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| row_effects_of(&s.effects)); if !fill.is_empty() || !stroke.is_empty() { - add_row_effects(doc, symbol, art, &fill, &stroke); + add_row_effects(doc, symbol, art, &fill, &stroke, live); } } @@ -413,8 +425,9 @@ fn places_symbol(doc: &Document, from: &str, to: &str, seen: &mut HashSet, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect]) { +/// instance of the symbol named `outer`. Without `live`, live objects are left as they are +/// ([`add_instance_row_effects_to_parts`]). +fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Effect], stroke: &[Effect], live: bool) { match &n.kind { NodeKind::Path { clipping: true, .. } | NodeKind::Path { guide: true, .. } | NodeKind::RulerGuide { .. } => return, NodeKind::SymbolInstance { symbol, .. } => { @@ -425,7 +438,12 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef } return; } - _ if vectorcraft_doc::live::is_live(n) => *n = evaluated(doc, n), + _ if vectorcraft_doc::live::is_live(n) => { + if !live { + return; + } + *n = evaluated(doc, n); + } _ => {} } let takes = |i: &AppearanceItem| { @@ -445,7 +463,7 @@ fn add_row_effects(doc: Option<&Document>, outer: &str, n: &mut Node, fill: &[Ef let clips = n.clips(); for (i, c) in n.children_mut().into_iter().flatten().enumerate() { if !(clips && i == 0) { - add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke); + add_row_effects(doc, outer, Arc::make_mut(c), fill, stroke, live); } } } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..0272e8fb76 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -24,6 +24,9 @@ impl Session { }); // Clicks find an image's own fills and strokes where their effects draw them. vectorcraft_doc::hit::set_image_paint(vectorcraft_render::effects::image_paint); + // Direct Selection picks and outlines the parts of a dynamic symbol's instance where the + // effects of the instance's fill and stroke draw them. + vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks and marquees find paths, compound paths, groups and layers where their geometry diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index e136d9f45b..6f4973cd15 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -587,6 +587,160 @@ fn direct_selection_paints_one_object_of_one_dynamic_instance() { assert_eq!(pixel(&s, 80, 30), BLUE); } +/// Instance `inst` with a new fill (`fill`) or stroke row without paint whose effect is `effect` +/// with `params`. +fn row_effect(s: &mut Session, inst: NodeId, fill: bool, effect: &str, params: Value) { + s.execute(if fill { "appearance.addFill" } else { "appearance.addStroke" }, &json!({"ids": [inst.0]})).unwrap(); + let row = node(s, inst).appearance.items.len() - 1; + s.execute("appearance.setItem", &json!({"ids": [inst.0], "index": row, "none": true})).unwrap(); + s.execute("effect.apply", &json!({"ids": [inst.0], "item": row, "effect": effect, "params": params})).unwrap(); +} + +/// The object of `inst`'s art that Direct Selection picks at (`x`, `y`) with `opt`. +fn part_at(s: &Session, inst: NodeId, (x, y): (f64, f64), opt: vectorcraft_doc::hit::HitOptions) -> Option> { + let doc = &s.doc().unwrap().doc; + vectorcraft_doc::hit::symbol_part_at(doc, doc.node(inst).unwrap(), vectorcraft_geom::Point::new(x, y), opt) +} + +/// The box of the outline of the object at `path` in `inst`'s art, as Direct Selection draws it. +fn part_outline_box(s: &Session, inst: NodeId, path: &[u32]) -> Rect { + use vectorcraft_geom::kurbo::Shape; + let doc = &s.doc().unwrap().doc; + let outline = vectorcraft_doc::hit::symbol_part_outline_in_view(doc, doc.node(inst).unwrap(), path, Default::default()).unwrap(); + outline.bounding_box() +} + +/// A geometry effect on a dynamic instance's fill or stroke moves where the objects of its art +/// are drawn: Direct Selection picks an object where it is drawn, not where its own shape no longer +/// paints, and outlines it there; Outline view still takes the plain shapes. +#[test] +fn direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let inst = pair(&mut s, "dynamic"); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The squares are drawn at x 110..150 and 160..200. + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the first square where it is drawn"); + assert_eq!(part_at(&s, inst, (180.0, 30.0), opt), Some(vec![1]), "the second square where it is drawn"); + assert_eq!(part_at(&s, inst, (80.0, 30.0), opt), None, "where the second square's own shape no longer paints"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), opt), None, "the plain edge of the second square"); + assert_eq!(part_at(&s, inst, (60.5, 30.0), HitOptions { outline: true, ..opt }), Some(vec![1]), "Outline view draws the plain shapes"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline follows the moved square: {b:?}"); + direct(&mut s, (130.0, 30.0), (130.0, 30.0), Mods::default()); + let sel = s.doc().unwrap().selection.clone(); + assert_eq!(sel.objects, [inst]); + assert_eq!(sel.symbol_part, Some(vectorcraft_doc::SymbolPart { instance: inst, path: vec![0] }), "a press on the drawn square picks it"); + + // A stroke effect: Offset Path moves the first square's stroke out to x = 0. + let mut s = session(); + let (a, b) = (square(&mut s, 10.0), square(&mut s, 60.0)); + s.execute("paint.setStroke", &json!({"ids": [a.0, b.0], "color": "#00ff00"})).unwrap(); + let inst = id(&s.execute("symbol.new", &json!({"name": "Pair", "ids": [a.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, false, "path.offsetPath", json!({"offset": 10})); + assert_eq!(part_at(&s, inst, (0.5, 30.0), opt), Some(vec![0]), "the moved stroke"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), Some(vec![0]), "the fill keeps its shape"); + let b = part_outline_box(&s, inst, &[0]); + assert!(b.x0 < 1.0 && b.x1 > 59.0, "the outline takes in the moved stroke: {b:?}"); + + // A symbol instance in the art takes the effect too: it is picked and outlined where its art is + // drawn, not in its box. The fill effect moves its square; its image has no fill and stays. + let mut s = session(); + let a = square(&mut s, 10.0); + place_image(&mut s); + let img = top(&s); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0, img.0]})).unwrap()); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance's square where it is drawn"); + assert_eq!(part_at(&s, inst, (65.0, 35.0), opt), Some(vec![0]), "the nested instance's image"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 50.0).abs() < 0.5 && (b.x1 - 150.0).abs() < 0.5, "the outline takes in the moved square and the image: {b:?}"); + + // A nested instance with a geometry effect of its own is picked where both effects draw it. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "distort.transform", "params": {"moveV": 30}})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 60.0), opt), Some(vec![0]), "the nested square moved by both effects"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the nested instance's own box"); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 110.0).abs() < 0.5 && (b.y0 - 40.0).abs() < 0.5 && (b.y1 - 80.0).abs() < 0.5, "the outline follows both effects: {b:?}"); + + // Type with a fill of its own in the art is picked and outlined where the fill effect draws its + // glyphs, not in its own bounds. + let mut s = session(); + let t = id(&s.execute("text.create", &json!({"x": 10, "y": 45, "size": 40, "text": "I"})).unwrap()); + s.execute("appearance.addFill", &json!({"ids": [t.0]})).unwrap(); + let plain = { + let doc = &s.doc().unwrap().doc; + doc.node(t).unwrap().geometric_bounds().unwrap() + }; + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [t.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The type's own color still paints the glyph in place; the new fill paints it 100 pt right. + let drawn = part_outline_box(&s, inst, &[0]); + assert!(drawn.x1 > plain.x1 + 90.0 && drawn.x1 < plain.x1 + 101.0, "the outline takes in the moved glyph: {drawn:?}, plain {plain:?}"); + let glyph = drawn.x1 - 100.0 - drawn.x0; + let (x, y) = (drawn.x1 - glyph / 2.0, (drawn.y0 + drawn.y1) / 2.0); + assert_eq!(part_at(&s, inst, (x, y), opt), Some(vec![0]), "the type where the fill effect draws its glyph"); + assert_eq!(part_at(&s, inst, (plain.x0 + 1.0, plain.y0 + 1.0), opt), None, "the type's own bounds, off its glyph"); + let by_path = HitOptions { type_path_only: true, ..opt }; + assert_eq!(part_at(&s, inst, (plain.x1 - 1.5, 45.0), by_path), Some(vec![0]), "Type Object Selection by Path Only takes the baseline"); + + // A nested instance whose own effect adds only pixels (a drop shadow) is still picked where the + // outer fill effect draws its art. + let mut s = session(); + let a = square(&mut s, 10.0); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [a.0]})).unwrap()); + s.execute("effect.apply", &json!({"ids": [inner.0], "effect": "stylize.dropShadow"})).unwrap(); + let b = square(&mut s, 60.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the shadowed nested square where it is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the shadowed nested instance's own box"); + + // An image whose fill has Convert to Shape is picked and outlined where the instance's fill + // effect moves that shape. + let mut s = session(); + place_image(&mut s); + let img = top(&s); + let frame = node(&s, img).geometric_bounds().unwrap(); + s.execute("appearance.addFill", &json!({"ids": [img.0]})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [img.0], "color": "#00ff00", "item": 0})).unwrap(); + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "convertToShape.rectangle", "item": 0})).unwrap(); + let b = square(&mut s, 200.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [img.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + let c = frame.center(); + assert_eq!(part_at(&s, inst, (c.x + 100.0, c.y), opt), Some(vec![0]), "the image where its fill is drawn"); + let o = part_outline_box(&s, inst, &[0]); + assert!(o.x1 > frame.x1 + 99.0, "the outline takes in the moved fill: {o:?}, frame {frame:?}"); +} + +/// A clipping path in a dynamic symbol's art with a geometry effect of its own is picked by its +/// own geometry, and Direct Selection outlines that geometry, not the shape the effect draws. +#[test] +fn a_picked_clipping_path_is_outlined_by_its_own_geometry() { + let mut s = session(); + let content = square(&mut s, 20.0); + let clip = square(&mut s, 10.0); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + s.execute("effect.apply", &json!({"ids": [clip.0], "effect": "path.offsetPath", "params": {"offset": 10}})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inst = id(&s.execute("symbol.new", &json!({"name": "Clip", "ids": [group.0], "type": "dynamic"})).unwrap()); + let b = part_outline_box(&s, inst, &[0]); + assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}"); +} + #[test] fn a_drag_of_a_picked_object_moves_nothing_and_says_why() { let mut s = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f8a3dc84a0..17eb1a0ee0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2102,6 +2102,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. + Direct Selection on a dynamic symbol's instance picks an object of the art where the geometry effects of the instance's fill and stroke draw it, not where the object's own shape no longer paints, and outlines it there. An instance nested in the art is picked and outlined where its reshaped art is drawn, and type with a fill or stroke of its own where its reshaped glyphs are drawn, not anywhere in their bounds; Type Object Selection by Path Only still picks type by its type path. An image is outlined where its own fills and strokes paint as well as by its frame. A clipping path is still picked and outlined by its own geometry. Outline view and layers with Preview off still take the plain shapes, and blends, envelopes and repeats in the art are picked without those effects. These are VectorCraft's own rules (engine `dynamic_symbols::direct_selection_picks_a_part_where_the_instance_fill_and_stroke_effects_draw_it`, `a_picked_clipping_path_is_outlined_by_its_own_geometry`). Before, a part was picked and outlined at its plain shape only. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). From 8e6f06574f212f3315bf1fa7aef6149a3f61d6e2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 02:49:58 -0800 Subject: [PATCH 16/19] Paths: a closed path starts at a kept anchor at its old start When the refit keeps an anchor at a closed path's old start, Simplify and Smooth now start the path at that anchor, even where a segment of the refit crosses the path at the same point. Before, a crossing segment that came first could be split there instead, adding an anchor and changing the segment the path starts along. --- crates/pathops/src/edit.rs | 57 +++++++++++++++++++++++++++++++++----- 1 file changed, 50 insertions(+), 7 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index dd5d84ebe7..c5a340365a 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -174,10 +174,11 @@ fn earliest_nearest(candidates: impl IntoIterator, or best.map(|(.., x)| x) } -/// The closed `sp` started at the point on it nearest `start`: at the anchor there, or at a new -/// anchor split into the segment there, which leaves the outline as it is. Of points equally near -/// `start`, the one earliest along `orig` (the path before it was refitted) from its first anchor is -/// used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest +/// The closed `sp` started at the point on it nearest `start`: at an anchor within [`START_SNAP`] of +/// `start` when it has one, even where a segment crosses the path there, otherwise at the anchor at +/// that point or at a new anchor split into the segment there, which leaves the outline as it is. Of +/// points equally near `start`, the one earliest along `orig` (the path before it was refitted) from +/// its first anchor is used, then the first in `sp`'s order. An open `sp`, or one with no segment or no finite nearest /// point, is returned as it is. pub fn start_nearest(sp: SubPath, start: Point, orig: &SubPath) -> SubPath { let n = sp.anchors.len(); @@ -194,6 +195,14 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within return (sp, None, 0); } let within = within.start.min(n)..within.end.min(n); + // The anchors of the segments `within`: each one's first, and the last one's end. + let anchors = || (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); + // An anchor within [`START_SNAP`] of `start` starts the path, before any segment through there. + let snapped = if within.is_empty() { None } else { earliest_nearest(anchors().filter(|(d, ..)| *d <= START_SNAP), orig) }; + if let Some(first) = snapped { + sp.anchors.rotate_left(first); + return (sp, None, first); + } let hits = within.clone().map(|i| { let c = sp.segment(i); let hit = c.nearest(start, 1e-9); @@ -219,9 +228,7 @@ fn start_near(mut sp: SubPath, start: Point, orig: &SubPath, split: bool, within sp.anchors.insert(i + 1, mid); (i + 1, Some(i)) } else { - // The anchors of the segments `within`: each one's first, and the last one's end. - let near = (within.start..=within.end).map(|j| j % n).map(|j| (sp.anchors[j].p.distance(start), sp.anchors[j].p, j)); - (earliest_nearest(near, orig).unwrap_or(0), None) + (earliest_nearest(anchors(), orig).unwrap_or(0), None) }; sp.anchors.rotate_left(first); (sp, cut, first) @@ -1600,6 +1607,42 @@ mod tests { assert!(got.anchors[0].p.x.abs() < 40.0 && got.anchors[0].p.y.abs() <= 1.0, "start {:?}", got.anchors[0].p); } + /// A closed polyline from its start at (0, 0) up to (0, 10) whose diagonal from (-20, -20) to + /// (20, 20) crosses it at that start, with two anchors on the diagonal that a refit drops. + fn crossing_at_start() -> SubPath { + let pts = [(0, 0), (0, 10), (40, 10), (40, -20), (-20, -20), (-10, -10), (10, 10), (20, 20), (20, 30), (-10, 30), (-10, 0)]; + SubPath::polyline(&pts.map(|(x, y)| Point::new(f64::from(x), f64::from(y))), true) + } + + /// A refitted run that keeps an anchor at the old start of a closed path starts the path at that + /// anchor, though a segment of the run that crosses the path there comes first in the run. + #[test] + fn a_run_that_keeps_the_start_anchor_starts_there() { + let path = PathData::new(vec![crossing_at_start()]); + let picked: BTreeSet<(usize, usize)> = [0, 4, 5, 6, 7, 8, 9, 10].into_iter().map(|s| (0, s)).collect(); + let opts = SimplifyOptions { tolerance: 0.01, corner_angle_deg: 1.0, straight_lines: true, ..SimplifyOptions::default() }; + let got = &simplify_part(&path, &picked, &opts).path.subpaths[0]; + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(ps.len(), 9, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + assert_eq!(ps.iter().filter(|&&p| p == Point::ZERO).count(), 1, "{ps:?}"); + } + + /// The whole closed path refitted keeps its start anchor first when a segment of the refit + /// crosses the path there. + #[test] + fn a_refit_that_keeps_the_start_anchor_starts_there() { + let sp = crossing_at_start(); + let mut fit = sp.clone(); + fit.anchors.retain(|a| ![Point::new(-10.0, -10.0), Point::new(10.0, 10.0)].contains(&a.p)); + fit.anchors.rotate_left(4); + let n = fit.anchors.len(); + let (got, cut, _) = keep_start(fit, &sp, 0..n); + let ps: Vec = got.anchors.iter().map(|a| a.p).collect(); + assert_eq!(cut, None, "{ps:?}"); + assert_eq!((ps[0], ps[1]), (Point::new(0.0, 0.0), Point::new(0.0, 10.0)), "{ps:?}"); + } + /// Candidates tied at one point are placed along the old path once, not once each, and the first /// given still wins the tie. #[test] From b06bccfaebab42ace4c09bd1f3a889df455c14fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 03:30:44 -0800 Subject: [PATCH 17/19] Symbols: picking and outlining a dynamic instance's part stays within one object limit Outlining a part of a dynamic symbol's instance expanded every nested instance whose fill or stroke effects reshape its art, at every level, with no limit, so art that nests many such instances a few levels deep took work that grew with each level. A part pick charged each object it tested but copied each nested instance's art before charging anything for it. The part outline now shares the object limit a click has, and each object it outlines takes one object of it. The art of a nested instance takes its size from the limit before it is copied, and the art an object's own effects draw takes its size once evaluated; nothing more is copied or evaluated once the limit is used up. The art of the instance itself is charged by its walk, as before. --- crates/doc/src/hit.rs | 73 ++++++++++++++++++++++++++----- crates/doc/src/hit/tests.rs | 85 +++++++++++++++++++++++++++++++++++-- 2 files changed, 145 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6286597882..6320be059d 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1609,7 +1609,17 @@ fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option /// is tested here. Never with `outline`, where the canvas draws no effects, nor while a /// [`DrawnOff`] guard lives. fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { - !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && !image_paint(Some(symbols.document()), n).is_empty() + !outline + && !DRAWN_OFF.get() + && matches!(n.kind, NodeKind::SymbolInstance { .. }) + && n.appearance.items.iter().any(|i| !i.effects().is_empty()) + && !image_paint(Some(symbols.document()), n).is_empty() +} + +/// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what +/// testing or outlining it takes from the [`ArtWalk`] limit. +fn walk_size(n: &Node) -> u64 { + u64::try_from(n.count_with_masks()).unwrap_or(u64::MAX) } /// The art that symbol instance `n` draws with a visible effect of its own, the effects of its @@ -1617,17 +1627,28 @@ fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool /// visible effects of its own and of its fills and strokes, as outlined paths ([`set_drawn_art`]). /// `None` for other objects, with `outline`, where the canvas draws no effects, for an instance or /// type without such an effect, while a [`DrawnOff`] guard lives, and when no geometry effect -/// changes what it draws. +/// changes what it draws. Evaluating the art is work that walking it does not count, so the art +/// takes its objects from the [`ArtWalk`] limit of the click or outline under way, and the walk of +/// it takes them again. Once the limit is used up, the result is `Some` of an empty group, which +/// hits and outlines nothing, and no more art is evaluated. fn own_effects_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> Option { let has = match n.kind { NodeKind::SymbolInstance { .. } => n.appearance.effects.iter().any(|e| e.visible), NodeKind::Text(_) => has_own_effects(n), _ => false, }; - if outline || DRAWN_OFF.get() || !has { + if outline || DRAWN_OFF.get() || !has || DRAWN_ART.get().is_none() { return None; } - DRAWN_ART.get()?(symbols, n) + let nothing = || Some(Node::group(n.id, vec![])); + if ArtWalk::used_up() { + return nothing(); + } + let art = DRAWN_ART.get()?(symbols, n)?; + if !ArtWalk::take(walk_size(&art)) { + return nothing(); + } + Some(art) } /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path @@ -1744,12 +1765,36 @@ impl<'a> InstanceArt<'a> { /// outlined where the canvas draws it. Not with `outline`, where the canvas draws no effects. fn drawn(doc: &'a Document, inst: &Node, outline: bool) -> Option { let mut art = Self::of(doc, inst)?; + #[cfg(test)] + ARTS_WALKED.with(|c| c.set(c.get() + 1)); if !outline && let Some(f) = INSTANCE_ROW_ART.get() { f(Some(doc), inst, &mut art.art); } Some(art) } + /// [`Self::drawn`] for symbol instance `inst` in the art of another instance, outside Outline. + /// Copying the art and adding the effects to it is work that walking it does not count, so the + /// art takes as many objects as placing it makes ([`Self::size`]) from the [`ArtWalk`] limit of + /// the click or outline under way before it is copied, as the marquee takes the art it places, + /// and the walk of it takes its objects again. `None` once fewer are left. + fn nested(doc: &'a Document, inst: &Node) -> Option { + if ArtWalk::used_up() { + return None; + } + let NodeKind::SymbolInstance { symbol, xf } = &inst.kind else { return None }; + let boxes = doc.symbol_boxes().quick(); + let source = boxes.symbol_art(symbol)?; + let size = match boxes.slice_map(symbol, *xf) { + Some(m) => m.most_placed_with(source, &boxes), + None => walk_size(source), + }; + if !ArtWalk::take(size) { + return None; + } + Self::drawn(doc, inst, false) + } + /// The map that the objects inside group or layer `n` are moved by as one piece: `whole`, the /// map of an object around `n` that is moved as one piece, or else the map of the 9-slice cell /// `n` lies in ([`crate::NineSliceMap::one_cell`]). `None` when `n` is placed through the guides @@ -1958,7 +2003,7 @@ fn drawn_instance_hit(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes if symbols.art(symbol).is_none() || ArtWalk::used_up() { return None; } - let art = InstanceArt::drawn(symbols.document(), n, false)?; + let art = InstanceArt::nested(symbols.document(), n)?; let opt = HitOptions { clip_outlines: false, ..opt }; let _art_only = ArtOnly::set(); FindPart { art: &art, p, opt, symbols, whole_instance: true, drawn: true }.find(&art.art, &mut vec![], None, false) @@ -2112,8 +2157,11 @@ pub fn symbol_part_outline(doc: &Document, inst: &Node, path: &[u32]) -> Option< /// outlines are cut to the bounds of the plain clipping paths, without their live effects, as /// [`symbol_part_at`] counts them. The outline is empty when the effects of a clipping path around /// the object leave no region. Elsewhere the outlines follow the geometry effects of the instance's -/// active fill and stroke, as [`symbol_part_at`] does. +/// active fill and stroke, as [`symbol_part_at`] does. Outlining visits at most as many objects of +/// symbol art as one click does ([`ArtWalk`]), the art of the instances nested in the part included, +/// and leaves out what is past that limit. pub fn symbol_part_outline_in_view(doc: &Document, inst: &Node, path: &[u32], opt: HitOptions) -> Option { + let _walk = ArtWalk::open(); let mut outline = opt.outline || below_preview_off(doc, inst, opt.scope); let art = InstanceArt::drawn(doc, inst, outline)?; let part = crate::symbol_overrides::part(&art.art, path)?; @@ -2164,11 +2212,16 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option, outline: bool, out: &mut BezPath) { use vectorcraft_geom::kurbo::Shape; + if !ArtWalk::take(1) { + return; + } if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && let Some(art) = drawn_art(symbols, n, outline) { @@ -2185,7 +2238,7 @@ fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: && reshapes_instance_art(n, symbols, outline) { if symbols.art(symbol).is_some() - && let Some(art) = InstanceArt::drawn(symbols.document(), n, false) + && let Some(art) = InstanceArt::nested(symbols.document(), n) && let Some(placed) = art.place(&art.art, None) { outline_within(&placed, symbols, limit, outline, out); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index ad037931a0..7c704511c3 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1324,11 +1324,11 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } -/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to -/// (320, 20); nothing for anything else. +/// For instances of the symbols whose names start with "Painted", a fill that paints the square +/// from (300, 0) to (320, 20); nothing for anything else. fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { match &n.kind { - NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + NodeKind::SymbolInstance { symbol, .. } if symbol.starts_with("Painted") => { let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] } @@ -3041,6 +3041,85 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); } +/// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect: +/// [`painted_far_away`] gives it shapes when the name starts with "Painted", so a part pick and a +/// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]). +fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc { + let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + Arc::new(n) +} + +/// Five levels of symbols: "Painted 0" is a 1 pt square, and each level above holds 8 instances +/// of the level below whose fills have a geometry effect. Returns the id of an instance of +/// "Painted 4" on the layer. +fn painted_chain(d: &mut Document) -> NodeId { + let l = d.layers[0].id; + let dot = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted 0".into(), art: Arc::new(dot) }); + for level in 1..5 { + let members = (0..8).map(|_| painted_instance_of(d, &format!("Painted {}", level - 1))).collect(); + group_symbol(d, &format!("Painted {level}"), members); + } + let inst = instance_of(d, "Painted 4"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + id +} + +/// The outline of a part of a dynamic symbol's instance visits at most the art walk's limit of +/// objects, though the part is an instance whose art, drawn with its fill's effects, nests +/// instances 3 levels deep, 8 at each level. Within the limit every square is outlined. +#[test] +fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let n = d.node(id).unwrap(); + let squares = |o: &BezPath| o.elements().iter().filter(|e| matches!(e, vectorcraft_geom::kurbo::PathEl::MoveTo(_))).count(); + // Part [0] is an instance of "Painted 3": 8 × 8 × 8 squares. + assert_eq!(squares(&symbol_part_outline(&d, n, &[0]).unwrap()), 512, "within the limit"); + let (outline, _, arts) = with_art_limit(100, || symbol_part_outline(&d, n, &[0]).unwrap()); + assert!(squares(&outline) < 100, "{} squares outlined", squares(&outline)); + assert!(arts < 100, "{arts} instances' art walked"); +} + +/// A part pick in a dynamic symbol's instance visits at most the art walk's limit of objects of +/// nested instances whose art, drawn with their fills' effects, is walked: in a chain of nested +/// instances, and in instances whose clip groups the click misses, where only the clip group +/// itself is tested. A click on the clipped art of a nested instance is still found. +#[test] +fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() { + set_image_paint(painted_far_away); + let mut d = Document::new(600.0, 400.0); + let id = painted_chain(&mut d); + let opt = HitOptions::default(); + let (hit, _, arts) = with_art_limit(100, || symbol_part_at(&d, d.node(id).unwrap(), Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 40, "chain: {arts} instances' art walked"); + // 30 instances of a clip group whose 10 pt clipping path holds 40 squares: 42 objects each. + let mut d = Document::new(600.0, 400.0); + let l = d.layers[0].id; + let mask = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default()); + let mut members = vec![Arc::new(mask)]; + members.extend((0..40).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())))); + let mut clip = Node::group(d.alloc_id(), members); + clip.set_clips(true); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted clip".into(), art: Arc::new(clip) }); + let members = (0..30).map(|_| painted_instance_of(&mut d, "Painted clip")).collect(); + group_symbol(&mut d, "Clips", members); + let inst = instance_of(&mut d, "Clips"); + let id = inst.id; + d.insert(Some(l), 0, Arc::unwrap_or_clone(inst)).unwrap(); + let n = d.node(id).unwrap(); + let (hit, _, arts) = with_art_limit(300, || symbol_part_at(&d, n, Point::new(150.0, 50.0), opt)); + assert_eq!(hit, None); + assert!(arts <= 8, "clip groups: {arts} instances' art walked"); + assert_eq!(with_art_limit(300, || symbol_part_at(&d, n, Point::new(2.0, 2.0), opt)).0, Some(vec![29]), "the clipped art"); +} + /// In a dynamic symbol's art that placing through its 9-slice guides could make more than /// [`crate::MAX_SYMBOL_NODES`] objects of, Direct Selection picks and outlines nothing, as the /// canvas draws nothing of it. At the art's natural size the same art is picked. From 05d5befece364ebcc9bf19df82fdf59f745db832 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:09:01 -0800 Subject: [PATCH 18/19] Symbols: Direct Selection follows a nested instance of a clip group moved by the instance's fill effects A symbol instance nested in a dynamic symbol's art was picked and outlined where its art is drawn only when the shapes its fill and stroke paint were non-empty. Those shapes leave out clip groups and type, so a nested instance whose art is a clip group was picked at its plain place although the canvas draws its members moved by the outer instance's fill or stroke effects. The test is now whether the nested instance's active fill or stroke has a visible geometry effect, which the engine registers with set_instance_reshapes. Picks and outlines no longer evaluate those shapes for each nested instance they visit. --- crates/doc/src/hit.rs | 29 ++++++++++++++++------ crates/doc/src/hit/tests.rs | 10 +++++++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/dynamic_symbols.rs | 26 +++++++++++++++++++ 4 files changed, 58 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6320be059d..6507112c24 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -131,6 +131,20 @@ pub fn set_instance_row_art(f: InstanceRowArt) { let _ = INSTANCE_ROW_ART.set(f); } +/// Does a symbol instance's active fill or stroke carry a visible geometry effect, which the art it +/// places takes on each of its fills and strokes ([`set_instance_row_art`])? Effects are classified +/// above this crate, so the engine registers one with [`set_instance_reshapes`]. +pub type InstanceReshapes = fn(&Node) -> bool; + +static INSTANCE_RESHAPES: OnceLock = OnceLock::new(); + +/// Register how Direct Selection tells whether a symbol instance's fill or stroke effects reshape +/// its art (the first registration stays). +pub fn set_instance_reshapes(f: InstanceReshapes) { + // Already set: the same engine, registered by another session. + let _ = INSTANCE_RESHAPES.set(f); +} + /// The shapes that [`ImagePaint`] gives for one object. type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; @@ -1603,17 +1617,18 @@ fn painted_hit(painted: &Painted, p: Point, opt: HitOptions) -> Option }) } -/// Is `n` a symbol instance whose active fill or stroke has geometry effects that reshape the art -/// it draws ([`image_paint`])? Callers ask [`own_effects_art`] first, which takes an instance whose +/// Is `n` a symbol instance whose active fill or stroke has a visible geometry effect, which +/// reshapes the art it draws ([`set_instance_reshapes`])? This holds whatever that art is, clip +/// groups and type included. Callers ask [`own_effects_art`] first, which takes an instance whose /// own effects change what it draws; an instance whose own effects add only pixels (a drop shadow) /// is tested here. Never with `outline`, where the canvas draws no effects, nor while a -/// [`DrawnOff`] guard lives. -fn reshapes_instance_art(n: &Node, symbols: &SymbolBoxes, outline: bool) -> bool { +/// [`DrawnOff`] guard lives, nor while nothing is registered. +fn reshapes_instance_art(n: &Node, outline: bool) -> bool { !outline && !DRAWN_OFF.get() && matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.appearance.items.iter().any(|i| !i.effects().is_empty()) - && !image_paint(Some(symbols.document()), n).is_empty() + && INSTANCE_RESHAPES.get().is_some_and(|f| f(n)) } /// How many objects `n` holds with its opacity masks' art ([`Node::count_with_masks`]), what @@ -1905,7 +1920,7 @@ impl FindPart<'_> { let _art_only = ArtOnly::set(); return hit_any(&art, self.p, opt, self.symbols); } - if reshapes_instance_art(&placed, self.symbols, opt.outline) { + if reshapes_instance_art(&placed, opt.outline) { return drawn_instance_hit(&placed, self.p, opt, self.symbols); } } @@ -2235,7 +2250,7 @@ fn outline_within(n: &Node, symbols: &SymbolBoxes, limit: Option, outline: return; } if let NodeKind::SymbolInstance { symbol, .. } = &n.kind - && reshapes_instance_art(n, symbols, outline) + && reshapes_instance_art(n, outline) { if symbols.art(symbol).is_some() && let Some(art) = InstanceArt::nested(symbols.document(), n) diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 7c704511c3..ea38de43b8 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -3041,8 +3041,14 @@ fn a_click_counts_the_members_of_an_intertwine_group_in_symbol_art_toward_one_li assert_eq!(with_art_limit(100, || at(140.0)).0, Some(id), "on the squares' paths"); } +/// Whether a symbol instance's fill or stroke effects reshape its art, for these tests: when +/// [`painted_far_away`] gives it shapes. +fn reshapes_when_painted(n: &Node) -> bool { + !painted_far_away(None, n).is_empty() +} + /// An instance of the symbol named `symbol`, not moved, whose fill has a geometry effect: -/// [`painted_far_away`] gives it shapes when the name starts with "Painted", so a part pick and a +/// [`reshapes_when_painted`] holds for it when the name starts with "Painted", so a part pick and a /// part outline walk its art as drawn with its fill's effects ([`InstanceArt::drawn`]). fn painted_instance_of(d: &mut Document, symbol: &str) -> Arc { let mut n = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: symbol.into(), xf: vectorcraft_geom::Affine::IDENTITY }); @@ -3075,6 +3081,7 @@ fn painted_chain(d: &mut Document) -> NodeId { #[test] fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); let mut d = Document::new(600.0, 400.0); let id = painted_chain(&mut d); let n = d.node(id).unwrap(); @@ -3093,6 +3100,7 @@ fn a_parts_outline_walks_nested_reshaped_symbol_instances_within_one_limit() { #[test] fn a_part_pick_walks_nested_reshaped_symbol_instances_within_one_limit() { set_image_paint(painted_far_away); + set_instance_reshapes(reshapes_when_painted); let mut d = Document::new(600.0, 400.0); let id = painted_chain(&mut d); let opt = HitOptions::default(); diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 0272e8fb76..1685adc40f 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -27,6 +27,7 @@ impl Session { // Direct Selection picks and outlines the parts of a dynamic symbol's instance where the // effects of the instance's fill and stroke draw them. vectorcraft_doc::hit::set_instance_row_art(vectorcraft_render::effects::add_instance_row_effects_to_parts); + vectorcraft_doc::hit::set_instance_reshapes(vectorcraft_render::effects::has_item_geometry); // Clicks inside a clip group fall in the region its clipping path's effects give it. vectorcraft_doc::hit::set_clip_region(vectorcraft_render::effects::reshaped_clip_outline); // Clicks and marquees find paths, compound paths, groups and layers where their geometry diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index 6f4973cd15..fc1305a0a7 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -741,6 +741,32 @@ fn a_picked_clipping_path_is_outlined_by_its_own_geometry() { assert!((b.x0 - 10.0).abs() < 0.5 && (b.x1 - 50.0).abs() < 0.5, "the clipping path's own edge: {b:?}"); } +/// A symbol instance in a dynamic symbol's art whose own art is a clip group takes the instance's +/// fill effect on the clip group's members, which the canvas draws moved: Direct Selection picks it +/// where its member is drawn, not where the member's own shape is, and outlines it there. +#[test] +fn a_nested_instance_of_a_clip_group_is_picked_where_the_fill_effect_draws_its_art() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let content = square(&mut s, 10.0); + let clip = id(&s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 200, "height": 60})).unwrap()); + s.execute("object.clippingMask.make", &json!({"ids": [content.0, clip.0]})).unwrap(); + let group = top(&s); + assert!(node(&s, group).clips()); + let inner = id(&s.execute("symbol.new", &json!({"name": "Inner", "ids": [group.0]})).unwrap()); + let b = square(&mut s, 160.0); + let inst = id(&s.execute("symbol.new", &json!({"name": "Outer", "ids": [inner.0, b.0], "type": "dynamic"})).unwrap()); + row_effect(&mut s, inst, true, "distort.transform", json!({"moveH": 100})); + // The member is drawn at x 110..150, inside the clipping path. + assert_eq!(pixel(&s, 130, 30), BLUE, "the canvas draws the member moved"); + assert_ne!(pixel(&s, 30, 30), BLUE, "and not in its own place"); + assert_eq!(part_at(&s, inst, (130.0, 30.0), opt), Some(vec![0]), "the nested instance where its member is drawn"); + assert_eq!(part_at(&s, inst, (30.0, 30.0), opt), None, "the member's own place"); + let o = part_outline_box(&s, inst, &[0]); + assert!((o.x0 - 110.0).abs() < 0.5 && (o.x1 - 150.0).abs() < 0.5, "the outline follows the moved member: {o:?}"); +} + #[test] fn a_drag_of_a_picked_object_moves_nothing_and_says_why() { let mut s = session(); From d54cbce77875bcc4ccfeccf3941f771514b3e744 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 04:52:00 -0800 Subject: [PATCH 19/19] Symbols: a part's outline leaves out hidden art of instances nested in it The outline of a dynamic instance's part walked the art of an instance nested in the part, drawn with that instance's fill and stroke effects, and outlined its hidden objects as well. It now skips a hidden object and what it holds, as the part pick does. --- crates/doc/src/hit.rs | 4 ++-- crates/doc/src/hit/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6507112c24..93a13296de 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2231,10 +2231,10 @@ fn limit_within(clip: &Node, limit: Option, outline: bool) -> Option