Merge pull request #8345 from dotCooCoo/feat/bounding-box-rotate

Transform: Rotate Bounding Box… turns the selection's bounding box without moving the art
This commit is contained in:
BFlat
2026-11-18 10:15:35 +07:00
committed by GitHub
36 changed files with 343 additions and 7 deletions
+79 -6
View File
@@ -1,6 +1,6 @@
//! Object menu long tail: Lock/Hide All Artwork Above & Other Layers, Transform Each, Reset
//! Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks, Convert to Shape and
//! Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
//! Bounding Box, Rotate Bounding Box, Rasterize, Crop Image, Mask (an image), Create Trim Marks,
//! Convert to Shape and Artboards → Convert / Rearrange. (Live blends are in `live.rs`.)
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
@@ -15,8 +15,8 @@ use vectorcraft_render::encode::{RasterExportOptions, RasterFormat};
use super::edit::{duplicate_in, selected_roots, selected_roots_to_transform};
use super::{
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, fileio, find_command, has_doc, has_selected_member,
has_selection, switch_or,
CommandSpec, EngineError, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, fileio, find_command, has_doc,
has_selected_member, has_selection, switch_or,
};
/// Session-level (not saved) state owned by the menu commands.
@@ -110,6 +110,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
reset_bounding_box
),
cmd!(
"object.rotateBoundingBox",
"Rotate Bounding Box…",
["Object", "Transform"],
None,
"{angle: degrees (counter-clockwise), absolute?: bool (true: turn the box to angle; default false: turn it by angle from the angle the selected objects share, 0 when theirs differ)} turn the bounding box of the selected objects to one angle without moving their art; the objects inside them (the children of groups, compound paths, clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks) turn with them and keep their angle relative to them; a path of a compound path selected on its own turns only its own box; one undo step, none when every box is already at the angle; object.resetBoundingBox squares the boxes again; a missing or non-numeric angle is an error → {angle: the new angle of the boxes, in (-180, 180], changed: objects whose box turned, the objects inside the selected ones included}",
has_selection,
rotate_bounding_box
),
cmd!(
"object.rasterize",
"Rasterize…",
@@ -225,9 +234,10 @@ pub(crate) fn squash(s: &mut Session, from: usize, label: &str) {
// ---------- Reset Bounding Box ----------
/// Squares each selected object and every object inside it: the children of groups, compound paths,
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks.
/// clip groups, blends, envelopes, repeats and intertwines, and the art of linked opacity masks. A
/// path of a compound path selected on its own is squared alone, as the transforms move it alone.
fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
let ids = selected_roots(s)?;
let ids = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let mut changed = 0;
let squared: Vec<(NodeId, Node)> = ids
@@ -251,6 +261,69 @@ fn reset_bounding_box(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "changed": changed }))
}
// ---------- Rotate Bounding Box ----------
/// Turns the bounding box of the selected objects to one angle without moving their art: by `angle`
/// from the angle they share (0 when it differs), or to `angle` with `absolute`. Each object's box
/// turns by what takes it there, and so do the boxes of the objects inside it (the children of
/// groups and the art of linked opacity masks), which keep their angle relative to it.
fn rotate_bounding_box(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.rotateBoundingBox";
// A JSON number is always finite.
let angle = f64_req(p, "angle", C)?;
let absolute = switch_or(p, "absolute", false, C)?;
// The same objects the transforms move: a path of a compound path selected on its own turns
// its own box. Layers are left out, as they have no box.
let owners = selected_roots_to_transform(s)?;
let d = &s.doc()?.doc;
let start = if absolute { 0.0 } else { d.bbox_angle(&owners) };
// An angle within the tolerance of 0 is stored as 0, as `Node::turn_boxes` stores it.
let target = match vectorcraft_geom::normalize_deg(start + angle) {
a if a.abs() <= BOX_EPS_DEG => 0.0,
a => a,
};
let mut changed = 0;
let turned: Vec<(NodeId, Node)> = owners
.iter()
.filter_map(|id| {
let n = d.node(*id)?;
let by = vectorcraft_geom::normalize_deg(target - n.bbox_angle);
(by.abs() > BOX_EPS_DEG).then(|| {
let mut c = n.clone();
c.turn_boxes(by);
// The selected object's box is set to the target itself, so repeated turns add no
// rounding error to it.
c.bbox_angle = target;
changed += boxes(&c);
(*id, c)
})
})
.collect();
if !turned.is_empty() {
s.edit("Rotate Bounding Box", |d, _| {
for (id, n) in turned {
if let Some(slot) = d.node_mut(id) {
*slot = n;
}
}
Ok(())
})?;
}
Ok(json!({ "angle": target, "changed": changed }))
}
/// Angles closer than this (degrees) are the same, as `vectorcraft_doc::orient` compares them.
const BOX_EPS_DEG: f64 = 1e-6;
/// The number of objects in `n`'s subtree whose box [`Node::turn_boxes`] turns: `n`, its children
/// and the art of a linked opacity mask, layers left out.
fn boxes(n: &Node) -> usize {
let own = usize::from(!n.is_layer());
let children: usize = n.children().into_iter().flatten().map(|c| boxes(c)).sum();
let mask = n.extras().mask.as_ref().filter(|m| m.linked).map_or(0, |m| boxes(&m.art));
own + children + mask
}
/// A copy of `n` with the angle of every object in its subtree set to 0, or `None` when no box in
/// it stands at an angle, and the number of objects squared. The subtree takes in children and the
/// art of linked opacity masks (an unlinked mask's art turns on its own); layers have no box. Only
@@ -366,6 +366,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.repeat.release",
"object.resetBoundingBox",
"object.rotate",
"object.rotateBoundingBox",
"object.scale",
"object.setBounds",
"object.setLiveShape",
+20
View File
@@ -2809,6 +2809,26 @@ fn an_isolated_compound_paths_member_moves_alone() {
assert_eq!((x0(&s, outer), x0(&s, hole)), (5.0, 55.0), "the compound path selected: the whole ring");
}
/// Rotate Bounding Box and Reset Bounding Box take the same objects as the transforms: a path of
/// a compound path selected alone turns or squares its own box, and the compound path selected
/// turns its box and its paths'.
#[test]
fn rotate_bounding_box_of_a_compound_paths_member_turns_only_that_path() {
let angle = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().bbox_angle;
let mut s = session();
let (c, outer, hole) = isolated_ring(&mut s);
s.execute("object.exitIsolation", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap();
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (0.0, 0.0, 30.0), "only the hole's box turned");
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap();
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 40.0), "the compound path and its paths");
s.execute("select.set", &json!({"ids": [hole.0]})).unwrap();
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
assert_eq!((angle(&s, c), angle(&s, outer), angle(&s, hole)), (10.0, 10.0, 0.0), "Reset squared only the hole's box");
}
/// The X, Y, W and H of the Properties and Transform panels run `object.setBounds`, which takes the
/// same objects as the other transforms: a path of a compound path selected alone sets its own
/// box and leaves the ring around it (#4046). The hole is off-centre, and a plain rectangle
+151
View File
@@ -579,6 +579,157 @@ fn reset_bounding_box_squares_the_turned_members_of_a_square_group() {
assert_eq!(selection_box(&s).angle, 0.0);
}
#[test]
fn rotate_bounding_box_turns_the_box_and_leaves_the_art() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
let art = anchors(&s, a);
let n = undo_len(&s);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 90})).unwrap();
assert_eq!((r["changed"].as_u64(), r["angle"].as_f64()), (Some(1), Some(90.0)));
assert_eq!(undo_len(&s), n + 1);
assert_eq!(anchors(&s, a), art, "the art stays where it is");
// The box is at 90°, so its width runs along the rectangle's 50 pt side.
let b = selection_box(&s);
assert!(near(b.angle, 90.0));
assert!(near(b.rect.width(), 50.0) && near(b.rect.height(), 100.0), "{b:?}");
// By an angle from the box's angle; absolute sets it; the result wraps to (-180, 180].
s.execute("object.rotateBoundingBox", &json!({"angle": 20})).unwrap();
assert!(near(angle(&s, a), 110.0));
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 200, "absolute": true})).unwrap();
assert!(near(r["angle"].as_f64().unwrap(), -160.0) && near(angle(&s, a), -160.0));
// A box already at the angle changes nothing and adds no step.
let n = undo_len(&s);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -160, "absolute": true})).unwrap();
assert_eq!(r["changed"], 0);
let r = s.execute("object.rotateBoundingBox", &json!({"angle": 360})).unwrap();
assert_eq!(r["changed"], 0);
assert_eq!(undo_len(&s), n);
// Undo turns the box back; Reset Bounding Box squares it.
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, a), 110.0));
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 1);
assert_eq!(anchors(&s, a), art);
}
/// Turns that add up to 0 within the tolerance leave the box at exactly 0, so the box measures
/// square to the page and Reset Bounding Box has nothing to square.
#[test]
fn rotate_bounding_box_back_to_zero_stores_zero() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
for by in [0.3, -0.1] {
s.execute("object.rotateBoundingBox", &json!({"angle": by})).unwrap();
}
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.2})).unwrap();
assert_eq!((r["angle"].as_f64(), angle(&s, a)), (Some(0.0), 0.0), "{r}");
assert_eq!(selection_box(&s).angle, 0.0);
let n = undo_len(&s);
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 0);
assert_eq!(undo_len(&s), n);
// A negative zero is reported and stored as 0.
let r = s.execute("object.rotateBoundingBox", &json!({"angle": -0.0, "absolute": true})).unwrap();
let got = r["angle"].as_f64().unwrap();
assert!(got == 0.0 && got.is_sign_positive(), "{r}");
assert_eq!(r["changed"], 0);
}
#[test]
fn rotate_bounding_box_gives_a_mixed_selection_one_angle() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = turned_rect(&mut s);
sel(&mut s, &[a, b]);
// The objects share no angle, so the box is square to the page and turns from 0.
assert_eq!(selection_box(&s).angle, 0.0);
let n = undo_len(&s);
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 2);
assert_eq!(undo_len(&s), n + 1, "one step for both");
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
assert!(near(selection_box(&s).angle, 10.0));
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, a), 0.0) && near(angle(&s, b), 45.0));
s.execute("edit.redo", &json!({})).unwrap();
assert!(near(angle(&s, a), 10.0) && near(angle(&s, b), 10.0));
}
#[test]
fn rotate_bounding_box_turns_the_objects_inside_a_group_with_it() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("object.rotate", &json!({"angle": 20})).unwrap();
let g = id_of(&s.execute("object.group", &json!({})).unwrap());
let art = (anchors(&s, a), anchors(&s, b));
// The group and both members, as Reset Bounding Box counts them.
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 3);
// The members keep their 20° relative to the group's box.
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
assert_eq!((anchors(&s, a), anchors(&s, b)), art);
s.execute("edit.undo", &json!({})).unwrap();
assert!(near(angle(&s, g), 0.0) && near(angle(&s, a), 20.0) && near(angle(&s, b), 20.0));
s.execute("edit.redo", &json!({})).unwrap();
assert!(near(angle(&s, g), 30.0) && near(angle(&s, a), 50.0) && near(angle(&s, b), 50.0));
// After Ungroup the members still share a turned box.
s.execute("object.ungroup", &json!({})).unwrap();
assert!(near(selection_box(&s).angle, 50.0));
}
/// The art of a linked opacity mask turns with its object; an unlinked mask's art keeps its angle.
#[test]
fn rotate_bounding_box_turns_a_linked_masks_art_only() {
let mask_angle = |s: &Session, a: NodeId| s.doc().unwrap().doc.node(a).unwrap().extras().mask.as_ref().unwrap().art.bbox_angle;
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).unwrap()["changed"], 2);
assert!(near(angle(&s, a), 30.0) && near(mask_angle(&s, a), 30.0));
s.execute("transparency.unlinkOpacityMask", &json!({})).unwrap();
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 10})).unwrap()["changed"], 1);
assert!(near(angle(&s, a), 40.0) && near(mask_angle(&s, a), 30.0));
}
/// Rotate Bounding Box and Reset Bounding Box act on the same boxes: after a turn of a group that
/// holds an object with a linked opacity mask, Reset squares every box it turned.
#[test]
fn reset_bounding_box_squares_every_box_rotate_bounding_box_turned() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
let b = rect(&mut s, 150.0, 120.0, 100.0, 50.0);
sel(&mut s, &[a, b]);
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
let c = rect(&mut s, 300.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a, c]);
s.execute("object.group", &json!({})).unwrap();
let art = (anchors(&s, a), anchors(&s, c));
// The group, the masked object, its mask's art and the other rectangle.
assert_eq!(s.execute("object.rotateBoundingBox", &json!({"angle": 25})).unwrap()["changed"], 4);
assert!(object_angles(&s).iter().all(|x| near(*x, 25.0)), "{:?}", object_angles(&s));
assert_eq!(s.execute("object.resetBoundingBox", &json!({})).unwrap()["changed"], 4);
assert!(object_angles(&s).iter().all(|x| *x == 0.0), "{:?}", object_angles(&s));
assert_eq!((anchors(&s, a), anchors(&s, c)), art);
}
#[test]
fn rotate_bounding_box_refuses_bad_params() {
let mut s = session();
let a = rect(&mut s, 100.0, 100.0, 100.0, 50.0);
sel(&mut s, &[a]);
let n = undo_len(&s);
for p in [json!({}), json!({"angle": null}), json!({"angle": "30"}), json!({"angle": 30, "absolute": "yes"})] {
assert!(s.execute("object.rotateBoundingBox", &p).is_err(), "{p}");
}
assert_eq!((angle(&s, a), undo_len(&s)), (0.0, n));
// Nothing selected: the command is not enabled.
s.execute("select.none", &json!({})).unwrap();
assert!(s.execute("object.rotateBoundingBox", &json!({"angle": 30})).is_err());
}
/// Two rectangles turned 20°, put in a container by `make`, turned 10° with it and reset, then
/// released by `release`: nothing stands at an angle before or after the release.
fn reset_then_release(make: &str, release: &str) -> Session {