From 99a04b9a78e584879e2a7ad37100f8179e8dbbe9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 17:52:07 -0800 Subject: [PATCH] Scripts: transforms keep path strokes within 1000 points and take empty paths `resize` and `transform` with `changeLineWidths` at the transformation's own scale scaled a path's strokes past the 1000-point limit that other line widths enforce, and could store a NaN weight for a scale too large for a number. Every stroke layer the transformation scales is now checked against the limit with the factor the transformation applies. `rotate`, `resize` and `transform` threw "the object has no bounds" on a path without points whenever the call named or defaulted to a point of the bounds. Such a path now takes the transformation about the origin, or the first artboard's bottom-left corner for `Transformation.DOCUMENTORIGIN`, so its linked mask, strokes, effects and patterns still transform. Both faults came in with #9295. --- crates/engine/src/script/dom/paths.rs | 14 +++++ crates/engine/src/script/dom/transform.rs | 41 +++++++++--- .../engine/src/tests/script_dom_transform.rs | 63 +++++++++++++++++++ docs/mcp.md | 12 ++-- 4 files changed, 116 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 50cd224f44..6761a0a40c 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -1156,6 +1156,20 @@ pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, c Ok(((new_width - width).abs() > 1e-9).then_some(new_width)) } +/// The largest stroke weight in the path `item`'s own appearance, in points. +pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result { + read_path(h, item, |_, n, _| { + n.appearance + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + vectorcraft_doc::AppearanceItem::Fill(_) => None, + }) + .fold(0.0, f64::max) + }) +} + /// Whether `item` is a path, so [`resized_stroke_weight`] applies to it. pub(super) fn is_path(h: &super::Host, item: Item) -> bool { with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))) diff --git a/crates/engine/src/script/dom/transform.rs b/crates/engine/src/script/dom/transform.rs index 6c07a070e1..1102a09450 100644 --- a/crates/engine/src/script/dom/transform.rs +++ b/crates/engine/src/script/dom/transform.rs @@ -20,9 +20,13 @@ //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale //! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to -//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any -//! other value, and a scale of strokes and effects with positions left as they are, throws an -//! error that says so. +//! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. +//! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight +//! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale +//! of strokes and effects with positions left as they are, throws an error that says so. +//! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` +//! still uses the first artboard's bottom-left corner; other named points use the origin. +//! Its linked opacity mask, strokes, effects and patterns transform with the same options. //! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a //! locked object, and an object on a locked artboard are refused with nothing changed, and so are //! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object @@ -132,8 +136,17 @@ fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { } /// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` -/// ([`anchor_name`]) names. -fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result { +/// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. +fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { + if r.is_none() && !paths::is_path(h, item) { + return Err(HostError::Error("the object has no bounds".into())); + } + if name == "DOCUMENTORIGIN" { + return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); + } + let Some(r) = r else { + return Ok(Point::ORIGIN); + }; let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); Ok(match name { "TOPLEFT" => Point::new(r.x0, r.y0), @@ -144,7 +157,6 @@ fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result Point::new(r.x0, r.y1), "BOTTOM" => Point::new(cx, r.y1), "BOTTOMRIGHT" => Point::new(r.x1, r.y1), - "DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?, _ => Point::new(cx, cy), }) } @@ -215,12 +227,10 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } - // The identity acts the same about every point, so an object without bounds (an empty path) - // takes it too. + // The identity acts the same about every point for any object. let o = match (about, bounds) { _ if m == IDENTITY => Point::ORIGIN, - (Some(name), Some(r)) => anchor(h, item, r, name)?, - (Some(_), None) => return Err(HostError::Error("the object has no bounds".into())), + (Some(name), r) => anchor(h, item, r, name)?, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); @@ -242,6 +252,17 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, } let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; + // Every stroke layer's weight is checked with the factor `object.transform` applies. + let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; + if let Some(k) = factor + && paths::is_path(h, item) + && (!k.is_finite() || { + let width = paths::largest_stroke_weight(h, item)? * k; + !width.is_finite() || width > paths::MAX_STROKE_WIDTH + }) + { + return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); + } let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; // The transformation and the stroke weight change together or not at all. atomically(h, |h| { diff --git a/crates/engine/src/tests/script_dom_transform.rs b/crates/engine/src/tests/script_dom_transform.rs index d57d4570d5..f3aa67c361 100644 --- a/crates/engine/src/tests/script_dom_transform.rs +++ b/crates/engine/src/tests/script_dom_transform.rs @@ -130,6 +130,69 @@ fn resize_scales_about_the_center_and_line_widths_follow_their_argument() { assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}"); } +#[test] +fn a_line_width_of_the_scale_itself_keeps_a_path_stroke_within_1000_points() { + let (mut s, _, _) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 600;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + for call in ["resize(200, 200, true, true, true, true, 200)", "transform(app.getScaleMatrix(200), true, true, true, true, 200)"] { + let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};")); + assert!(e.contains("more than 1000 points"), "{call}: {e}"); + } + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + // A scale that keeps the weight within the limit still scales it. + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.resize(150, 150, true, true, true, true, 150); vc.log(i.strokeWidth);"); + assert!(close(&numbers(&out[0]), &[900.0]), "{out:?}"); + + // The lower stroke must stay within the limit too. + let (mut s, a, _) = doc(); + s.execute("stroke.set", &json!({"id": a.0, "weight": 600})).unwrap(); + s.execute("appearance.addStroke", &json!({"id": a.0})).unwrap(); + log(&mut s, "app.activeDocument.pageItems[0].strokeWidth = 1;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(200, 200, true, true, true, true, 200);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); + + // A nonfinite scale must not turn a zero-width stroke into NaN. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.strokeWidth = 0;"); + let before = s.active().unwrap().doc.clone(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.pathItems[0].resize(1e202, 1e202, true, true, true, true, 1e202);"); + assert!(e.contains("more than 1000 points"), "{e}"); + assert_eq!(undo_steps(&s), steps); + assert_eq!(*s.active().unwrap().doc, *before); +} + +#[test] +fn an_empty_path_takes_any_transformation_about_any_point() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "app.activeDocument.pathItems.add();"); + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.rotate(30); n.rotate(30, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(50, 200); n.resize(50, 50, true, true, true, true, 100, Transformation.BOTTOM);\ + n.transform(app.getRotationMatrix(45)); n.rotate(30, true, true, true, true, Transformation.DOCUMENTORIGIN);\ + vc.log(n.pathPoints.length);", + ); + assert_eq!(out, vec![json!(0)]); + // Its stroke weight still scales with the transformation. + let out = log( + &mut s, + "var n = app.activeDocument.pathItems[0]; n.strokeWidth = 10; n.resize(200, 200, true, true, true, true, 200); vc.log(n.strokeWidth);", + ); + assert!(close(&numbers(&out[0]), &[20.0]), "{out:?}"); + let e = failure(&mut s, "app.activeDocument.pathItems[0].rotate(30, true, true, true, true, 'x');"); + assert!(e.contains("Transformation value"), "{e}"); +} + #[test] fn transform_applies_a_matrix_record_about_the_center() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 8507629dc6..75d6f17110 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3181,13 +3181,17 @@ through `$`: object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is, so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and `transform` act about the center of the geometric bounds unless a `Transformation` value names another point of - them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients - default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different + them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. A path without points takes + any of them about any point named. `Transformation.DOCUMENTORIGIN` still uses the first artboard's bottom-left + corner; other named points use the origin. Its linked opacity mask, strokes, effects and patterns transform with + the same options. Positions and gradients default to `true` and patterns to the Transform Pattern Tiles + preference. Fill and stroke patterns with different values, and gradients different from positions, counting the defaults of arguments left out, throw an error that says they are not available yet. `changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the - square root of the area it scales by (stroke weights and effects scale with it). `resize` on a path also takes any - other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, + square root of the area it scales by (stroke weights and effects scale with it; the scale and every stroke layer's + resulting weight on a path must stay finite, and a weight that would pass 1000 points throws). `resize` on a path + also takes any other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`, at most 1000 points). On a member of a compound path or compound shape, the compound's stroke weight follows the percent through `stroke.set`; when the percent is the resize's own scale, the member's own strokes and effects also scale with it. `transform` with `changeLineWidths` at the matrix's own scale sets the compound's stroke weight the