From b4d5d192ba13541c4c9e5b761e2367392cc509be Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 15:57:45 -0800 Subject: [PATCH 1/3] Shear: angles from -359 to 359 shear by their own tangent instead of stopping at 89 object.shear clamped its angle to -89..89 without an error, so any angle past 89 sheared by 89. It now takes the Shear dialog's documented range of -359 to 359 degrees and shears by the angle's tangent, so 120 slants as -60. An angle outside that range, and +-90 and +-270 (within 1e-9 degrees), where the tangent is unbounded, return an error naming `angle`; nothing moves and no undo step is recorded. Docs: params text, docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 14 ++++++- crates/engine/src/tests/xform.rs | 46 +++++++++++++++++++++++ docs/mcp.md | 6 ++- docs/target-app-parity.md | 2 +- 5 files changed, 66 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..e17d9ef634 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..881776cc3a 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -414,12 +414,24 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// Angles closer than this many degrees to ±90 or ±270 count as those angles. It is far above the +/// rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let angle = f64_or(p, "angle", 0.0); + if !(-359.0..=359.0).contains(&angle) { + return Err(bad("object.shear", format!("`angle` must be from -359 to 359 degrees, not {angle}"))); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + if (angle.rem_euclid(180.0) - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(bad("object.shear", format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"))); + } let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); + let t = angle.to_radians().tan(); let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 4e13e5fe02..7c6a53d27e 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -511,6 +511,52 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}"); } +/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant +/// opposite ways, and 120 and 300 slant as -60 does. +#[test] +fn shear_angles_slant_by_their_tangent() { + let run = 100.0 * 60f64.to_radians().tan(); + for (angle, want) in [ + (60.0, Rect::new(-run, 0.0, 100.0, 100.0)), + (-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)), + ] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap(); + assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a)); + } +} + +/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no +/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded. +#[test] +fn shear_rejects_angles_with_no_shear_or_out_of_range() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let n = undo_len(&s); + let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear"); + let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}"); + for (angle, msg) in [ + (90.0, none(90.0)), + (-90.0, none(-90.0)), + (270.0, none(270.0)), + (-270.0, none(-270.0)), + (90.0 + 1e-12, none(90.0 + 1e-12)), + (360.0, range(360.0)), + (-359.5, range(-359.5)), + (1e300, range(1e300)), + ] { + let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string()); + assert_eq!(e.to_string(), msg); + } + assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle"); + assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n, "no undo step"); +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..6d973eeb44 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6842,7 +6842,11 @@ wide. `object.align` needs `horizontal` or `vertical`. The three Align commands, `object.reflect` and `object.shear` return an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or `bounds` param given another value (`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing -moves. +moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the +[Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), +and shears by its tangent, so 120 slants as -60. It returns an error for an angle outside that range, and, as +VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo +step is recorded. ## Glyph bounds for type diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..ea540d6390 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1277,7 +1277,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). - Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). + Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Space held during the Pen's closing drag moves the first anchor, handles and all, as that page also describes (`path.close`'s `at`). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). From cd259b9fa8ff82f8ba0bf785ba4ca389ea3a9d42 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:04:12 -0800 Subject: [PATCH 2/3] Shear: 180 and -180 leave the art unchanged The tangent of 180 degrees in radians is about 1e-16, not 0, so a shear by 180 or -180 moved coordinates very slightly and recorded an undo step. Angles within 1e-9 degrees of 0, 180 or -180 now shear by 0: without `copy`, nothing moves and no undo step is recorded. Docs: params text, docs/mcp.md. --- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/transform.rs | 8 +++++--- crates/engine/src/tests/xform.rs | 17 +++++++++++++++++ docs/mcp.md | 3 ++- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index e17d9ef634..fd7c1a5794 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 881776cc3a..f5fb74cd1a 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -414,8 +414,8 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } -/// Angles closer than this many degrees to ±90 or ±270 count as those angles. It is far above the -/// rounding error of an angle up to 359° and below any angle a field shows. +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; pub(super) fn shear(s: &mut Session, p: &Value) -> Result { @@ -431,7 +431,9 @@ pub(super) fn shear(s: &mut Session, p: &Value) -> Result { } let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = angle.to_radians().tan(); + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + let flat = angle.rem_euclid(180.0); + let t = if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }; let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 7c6a53d27e..0bae55a3de 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -557,6 +557,23 @@ fn shear_rejects_angles_with_no_shear_or_out_of_range() { assert_eq!(undo_len(&s), n, "no undo step"); } +/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact +/// coordinates and no undo step is recorded. +#[test] +fn shear_by_0_and_180_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let before = bounds(&s, a); + let n = undo_len(&s); + for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] { + for axis in ["horizontal", "vertical"] { + s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap(); + assert_eq!(bounds(&s, a), before, "{angle} {axis}"); + assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step"); + } + } +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 6d973eeb44..f535ab2b28 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6844,7 +6844,8 @@ an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or ` (`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the [Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), -and shears by its tangent, so 120 slants as -60. It returns an error for an angle outside that range, and, as +and shears by its tangent, so 120 slants as -60. An angle of 0 or ±180 (within 1e-9 degrees) has no slant: without +`copy`, nothing moves and no undo step is recorded, and with `copy` the copies keep the art's place. It returns an error for an angle outside that range, and, as VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo step is recorded. From 9f84820d888728b45c23df02cb1092420f85bcc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:42:44 -0800 Subject: [PATCH 3/3] MCP: transform checks scale, reflect and shear before any step runs The transform tool runs move, rotate, scale, reflect and shear as separate commands. A shear angle that object.shear refuses, such as 90, a reflect axis other than vertical or horizontal, or a scale of 0 failed only after the earlier steps had changed the art and recorded undo steps. The tool now checks those params first with the rules the commands use (scale_factors, reflect_axis and shear_tangent, shared with object.scale, object.reflect and object.shear), so a refused request changes nothing and records no undo step. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/object.rs | 1 + crates/engine/src/cmd/object/transform.rs | 71 ++++++++++++++--------- crates/mcp/src/tests.rs | 27 +++++++++ crates/mcp/src/tools/definitions.rs | 2 +- crates/mcp/src/tools/handlers.rs | 24 ++++++-- docs/mcp.md | 2 +- 7 files changed, 97 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..99dedd5bda 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -827,6 +827,8 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index f5fb74cd1a..3eb9482692 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -360,15 +360,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +400,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,26 +412,47 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + /// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It /// is far above the rounding error of an angle up to 359° and below any angle a field shows. const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; - let angle = f64_or(p, "angle", 0.0); - if !(-359.0..=359.0).contains(&angle) { - return Err(bad("object.shear", format!("`angle` must be from -359 to 359 degrees, not {angle}"))); - } - // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. - if (angle.rem_euclid(180.0) - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { - return Err(bad("object.shear", format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear"))); - } + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. - let flat = angle.rem_euclid(180.0); - let t = if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }; let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; apply_transform(s, "Shear", ids, about(o, m), p, true) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index a6d1fe6c5d..89299c484c 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1634,6 +1634,33 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 1b86095c6e..d730f8deaf 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..381cc93e44 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -292,6 +292,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + let reflect = a.get("reflect").and_then(Value::as_str); + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); @@ -312,17 +330,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/docs/mcp.md b/docs/mcp.md index f535ab2b28..3a076b314f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -696,7 +696,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. |