Merge pull request #7213 from dotCooCoo/feat/rotated-box-scale-reflect

Transform: Scale and Reflect act along a rotated bounding box
This commit is contained in:
BFlat
2026-11-15 09:47:18 +07:00
committed by GitHub
14 changed files with 388 additions and 37 deletions
@@ -531,8 +531,13 @@ fn an_anchor_edit_makes_it_a_plain_path_and_transforms_keep_it_editable() {
s.execute("addon.pathtools.shape.set", &json!({"id": id.0, "count": 6})).unwrap();
assert_eq!((path(&s, id).anchor_count(), steps(&s)), (12, n + 1));
assert!((shape_of(&s, id).unwrap().rotation + 30.0).abs() < 1e-6, "the turn stays");
// Stretched across its own axes (it is turned): skewed, so no longer.
// Stretched along its turned bounding box: still the shape, wider along its own axis.
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140]})).unwrap();
let r = shape_of(&s, id).unwrap();
assert!((r.width - 300.0).abs() < 1e-6 && (r.height - 200.0).abs() < 1e-6 && (r.rotation + 30.0).abs() < 1e-6, "{r:?}");
s.execute("edit.undo", &json!({})).unwrap();
// Stretched across the page's axes (it is turned): skewed, so no longer.
s.execute("object.scale", &json!({"sx": 150, "sy": 100, "origin": [220, 140], "basis": "page"})).unwrap();
assert_eq!(shape_of(&s, id), None);
s.execute("edit.undo", &json!({})).unwrap();
assert!(shape_of(&s, id).is_some(), "undo brings it back");
+2 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Scale…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), sx: %, sy?: %, origin?: [x,y], copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), 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)} (strokes/corners default to the preferences). 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), sx: % (along the bounding box's width), sy?: % (along its height), origin?: [x,y] (a page point), basis?: \"box\"|\"page\" (box, the default: sx and sy follow the bounding box, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), copy?, strokes?: bool (Scale Strokes & Effects: stroke weights, dashes and effect distances scale; off keeps them, type strokes included), corners?: bool (Scale Corners: live corner radii scale), 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)} (strokes/corners default to the preferences). 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,
scale
),
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reflect…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: 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), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical; vertical and horizontal are the bounding box's own axes, deg a line on the page), origin?, basis?: \"box\"|\"page\" (for a named axis; box, the default: the bounding box's axes, turned with rotated objects until Reset Bounding Box; page: the page's axes; a saved step without basis, recorded before it, plays along the page's axes), 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,
reflect
),
+37 -11
View File
@@ -1,7 +1,7 @@
use super::align::choice;
use super::{
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, Point, Result, Scaling, Session, Value, Vec2, bad, bool_or,
check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
Affine, Arc, Document, EngineError, LastTransform, Node, NodeId, NodeKind, OrientedBox, Point, Rect, Result, Scaling, Session, Value, Vec2, bad,
bool_or, check_numbers, check_switches, duplicate_in, effects, f64_or, f64_req, ids_param, json, matrix_param, ok, outermost, point_param,
selected_roots_to_transform,
};
@@ -358,26 +358,52 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
if sx == 0.0 || sy == 0.0 {
return Err(bad("object.scale", "scale must be non-zero"));
}
apply_transform(s, "Scale", ids, about(o, Affine::scale_non_uniform(sx, sy)), p, true)
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 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
/// Direct Selection (with no copy and Transform Objects on) transform along the page's axes, as
/// their own box does. The basis joins the journal entry, so a replay acts in the same frame. A
/// saved step without `basis` ([`Session::replay`]) was recorded before Scale and Reflect followed
/// the box, so it acts along the page's axes, as it did when it was recorded.
fn basis_frame(s: &mut Session, p: &Value, cmd: &str, ids: &[NodeId]) -> Result<OrientedBox> {
let basis = choice(p, cmd, "basis", &["box", "page"])?;
let page = basis == Some("page") || (basis.is_none() && s.replaying());
let st = s.doc()?;
let anchors = !bool_or(p, "copy", false)
&& transforms_objects(p)
&& effects::preview::anchor_bounds_with(&st.selection, &st.doc, s.bounds_measure()).is_some();
let angle = if page || anchors { 0.0 } else { st.doc.bbox_angle(ids) };
s.note_journal("basis", json!(if page { "page" } else { "box" }));
Ok(OrientedBox { angle, rect: Rect::ZERO })
}
pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
check_switches(p, &TRANSFORM_SWITCHES, "object.reflect")?;
let ids = selected_roots_to_transform(s)?;
let o = origin_of(s, p, &ids)?;
let m = match p.get("axis") {
Some(Value::String(a)) if a == "horizontal" => Affine::scale_non_uniform(1.0, -1.0),
Some(Value::Number(n)) => {
let t = -n.as_f64().unwrap_or(90.0).to_radians();
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
}
None | Some(Value::Null) => Affine::scale_non_uniform(-1.0, 1.0),
Some(Value::String(a)) if a == "vertical" => Affine::scale_non_uniform(-1.0, 1.0),
// 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 m = match named {
Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m),
None => {
choice(p, "object.reflect", "basis", &["box", "page"])?;
let t = -p.get("axis").and_then(Value::as_f64).unwrap_or(90.0).to_radians();
Affine::rotate(t) * Affine::scale_non_uniform(1.0, -1.0) * Affine::rotate(-t)
}
};
apply_transform(s, "Reflect", ids, about(o, m), p, true)
}
+6 -1
View File
@@ -1293,7 +1293,12 @@ fn a_transform_that_moves_nothing_records_no_undo_step() {
for (id, p) in calls {
assert_eq!(s.execute(id, &p).unwrap(), json!({"ids": [a.0]}), "{id} {p}");
assert_eq!(history(&s), before, "{id} {p}");
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), p));
// The journal adds the frame a scale acted in, so a replay acts in the same one.
let mut recorded = p;
if id == "object.scale" {
recorded["basis"] = json!("box");
}
assert_eq!(s.journal.last().unwrap(), &(id.to_string(), recorded));
}
assert_eq!(
s.doc().unwrap().last_transform,
+155 -1
View File
@@ -666,7 +666,7 @@ fn expanding_a_reflected_symbol_instance_keeps_its_box() {
for reset in [false, true] {
let (mut s, inst) = turned_instance(0.0);
s.execute("object.rotate", &json!({"angle": 150})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
assert!(near(angle(&s, inst), -170.0), "{}", angle(&s, inst));
if reset {
s.execute("object.resetBoundingBox", &json!({})).unwrap();
@@ -719,10 +719,164 @@ fn page_flips_keep_an_upright_box_upright() {
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
assert_eq!(angle(&s, a), 0.0);
s.execute("object.rotate", &json!({"angle": 30})).unwrap();
// A named axis is the turned box's own: the box keeps its angle.
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
assert!(near(angle(&s, a), 30.0));
s.execute("object.reflect", &json!({"axis": "vertical", "basis": "page"})).unwrap();
assert!(near(angle(&s, a), -30.0));
}
fn same_matrix(a: Affine, b: Affine) -> bool {
a.as_coeffs().iter().zip(b.as_coeffs()).all(|(x, y)| near(*x, y))
}
/// After a rotation, Scale and a named Reflect act along the turned bounding box until Reset
/// Bounding Box; `basis: "page"` keeps the page's axes, and Transform Again repeats the matrix the
/// transform applied on the page.
#[test]
fn scale_and_reflect_follow_the_turned_box() {
let mut s = session();
let a = turned_rect(&mut s);
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
let c = Point::new(200.0, 200.0);
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let b = selection_box(&s);
assert!(near(b.angle, 45.0) && near(angle(&s, a), 45.0), "{b:?}");
assert!(near(b.rect.width(), 200.0) && near(b.rect.height(), 50.0), "{b:?}");
assert!(b.center().distance(c) < 1e-6, "{b:?}");
let want = Affine::translate(c.to_vec2()) * frame.conjugate(Affine::scale_non_uniform(2.0, 1.0)) * Affine::translate(-c.to_vec2());
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
assert!(same_matrix(m, want), "{m:?}");
// The recorded step names its basis, so a replay acts in the same frame.
let steps = s.journal_for_action(0);
assert!(steps.iter().any(|(id, p)| id == "object.scale" && p["basis"] == "box"), "{steps:?}");
// Reflected across the box's vertical axis through its left side: the box keeps its angle and
// size, and its centre moves a width to the left along the box.
let left = b.reference_point(3);
s.execute("object.reflect", &json!({"axis": "vertical", "origin": [left.x, left.y]})).unwrap();
let r = selection_box(&s);
let moved = c + (frame.to_doc() * Point::new(-200.0, 0.0)).to_vec2();
assert!(near(r.angle, 45.0) && near(r.rect.width(), 200.0) && near(r.rect.height(), 50.0), "{r:?}");
assert!(r.center().distance(moved) < 1e-6, "{r:?}");
// Across its horizontal axis through its centre: the box stays where it is.
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
assert!(selection_box(&s).center().distance(moved) < 1e-6 && near(angle(&s, a), 45.0));
// Unknown bases are errors and change nothing.
let n = undo_len(&s);
assert!(s.execute("object.scale", &json!({"sx": 50, "basis": "turned"})).is_err());
assert!(s.execute("object.reflect", &json!({"axis": "vertical", "basis": 1})).is_err());
assert!(s.execute("object.reflect", &json!({"axis": 30, "basis": "turned"})).is_err());
assert_eq!(undo_len(&s), n);
// On the page's axes, the box no longer stands at 45°.
s.execute("object.scale", &json!({"sx": 50, "sy": 100, "basis": "page"})).unwrap();
assert!(!near(angle(&s, a), 45.0));
// Transform Again repeats the page matrix after Reset Bounding Box too.
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let Some(LastTransform::Matrix(m, _)) = s.doc().unwrap().last_transform.clone() else { panic!("no transform to repeat") };
s.execute("object.resetBoundingBox", &json!({})).unwrap();
let before = s.doc().unwrap().doc.node(a).unwrap().clone();
s.execute("object.transformAgain", &json!({})).unwrap();
let mut want = before;
want.transform(m, false);
let (got, want) = (page(&s, &[a]), want.geometric_bounds_with(&s.doc().unwrap().doc.symbol_boxes()).unwrap());
assert!([got.x0 - want.x0, got.y0 - want.y0, got.x1 - want.x1, got.y1 - want.y1].iter().all(|d| d.abs() < 1e-6), "{got:?} {want:?}");
}
/// A saved step without `basis` was recorded before Scale and Reflect followed the turned box, so a
/// replay of it acts along the page's axes, as it did then, and its new journal entry says so. A
/// step recorded now names its basis and replays along the box. A call without `basis` that is not
/// a replay acts along the box.
#[test]
fn saved_steps_without_a_basis_replay_on_the_page() {
// The turned rectangle after `run` runs on it: its page bounds and its box's angle.
let after = |run: &dyn Fn(&mut Session)| {
let mut s = session();
let a = turned_rect(&mut s);
run(&mut s);
let st = (s.doc().unwrap().doc.bounds_of(&[a], false).unwrap(), angle(&s, a));
(st, s.journal.last().unwrap().clone())
};
let same = |(r, a): (Rect, f64), (q, b): (Rect, f64)| [r.x0 - q.x0, r.y0 - q.y0, r.x1 - q.x1, r.y1 - q.y1, a - b].iter().all(|d| d.abs() < 1e-6);
for (id, p) in [("object.scale", json!({"sx": 200, "sy": 100})), ("object.reflect", json!({"axis": "vertical"}))] {
let mut on_page = p.clone();
on_page["basis"] = json!("page");
let (page, _) = after(&|s| {
s.execute(id, &on_page).unwrap();
});
let (old, (_, noted)) = after(&|s| {
s.replay(id, &p).unwrap();
});
assert!(same(old, page), "{id}: {old:?} {page:?}");
assert_eq!(noted["basis"], "page", "{id}");
let (boxed, (recorded_id, recorded)) = after(&|s| {
s.execute(id, &p).unwrap();
});
assert!(!same(boxed, page) && near(boxed.1, 45.0), "{id}: {boxed:?}");
assert_eq!(recorded["basis"], "box", "{id}");
let (replayed, _) = after(&|s| {
s.replay(&recorded_id, &recorded).unwrap();
});
assert!(same(replayed, boxed), "{id}: {replayed:?} {boxed:?}");
}
}
/// Once Reset Bounding Box squares the box, and for objects standing at different angles, Scale
/// acts along the page's axes.
#[test]
fn scale_follows_the_page_after_a_reset_and_for_mixed_angles() {
let mut s = session();
let a = turned_rect(&mut s);
s.execute("object.resetBoundingBox", &json!({})).unwrap();
let page = |s: &Session, ids: &[NodeId]| s.doc().unwrap().doc.bounds_of(ids, false).unwrap();
let w = page(&s, &[a]);
s.execute("object.scale", &json!({"sx": 200, "sy": 100})).unwrap();
let r = page(&s, &[a]);
assert!(near(r.width(), 2.0 * w.width()) && near(r.height(), w.height()), "{w:?} {r:?}");
assert_eq!(angle(&s, a), 0.0);
// A turned rectangle with an upright one: the box is square to the page.
let b = turned_rect(&mut s);
let u = rect(&mut s, 400.0, 100.0, 50.0, 50.0);
sel(&mut s, &[b, u]);
let w = page(&s, &[b, u]);
s.execute("object.scale", &json!({"sx": 100, "sy": 200})).unwrap();
let r = page(&s, &[b, u]);
assert!(near(r.width(), w.width()) && near(r.height(), 2.0 * w.height()), "{w:?} {r:?}");
}
/// With anchors selected, Scale and a named Reflect move the anchors along the page's axes, but
/// with Transform Objects off they move the whole objects' pattern tiles, along the turned box.
#[test]
fn pattern_only_transforms_of_selected_anchors_follow_the_turned_box() {
let c = Point::new(200.0, 200.0);
let frame = OrientedBox { angle: 45.0, rect: Rect::ZERO };
let about = |m: Affine| Affine::translate(c.to_vec2()) * m * Affine::translate(-c.to_vec2());
let last = |s: &Session| match s.doc().unwrap().last_transform.clone() {
Some(LastTransform::Matrix(m, _)) => m,
other => panic!("no matrix to repeat: {other:?}"),
};
let scale = Affine::scale_non_uniform(2.0, 1.0);
let flip = Affine::scale_non_uniform(-1.0, 1.0);
for (cmd, p, m) in [("object.scale", json!({"sx": 200, "sy": 100}), scale), ("object.reflect", json!({"axis": "vertical"}), flip)] {
for objects in [false, true] {
let mut s = session();
let a = turned_rect(&mut s);
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "set"})).unwrap();
let mut p = p.clone();
p["origin"] = json!([c.x, c.y]);
p["objects"] = json!(objects);
p["patterns"] = json!(true);
s.execute(cmd, &p).unwrap();
let want = if objects { about(m) } else { about(frame.conjugate(m)) };
assert!(same_matrix(last(&s), want), "{cmd} objects {objects}: {:?}", last(&s));
}
}
}
#[test]
fn groups_type_and_multiple_selections_keep_their_angle() {
let mut s = session();
+3 -2
View File
@@ -219,9 +219,10 @@ fn rotate_reflect_and_scale_carry_unplaced_gradients() {
s.execute("object.rotate", &json!({"angle": 90})).unwrap();
let g = fill_geom(&s, id);
assert!((g.end.x - g.start.x).abs() < 1e-9 && (g.length() - 100.0).abs() < 1e-9, "vertical after a 90° turn: {g:?}");
s.execute("object.reflect", &json!({"axis": "horizontal"})).unwrap();
s.execute("object.reflect", &json!({"axis": "horizontal", "basis": "page"})).unwrap();
let r = fill_geom(&s, id);
// The vertical vector is centred on the object, so the reflection swaps its ends.
// The vertical vector is centred on the object, so the reflection across the page's
// horizontal axis swaps its ends.
assert!(r.start.distance(g.end) < 1e-9 && r.end.distance(g.start) < 1e-9, "{g:?} → {r:?}");
// A circle's radial gradient becomes an ellipse under a non-uniform scale.
+1 -1
View File
@@ -406,7 +406,7 @@ fn a_batch_step_records_what_it_took_from_the_preferences() {
]);
s.execute("command.batch", &json!({ "commands": steps })).unwrap();
let p = &s.journal.last().unwrap().1;
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false}));
assert_eq!(p["commands"][2]["params"], json!({"sx": 300, "strokes": true, "corners": false, "basis": "box"}));
// Replayed with other preferences, the scale still scales the stroke.
let r = replayed(&s);
assert!(!r.prefs.scale_strokes);
+1 -1
View File
@@ -216,7 +216,7 @@ fn the_journal_records_the_scale_options_used() {
run(&mut s, "object.scale", json!({"sx": 150}));
let (cmd, p) = s.journal.last().unwrap().clone();
assert_eq!(cmd, "object.scale");
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true}));
assert_eq!(p, json!({"sx": 150, "strokes": false, "corners": true, "basis": "box"}));
// An explicit value stays; moves don't scale, so they record nothing.
run(&mut s, "object.scale", json!({"sx": 150, "strokes": true}));
assert_eq!(s.journal.last().unwrap().1["strokes"], json!(true));
+1 -1
View File
@@ -465,7 +465,7 @@ pub fn tool_definitions() -> Vec<Value> {
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 %. `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.",
obj(
json!({
"ids": {"type": "array", "items": {"type": "integer"}},
+131 -13
View File
@@ -8,10 +8,12 @@
//! while hovering, so transforms pivot exactly on a corner. A drag starts from the point it grabbed
//! snapped the same way, and the pointer snaps as a drawn point does (Smart Guides: the other
//! objects' anchors, centres and edges; or the grid, pixels, Snap to Point), so a corner dragged
//! onto another object's anchor scales exactly onto it.
//! onto another object's anchor scales exactly onto it. Scale stretches along the bounding box's
//! own width and height, turned with rotated objects until Reset Bounding Box; Reflect's default
//! axis is the box's vertical one, and Shift constrains a drawn axis to 45° steps from the box.
use serde_json::{Value, json};
use vectorcraft_doc::NodeId;
use vectorcraft_doc::{NodeId, OrientedBox};
use vectorcraft_geom::{Affine, Point, Rect, Vec2};
use super::target_overlays;
@@ -68,9 +70,28 @@ struct Drag {
/// Alt was down at the press: a click opens the dialog, a drag transforms a copy.
alt: bool,
bounds: Rect,
/// The angle of the selection's bounding box: Scale and Reflect act along its axes
/// ([`TransformTool::matrix_in`]).
angle: f64,
/// Anchors are selected with Direct Selection: they transform alone along the page's axes,
/// and a copy or a pattern-only drag transforms the whole objects along the box
/// ([`Drag::angle_for`]).
anchors: bool,
/// The snapped pointer and Shift at the last drag event, to work out the transform again
/// when the Alt state at the release changes what it transforms.
pointer: Point,
shift: bool,
last: Affine,
}
impl Drag {
/// The angle Scale and Reflect act along, for a drag that copies (`copy`) or not, and that
/// transforms only pattern tiles (`patterns_only`, the backquote key) or not.
fn angle_for(&self, copy: bool, patterns_only: bool) -> f64 {
if self.anchors && !copy && !patterns_only { 0.0 } else { self.angle }
}
}
pub struct TransformTool {
kind: TransformKind,
/// Custom reference point and the selection it was set for.
@@ -125,6 +146,16 @@ impl TransformTool {
/// Transform for dragging from `start` to `p` about `o`; returns the matrix and a readout.
pub fn matrix_for(&self, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
self.matrix_in(0.0, o, start, p, shift, bounds)
}
/// [`TransformTool::matrix_for`] with the bounding box turned by `angle` (counter-clockwise
/// degrees): Scale stretches along the box's own width and height, and Reflect's default axis
/// and Shift's 45° steps start from the box's axes. A Reflect axis drawn by the drag is the
/// line the pointer draws on the page.
pub fn matrix_in(&self, angle: f64, o: Point, start: Point, p: Point, shift: bool, bounds: Rect) -> (Affine, String) {
let frame = OrientedBox { angle, rect: Rect::ZERO };
let local = |v: Vec2| frame.to_doc().inverse() * v.to_point();
match self.kind {
TransformKind::Rotate => {
let (a, deg) = rotate_for_drag(o, start, p, shift);
@@ -132,15 +163,17 @@ impl TransformTool {
}
TransformKind::Reflect => {
let mut v = p - o;
if shift {
v = vectorcraft_geom::constrain_angle(v, 45.0);
if v.hypot() < 1e-9 {
v = (frame.to_doc() * Point::new(0.0, 1.0)).to_vec2();
} else if shift {
v = (frame.to_doc() * vectorcraft_geom::constrain_angle(local(v).to_vec2(), 45.0).to_point()).to_vec2();
}
let theta = if v.hypot() < 1e-9 { std::f64::consts::FRAC_PI_2 } else { v.y.atan2(v.x) };
let theta = v.y.atan2(v.x);
(reflect_matrix(o, theta), format!("{:.1}°", vectorcraft_geom::normalize_deg(-theta.to_degrees())))
}
TransformKind::Scale => {
let d0 = start - o;
let d1 = p - o;
let d0 = local(start - o).to_vec2();
let d1 = local(p - o).to_vec2();
let ratio = |a: f64, b: f64| if a.abs() > 1e-6 { b / a } else { 1.0 };
let (mut sx, mut sy) = (ratio(d0.x, d1.x), ratio(d0.y, d1.y));
if shift {
@@ -151,7 +184,7 @@ impl TransformTool {
}
let clamp = |s: f64| if s.abs() < 1e-4 { 1e-4f64.copysign(s) } else { s };
let (sx, sy) = (clamp(sx), clamp(sy));
(about(o, Affine::scale_non_uniform(sx, sy)), format!("W: {:.1}%\nH: {:.1}%", sx * 100.0, sy * 100.0))
(about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), format!("W: {:.1}%\nH: {:.1}%", sx * 100.0, sy * 100.0))
}
TransformKind::Shear => {
// The shear axis follows the dominant drag direction. Shift keeps the drag on that
@@ -227,7 +260,21 @@ impl Tool for TransformTool {
// Alt: decided on release. A click sets the point and opens the dialog; a drag
// transforms a copy about the reference point as it was.
let origin = self.reference_point(cx).unwrap_or(bounds.center());
self.drag = Some(Drag { start: p, pick, origin, began: false, alt: ev.mods.alt, bounds, last: Affine::IDENTITY });
let anchors = vectorcraft_effects::preview::anchor_bounds_with(cx.selection, cx.doc, cx.bounds_measure()).is_some();
let angle = selection_box(cx).map_or(0.0, |b| b.angle);
self.drag = Some(Drag {
start: p,
pick,
origin,
began: false,
alt: ev.mods.alt,
bounds,
angle,
anchors,
pointer: p,
shift: false,
last: Affine::IDENTITY,
});
vec![]
}
PointerKind::Drag => {
@@ -247,8 +294,8 @@ impl Tool for TransformTool {
}
let (p, guides) = self.snap.as_ref().map_or((p, vec![]), |s| s.snap(cx, p));
self.hover = guides;
let (m, text) = self.matrix_for(d.origin, d.pick, p, ev.mods.shift, d.bounds);
d.last = m;
let (m, text) = self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, p, ev.mods.shift, d.bounds);
(d.last, d.pointer, d.shift) = (m, p, ev.mods.shift);
self.drag = Some(d);
self.measure = Some((p, text));
out.push(preview(m, ev.mods.alt, ev.backquote));
@@ -257,8 +304,15 @@ impl Tool for TransformTool {
PointerKind::Up => {
let Some(d) = self.end_drag() else { return vec![] };
if d.began {
// The Alt state at release decides whether the result is a copy.
vec![preview(d.last, ev.mods.alt, ev.backquote), Action::Commit]
// The Alt and backquote states at release decide whether the result is a copy
// or moves only pattern tiles, and with anchors selected, whether it acts
// along the box or the page.
let m = if d.anchors {
self.matrix_in(d.angle_for(ev.mods.alt, ev.backquote), d.origin, d.pick, d.pointer, d.shift, d.bounds).0
} else {
d.last
};
vec![preview(m, ev.mods.alt, ev.backquote), Action::Commit]
} else {
// A click sets the reference point; with Alt, it opens the dialog too.
self.origin = Some((d.pick, cx.selection.objects.clone()));
@@ -579,6 +633,70 @@ mod tests {
assert!((m * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9);
}
/// With the selection turned by 30°, a Scale drag stretches along the box's own sides, and
/// Reflect's default axis and Shift steps start from the box's axes while a drawn axis stays
/// the line drawn on the page.
#[test]
fn scale_and_reflect_drags_follow_a_turned_bounding_box() {
let (mut d, id) = doc_with_rect();
let c = Point::new(150.0, 150.0);
d.node_mut(id).unwrap().transform(about(c, Affine::rotate(-30f64.to_radians())), false);
let mut s = Selection::default();
s.add(id);
let p = paint();
let mut cx = cx(&d, &s, &p);
(cx.smart_guides, cx.snap_to_point) = (false, false);
let frame = OrientedBox { angle: 30.0, rect: Rect::ZERO };
let along = |x: f64, y: f64| c + (frame.to_doc() * Point::new(x, y)).to_vec2();
// The right side's middle dragged out to twice its distance: the width doubles along the
// box, and the height stays.
let mut t = TransformTool::new(TransformKind::Scale);
let (from, to) = (along(50.0, 0.0), along(100.0, 0.0));
t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y));
let a = t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y));
let m = matrix(&a[1]);
assert!((m * along(50.0, 50.0)).distance(along(100.0, 50.0)) < 1e-9, "{m:?}");
assert!((m * along(0.0, 50.0)).distance(along(0.0, 50.0)) < 1e-9, "{m:?}");
assert!(a.iter().any(|x| matches!(x, Action::Preview(..))));
let t = TransformTool::new(TransformKind::Reflect);
// No axis drawn: the box's vertical axis.
let (m, _) = t.matrix_in(30.0, c, c, c, false, Rect::ZERO);
assert!((m * along(40.0, 10.0)).distance(along(-40.0, 10.0)) < 1e-9, "{m:?}");
// Shift: 39° from the box's horizontal axis steps to 45° from it.
let (m, text) = t.matrix_in(30.0, c, c, along(10.0, 8.0), true, Rect::ZERO);
assert!((m * along(10.0, 0.0)).distance(along(0.0, 10.0)) < 1e-9, "{m:?}");
assert_eq!(text, "-15.0°");
// A drawn axis is the line on the page.
let (m, _) = t.matrix_in(30.0, c, c, c + Vec2::new(0.0, -50.0), false, Rect::ZERO);
assert!((m * Point::new(100.0, 120.0)).distance(Point::new(200.0, 120.0)) < 1e-9, "{m:?}");
// Anchors selected with Direct Selection scale alone along the page's axes; Alt at the
// release copies the whole object, which scales along its box.
let mut s = s.clone();
s.anchors.insert(id, [(0, 0), (0, 1)].into());
let mut cx = crate::testutil::cx(&d, &s, &p);
(cx.smart_guides, cx.snap_to_point) = (false, false);
let page_axes = |m: Affine| m.as_coeffs()[1].abs() < 1e-9 && m.as_coeffs()[2].abs() < 1e-9;
let (from, to) = (along(50.0, 0.0), along(100.0, 30.0));
for copy in [false, true] {
let mut t = TransformTool::new(TransformKind::Scale);
t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y));
let a = t.pointer(&cx, &ev(PointerKind::Drag, to.x, to.y));
assert!(page_axes(matrix(&a[1])), "{a:?}");
let up = t.pointer(&cx, &ev(PointerKind::Up, to.x, to.y).with_mods(if copy { alt() } else { Mods::default() }));
assert_eq!(page_axes(matrix(&up[0])), !copy, "copy {copy}: {up:?}");
}
// With the backquote key the drag moves only the whole objects' pattern tiles, which
// scale along the box, both while dragging and at the release.
let mut t = TransformTool::new(TransformKind::Scale);
t.pointer(&cx, &ev(PointerKind::Down, from.x, from.y));
let a = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Drag, to.x, to.y) });
assert!(!page_axes(matrix(&a[1])), "{a:?}");
let up = t.pointer(&cx, &PointerEvent { backquote: true, ..ev(PointerKind::Up, to.x, to.y) });
assert!(!page_axes(matrix(&up[0])), "{up:?}");
}
#[test]
fn shear_horizontal_keeps_origin_row() {
let t = TransformTool::new(TransformKind::Shear);
+23 -1
View File
@@ -312,7 +312,7 @@ pub fn default_sets() -> Vec<ActionSet> {
Action::new("Center on Artboard", vec![step("object.align", json!({"horizontal": "center", "vertical": "center", "to": "artboard"}))]),
Action::new("Outline Text", vec![step("type.createOutlines", json!({}))]),
Action::new("Rotate 90° CW", vec![step("object.rotate", json!({"angle": -90}))]),
Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical"}))]),
Action::new("Reflect Horizontal", vec![step("object.reflect", json!({"axis": "vertical", "basis": "box"}))]),
],
)]
}
@@ -2721,6 +2721,28 @@ mod tests {
}
}
/// The built-in Reflect Horizontal reflects a rotated object across its bounding box's own axis,
/// as the Reflect dialog does, so the box keeps its angle; a saved step without a basis, recorded
/// before Reflect followed the box, still reflects across the page's axis.
#[test]
fn the_built_in_reflect_follows_the_turned_box() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = vectorcraft_doc::NodeId(
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap(),
);
app.run("select.set", json!({"ids": [id.0]})).unwrap();
app.run("object.rotate", json!({"angle": 30})).unwrap();
let angle = |app: &VectorcraftApp| app.session.active().unwrap().doc.bbox_angle(&[id]);
let reflect = default_sets()[0].actions.iter().position(|a| a.name == "Reflect Horizontal").unwrap();
app.ui.action_sets = default_sets();
play(&mut app, 0, reflect).unwrap();
assert!((angle(&app) - 30.0).abs() < 1e-6, "{}", angle(&app));
app.ui.action_sets = vec![ActionSet::new("Old", vec![Action::new("Reflect", vec![("object.reflect".into(), json!({"axis": "vertical"}))])])];
play(&mut app, 0, 0).unwrap();
assert!((angle(&app) + 30.0).abs() < 1e-6, "{}", angle(&app));
}
/// An action recorded with a key its command no longer reads still plays, accelerated and one
/// step at a time, though the same command run by itself is refused.
#[test]
+19
View File
@@ -5711,6 +5711,25 @@ used, as a transform's does.
{"name":"run_command","arguments":{"command":"object.transformEach","params":{"scaleH":50,"scaleV":50,"strokes":false}}}
```
## Scale and Reflect on a turned bounding box
`object.scale` and `object.reflect` with a named axis act along the selection's bounding box: after a rotation, `sx`
stretches along the box's own width and `sy` along its height, and `"vertical"` and `"horizontal"` are the box's own
axes, until Object › Transform › Reset Bounding Box squares the box to the page. Both take `basis?: "box"|"page"`:
`"box"` is the default, and `"page"` acts along the page's axes. Any other `basis` is an error, and nothing changes.
`origin` is still a page point, and a numeric `axis` is still a line on the page at that angle. Selections whose
objects stand at different angles, and anchors selected with Direct Selection, use the page's axes; with `copy` or
with `objects: false`, the whole objects or their pattern tiles transform, along the box. The journal entry
records the `basis` used, so a recorded action replays in the same frame; a saved step without `basis` (an action or
journal entry recorded before it) plays along the page's axes, as it did when it was recorded. `object.transformAgain` repeats the transform's page matrix, also after Reset Bounding Box. The Scale
and Reflect dialogs, the Transform and Properties panels' flips, the Scale tool and the Reflect tool's default axis
and Shift steps follow the box the same way; a Reflect axis drawn with the tool is the line drawn on the page.
```json
{"name":"run_command","arguments":{"command":"object.scale","params":{"sx":200,"sy":100}}}
{"name":"run_command","arguments":{"command":"object.reflect","params":{"axis":"vertical","basis":"page"}}}
```
## Free Distort on a turned bounding box
`object.distort` maps the corners of `from` (TL, TR, BR, BL) onto `corners`, which are page coordinates. With
+2 -1
View File
@@ -952,7 +952,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`).
- Break Link to Symbol and Object › Expand give a symbol instance's art the instance's own bounding box: after Reset Bounding Box the art stands square to the page, an object turned inside the symbol keeps its angle relative to the instance's box, a group added for the instance's opacity takes the instance's box, and the clip groups of 9-slice art take the angle of their cell. Compound shapes and Pathfinder receive an instance's art with the same angles (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_then_expand_symbol_instance`, `reset_bounding_box_then_expand_keeps_the_angles_inside_the_symbol`, `expanding_a_faded_symbol_instance_gives_its_group_the_instance_box`, `expanding_a_reflected_symbol_instance_keeps_its_box`, `symbol_nine_slice::break_link_turns_the_cells_of_a_sliced_instance_with_its_box`, effects `outline_object_turns_an_instances_art_with_its_box`).
- Object › Transform › Reset Bounding Box squares the box of every object inside the selected ones as well: the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. Ungroup and the release commands then bring back boxes square to the page (VectorCraft's own behavior; `bboxrotate::reset_bounding_box_squares_the_objects_inside_a_group`, `reset_bounding_box_squares_the_turned_members_of_a_square_group`, `reset_bounding_box_then_release_clipping_mask` and the other `reset_bounding_box_then_*` tests, `reset_bounding_box_leaves_the_art_of_an_unlinked_opacity_mask`).
- After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`). The Scale and Reflect tools, their dialogs and commands, and the Transform panel's flips keep the page's axes (VectorCraft's own rule; `bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`).
- After a rotation the Free Transform tool shows and drags the same turned bounding box as the Selection tool: its handles, their cursors and its rotate zone sit on the selection's own sides, a handle scales along those sides from the opposite handle ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html)), Cmd/Ctrl on a side handle shears along that side, and Perspective Distort and Free Distort start from the turned box's corners (`object.distort` takes `angle` with `from`) (`bboxrotate::free_transform_handles_turn_with_the_object_and_scale_along_its_axes`, `free_transform_shears_along_the_turned_side`, `free_transform_distort_starts_from_the_turned_box`, `xform::distort_reads_from_in_a_turned_frame_and_rejects_a_bad_angle`, tools `xform::free::tests::the_box_and_its_handles_turn_with_the_selection`).
- After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`).
- Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`).
- The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`).
- Native macOS menu bar, vector tool cursors, a ⌘K command palette, middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8).
+1 -1
View File
@@ -269,7 +269,7 @@ tools, never checked side by side) isn't captured row by row.
| Bounding-box handles: Shift proportional, Alt from centre, rotate outside the corners | done | |
| Rotated objects keep a rotated bounding box and their angle; Reset Bounding Box | done | |
| Vector Halftone Preview keeps the selection box and hides selection marks on the temporary dots | done | #6369; Preview off and Cancel restore the original marks. |
| Free Transform, Scale and Reflect along a rotated box | missing | |
| Free Transform, Scale and Reflect along a rotated box | done | The Scale and Reflect tools, dialogs and commands and the Transform and Properties panels' flips act along the turned box until Reset Bounding Box; `basis: "page"` keeps the page's axes |
| Free Transform widget: constrain, free distort, perspective distort; the key-held variants | done | |
| Transform tools: click sets the reference point (snaps to anchors/centres), Alt-click opens the dialog, Alt-release copies | done | with anchors selected with Direct Selection, the tools, the dialogs and Move transform those anchors alone, about the centre of their box by default (#1408; the default point and whole-object copies are our choices) |
| Move, Rotate, Scale, Reflect and Shear dialogs: live Preview; Up/Down step angles and percentages by 1, Shift by 10 | done | #1412; Preview starts off (our choice: the public documentation gives no default), Move's as it was last confirmed; OK is one undo step and Transform Again repeats it |