mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 08:11:41 +00:00
Merge current main while preserving pattern-only keyboard nudges
This commit is contained in:
@@ -80,11 +80,16 @@ pub(super) fn send_to_current_layer(s: &mut Session, _: &Value) -> Result<Value>
|
||||
if st.doc.children(Some(layer)).is_some_and(|c| c.iter().rev().filter(art).map(|n| n.id).take(ids.len()).eq(ids.iter().rev().copied())) {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Send to Current Layer", |d, _| {
|
||||
let placed: Vec<(NodeId, Option<NodeId>)> = ids.iter().map(|i| (*i, st.doc.parent_of(*i))).collect();
|
||||
let left = crate::cmd::intertwine::groups_of(&st.doc, &ids);
|
||||
s.edit("Send to Current Layer", |d, sel| {
|
||||
let moved = d.remove_many(&ids)?;
|
||||
let ch = d.children_mut(Some(layer))?;
|
||||
let at = Node::guide_run_start(ch);
|
||||
ch.splice(at..at, moved);
|
||||
// Members sent out of an Intertwine group leave it as ordinary art.
|
||||
crate::cmd::intertwine::settle_members(d, &placed, &left)?;
|
||||
sel.prune(d);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
@@ -352,6 +357,7 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& prev != isolation
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, prev, Some(isolation))?;
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, prev);
|
||||
}
|
||||
@@ -364,7 +370,30 @@ pub(super) fn isolate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Leaving isolation mode in `isolated` for `next` (None: out of isolation mode) adds the paths drawn
|
||||
/// in each Live Paint group that is `isolated` or holds it to that group, as `livePaint.merge` does,
|
||||
/// innermost group first, one undo step per group ([`crate::cmd::buildcmds::merge_drawn_in_isolation`]).
|
||||
/// A group that `next` is or is inside is skipped, since isolation stays in it. → the outermost group
|
||||
/// that paths were added to.
|
||||
fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) -> Result<Option<NodeId>> {
|
||||
let d = &s.doc()?.doc;
|
||||
let stays = next.and_then(|n| d.ancestry(n)).unwrap_or_default();
|
||||
let left: Vec<NodeId> = crate::cmd::buildcmds::isolated_live_paints(d, isolated).into_iter().filter(|g| !stays.contains(g)).collect();
|
||||
let mut added = None;
|
||||
for g in left {
|
||||
if crate::cmd::buildcmds::merge_drawn_in_isolation(s, g)? {
|
||||
added = Some(g);
|
||||
}
|
||||
}
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let key = "all";
|
||||
let all = match p.get(key) {
|
||||
None => false,
|
||||
Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?,
|
||||
};
|
||||
// Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving
|
||||
// isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's
|
||||
// Done do. A group isolated inside the symbol's art goes back to the symbol's layer.
|
||||
@@ -373,10 +402,11 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& let Some(inner) = st.isolation.filter(|i| *i != layer && st.doc.ancestry(*i).is_some_and(|a| a.contains(&layer)))
|
||||
{
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, inner, Some(layer))?.unwrap_or(inner);
|
||||
let st = s.doc_mut()?;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, inner);
|
||||
st.isolation = Some(layer);
|
||||
st.selection.set([inner]);
|
||||
st.selection.set([left]);
|
||||
st.revision += 1;
|
||||
return ok();
|
||||
}
|
||||
@@ -391,19 +421,28 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
if let Some(leave_mode) = leave_mode {
|
||||
if let Some(i) = st.isolation {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
add_drawn_live_paint(s, i, None)?;
|
||||
crate::cmd::distortcmds::finish_edit_text(s.doc_mut()?, i);
|
||||
}
|
||||
leave_mode(s, p)?;
|
||||
return ok();
|
||||
}
|
||||
let menu = s.menu.clone();
|
||||
let prev = s.active().and_then(|d| d.isolation);
|
||||
let prev = st.isolation;
|
||||
// An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or
|
||||
// that layer is hidden or locked; anything else leaves isolation mode.
|
||||
let up = prev
|
||||
.filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer))
|
||||
.and_then(|i| st.doc.parent_of(i))
|
||||
.filter(|parent| st.doc.is_editable(*parent));
|
||||
if let Some(i) = prev {
|
||||
crate::cmd::settle_interaction(s)?;
|
||||
let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i);
|
||||
let st = s.doc_mut()?;
|
||||
st.isolation = None;
|
||||
st.isolation = up;
|
||||
crate::cmd::distortcmds::finish_edit_text(st, i);
|
||||
let target = st.doc.parent_of(i).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(i);
|
||||
let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left);
|
||||
st.selection.set([target]);
|
||||
// A guide path isolated while Lock Guides is on isn't selected (#1534).
|
||||
crate::deselect_hidden(&menu, &st.doc, &mut st.selection);
|
||||
|
||||
@@ -56,9 +56,10 @@ pub(crate) fn object_bounds_transform(s: &Session, p: &Value, id: NodeId) -> Res
|
||||
/// direct-selected anchors are what changes ([`Bounds::Anchors`]).
|
||||
fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchors: bool) -> Result<Bounds> {
|
||||
check_numbers(p, &["x", "y", "width", "height", "reference"], "object.setBounds")?;
|
||||
let refi = reference_index(p)?;
|
||||
let st = s.doc()?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?;
|
||||
check_switches(p, &["proportional"], "object.setBounds")?;
|
||||
check_switches(p, &["proportional", "interpolate"], "object.setBounds")?;
|
||||
let how = s.bounds_measure();
|
||||
if anchors
|
||||
&& transforms_objects(p)
|
||||
@@ -90,7 +91,6 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec<NodeId>, least: f64, anchor
|
||||
let margins = |b: Rect| [g.x0 - b.x0, g.y0 - b.y0, b.x1 - g.x1, b.y1 - g.y1];
|
||||
let (m, all) = (margins(vs), margins(v));
|
||||
let fixed = [all[0] - m[0], all[1] - m[1], all[2] - m[2], all[3] - m[3]];
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let rp = vectorcraft_geom::reference_point(v, refi);
|
||||
let (w, h) = wanted_size(p, v);
|
||||
// The geometric scale that gives the visual size: margins grow by the strokes' scale `f`. It is
|
||||
@@ -262,7 +262,7 @@ fn wanted_size(p: &Value, b: Rect) -> (f64, f64) {
|
||||
/// `b`, the box around the anchors (and the objects selected whole) square to the page, and only
|
||||
/// the anchors, their handles with them, and those objects move or scale.
|
||||
fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> Result<Value> {
|
||||
let refi = p.get("reference").and_then(Value::as_u64).unwrap_or(4).min(8) as usize;
|
||||
let refi = reference_index(p)?;
|
||||
let rp = vectorcraft_geom::reference_point(b, refi);
|
||||
let (w, h) = wanted_size(p, b);
|
||||
// A single anchor, or anchors in a line, have no size to scale on that side.
|
||||
@@ -272,6 +272,14 @@ fn set_anchor_bounds(s: &mut Session, p: &Value, ids: Vec<NodeId>, b: Rect) -> R
|
||||
apply_transform(s, "Transform", ids, Affine::translate(to - rp) * scale, p, true)
|
||||
}
|
||||
|
||||
fn reference_index(p: &Value) -> Result<usize> {
|
||||
let reference = crate::cmd::number_or(p, "reference", 4.0, "object.setBounds")?;
|
||||
if !reference.is_finite() || reference < 0.0 || reference.fract() != 0.0 {
|
||||
return Err(crate::cmd::bad("object.setBounds", "`reference` must be a whole number"));
|
||||
}
|
||||
Ok(reference.min(8.0) as usize)
|
||||
}
|
||||
|
||||
/// The visual box of `ids` square to `frame`, as [`Document::oriented_bounds`] measures it, with
|
||||
/// symbol instances measured without the strokes in their art
|
||||
/// ([`vectorcraft_doc::SymbolBoxes::without_art_strokes`]).
|
||||
|
||||
@@ -16,7 +16,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform",
|
||||
[],
|
||||
None,
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, 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), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
"{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, 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), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do",
|
||||
has_doc,
|
||||
transform
|
||||
),
|
||||
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Move…",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+Shift+M"),
|
||||
"{ids?: [id…] (selected first; default: the selection), dx, dy, 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), dx, dy, 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), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. 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_or_guides,
|
||||
move_cmd
|
||||
),
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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; 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\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), 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
|
||||
),
|
||||
@@ -70,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Transform Again",
|
||||
["Object", "Transform"],
|
||||
Some("Cmd+D"),
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
"{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)",
|
||||
has_selection,
|
||||
transform_again
|
||||
),
|
||||
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Nudge",
|
||||
[],
|
||||
None,
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
"{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)",
|
||||
has_selection_or_guides,
|
||||
nudge
|
||||
),
|
||||
@@ -245,13 +245,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
crate::cmd::maskedit::outside_mask_editing,
|
||||
isolate
|
||||
),
|
||||
cmd!("object.exitIsolation", "Exit Isolation Mode", [], None, "{}", has_doc, exit_isolation),
|
||||
cmd!(
|
||||
"object.exitIsolation",
|
||||
"Exit Isolation Mode",
|
||||
[],
|
||||
None,
|
||||
"{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same. Leaving a Live Paint group drawn in another isolated Live Paint group, and that group too, does this for each, innermost first, one undo step each",
|
||||
has_doc,
|
||||
exit_isolation
|
||||
),
|
||||
cmd!(
|
||||
"object.setProps",
|
||||
"Object Properties",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, the graph stores the label's opacity and blend mode for every label of its kind",
|
||||
"{ids?|id?, name?, visible?, locked? (visible: false or locked: true deselects every selected object hidden or locked after the call, the key object included), opacity?: 0..100, blend?: \"Multiply\"…, isolate?, knockout?: \"on\"|\"off\"|\"neutral\"|bool (true = on, false = neutral), knockoutShape?: bool, data?: {key: \"value\" | null (removes it)} (the object's own data, SVG data-* attributes: {pivot: \"100,180\"} is data-pivot; document.node → attrs.data)}. On a path directly in a graph series, the graph also stores the object's opacity and blend mode, and on a series group the group's opacity, blend mode, isolate, knockout and knockoutShape (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring, the graph stores that object's opacity and blend mode for every label or line of its kind. A path directly in a Live Paint group can't take the name Face or Edge, which name the group's faces and edges, unless it has it already",
|
||||
has_doc,
|
||||
set_props
|
||||
),
|
||||
@@ -260,7 +268,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Align",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}, the last point a Shift-click added), to the key anchor, which stays put",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", to?: \"selection\"|\"artboard\"|\"key\" (default: the key object when the selection has one, select.key, else the selection; a key guide, select.key {guide}, stays put and the objects line up on its line: a vertical guide sets where left, center and right go and vertical alignment leaves them, a horizontal one the other way round; aligning to the key, the other selected ruler guides move too: a vertical guide to the key's left edge, center or right edge, a horizontal one to its top, center or bottom; aligning to the artboard moves selected guides to its edges too (#3463), and with only guides selected aligning to the selection moves them to their collective bounds), artboard?: index (0-based; with to: \"artboard\", the artboard to align to; the app passes the active one; default: the artboard under the center of the selection, else the first), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} With anchor points selected (Direct Selection), the points align instead: to their own bounds, to the artboard (#1180), or, aligning to the key with a key anchor (select.key {id, anchor}), to the key anchor, which stays put",
|
||||
has_selection_or_guides,
|
||||
align
|
||||
),
|
||||
@@ -269,7 +277,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
"{horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\", spacing?: pt (used with a key, select.key: the key object, or the key guide, select.key {guide}, stays put and the lines are placed this far apart, outward from its line, in their order on that line; 0 puts them all on its line; a key guide along the axis leaves everything where it is; not used without a key, or with anchor points selected and no key anchor), to?: \"selection\"|\"artboard\"|\"key\" (default: the key while there is one, else the selection; \"key\" without spacing distributes as \"selection\" does; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; not used with spacing and a key object; with a key guide, \"selection\" or \"artboard\" distributes without it as the key), artboard?: index (0-based; with to: \"artboard\", the artboard to distribute across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} space the selected objects' left edges, centers or right edges (top edges, centers or bottom edges) in their order on that line, with the selected ruler guides across the axis (vertical ones for horizontal; #1597): a guide has no size, so its edges and center are its line, and guides along the axis stay. Without spacing and a key they are spaced evenly, the first and last stay put, and fewer than three don't move; with spacing and a key, see spacing (two are enough); with to: \"artboard\", the first one's left (top) edge goes to the artboard's left (top) edge, the last one's right (bottom) edge goes to the artboard's right (bottom) edge, and two are enough. With anchor points selected (Direct Selection), the points are spaced evenly between the first and the last along the axis instead (#1636); with spacing and a key anchor (select.key {id, anchor}), the key anchor stays put and the others are placed spacing apart, outward from it, in their order along the axis",
|
||||
can_distribute,
|
||||
distribute
|
||||
),
|
||||
@@ -278,7 +286,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Distribute Spacing",
|
||||
["Window", "Align"],
|
||||
None,
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
"{axis?: \"horizontal\"|\"vertical\" (default: \"horizontal\"), spacing?: pt (the key object, select.key, or the key guide, select.key {guide}, stays put and the others are spaced from it; a key guide along the axis leaves everything where it is), to?: \"selection\"|\"artboard\"|\"key\" (used without spacing, and with a key guide; with anchor points selected, with \"selection\" or \"artboard\" the key anchor is not the key and all the points are spaced as without one; default: the key while there is one, else the selection; \"key\" without spacing spaces as \"selection\" does), artboard?: index (0-based; with to: \"artboard\", the artboard to space across; the app passes the active one; default: as object.align's), bounds?: \"preview\"|\"geometric\" (default: the Use Preview Bounds preference; preview bounds take in strokes, geometry effects and projected 3D art), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles)} without spacing, make the gaps between the selected objects equal, in the order of their left (top) edges, with the selected ruler guides across the axis as items with no size (#1597; guides along the axis stay): the first item's left (top) edge and the last one's right (bottom) edge stay put, or with to: \"artboard\" go to the artboard's left (top) and right (bottom) edges. With anchor points selected (Direct Selection), the points are spaced evenly along the axis instead, or `spacing` apart from the first (#1636), or with a key anchor (select.key {id, anchor}) `spacing` apart outward from the key anchor, which stays put",
|
||||
can_distribute,
|
||||
distribute_spacing
|
||||
),
|
||||
@@ -287,7 +295,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Bounds",
|
||||
[],
|
||||
None,
|
||||
"{x?, y?, width?, height?, reference?: 0..8 (9-point grid; a number past 8 is read as 8), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
"{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))",
|
||||
has_selection,
|
||||
set_bounds
|
||||
),
|
||||
@@ -297,7 +305,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Shape Properties",
|
||||
[],
|
||||
None,
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)",
|
||||
"{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)",
|
||||
has_selection,
|
||||
set_live_shape
|
||||
),
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Transform panel › Align to Pixel Grid: an object's pixel-aligned property, and the snapping that
|
||||
//! keeps the horizontal and vertical segments of a pixel-aligned object on the pixel grid
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>).
|
||||
//! (<https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html>),
|
||||
//! and Symbol Options › Align to Pixel Grid, which keeps a symbol's instances on the pixel grid.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use vectorcraft_doc::{AppearanceItem, LiveShape, StrokeAlign};
|
||||
|
||||
@@ -150,10 +153,250 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
refresh_symbols(before, doc);
|
||||
}
|
||||
|
||||
/// How far the linear part of an instance's transform may be from its symbol's natural size, as a
|
||||
/// fraction of that size, for the instance to count as placed at actual size.
|
||||
const ACTUAL_SIZE_TOLERANCE: f64 = 1e-9;
|
||||
|
||||
/// After any edit: Symbol Options › Align to Pixel Grid. The art of a pixel-aligned symbol snaps to
|
||||
/// the pixel grid at the symbol's natural size ([`snap_symbol_art`]) when the symbol becomes
|
||||
/// pixel-aligned, when its art or natural size changes, and when symbol editing mode for it ends
|
||||
/// (while it is edited, the art snaps as the editing layer is written back to it). Every instance
|
||||
/// of such a symbol then goes to whole points ([`snap_instance`]), and so does each instance of a
|
||||
/// pixel-aligned symbol in an object the edit changed or added, the art of opacity masks included.
|
||||
/// An instance in another symbol's art, the art on the symbol editing layer included, is placed by
|
||||
/// that symbol's instances and is left as it is. A document without pixel-aligned symbols is not walked.
|
||||
fn refresh_symbols(before: &Document, doc: &mut Document) {
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let was = before.pixel_aligned_symbols();
|
||||
// The symbol whose editing mode this edit ended, if any.
|
||||
let edited_before = before.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edited_now = doc.symbol_edit.as_ref().map(|e| e.symbol.as_str());
|
||||
let edit_ended = edited_before.filter(|b| edited_now != Some(*b)).map(str::to_owned);
|
||||
let mut every = false;
|
||||
for name in &aligned {
|
||||
let art_before = before.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_now = doc.symbols.iter().find(|s| &s.name == name).map(|s| &s.art);
|
||||
let art_changed = match (art_before, art_now) {
|
||||
(Some(b), Some(a)) => !Arc::ptr_eq(b, a),
|
||||
_ => true,
|
||||
};
|
||||
let size_changed = before.symbol_natural_xf(name) != doc.symbol_natural_xf(name);
|
||||
if !was.contains(name) || edit_ended.as_deref() == Some(name.as_str()) || art_changed || size_changed {
|
||||
snap_symbol_art(doc, name);
|
||||
every = true;
|
||||
}
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
// The symbol editing layer holds another symbol's art.
|
||||
let editing = doc.symbol_edit.as_ref().map(|e| e.layer);
|
||||
if every {
|
||||
for layer in doc.layers.iter_mut() {
|
||||
if Some(layer.id) != editing && holds_instance(layer, &natural) {
|
||||
snap_instances_in(Arc::make_mut(layer), &natural);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut ids, mut masked) = (vec![], vec![]);
|
||||
if let Some(layer) = editing {
|
||||
let outside = |layers: &[Arc<Node>]| layers.iter().filter(|l| l.id != layer).cloned().collect::<Vec<_>>();
|
||||
changed_instances(&outside(&before.layers), &outside(&doc.layers), &natural, &mut ids, &mut masked);
|
||||
} else {
|
||||
changed_instances(&before.layers, &doc.layers, &natural, &mut ids, &mut masked);
|
||||
}
|
||||
for id in ids {
|
||||
if let Some(n) = doc.node_mut(id) {
|
||||
snap_instance(n, &natural);
|
||||
}
|
||||
}
|
||||
for id in masked {
|
||||
if let Some(m) = doc.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_mut()) {
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Among the objects of `after` that differ from their counterparts in `before` (or are new), in
|
||||
/// groups too: the instances of the symbols in `natural` (`ids`), and the objects whose opacity
|
||||
/// mask art holds such instances (`masked`).
|
||||
fn changed_instances(before: &[Arc<Node>], after: &[Arc<Node>], natural: &HashMap<String, Affine>, ids: &mut Vec<NodeId>, masked: &mut Vec<NodeId>) {
|
||||
let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None;
|
||||
for (i, a) in after.iter().enumerate() {
|
||||
let b = match before.get(i) {
|
||||
Some(b) if b.id == a.id => Some(b),
|
||||
_ => by_id.get_or_insert_with(|| before.iter().map(|b| (b.id, b)).collect()).get(&a.id).copied(),
|
||||
};
|
||||
if b.is_some_and(|b| Arc::ptr_eq(b, a)) {
|
||||
continue;
|
||||
}
|
||||
if a.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural)) {
|
||||
masked.push(a.id);
|
||||
}
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &a.kind {
|
||||
if natural.contains_key(symbol) {
|
||||
ids.push(a.id);
|
||||
}
|
||||
} else if let Some(children) = a.children() {
|
||||
changed_instances(b.and_then(|b| b.children()).map_or(&[], Vec::as_slice), children, natural, ids, masked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n`, an object in it or the art of an opacity mask in it is an instance of a symbol in
|
||||
/// `natural`.
|
||||
fn holds_instance(n: &Node, natural: &HashMap<String, Affine>) -> bool {
|
||||
matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if natural.contains_key(symbol))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_instance(&m.art, natural))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_instance(c, natural)))
|
||||
}
|
||||
|
||||
/// [`snap_instance`] on every instance of a symbol in `natural` in `n`, the art of its opacity
|
||||
/// masks included. Only what holds such an instance is copied for editing.
|
||||
fn snap_instances_in(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
snap_instance(n, natural);
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_instance(&m.art, natural)
|
||||
{
|
||||
snap_instances_in(Arc::make_mut(&mut m.art), natural);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_instance(c, natural) {
|
||||
snap_instances_in(Arc::make_mut(c), natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Snap the art of pixel-aligned symbol `name` to the pixel grid as it is drawn at the symbol's
|
||||
/// natural size: each path and compound path in it snaps as a pixel-aligned object does
|
||||
/// ([`snap_object`]), measured from the symbol's origin. The art is stored again only when
|
||||
/// something in it moved, and the answer says whether it did.
|
||||
pub(crate) fn snap_symbol_art(doc: &mut Document, name: &str) -> bool {
|
||||
let natural = doc.symbol_natural_xf(name);
|
||||
let det = natural.determinant();
|
||||
if !det.is_finite() || det.abs() < 1e-18 {
|
||||
return false;
|
||||
}
|
||||
let Some(sym) = doc.symbols.iter_mut().find(|s| s.name == name) else { return false };
|
||||
// Instances draw the art's strokes at their stored width, and the art of unlinked opacity
|
||||
// masks, which `Node::transform` leaves alone, at the natural size too.
|
||||
let mut art = (*sym.art).clone();
|
||||
art.transform(natural, false);
|
||||
transform_unlinked_masks(&mut art, natural);
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
let inverse = natural.inverse();
|
||||
art.transform(inverse, false);
|
||||
transform_unlinked_masks(&mut art, inverse);
|
||||
sym.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Transform the art of every unlinked opacity mask in `n` by `xf`, in the art of other masks
|
||||
/// too. Only what holds such a mask is copied for editing.
|
||||
fn transform_unlinked_masks(n: &mut Node, xf: Affine) {
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut())
|
||||
&& holds_unlinked_mask(&m.art, !m.linked)
|
||||
{
|
||||
let linked = m.linked;
|
||||
let art = Arc::make_mut(&mut m.art);
|
||||
if !linked {
|
||||
art.transform(xf, false);
|
||||
}
|
||||
transform_unlinked_masks(art, xf);
|
||||
}
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if holds_unlinked_mask(c, false) {
|
||||
transform_unlinked_masks(Arc::make_mut(c), xf);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `n` is the art of an unlinked mask (`unlinked`), or it or an object in it, in the art of
|
||||
/// its masks too, has an unlinked opacity mask.
|
||||
fn holds_unlinked_mask(n: &Node, unlinked: bool) -> bool {
|
||||
unlinked
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| holds_unlinked_mask(&m.art, !m.linked))
|
||||
|| n.children().is_some_and(|ch| ch.iter().any(|c| holds_unlinked_mask(c, false)))
|
||||
}
|
||||
|
||||
/// Snap every path and compound path in `n` ([`can_align`]) with [`snap_object`], the art of
|
||||
/// opacity masks included (those of a compound path's paths too). Returns whether anything
|
||||
/// changed.
|
||||
fn snap_art(n: &mut Node) -> bool {
|
||||
let mut moved = false;
|
||||
if can_align(n) {
|
||||
let was = n.clone();
|
||||
snap_object(n, Scaling::default());
|
||||
moved = *n != was;
|
||||
if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
if c.extras().mask.is_some() {
|
||||
moved |= snap_mask(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if let Some(children) = n.children_mut() {
|
||||
for c in children.iter_mut() {
|
||||
moved |= snap_art(Arc::make_mut(c));
|
||||
}
|
||||
}
|
||||
// After the object itself, which a linked mask follows.
|
||||
snap_mask(n) || moved
|
||||
}
|
||||
|
||||
/// [`snap_art`] on the art of `n`'s opacity mask. Returns whether anything changed.
|
||||
fn snap_mask(n: &mut Node) -> bool {
|
||||
let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) else { return false };
|
||||
let mut art = (*m.art).clone();
|
||||
if !snap_art(&mut art) {
|
||||
return false;
|
||||
}
|
||||
m.art = Arc::new(art);
|
||||
true
|
||||
}
|
||||
|
||||
/// Move symbol instance `n` to whole points when its transform places its symbol's art at the
|
||||
/// symbol's natural size (`natural`, by symbol name), reflected across one axis or not. A scaled,
|
||||
/// rotated (a half turn included) or sheared instance stays where it is. The instance moves as any
|
||||
/// move moves it ([`Node::transform`]), so the art of a linked opacity mask moves with it.
|
||||
fn snap_instance(n: &mut Node, natural: &HashMap<String, Affine>) {
|
||||
let NodeKind::SymbolInstance { symbol, xf } = &n.kind else { return };
|
||||
let Some(nat) = natural.get(symbol.as_str()) else { return };
|
||||
let [a, b, c, d, e, f] = xf.as_coeffs();
|
||||
let [na, _, _, nd, _, _] = nat.as_coeffs();
|
||||
let near = |v: f64, to: f64| (v.abs() - to.abs()).abs() <= ACTUAL_SIZE_TOLERANCE * to.abs().max(1.0);
|
||||
let actual =
|
||||
near(a, na) && near(d, nd) && b.abs() <= ACTUAL_SIZE_TOLERANCE * na.abs().max(1.0) && c.abs() <= ACTUAL_SIZE_TOLERANCE * nd.abs().max(1.0);
|
||||
// Flipped along both axes is a half turn, which counts as rotated.
|
||||
let half_turn = a * na < 0.0 && d * nd < 0.0;
|
||||
if !actual || half_turn || !e.is_finite() || !f.is_finite() {
|
||||
return;
|
||||
}
|
||||
let (x, y) = (e.round(), f.round());
|
||||
if x == e && y == f {
|
||||
return;
|
||||
}
|
||||
n.transform(Affine::translate((x - e, y - f)), Scaling::default());
|
||||
// Whole points exactly, which adding the offset to the old position need not give.
|
||||
if let NodeKind::SymbolInstance { xf, .. } = &mut n.kind {
|
||||
*xf = Affine::new([a, b, c, d, x, y]);
|
||||
}
|
||||
}
|
||||
|
||||
/// After a pass that moved what objects `ids` hold (Objects on Path placing its members): snap the
|
||||
/// pixel-aligned objects in them to the pixel grid again.
|
||||
/// pixel-aligned objects and the instances of pixel-aligned symbols in them to the pixel grid
|
||||
/// again.
|
||||
pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(holds_aligned)
|
||||
@@ -162,6 +405,18 @@ pub(crate) fn keep_aligned_in(doc: &mut Document, ids: &[NodeId]) {
|
||||
keep_pixel_aligned(n, Scaling::default());
|
||||
}
|
||||
}
|
||||
let aligned = doc.pixel_aligned_symbols();
|
||||
if aligned.is_empty() {
|
||||
return;
|
||||
}
|
||||
let natural: HashMap<String, Affine> = aligned.iter().map(|name| (name.clone(), doc.symbol_natural_xf(name))).collect();
|
||||
for id in ids {
|
||||
if doc.node(*id).is_some_and(|n| holds_instance(n, &natural))
|
||||
&& let Some(n) = doc.node_mut(*id)
|
||||
{
|
||||
snap_instances_in(n, &natural);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects of `after` that differ from their counterparts in `before` (or are new) and are
|
||||
|
||||
@@ -65,6 +65,9 @@ pub(super) fn set_props(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if let Some(v) = str_param(p, "name") {
|
||||
crate::cmd::buildcmds::check_part_name(d, &ids, v)?;
|
||||
}
|
||||
// A graph keeps the object opacity and blend mode set on a mark of a series for the whole series, and set on a label
|
||||
// for its kind of label, so a value a mark or label already has still replaces the one another left on the graph.
|
||||
let transparency = opacity.is_some() || blend.is_some();
|
||||
|
||||
@@ -6,6 +6,7 @@ use super::{
|
||||
BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches,
|
||||
convert_radii_relative, ok, selected_roots, set_corners, targets,
|
||||
};
|
||||
use crate::MAX_COORD;
|
||||
|
||||
/// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`,
|
||||
/// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across
|
||||
@@ -98,8 +99,32 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> {
|
||||
list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some)
|
||||
}
|
||||
|
||||
/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about
|
||||
/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it.
|
||||
fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> {
|
||||
let now = l.line_length()?;
|
||||
let mut new = l.clone();
|
||||
let mut changed = false;
|
||||
if let Some(len) = len
|
||||
&& (len - now).abs() > 1e-9 * len.max(now)
|
||||
{
|
||||
new.set_line_length(len);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(a) = angle
|
||||
&& new.line_length().is_some_and(|n| n > 0.0)
|
||||
&& let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0))
|
||||
&& turn > 1e-9
|
||||
&& turn < 360.0 - 1e-9
|
||||
{
|
||||
new.set_line_angle(a);
|
||||
changed = true;
|
||||
}
|
||||
(changed && new != *l).then_some(new)
|
||||
}
|
||||
|
||||
pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?;
|
||||
check_numbers(p, &["radius", "sides"], "object.setLiveShape")?;
|
||||
// `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them.
|
||||
let items = match p.get("items").filter(|v| !v.is_null()) {
|
||||
@@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0)));
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0");
|
||||
let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0");
|
||||
// Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these
|
||||
// checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and
|
||||
// a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a
|
||||
@@ -168,21 +193,58 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them).
|
||||
let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?);
|
||||
let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true);
|
||||
// Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps
|
||||
// its span (its end angle less its start angle, counterclockwise).
|
||||
let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true);
|
||||
if constrain && (invert || pie_start.is_some() == pie_end.is_some()) {
|
||||
return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`"));
|
||||
}
|
||||
// A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal.
|
||||
let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?);
|
||||
let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true);
|
||||
// A line's Line Properties: its length (its first end stays) and its angle (about its midpoint).
|
||||
// A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below.
|
||||
let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?;
|
||||
let line_angle = angle("lineAngle")?;
|
||||
// An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole
|
||||
// ellipse as 0° to 360°).
|
||||
let end_of = |a: f64| if a == 0.0 { 360.0 } else { a };
|
||||
let pie_of = |pie: (f64, f64)| {
|
||||
let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of));
|
||||
let span = (pie.1 - pie.0).rem_euclid(360.0);
|
||||
let pie = match (constrain, pie_start, pie_end) {
|
||||
// The angle it already has: nothing moves.
|
||||
(true, Some(a), _) if a == pie.0 => pie,
|
||||
(true, _, Some(a)) if end_of(a) == pie.1 => pie,
|
||||
// A whole ellipse (a span of 0) stays whole.
|
||||
(true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))),
|
||||
(true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)),
|
||||
_ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)),
|
||||
};
|
||||
if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie }
|
||||
};
|
||||
// When every value given is the current one, the document and its undo history stay as they
|
||||
// are.
|
||||
let st = s.doc()?;
|
||||
// The lines that Line Length or Line Angle changes, as they become. A line that would reach
|
||||
// past the document's coordinate limit is an error before anything changes.
|
||||
let mut lines = std::collections::BTreeMap::new();
|
||||
if line_length.is_some() || line_angle.is_some() {
|
||||
for id in &ids {
|
||||
let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue };
|
||||
if let Some(new) = line_edit(l, line_length, line_angle) {
|
||||
let LiveShape::Line { a, b } = &new else { continue };
|
||||
if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) {
|
||||
return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)")));
|
||||
}
|
||||
lines.insert(*id, new);
|
||||
}
|
||||
}
|
||||
}
|
||||
let has_values = |id: &NodeId| {
|
||||
let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true };
|
||||
if lines.contains_key(id) {
|
||||
return false;
|
||||
}
|
||||
match live.as_deref() {
|
||||
Some(l @ LiveShape::Polygon { sides: now, .. })
|
||||
if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now))
|
||||
@@ -244,6 +306,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(new) = lines.get(id)
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
*l = new.clone();
|
||||
*path = l.to_path();
|
||||
}
|
||||
if let Some(on) = relative_radii
|
||||
&& let Some(l) = live.as_deref_mut()
|
||||
{
|
||||
|
||||
@@ -125,9 +125,14 @@ fn apply_transform_moving_guides(
|
||||
let d = &s.doc()?.doc;
|
||||
let paths = d.index_paths(ids.iter().copied());
|
||||
let none = paths.is_empty() && !has_guides;
|
||||
// A move of direct-selected anchors may re-map the handles beside them (`interpolate`).
|
||||
let mut interpolate = None;
|
||||
let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() {
|
||||
if c[..4] == [1.0, 0.0, 0.0, 1.0] {
|
||||
interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?);
|
||||
}
|
||||
if xf != Affine::IDENTITY {
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc)?;
|
||||
crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?;
|
||||
}
|
||||
ids
|
||||
} else if none || (!copy && xf == Affine::IDENTITY) {
|
||||
@@ -195,6 +200,9 @@ fn apply_transform_moving_guides(
|
||||
options["strokes"] = json!(sc.strokes);
|
||||
options["corners"] = json!(!sc.keep_corners);
|
||||
}
|
||||
if let Some(on) = interpolate {
|
||||
options["interpolate"] = json!(on);
|
||||
}
|
||||
st.last_transform = Some(LastTransform::Matrix(xf, options));
|
||||
st.last_perspective = None;
|
||||
}
|
||||
@@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool {
|
||||
|
||||
pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside"], "object.transform")?;
|
||||
check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?;
|
||||
let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?;
|
||||
// An object selected in a symbol instance's art stays where the symbol puts it: the selection
|
||||
// is left as it is, and the reply's warning goes to the status bar.
|
||||
@@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.move")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.move")?;
|
||||
check_switches(p, &["interpolate"], "object.move")?;
|
||||
let ids = selected_roots_to_transform(s)?;
|
||||
apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true)
|
||||
}
|
||||
@@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) {
|
||||
pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_numbers(p, &["dx", "dy"], "object.nudge")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?;
|
||||
check_switches(p, &["big"], "object.nudge")?;
|
||||
check_switches(p, &["big", "interpolate"], "object.nudge")?;
|
||||
let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 };
|
||||
let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k);
|
||||
// Guides keep to the page's axes; art and anchors move along the constrain angle's.
|
||||
@@ -323,7 +332,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
return ok();
|
||||
}
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") }));
|
||||
return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") }));
|
||||
}
|
||||
if objects && s.doc()?.selection.is_empty() {
|
||||
let copy = bool_or(p, "copy", false);
|
||||
@@ -376,15 +385,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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
|
||||
@@ -409,16 +425,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 => {
|
||||
@@ -430,22 +437,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Option<Affine>, 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<f64, String> {
|
||||
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<Value> {
|
||||
check_numbers(p, &["angle"], "object.shear")?;
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.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)?;
|
||||
let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).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]) };
|
||||
let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]);
|
||||
// A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal.
|
||||
let m = match p.get("axis") {
|
||||
None | Some(Value::Null) => horizontal,
|
||||
Some(Value::String(a)) if a == "horizontal" => horizontal,
|
||||
Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]),
|
||||
Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => {
|
||||
// y is down, so the page's counter-clockwise angle turns the other way on screen.
|
||||
let r = -n.as_f64().unwrap_or(0.0).to_radians();
|
||||
Affine::rotate(r) * horizontal * Affine::rotate(-r)
|
||||
}
|
||||
Some(v) => {
|
||||
let given = v.as_str().map_or_else(|| v.to_string(), str::to_string);
|
||||
let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}");
|
||||
return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`")));
|
||||
}
|
||||
};
|
||||
apply_transform(s, "Shear", ids, about(o, m), p, true)
|
||||
}
|
||||
|
||||
/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees.
|
||||
const SHEAR_AXIS_MAX: f64 = 359.0;
|
||||
|
||||
/// The last transform on the selection, with the options `last_transform` keeps for it; an option
|
||||
/// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform
|
||||
/// Each is repeated by running it again (its transform is per object, about each one's bounds).
|
||||
pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?;
|
||||
check_switches(p, &["interpolate"], "object.transformAgain")?;
|
||||
if let Some(again) = s.doc()?.last_perspective.clone() {
|
||||
return crate::cmd::distortcmds::transform_again(s, &again);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user