//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the //! help page describes them. Each one //! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo //! step for the document; a call that changes nothing runs no command. `PathItem` uses these //! methods too. //! //! VectorCraft's own rules, which the help page does not state: //! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever //! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns //! it counterclockwise. //! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds, //! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the //! bottom-left corner of the first artboard. A matrix's own translation is added after it acts //! about that point. The value is checked even when the call changes nothing. //! - Positions, pattern fills and pattern strokes, and gradients each follow their argument: //! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles //! preference. Fill and stroke patterns transform together, and gradients with the object, so a //! call whose values differ, counting the defaults of the arguments it leaves out, throws an error //! that says so. //! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own //! scale in percent, the square root of the area it scales by (stroke weights and effects scale //! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to //! 100000, which sets the stroke weight to that percent of what it was, at most 1000 points. //! When strokes and effects scale on a path, the scale and every stroke layer's resulting weight //! must stay finite, and each weight can reach at most 1000 points. Any other value, and a scale //! of strokes and effects with positions left as they are, throws an error that says so. //! - A path without points takes any transformation about any point named. `DOCUMENTORIGIN` //! still uses the first artboard's bottom-left corner; other named points use the origin. //! Its linked opacity mask, strokes, effects and patterns transform with the same options. //! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a //! locked object, an object on a locked artboard and a guide while guides are locked are refused //! with nothing changed, and so are //! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object //! past the canvas. use serde_json::json; use vectorcraft_geom::{Affine, Point, Rect}; use vectorcraft_js::{Data, HostError}; use super::matrix::{self, Matrix}; use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc}; /// The error for an object on a locked artboard. pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"; /// The error for a locked object. pub(super) const LOCKED: &str = "cannot transform locked objects"; /// The error for a guide while guides are locked. const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked"; /// The error for a hidden object. pub(super) const HIDDEN: &str = "cannot transform hidden objects"; /// The identity matrix. const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; /// What a transform method changes besides the object's geometry. struct Options { /// Positions and orientations (`changePositions`, `transformObjects`). objects: bool, /// Pattern fills and strokes. patterns: bool, /// Stroke weights and effects (`changeLineWidths`). strokes: bool, } /// An optional `true` or `false` argument. fn flag(d: &Data, what: &str) -> std::result::Result, HostError> { match d { Data::Undefined => Ok(None), Data::Bool(b) => Ok(Some(*b)), _ => Err(HostError::Type(format!("{what} must be true or false"))), } } /// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after, /// with the names the method gives them. fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result { let tiles = h.session.borrow().prefs.transform_pattern_tiles; let objects = flag(arg(a, at), names[0])?.unwrap_or(true); let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles); let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true); let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles); if fill != stroke { return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3]))); } if gradients != objects { return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0]))); } Ok(Options { objects, patterns: fill, strokes: false }) } /// Whether `changeLineWidths` (`d`) is the scale of the linear part `m` of a matrix, so stroke /// weights and effects scale with it (`Some(true)`), or 100 (`Some(false)`); `None` for any other /// number. fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option, f64, f64), HostError> { let lw = match d { Data::Undefined => return Ok((Some(false), 100.0, 100.0)), d => number(d, "changeLineWidths")?, }; if lw < 0.0 { return Err(HostError::Range("changeLineWidths must not be negative".into())); } // The determinant is taken past the range of a number, so a scale whose square is too large // for one still has its own value. // 100 keeps the stroke weights, even for a scale within the tolerance of it. let own = matrix::area_scale(m) * 100.0; if (lw - 100.0).abs() <= 1e-9 { return Ok((Some(false), lw, own)); } if lw > 0.0 && own.is_finite() && (lw - own).abs() <= 1e-9 * own { return Ok((Some((own - 100.0).abs() > 1e-9), lw, own)); } Ok((None, lw, own)) } /// The error for a `changeLineWidths` the method does not take. fn other_line_widths(own: f64) -> HostError { HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet")) } /// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix. fn line_widths(d: &Data, m: Matrix) -> std::result::Result { match own_line_widths(d, m)? { (Some(strokes), _, _) => Ok(strokes), (None, _, own) => Err(other_line_widths(own)), } } /// The member of `Transformation` that `d` names (left out: `CENTER`). fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> { const MEMBERS: [&str; 10] = ["CENTER", "TOPLEFT", "TOP", "TOPRIGHT", "LEFT", "RIGHT", "BOTTOMLEFT", "BOTTOM", "BOTTOMRIGHT", "DOCUMENTORIGIN"]; let name = match d { Data::Undefined => "CENTER", Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""), _ => "", }; if MEMBERS.contains(&name) { Ok(name) } else { Err(HostError::Type("the point to transform about must be a Transformation value".into())) } } /// The point of `r` (document coordinates, Y down) that the `Transformation` member `name` /// ([`anchor_name`]) names. Without bounds, a path uses the origin except for `DOCUMENTORIGIN`. fn anchor(h: &Host, item: Item, r: Option, name: &str) -> std::result::Result { if r.is_none() && !paths::is_path(h, item) { return Err(HostError::Error("the object has no bounds".into())); } if name == "DOCUMENTORIGIN" { return with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0]))); } let Some(r) = r else { return Ok(Point::ORIGIN); }; let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); Ok(match name { "TOPLEFT" => Point::new(r.x0, r.y0), "TOP" => Point::new(cx, r.y0), "TOPRIGHT" => Point::new(r.x1, r.y0), "LEFT" => Point::new(r.x0, cy), "RIGHT" => Point::new(r.x1, cy), "BOTTOMLEFT" => Point::new(r.x0, r.y1), "BOTTOM" => Point::new(cx, r.y1), "BOTTOMRIGHT" => Point::new(r.x1, r.y1), _ => Point::new(cx, cy), }) } /// The matrix `m` (Y up) as it acts on the page (Y down), about `o`. fn on_page(m: Matrix, o: Point) -> Affine { let [a, b, c, d, tx, ty] = m; let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty); if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] { return Affine::translate((tx, ty)); } Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y)) } /// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol /// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The /// object is measured whole, and a group is looked into object by object, as the native file's /// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its /// clipping path's and leave out the art it clips. fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool { fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool { if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) { n.children().into_iter().flatten().all(|c| within(c, symbols)) } else { n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range) } } d.node(id).is_some_and(|n| { let mut n = n.clone(); n.transform(xf, false); within(&n, &d.symbol_boxes()) }) } /// Applies `m` (Y up) to `item`, about the point `about` names (`None`: the matrix acts as a move, /// which needs no point), with `opts`, then sets the stroke weight of a path to `weight` points /// when it is given. fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, weight: Option) -> Answer { let about = about.map(anchor_name).transpose()?; if m.iter().any(|v| !v.is_finite()) { return Err(HostError::Range("the transformation has a value too large for a number".into())); } if matrix::singular(m) { return Err(HostError::Error("the transformation is singular and would flatten the object".into())); } let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| { let d = &st.doc; let line = d.ancestry(item.id); let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked))); let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible))); let (mut uses, mut clipped) = (false, false); if let Some(n) = d.node(item.id) { n.walk(&mut |c| { locked |= c.locked; uses |= vectorcraft_doc::pattern::uses_pattern(c, None); clipped |= matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. }); }); } (locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped) }); if locked { return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0))); } if hidden { return Err(HostError::Error(format!("{HIDDEN}: {}", item.id.0))); } if on_locked { return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); } if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) { return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0))); } // The identity acts the same about every point for any object. let o = match (about, bounds) { _ if m == IDENTITY => Point::ORIGIN, (Some(name), r) => anchor(h, item, r, name)?, (None, _) => Point::ORIGIN, }; let xf = on_page(m, o); if opts.strokes && !opts.objects { return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into())); } if opts.objects && xf != Affine::IDENTITY { // The transformed corners of the bounds hold the transformed object. When one of them is // past the canvas, or the object holds a clipping group (whose bounds leave out the art // it clips), the transformed object itself is measured. let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD; let outside = bounds.is_some_and(|r| { let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)]; !corners.iter().all(|p| inside(xf * *p)) }); if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) { return Err(HostError::Range("the transformation would take the object past the canvas".into())); } } let c = xf.as_coeffs(); let identity = xf == Affine::IDENTITY; // Every stroke layer's weight is checked with the factor `object.transform` applies. let factor = if opts.strokes { vectorcraft_doc::Scaling::factor(xf) } else { None }; if let Some(k) = factor && paths::is_path(h, item) && (!k.is_finite() || { let width = paths::largest_stroke_weight(h, item)? * k; !width.is_finite() || width > paths::MAX_STROKE_WIDTH }) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity }; // The transformation and the stroke weight change together or not at all. atomically(h, |h| { if changes { let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes}); edit_item(h, item, "object.transform", &p)?; } if let Some(w) = weight { paths::set_stroke_weight(h, item, w)?; } Ok(Data::Undefined) }) } /// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?, /// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out). pub(super) fn translate(h: &Host, a: &[Data]) -> Answer { let delta = |i: usize, what: &str| match arg(a, i) { Data::Undefined => Ok(0.0), d => number(d, what), }; let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?); let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"]; let opts = options(h, a, 3, names)?; let item = this_item(h, a)?; // An offset past the canvas is refused only when the call moves the object or a pattern it // uses. let limit = coordinate(&Data::Number(dx), "deltaX").and_then(|_| coordinate(&Data::Number(dy), "deltaY")); if let Err(e) = limit { let moves = opts.objects || opts.patterns && with_doc(h, item.doc, |_, st| { st.doc.node(item.id).is_some_and(|n| { let mut uses = false; n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None)); uses }) }); if moves { return Err(e); } } apply(h, item, matrix::translate(dx, dy), None, &opts, None) } const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"]; /// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?, /// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive. pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer { let angle = number(arg(a, 1), "angle")?; let opts = options(h, a, 2, CHANGE_NAMES)?; apply(h, this_item(h, a)?, matrix::rotate(angle), Some(arg(a, 6)), &opts, None) } /// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, /// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and /// `scaleY` percent along the page's axes. pub(super) fn resize(h: &Host, a: &[Data]) -> Answer { let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?); if sx == 0.0 || sy == 0.0 { return Err(HostError::Range("scaleX and scaleY must not be 0".into())); } let m = matrix::scaled(sx, sy); let mut opts = options(h, a, 3, CHANGE_NAMES)?; let item = this_item(h, a)?; let weight = match own_line_widths(arg(a, 7), m)? { // The compound holds a member's visible stroke, so its weight is set through the compound // as well as the member's own strokes and effects scaling, by the scale itself. (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { opts.strokes = true; paths::resized_stroke_weight(h, item, own, false)? } (Some(strokes), _, _) => { opts.strokes = strokes; None } (None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw, true)?, (None, _, own) => return Err(other_line_widths(own)), }; apply(h, item, m, Some(arg(a, 8)), &opts, weight) } /// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?, /// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the /// object. pub(super) fn transform(h: &Host, a: &[Data]) -> Answer { let m = matrix::matrix(arg(a, 1), "transformationMatrix")?; let mut opts = options(h, a, 2, CHANGE_NAMES)?; let item = this_item(h, a)?; let weight = match own_line_widths(arg(a, 6), m)? { // As in `resize`: the compound holds a member's visible stroke, so its weight is set // through the compound as well. (Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => { opts.strokes = true; paths::resized_stroke_weight(h, item, own, false)? } _ => { opts.strokes = line_widths(arg(a, 6), m)?; None } }; apply(h, item, m, Some(arg(a, 7)), &opts, weight) }