diff --git a/.github/workflows/affinity-corpus.yml b/.github/workflows/affinity-corpus.yml
index 41ac5a00d7..b3e0178f56 100644
--- a/.github/workflows/affinity-corpus.yml
+++ b/.github/workflows/affinity-corpus.yml
@@ -30,7 +30,7 @@ jobs:
egress-policy: audit
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Rust
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
+ uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0
with:
toolchain: "1.95"
- name: Fetch pinned and checksum-verified corpus
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index eee66ab3be..fd836de6c7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -3,6 +3,10 @@
name: Release
on:
+ # A nightly dry run on main: every release build except macOS, nothing signed or released
+ # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day.
+ schedule:
+ - cron: "52 2 * * *"
push:
branches: [release]
workflow_dispatch:
@@ -77,6 +81,7 @@ jobs:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/release.yml@main
with:
+ dry-run: ${{ github.event_name == 'schedule' }}
app-name: vectorcraft
app-title: VectorCraft
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
diff --git a/ASSETS.md b/ASSETS.md
index 17ab680ff4..27bbcfc5e7 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -159,6 +159,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-fx.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-gamut.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-grad-conic.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-freeform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-linear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-grad-radial.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
diff --git a/assets/icons/dc-grad-conic.svg b/assets/icons/dc-grad-conic.svg
new file mode 100644
index 0000000000..f6e49150be
--- /dev/null
+++ b/assets/icons/dc-grad-conic.svg
@@ -0,0 +1 @@
+
diff --git a/crates/affinity/README.md b/crates/affinity/README.md
index fd2d6dc71a..d0a641697d 100644
--- a/crates/affinity/README.md
+++ b/crates/affinity/README.md
@@ -35,7 +35,7 @@ Affinity files.
Everything else is reported in the import warnings, one line per kind with a count, never
dropped silently: bevel, blur and other layer effects, adjustment layers and live filters, brush strokes, pressure curves that can't be read or that go past the million points one document may hold,
-transparency gradients, fill opacity, bitmap fills, master pages based on other master pages, conical gradients (as radial),
+transparency gradients, fill opacity, bitmap fills, master pages based on other master pages,
special shapes (cloud, heart, cog, callouts, arrows…, imported as their bounding ellipse), corner
types other than round or straight, stars with rounded points, several fills or strokes on one object (the
active one is used), skewed or flipped text, characters of different transparency in one text, text fields such as page numbers, text threading, frames with
diff --git a/crates/color/src/gradient.rs b/crates/color/src/gradient.rs
index 03d0f5670c..18aa1bd189 100644
--- a/crates/color/src/gradient.rs
+++ b/crates/color/src/gradient.rs
@@ -15,20 +15,36 @@ pub enum GradientKind {
Radial,
/// Freeform gradients: colour points and lines (see [`crate::freeform`]).
Freeform,
+ /// Conic (angle) gradients: the stops sweep once around the center (`start`), clockwise on
+ /// the page from the vector, with a seam where the last stop meets the first. A negative
+ /// `aspect` mirrors the sweep (see [`GradientGeom::transform`]).
+ Conic,
}
impl GradientKind {
- /// Parse a kind name (`linear`, `radial`, `freeform`; any case).
+ /// Every kind, in the order the Gradient panel lists them.
+ pub const ALL: [GradientKind; 4] = [GradientKind::Linear, GradientKind::Radial, GradientKind::Conic, GradientKind::Freeform];
+ /// Parse a kind name (`linear`, `radial`, `conic`, `freeform`; any case). `angle` and
+ /// `conical` also mean conic.
pub fn parse(s: &str) -> Option {
- [GradientKind::Linear, GradientKind::Radial, GradientKind::Freeform].into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
+ if s.eq_ignore_ascii_case("angle") || s.eq_ignore_ascii_case("conical") {
+ return Some(GradientKind::Conic);
+ }
+ Self::ALL.into_iter().find(|k| k.label().eq_ignore_ascii_case(s))
}
pub fn label(self) -> &'static str {
match self {
GradientKind::Linear => "Linear",
GradientKind::Radial => "Radial",
GradientKind::Freeform => "Freeform",
+ GradientKind::Conic => "Conic",
}
}
+ /// Is it placed by a center (`start`) and an extent ellipse (radial and conic), rather than
+ /// by a line?
+ pub fn is_centered(self) -> bool {
+ matches!(self, GradientKind::Radial | GradientKind::Conic)
+ }
}
/// How a gradient mixes the colours between its stops (the Gradient panel's Method).
@@ -642,19 +658,23 @@ pub struct GradientGeom {
/// How far out a focal point may sit, as a fraction of the extent ellipse.
const FOCAL_MAX: f64 = 0.99;
+/// Most wedges [`GradientGeom::conic_wedges`] draws a conic gradient as.
+pub const MAX_CONIC_WEDGES: usize = 4096;
+
fn one64() -> f64 {
1.0
}
impl GradientGeom {
/// Default placement for a bounding box: linear spans the box through the centre at `angle_deg`,
- /// radial is centred with radius = half the larger dimension and its vector at `angle_deg`.
+ /// radial and conic are centered with radius = half the larger dimension and their vector at
+ /// `angle_deg`.
pub fn fit(kind: GradientKind, b: Rect, angle_deg: f64) -> Self {
let c = b.center();
let a = angle_deg.to_radians();
let d = Vec2::new(a.cos(), -a.sin());
match kind {
- GradientKind::Radial => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
+ GradientKind::Radial | GradientKind::Conic => Self { start: c, end: c + d * (b.width().max(b.height()) / 2.0), aspect: 1.0, focal: None },
_ => {
// Project the box corners onto the direction to cover the whole box.
let half = (b.width() * d.x.abs() + b.height() * d.y.abs()) / 2.0;
@@ -668,7 +688,12 @@ impl GradientGeom {
/// Linear (and freeform) gradients keep their isolines: the new vector is the normal to the
/// mapped isolines, reaching the line the old end maps onto. Radial gradients map their ellipse
/// (the radius along the vector, `aspect` × the radius across it); its principal axes give the
- /// new end (on the axis nearest the mapped vector) and aspect.
+ /// new end (on the axis nearest the mapped vector) and aspect. Conic gradients keep their
+ /// vector exactly (where the sweep starts, so the seam stays in place) and take the mapped
+ /// extent across it as their aspect, its sign flipping under a mirror so the sweep turns the
+ /// other way: exact for moves, rotations, uniform scales and mirrors, and the nearest frame
+ /// that keeps the seam under a shear or a non-uniform scale. A conic whose vector has no
+ /// length, or whose aspect is 0, still has the sign of its aspect flipped by a mirror.
pub fn transform(&mut self, a: Affine, kind: GradientKind) {
// The focal point is a point like any other.
self.focal = self.focal.map(|f| a * f);
@@ -677,9 +702,26 @@ impl GradientGeom {
let perp = |v: Vec2| Vec2::new(-v.y, v.x);
let start = a * self.start;
let u = self.end - self.start;
+ let mirror = m0 * m3 - m1 * m2 < 0.0;
if u.hypot2() < 1e-18 {
self.start = start;
self.end = start;
+ if kind == GradientKind::Conic && mirror {
+ self.aspect = -self.aspect;
+ }
+ return;
+ }
+ if kind == GradientKind::Conic {
+ let (lu, lw) = (lin(u), lin(perp(u) * self.aspect));
+ self.start = start;
+ self.end = start + lu;
+ let aspect = lw.dot(perp(lu)) / lu.hypot2();
+ self.aspect = match (lu.hypot2() > 1e-18 && aspect.is_finite(), aspect == 0.0) {
+ (false, _) => 1.0,
+ // A flat extent keeps its sign, so a mirror still turns the sweep the other way.
+ (true, true) => 0.0f64.copysign(if self.aspect.is_sign_negative() != mirror { -1.0 } else { 1.0 }),
+ (true, false) => aspect,
+ };
return;
}
if kind != GradientKind::Radial {
@@ -724,8 +766,15 @@ impl GradientGeom {
/// The gradient parameter (0 at the start, 1 at the end) at document point `p`: the projection
/// onto the vector for linear gradients, the elliptical radius (honouring `aspect`) for radial,
/// measured from the focal point (each level is the ellipse scaled about the line from the
- /// focal point to the centre).
+ /// focal point to the centre). For conic gradients it is the turn from the vector in
+ /// [`Self::conic_frame`], clockwise on the page (counterclockwise when mirrored), in 0..=1.
pub fn param_at(&self, kind: GradientKind, p: Point) -> f64 {
+ if kind == GradientKind::Conic {
+ let q = (self.conic_frame().inverse() * p).to_vec2();
+ let t = q.y.atan2(q.x) / std::f64::consts::TAU;
+ let t = if t < 0.0 { t + 1.0 } else { t };
+ return if t.is_finite() { t.clamp(0.0, 1.0) } else { 0.0 };
+ }
let u = self.end - self.start;
if u.hypot2() < 1e-18 {
return 0.0;
@@ -746,13 +795,72 @@ impl GradientGeom {
(-b - (b * b - a * d.hypot2()).max(0.0).sqrt()) / a
}
- /// The map from the unit circle onto a radial's extent ellipse: (1, 0) to the end, (0, 1) to
- /// `aspect` × the radius across the vector. None when the ellipse is flat (no inverse).
+ /// The map from the unit circle onto a radial's (or conic's) extent ellipse: (1, 0) to the
+ /// end, (0, 1) to `aspect` × the radius across the vector (a conic's negative aspect mirrors
+ /// it). None when the ellipse is flat (no inverse).
pub fn unit_frame(&self) -> Option {
let u = self.end - self.start;
(u.hypot2() * self.aspect.abs() > 1e-18).then(|| Affine::new([u.x, u.y, -u.y * self.aspect, u.x * self.aspect, self.start.x, self.start.y]))
}
+ /// The frame a conic gradient sweeps in: its [`Self::unit_frame`], or, when the extent
+ /// ellipse is flat or not finite (a vector without length, an aspect of 0, or a file's
+ /// out-of-range numbers), the unit circle about the start turning from the vector's direction
+ /// (from the right when the vector has none), mirrored by a negative aspect. The canvas,
+ /// Expand and every export draw a conic in this frame.
+ pub fn conic_frame(&self) -> Affine {
+ if let Some(m) = self.unit_frame().filter(|m| m.is_finite() && m.determinant().abs() > 1e-18) {
+ return m;
+ }
+ if !self.start.is_finite() {
+ return Affine::IDENTITY;
+ }
+ let u = self.end - self.start;
+ let len = u.hypot();
+ let d = if len.is_finite() && len > 1e-9 { u / len } else { Vec2::new(1.0, 0.0) };
+ let s = if self.aspect.is_sign_negative() && !self.aspect.is_nan() { -1.0 } else { 1.0 };
+ Affine::new([d.x, d.y, -d.y * s, d.x * s, self.start.x, self.start.y])
+ }
+
+ /// Is the sweep mirrored (counterclockwise on the page): a conic's negative aspect?
+ pub fn is_mirrored(&self) -> bool {
+ self.conic_frame().determinant() < 0.0
+ }
+
+ /// A conic gradient as `n` solid wedges around its center (at most [`MAX_CONIC_WEDGES`]), for
+ /// formats without conic gradients: each wedge's outline (the center, then an arc that
+ /// reaches past every corner of `b`) and the turn its color is sampled at (its middle). With
+ /// `overlap` (opaque stops), each wedge runs on to the seam and the next is drawn over it, so
+ /// no hairline of what lies below shows between neighbors and the seam stays sharp.
+ pub fn conic_wedges(&self, b: Rect, n: usize, overlap: bool) -> Vec<(Vec, f64)> {
+ let n = n.clamp(1, MAX_CONIC_WEDGES);
+ let frame = self.conic_frame();
+ let to_unit = frame.inverse();
+ let corners = [b.origin(), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
+ let reach = corners.iter().map(|&c| (to_unit * c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
+ let reach = if reach.is_finite() { reach * 1.01 } else { 1.0 };
+ // Arc points at most ARC of a turn apart, at a radius where their chords stay outside
+ // `reach`.
+ const ARC: f64 = 1.0 / 32.0;
+ let r = reach / (std::f64::consts::PI * ARC).cos();
+ let at = |turn: f64| {
+ let a = turn * std::f64::consts::TAU;
+ frame * Point::new(r * a.cos(), r * a.sin())
+ };
+ let center = frame * Point::ORIGIN;
+ (0..n)
+ .map(|k| {
+ let from = k as f64 / n as f64;
+ let to = if overlap { 1.0 } else { (k + 1) as f64 / n as f64 };
+ let steps = ((to - from) / ARC).ceil().max(1.0) as usize;
+ let mut pts = Vec::with_capacity(steps + 2);
+ pts.push(center);
+ pts.extend((0..=steps).map(|i| at(from + (to - from) * i as f64 / steps as f64)));
+ (pts, (k as f64 + 0.5) / n as f64)
+ })
+ .collect()
+ }
+
/// The map that squashes a radial gradient's circle (centre `start`, radius the vector's
/// length) into its extent ellipse: by `aspect` across the vector, about the centre.
pub fn radial_squash(&self) -> Affine {
@@ -901,7 +1009,7 @@ impl GradientPaint {
pub fn draws_as_pixels(&self, fill: bool) -> bool {
self.gradient.kind == GradientKind::Freeform || (fill && self.gradient.dither) || !self.gradient.method.is_classic()
}
- /// A linear or radial gradient placed on box `bounds` as a `cols` × `rows` grid of
+ /// A linear, radial or conic gradient placed on box `bounds` as a `cols` × `rows` grid of
/// unpremultiplied RGBA8 pixels over `area`, row by row, each sampled at its centre (colours
/// as `rgb` gives them, mixed as the renderer mixes them: [`Ramp`]). Dithered and painting a
/// fill (`fill`; dither applies to fills only), each colour channel of pixel (column, row) gets
@@ -932,7 +1040,7 @@ impl GradientPaint {
) -> impl Iterator + use<> {
self.grid(Ramp::new(&self.gradient, rgb), bounds, area, cols, rows, cells, fill, false)
}
- /// [`Self::pixels`] of a linear or radial gradient whose stops are all CMYK, as C, M, Y, K
+ /// [`Self::pixels`] of a linear, radial or conic gradient whose stops are all CMYK, as C, M, Y, K
/// and opacity levels mixed from the stops' inks; `None` when a stop is in another model,
/// there are no stops, or a Perceptual curve has too many stops for [`Gradient::ink_mixes`].
/// Dither's noise adds no ink where the ramp has none.
diff --git a/crates/color/src/gradient/tests.rs b/crates/color/src/gradient/tests.rs
index 87372a1c24..c8d0a4bb64 100644
--- a/crates/color/src/gradient/tests.rs
+++ b/crates/color/src/gradient/tests.rs
@@ -697,3 +697,186 @@ fn ink_pixels_stop_at_the_ink_mixes_limit() {
assert!(GradientPaint::new(perceptual).ink_pixels(b, b, 2, 1, false).is_none());
assert!(GradientPaint::new(classic).ink_pixels(b, b, 2, 1, false).is_some());
}
+
+/// A conic placed at `center` with its vector `dx` long to the right and aspect `aspect`.
+fn conic_at(center: Point, dx: f64, aspect: f64) -> GradientGeom {
+ GradientGeom { start: center, end: center + Vec2::new(dx, 0.0), aspect, focal: None }
+}
+
+#[test]
+fn a_conic_turns_clockwise_on_the_page_from_its_vector() {
+ // The page's y runs down: a quarter turn clockwise from a vector pointing right is straight
+ // below the center.
+ let g = conic_at(Point::new(100.0, 100.0), 50.0, 1.0);
+ let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
+ assert!(t(200.0, 100.0).abs() < 1e-12);
+ assert!((t(100.0, 130.0) - 0.25).abs() < 1e-12);
+ assert!((t(10.0, 100.0) - 0.5).abs() < 1e-12);
+ assert!((t(100.0, 3.0) - 0.75).abs() < 1e-12);
+ // Either side of the seam: the start of the ramp just below the vector, its end just above.
+ assert!(t(200.0, 100.01) < 1e-3);
+ let before = t(200.0, 99.99);
+ assert!(before > 0.999 && before <= 1.0, "{before}");
+ // A flatter extent ellipse turns faster near the vector's line: half as tall, the point 1/8
+ // of a turn around is half as far below it.
+ let squashed = conic_at(Point::new(100.0, 100.0), 50.0, 0.5);
+ let p = Point::new(150.0, 125.0);
+ assert!((squashed.param_at(GradientKind::Conic, p) - 0.125).abs() < 1e-12);
+ assert!(g.param_at(GradientKind::Conic, p) < 0.1);
+ // Mirrored (a negative aspect), it turns counterclockwise.
+ let mirrored = conic_at(Point::new(100.0, 100.0), 50.0, -1.0);
+ assert!(mirrored.is_mirrored() && !g.is_mirrored());
+ assert!((mirrored.param_at(GradientKind::Conic, Point::new(100.0, 70.0)) - 0.25).abs() < 1e-12);
+}
+
+#[test]
+fn a_conic_follows_moves_turns_scales_and_mirrors() {
+ let c = Point::new(10.0, 20.0);
+ let g0 = conic_at(c, 30.0, 1.0);
+ let probes = [c + Vec2::new(5.0, 7.0), c + Vec2::new(-9.0, 2.0), c + Vec2::new(3.0, -11.0)];
+ for a in [
+ Affine::rotate(0.7),
+ Affine::scale(2.5),
+ Affine::translate((4.0, -9.0)) * Affine::rotate(-2.0),
+ Affine::FLIP_X,
+ Affine::FLIP_Y * Affine::rotate(1.1),
+ Affine::scale_non_uniform(2.0, 0.5),
+ ] {
+ let mut g = g0;
+ g.transform(a, GradientKind::Conic);
+ assert!(g.start.distance(a * c) < 1e-9, "{a:?}");
+ for p in probes {
+ let (want, got) = (g0.param_at(GradientKind::Conic, p), g.param_at(GradientKind::Conic, a * p));
+ assert!((want - got).abs() < 1e-9, "{a:?} at {p:?}: {want} vs {got}");
+ }
+ }
+ // A mirror and a mirror back: the same sweep.
+ let mut g = g0;
+ g.transform(Affine::FLIP_X, GradientKind::Conic);
+ assert!(g.is_mirrored());
+ g.transform(Affine::FLIP_X, GradientKind::Conic);
+ assert!(!g.is_mirrored() && (g.aspect - 1.0).abs() < 1e-12);
+ // A conic without a vector, or with a flat extent, turns the other way under a mirror too.
+ for flat in [conic_at(c, 0.0, 1.0), conic_at(c, 30.0, 0.0)] {
+ let mut g = flat;
+ g.transform(Affine::FLIP_Y, GradientKind::Conic);
+ assert!(g.is_mirrored(), "{g:?}");
+ g.transform(Affine::rotate(0.3), GradientKind::Conic);
+ assert!(g.is_mirrored(), "{g:?}");
+ g.transform(Affine::FLIP_X, GradientKind::Conic);
+ assert!(!g.is_mirrored(), "{g:?}");
+ }
+ // Under a shear the seam stays where the vector maps.
+ let shear = Affine::new([1.0, 0.0, 0.6, 1.0, 0.0, 0.0]);
+ let mut g = g0;
+ g.transform(shear, GradientKind::Conic);
+ let on_seam = shear * (c + Vec2::new(20.0, 0.0));
+ assert!(g.param_at(GradientKind::Conic, on_seam) < 1e-9, "{g:?}");
+}
+
+#[test]
+fn conic_kind_names_and_fit() {
+ for s in ["conic", "Conic", "angle", "CONICAL"] {
+ assert_eq!(GradientKind::parse(s), Some(GradientKind::Conic), "{s}");
+ }
+ assert_eq!(GradientKind::parse("spiral"), None);
+ assert_eq!(GradientKind::Conic.label(), "Conic");
+ assert!(GradientKind::Conic.is_centered() && GradientKind::Radial.is_centered() && !GradientKind::Linear.is_centered());
+ let fit = GradientGeom::fit(GradientKind::Conic, Rect::new(0.0, 0.0, 200.0, 100.0), 90.0);
+ assert_eq!(fit.start, Point::new(100.0, 50.0));
+ assert!(fit.end.distance(Point::new(100.0, -50.0)) < 1e-9);
+}
+
+/// Is `p` inside polygon `poly` (non-zero winding)?
+fn inside(poly: &[Point], p: Point) -> bool {
+ let mut w = 0i32;
+ for (i, &a) in poly.iter().enumerate() {
+ let c = poly[(i + 1) % poly.len()];
+ let cross = (c - a).cross(p - a);
+ if a.y <= p.y && c.y > p.y && cross > 0.0 {
+ w += 1;
+ } else if a.y > p.y && c.y <= p.y && cross < 0.0 {
+ w -= 1;
+ }
+ }
+ w != 0
+}
+
+#[test]
+fn conic_wedges_cover_the_box_and_meet_at_the_seam() {
+ let b = Rect::new(0.0, 0.0, 200.0, 100.0);
+ let g = conic_at(Point::new(60.0, 40.0), 30.0, 0.5);
+ let wedges = g.conic_wedges(b, 36, false);
+ assert_eq!(wedges.len(), 36);
+ // Each point of the box lies in the wedge whose share of the turn holds it.
+ for (x, y) in [(1.0, 1.0), (199.0, 99.0), (150.0, 30.0), (10.0, 90.0), (61.0, 39.0), (59.0, 41.0)] {
+ let p = Point::new(x, y);
+ let t = g.param_at(GradientKind::Conic, p);
+ let k = ((t * 36.0).floor() as usize).min(35);
+ assert!(inside(&wedges[k].0, p), "({x}, {y}) at {t} is not in wedge {k}");
+ assert!((wedges[k].1 - (k as f64 + 0.5) / 36.0).abs() < 1e-12);
+ }
+ // Overlapping wedges run on from their own start to the seam.
+ let over = g.conic_wedges(b, 36, true);
+ let frame = g.unit_frame().unwrap();
+ let on = |turn: f64| frame * Point::new(0.5 * (turn * std::f64::consts::TAU).cos(), 0.5 * (turn * std::f64::consts::TAU).sin());
+ assert!(inside(&over[0].0, on(0.5)) && inside(&over[0].0, on(35.9 / 36.0)));
+ assert!(inside(&over[20].0, on(35.9 / 36.0)) && !inside(&over[20].0, on(19.9 / 36.0)));
+ // The count is kept to what a file can hold.
+ assert_eq!(g.conic_wedges(b, 0, false).len(), 1);
+ assert_eq!(g.conic_wedges(b, usize::MAX, false).len(), MAX_CONIC_WEDGES);
+}
+
+/// A conic whose extent can't be drawn (a vector without length, an aspect of 0, or numbers out
+/// of range, as a file can hold them) sweeps from the right about its start, or the origin; the
+/// parameter, the frame and the wedges stay finite.
+#[test]
+fn a_conic_with_no_extent_or_bad_numbers_still_sweeps() {
+ let c = Point::new(50.0, 50.0);
+ for g in [
+ conic_at(c, 0.0, 1.0),
+ conic_at(c, 30.0, 0.0),
+ conic_at(c, 30.0, f64::NAN),
+ conic_at(c, 30.0, f64::INFINITY),
+ conic_at(c, f64::INFINITY, 1.0),
+ GradientGeom { end: Point::new(f64::NAN, 3.0), ..conic_at(c, 30.0, 1.0) },
+ ] {
+ assert!(g.conic_frame().as_coeffs().iter().all(|v| v.is_finite()), "{g:?}");
+ let t = |x: f64, y: f64| g.param_at(GradientKind::Conic, Point::new(x, y));
+ assert!(t(90.0, 50.0).abs() < 1e-12, "{g:?}");
+ assert!((t(50.0, 90.0) - 0.25).abs() < 1e-12, "{g:?}");
+ let wedges = g.conic_wedges(Rect::new(0.0, 0.0, 100.0, 100.0), 4, false);
+ assert!(wedges.iter().flat_map(|(pts, _)| pts).all(|p| p.is_finite()), "{g:?}");
+ }
+ // A flat extent keeps the vector's direction and the sign of its aspect.
+ let down = GradientGeom { end: Point::new(50.0, 80.0), ..conic_at(c, 30.0, 0.0) };
+ assert!(down.param_at(GradientKind::Conic, Point::new(50.0, 90.0)).abs() < 1e-12);
+ assert!((down.param_at(GradientKind::Conic, Point::new(10.0, 50.0)) - 0.25).abs() < 1e-12);
+ for g in [conic_at(c, 0.0, -1.0), conic_at(c, 30.0, -0.0), conic_at(c, 30.0, f64::NEG_INFINITY)] {
+ assert!(g.is_mirrored(), "{g:?}");
+ assert!((g.param_at(GradientKind::Conic, Point::new(50.0, 10.0)) - 0.25).abs() < 1e-12, "{g:?}");
+ }
+ let lost = GradientGeom { start: Point::new(f64::NAN, 0.0), ..conic_at(c, 30.0, 1.0) };
+ assert_eq!(lost.conic_frame(), Affine::IDENTITY);
+ for p in [Point::new(3.0, 4.0), Point::new(f64::NAN, 1.0), Point::new(f64::INFINITY, 0.0)] {
+ let t = lost.param_at(GradientKind::Conic, p);
+ assert!((0.0..=1.0).contains(&t), "{t}");
+ }
+}
+
+/// A conic's pixels (what SVG and PDF draw a dithered or Perceptual one as) follow the sweep,
+/// with one stop as well as many.
+#[test]
+fn conic_pixels_follow_the_sweep() {
+ let b = Rect::new(0.0, 0.0, 4.0, 4.0);
+ let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, Gradient::default().stops));
+ g.geom = Some(conic_at(Point::new(2.0, 2.0), 1.0, 1.0));
+ let px: Vec<[u8; 4]> = g.pixels(b, b, 4, 4, true, &Color::to_rgb).collect();
+ // Below right of the center, early in the sweep: light. Above right, late: dark.
+ assert!(px[3 * 4 + 3][0] > 180 && px[3][0] < 75, "{px:?}");
+ let one = GradientPaint { gradient: Gradient::new(GradientKind::Conic, vec![GradientStop::new(0.3, Color::rgb(1.0, 0.0, 0.0))]), ..g.clone() };
+ assert!(one.pixels(b, b, 4, 4, true, &Color::to_rgb).all(|p| p == [255, 0, 0, 255]));
+ let many = (0..=1000).map(|i| GradientStop::new(i as f32 / 1000.0, Color::gray((i % 2) as f32))).collect();
+ let many = GradientPaint { gradient: Gradient::new(GradientKind::Conic, many), ..g };
+ assert_eq!(many.pixels(b, b, 4, 4, true, &Color::to_rgb).count(), 16);
+}
diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs
index b331d43e6a..6be0f2abf5 100644
--- a/crates/color/src/palette_io.rs
+++ b/crates/color/src/palette_io.rs
@@ -189,10 +189,22 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String {
let value = match &w.paint {
Paint::Solid { color, .. } => css_color(color, 1.0),
Paint::Gradient(g) if g.gradient.kind != GradientKind::Freeform => {
+ // A mirrored conic turns counterclockwise, and CSS only turns clockwise: its stops
+ // are written mirrored about the seam instead.
+ let mirrored = g.gradient.kind == GradientKind::Conic && g.geom.is_some_and(|geom| geom.is_mirrored());
+ let stop = |s: &crate::GradientStop| {
+ let at = if mirrored { 1.0 - s.offset } else { s.offset };
+ format!("{} {}%", css_color(&s.color, s.opacity), at * 100.0)
+ };
let stops: Vec =
- g.gradient.stops.iter().map(|s| format!("{} {}%", css_color(&s.color, s.opacity), s.offset * 100.0)).collect();
+ if mirrored { g.gradient.stops.iter().rev().map(stop).collect() } else { g.gradient.stops.iter().map(stop).collect() };
match g.gradient.kind {
GradientKind::Radial => format!("radial-gradient(circle, {})", stops.join(", ")),
+ // CSS sweeps clockwise from straight up; the angle is counted counterclockwise
+ // from the right.
+ GradientKind::Conic => {
+ format!("conic-gradient(from {}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", "))
+ }
_ => format!("linear-gradient({}deg, {})", (90.0 - g.angle).rem_euclid(360.0).round(), stops.join(", ")),
}
}
diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs
index b0342d7a52..9ee07cb623 100644
--- a/crates/color/src/palette_io/tests.rs
+++ b/crates/color/src/palette_io/tests.rs
@@ -166,6 +166,26 @@ fn css_escapes_names_and_writes_gradients() {
assert!(read(&text, "x").is_err(), "CSS is written only");
}
+/// A conic gradient swatch is a CSS conic gradient starting where its angle points (CSS turns
+/// clockwise from straight up); a mirrored one, which turns counterclockwise, has its stops mirrored
+/// about the seam so each color lies on the same side.
+#[test]
+fn css_writes_conic_gradient_swatches() {
+ let one = |name: &str, g: GradientPaint| SwatchLibrary {
+ name: "x".into(),
+ swatches: vec![Swatch { name: name.into(), paint: Paint::Gradient(Box::new(g)), global: false, spot: false }],
+ groups: vec![],
+ };
+ let mut conic = GradientPaint::new(Gradient { kind: GradientKind::Conic, ..Gradient::default() });
+ conic.angle = 90.0;
+ let text = written(&one("Sweep", conic.clone()), PaletteFormat::Css);
+ assert!(text.contains("--sweep: conic-gradient(from 0deg, #ffffff 0%, #000000 100%);"), "{text}");
+ conic.gradient.stops[0].offset = 0.2;
+ conic.geom = Some(crate::GradientGeom { start: kurbo::Point::ZERO, end: kurbo::Point::new(0.0, -10.0), aspect: -1.0, focal: None });
+ let text = written(&one("Back", conic), PaletteFormat::Css);
+ assert!(text.contains("--back: conic-gradient(from 0deg, #000000 0%, #ffffff 80%);"), "{text}");
+}
+
#[test]
fn css_preserves_fractional_gradient_stop_positions() {
for kind in [GradientKind::Linear, GradientKind::Radial] {
diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs
index 2e19ad44a3..c057aeb231 100644
--- a/crates/doc/src/appearance.rs
+++ b/crates/doc/src/appearance.rs
@@ -444,13 +444,13 @@ impl Appearance {
}
}
/// Map placed gradients through a warp, given its local affine approximation at a point (taken
- /// at each gradient's centre: the start of a radial, the middle of a linear vector). Freeform
- /// points each follow the warp at their own position.
+ /// at each gradient's center: the start of a radial or conic, the middle of a linear vector).
+ /// Freeform points each follow the warp at their own position.
pub fn warp_gradients(&mut self, near: &dyn Fn(vectorcraft_geom::Point) -> vectorcraft_geom::Affine) {
for g in self.gradients_mut() {
let freeform = g.freeform.take();
if let Some(geom) = g.geom {
- let c = if g.gradient.kind == vectorcraft_color::GradientKind::Radial { geom.start } else { geom.start.midpoint(geom.end) };
+ let c = if g.gradient.kind.is_centered() { geom.start } else { geom.start.midpoint(geom.end) };
g.transform(near(c));
}
g.freeform = freeform.map(|mut f| {
diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs
index 8f9b197048..8abe961841 100644
--- a/crates/doc/src/live/envelope.rs
+++ b/crates/doc/src/live/envelope.rs
@@ -78,7 +78,9 @@ pub struct EnvelopeOptions {
/// Rasters: Preserve Shape Using.
pub preserve_shape: PreserveShape,
/// Distort Appearance: strokes and live effects are applied before the distortion, so they
- /// bend with the art (off: they apply to the distorted paths).
+ /// bend with the art (off: they apply to the distorted paths). Type's strokes are the exception:
+ /// they paint along its distorted glyph outlines at their own weight either way, as `.ai` files
+ /// draw them (#6644).
pub distort_appearance: bool,
/// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art.
pub distort_linear_gradients: bool,
@@ -638,6 +640,7 @@ pub(super) fn expand_envelope(
hooks,
options,
depth: 0,
+ type_outlines: false,
};
content.iter().map(|c| map_node(c, &w)).collect()
}
diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs
index 1cc8ba0863..8675dcc011 100644
--- a/crates/doc/src/live/expand.rs
+++ b/crates/doc/src/live/expand.rs
@@ -21,6 +21,11 @@ pub struct Hooks<'a> {
/// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None`
/// when it has none to bake).
pub appearance: Outliner<'a>,
+ /// Distort Appearance for the pieces of type's glyph outlines: their geometry effects baked
+ /// as [`Hooks::appearance`] bakes them, their strokes left as strokes, which then paint along
+ /// the bent outlines at their own weight (#6644). `None` when a piece has nothing to bake, and
+ /// without this hook nothing in type's outlines is baked.
+ pub type_appearance: Outliner<'a>,
/// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]).
pub pattern: Option>,
/// The document whose symbols' art counts toward the instance budget of a Repeat of their
@@ -61,6 +66,12 @@ pub(super) struct Warper<'a> {
pub(super) options: EnvelopeOptions,
/// How many hooks the art being mapped came through.
pub(super) depth: u32,
+ /// Are groups marked as type's glyph outlines ([`crate::NodeExtras::type_outlines`]) in the art
+ /// being mapped type that live evaluation outlined: the type of the envelope's contents, or of
+ /// a live object in them, such as an envelope inside the envelope? Their strokes then paint
+ /// along the bent outlines at their own weight (#6644). Groups so marked in the contents as
+ /// they are, art an earlier Expand made of type, are plain art.
+ pub(super) type_outlines: bool,
}
impl Warper<'_> {
@@ -117,6 +128,13 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
*live = None;
}
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
+ // Type's glyph outlines: with Distort Appearance too, their strokes paint along the
+ // bent outlines at their own weight, as `.ai` files draw them (#6644). Their pieces are
+ // baked by `type_appearance`, which keeps strokes as strokes; their geometry effects,
+ // gradients and pattern fills follow the options as a path's do. The group's opacity
+ // mask, mapped above, bends as other art does.
+ let typed = Warper { hooks: Hooks { appearance: w.hooks.type_appearance, ..w.hooks }, ..*w };
+ let w = if w.type_outlines && n.extras().type_outlines { &typed } else { w };
for c in children.iter_mut() {
*c = Arc::new(map_node(c, w));
}
@@ -124,14 +142,17 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node {
NodeKind::Mesh(m) => m.map(w.f),
NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => {
if let Some(d) = &deeper {
- return map_node(&expanded_group_hooks(n, w.hooks), d);
+ // The type's outlines in its art are type (an envelope inside the envelope, #6644).
+ return map_node(&expanded_group_hooks(n, w.hooks), &Warper { type_outlines: true, ..*d });
}
}
NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => {
if let Some(d) = &deeper
&& let Some(o) = w.hooks.outline.and_then(|h| h(n))
{
- return map_node(&carry_look(n, o), d);
+ // Type's outlines are type (#6644, the group arm above).
+ let d = Warper { type_outlines: d.type_outlines || matches!(n.kind, NodeKind::Text(_)), ..*d };
+ return map_node(&carry_look(n, o), &d);
}
}
NodeKind::Image(im) => {
@@ -439,8 +460,11 @@ pub fn subtree_has_live(n: &Node) -> bool {
any
}
-/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the
-/// outsets in the art of the symbols its instances show count too
+/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the
+/// reach of symbol art), type's character strokes included as type's own visual bounds measure them
+/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight
+/// around the bent glyphs, past its grid where the glyphs reach its edge (#6644). With
+/// `symbols`, the outsets in the art of the symbols its instances show count too
/// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made
/// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad
/// does.
@@ -449,6 +473,9 @@ pub(crate) fn max_outset(nodes: &[Arc], symbols: Option<&crate::SymbolBoxe
for n in nodes {
n.walk(&mut |c| {
o = o.max(c.appearance.outset());
+ if let NodeKind::Text(t) = &c.kind {
+ o = o.max(t.char_stroke_outset());
+ }
if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind)
&& let Some(art) = s.art(symbol)
{
diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs
index 0be38d261e..05f9c29041 100644
--- a/crates/doc/src/text.rs
+++ b/crates/doc/src/text.rs
@@ -77,10 +77,13 @@ pub struct TextObject {
/// them up round the inside.
#[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")]
pub path_spacing: f64,
- /// Type › Dynamic Text (type on a path only): the layout scales the text by one factor so it
- /// fills the span between its start and end brackets, and fits it again after each edit. The
- /// stored sizes keep their proportions; the layout's `fit_scale` is the factor drawn. Off for new
- /// type and for documents from before it, and saved only when on.
+ /// Type › Dynamic Text. On type on a path, the layout scales the text by one factor so it
+ /// fills the span between its start and end brackets, and fits it again after each edit; the
+ /// stored sizes keep their proportions, and the layout's `fit_scale` is the factor drawn. On
+ /// area type it is Block: after each edit the engine sets each line as typed to the frame's
+ /// width by its font size and writes the sizes into the characters, with the gaps of
+ /// [`AreaOptions::word_gap`] and [`AreaOptions::line_gap`]. Point type does not use it. Off for
+ /// new type and for documents from before it, and saved only when on.
#[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")]
pub dynamic_text: bool,
/// Wrap objects above this area type, resolved by the engine after each edit (text space).
diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs
index 7bb742f483..848add8f53 100644
--- a/crates/doc/src/text/area.rs
+++ b/crates/doc/src/text/area.rs
@@ -167,6 +167,15 @@ pub struct AreaOptions {
/// How the frame and its text fit each other (Auto Size, Shrink Text to Fit).
#[serde(skip_serializing_if = "crate::skip::is_default")]
pub fit: AreaFit,
+ /// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): the Desired word
+ /// spacing the layout sets every paragraph with ([`super::TextObject::layout_justification`]), in
+ /// percent of a word space (100, the default, is left out when saved).
+ #[serde(skip_serializing_if = "AreaOptions::is_default_word_gap")]
+ pub word_gap: f64,
+ /// Dynamic Text's Block: the points added to each character's size to give its leading (0, the
+ /// default, is left out when saved).
+ #[serde(skip_serializing_if = "crate::skip::is_default")]
+ pub line_gap: f64,
}
impl Default for AreaOptions {
@@ -182,6 +191,8 @@ impl Default for AreaOptions {
vertical_align: VerticalAlign::Top,
flow: TextFlow::Columns,
fit: AreaFit::None,
+ word_gap: Self::DEFAULT_WORD_GAP,
+ line_gap: 0.0,
}
}
}
@@ -189,6 +200,21 @@ impl Default for AreaOptions {
impl AreaOptions {
/// The most rows, and the most columns, area type can have.
pub const MAX_ROWS_COLUMNS: usize = 100;
+ /// Block's word gap range (percent of a word space), the Justification word spacing range.
+ pub const WORD_GAP: (f64, f64) = (0.0, 1000.0);
+ /// Block's word gap new type starts with: the font's own word space.
+ pub const DEFAULT_WORD_GAP: f64 = 100.0;
+ /// Block's line gap range in points.
+ pub const LINE_GAP: (f64, f64) = (-1296.0, 1296.0);
+ fn is_default_word_gap(v: &f64) -> bool {
+ *v == Self::DEFAULT_WORD_GAP
+ }
+ /// Block's gaps kept within their ranges; a gap that is not a number gives its default.
+ pub fn block_gaps(&self) -> (f64, f64) {
+ let word = if self.word_gap.is_finite() { self.word_gap.clamp(Self::WORD_GAP.0, Self::WORD_GAP.1) } else { Self::DEFAULT_WORD_GAP };
+ let line = if self.line_gap.is_finite() { self.line_gap.clamp(Self::LINE_GAP.0, Self::LINE_GAP.1) } else { 0.0 };
+ (word, line)
+ }
}
/// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to
diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs
index 1092b871f2..d46b45b1f7 100644
--- a/crates/doc/src/text/object.rs
+++ b/crates/doc/src/text/object.rs
@@ -1,6 +1,6 @@
use super::area::{AreaOptions, PathAlign, PathEffect};
use super::char_style::CharStyle;
-use super::para_style::ParaStyle;
+use super::para_style::{JustificationOptions, ParaStyle};
use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end};
use super::tabs_lists::{ListCounts, ParaList};
use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2};
@@ -170,6 +170,19 @@ impl TextObject {
pub fn para_at(&self, i: usize) -> &ParaStyle {
self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para)
}
+ /// The Justification… options the layout sets `para` with: its own, except that with Dynamic
+ /// Text's Block on area type ([`Self::dynamic_text`]) the Desired word spacing is the word gap
+ /// ([`AreaOptions::block_gaps`]), and Minimum and Maximum move out to it when it lies outside
+ /// them. The paragraph keeps its own values, which apply again when Block is off.
+ pub fn layout_justification(&self, para: &ParaStyle) -> JustificationOptions {
+ let mut j = para.justification.clone();
+ if self.dynamic_text && matches!(self.kind, TextKind::Area { .. }) {
+ let gap = self.area.block_gaps().0;
+ let [min, _, max] = j.word_spacing;
+ j.word_spacing = [min.min(gap), gap, max.max(gap)];
+ }
+ j
+ }
/// Every paragraph's attributes, one per paragraph.
pub fn paragraph_styles(&self) -> Vec {
(0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect()
diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs
index 5d27ac60af..795fc69bdf 100644
--- a/crates/effects/src/bake.rs
+++ b/crates/effects/src/bake.rs
@@ -552,6 +552,21 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) {
/// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to
/// outline nor a geometry effect, so bending first changes nothing.
pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option {
+ bake_appearance_as(doc, n, true)
+}
+
+/// [`bake_appearance`] for the glyph outlines of type in an envelope with Distort Appearance:
+/// geometry effects are applied as it applies them, and fills, gradients and patterns are left as
+/// it leaves them, but every stroke stays a stroke on its piece instead of becoming its filled
+/// outline. The envelope then bends the piece's path, and the stroke paints along the bent outline
+/// at its own weight, as `.ai` files draw the strokes of type in an envelope (#6644). `None` when
+/// it has no geometry effect, so bending first changes nothing.
+pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option {
+ bake_appearance_as(doc, n, false)
+}
+
+/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`].
+fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option {
if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) {
return Some(m);
}
@@ -564,10 +579,10 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option {
if crate::has_transform_art(n)
&& let Some(mut m) = reshape(doc, n, None)
{
- bake_appearance_pieces(doc, &mut m);
+ bake_appearance_pieces(doc, &mut m, outline_strokes);
return Some(m);
}
- let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
+ let outlined = |i: &AppearanceItem| outline_strokes && paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none());
let geometric = has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(item_effects(i)));
if !geometric && !n.appearance.items.iter().any(outlined) {
return None;
@@ -585,7 +600,7 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option {
let (ig, mut it) = apply_item(item, carried, &g, &ctx);
clear_item_effects(&mut it);
pieces.push(match &it {
- AppearanceItem::Stroke(st) if st.brush.is_none() => {
+ AppearanceItem::Stroke(st) if outline_strokes && st.brush.is_none() => {
let outline = crate::stroke::outline_region(&ig, rule, st);
match st.path_gradient() {
// A gradient along or across the stroke: its gradient meshes clipped to the outline.
@@ -618,16 +633,16 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option {
Some(m)
}
-/// [`bake_appearance`] every path and compound path in `n` that it changes, in place.
-fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) {
+/// [`bake_appearance_as`] every path and compound path in `n` that it changes, in place.
+fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: bool) {
if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) {
- if let Some(m) = bake_appearance(doc, n) {
+ if let Some(m) = bake_appearance_as(doc, n, outline_strokes) {
*n = m;
}
return;
}
for c in n.children_mut().into_iter().flatten() {
- bake_appearance_pieces(doc, Arc::make_mut(c));
+ bake_appearance_pieces(doc, Arc::make_mut(c), outline_strokes);
}
}
diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs
index 4751b137c9..2bcc026340 100644
--- a/crates/effects/src/bake/tests.rs
+++ b/crates/effects/src/bake/tests.rs
@@ -575,6 +575,27 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline
assert_eq!(ch[1].opacity, 0.5);
}
+/// Distort Appearance on the pieces of type's glyph outlines (#6644): a stroke's geometry effect
+/// still bakes into its piece, but the stroke stays a stroke at its own weight; a piece with no
+/// geometry effect is left as it is, its stroke on it (Distort Appearance on a path outlines it).
+#[test]
+fn type_pieces_bake_their_geometry_effects_and_keep_their_strokes() {
+ let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art());
+ assert!(bake_type_appearance(None, &n).is_none(), "nothing to bake");
+ assert!(bake_appearance(None, &n).is_some(), "a path's stroke is outlined");
+ if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] {
+ s.width = 4.0;
+ s.effects.push(fx("path.offsetPath", json!({"offset": 5.0})));
+ }
+ let m = bake_type_appearance(None, &n).unwrap();
+ let ch = m.children().unwrap();
+ assert_eq!(ch.len(), 2);
+ let Some(AppearanceItem::Stroke(st)) = ch[1].appearance.items.first() else { panic!("still a stroke: {:?}", ch[1].appearance) };
+ assert!(st.width == 4.0 && st.effects.is_empty(), "{st:?}");
+ assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5, "the stroke's offset is baked into its path");
+ assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6, "the fill keeps the square");
+}
+
/// A 100 pt square at the origin painted by `fill` and `stroke` (`width` pt), with the Transform
/// effect `params`.
fn transformed(fill: Paint, stroke: Paint, width: f64, params: serde_json::Value) -> Node {
diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs
index ae8b7d9e90..67b4b464fd 100644
--- a/crates/effects/src/lib.rs
+++ b/crates/effects/src/lib.rs
@@ -68,7 +68,7 @@ pub use adjust::{
ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment,
is_channel,
};
-pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake};
+pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake};
pub use clip::clip_outline;
pub use group::{
OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder,
diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs
index 03b335f010..2c02f886c0 100644
--- a/crates/effects/src/live.rs
+++ b/crates/effects/src/live.rs
@@ -2,8 +2,9 @@
//! every exporter, with what the pure evaluation in [`vectorcraft_doc::live`] can't do itself
//! ([`Hooks`]): type inside an envelope distorts as its glyph outlines, run by run
//! ([`outline_text`]); symbol instances as their symbol's art; with Distort Appearance strokes and
-//! geometry effects bend with the art ([`bake_appearance`]); with Distort Pattern Fills the pattern
-//! tiles do.
+//! geometry effects bend with the art ([`bake_appearance`]), except type's strokes, which paint
+//! along its bent outlines at their own weight ([`bake_type_appearance`], #6644); with Distort
+//! Pattern Fills the pattern tiles do.
use std::sync::Arc;
@@ -11,7 +12,7 @@ use vectorcraft_doc::live::{self, Hooks, Outliner};
use vectorcraft_doc::{Document, Node, NodeKind};
use vectorcraft_geom::{Affine, Rect};
-use crate::{bake_appearance, outline_text};
+use crate::{bake_appearance, bake_type_appearance, outline_text};
/// The text outliner live evaluation uses: type as its glyph outlines, one path per run in the
/// run's paint ([`outline_text`]).
@@ -44,7 +45,8 @@ fn with_hooks(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R {
let outline = |n: &Node| outline_object(doc, n);
let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region));
let appearance = |n: &Node| bake_appearance(doc, n);
- f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc })
+ let type_appearance = |n: &Node| bake_type_appearance(doc, n);
+ f(Hooks { outline: Some(&outline), appearance: Some(&appearance), type_appearance: Some(&type_appearance), pattern: Some(&tiles), symbols: doc })
}
/// One level of evaluation of live object `n` ([`live::expand_live_hooks`]).
diff --git a/crates/engine/src/cmd/addons/pen/tests.rs b/crates/engine/src/cmd/addons/pen/tests.rs
index 1bb9f3345e..b314b8db32 100644
--- a/crates/engine/src/cmd/addons/pen/tests.rs
+++ b/crates/engine/src/cmd/addons/pen/tests.rs
@@ -285,3 +285,54 @@ fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() {
assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3);
assert_eq!(steps(&s), n + 8);
}
+
+/// #6634: the tool's closing drag on the first anchor sets that anchor's incoming handle to the
+/// mirror of the pointer and does not give it symmetric handles: a corner keeps its outgoing
+/// handle, a smooth anchor turns it to stay in line at its own length, and Alt pressed mid-drag
+/// keeps it where the drag had turned it.
+#[test]
+fn the_tools_closing_drag_does_not_make_the_first_anchor_symmetric() {
+ // An open path whose first anchor, at (50, 50), has the handles `first`, drawn on from its last
+ // anchor; the closing gesture is then up to the caller.
+ let draw = |first: Value| {
+ let mut s = session();
+ let mut a = json!({"x": 50, "y": 50});
+ a.as_object_mut().unwrap().extend(first.as_object().unwrap().clone());
+ let anchors = json!([a, {"x": 150, "y": 50}, {"x": 150, "y": 150}]);
+ let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap());
+ s.select_tool("smartPen", view()).unwrap();
+ gesture(&mut s, &[(150.0, 150.0)], Mods::default());
+ (s, id)
+ };
+ let first = |s: &Session, id: NodeId| {
+ let sp = &path(s, id).subpaths[0];
+ assert!(sp.closed, "{sp:?}");
+ sp.anchors[0]
+ };
+ let near = |a: Point, b: Point| a.distance(b) < 1e-6;
+
+ // A corner: the first segment keeps its shape.
+ let (mut s, id) = draw(json!({"out": [80, 30]}));
+ gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
+ let a = first(&s, id);
+ assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(50.0, 0.0), Point::new(80.0, 30.0), AnchorKind::Corner), "{a:?}");
+
+ // A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 30.
+ let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
+ assert_eq!(path(&s, id).subpaths[0].anchors[0].kind, AnchorKind::Smooth);
+ gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default());
+ let a = first(&s, id);
+ assert_eq!((a.h_in, a.kind), (Point::new(50.0, 0.0), AnchorKind::Smooth), "{a:?}");
+ assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
+
+ // Alt pressed mid-drag: a corner, its outgoing handle where the drag had turned it.
+ let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]}));
+ let alt = Mods { alt: true, ..Mods::default() };
+ s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), view()).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 50.0, 100.0), view()).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Drag, 80.0, 100.0).with_mods(alt), view()).unwrap();
+ s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 100.0).with_mods(alt), view()).unwrap();
+ let a = first(&s, id);
+ assert_eq!((a.h_in, a.kind), (Point::new(20.0, 0.0), AnchorKind::Corner), "{a:?}");
+ assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}");
+}
diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs
index 8de9dd5c84..300d9f6aa1 100644
--- a/crates/engine/src/cmd/brushlib.rs
+++ b/crates/engine/src/cmd/brushlib.rs
@@ -21,7 +21,7 @@ use super::clipboard::Clipboard;
use super::clipboard::resources::SwatchChoices;
use super::patterncmds::add_pattern;
use super::swatch::str_list;
-use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
+use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem};
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, str_param};
/// The extension of saved brush libraries: native documents.
@@ -462,6 +462,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc
if let Some(found) = s.brush_libraries.get(key) {
return Some(found);
}
+ if let Some(found) = concealed_library_id(s, key).and_then(|id| s.brush_libraries.get(&id)) {
+ return Some(found);
+ }
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
return Some((builtin_info(b), builtin_library(key)?));
}
@@ -476,20 +479,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
fn list(s: &mut Session, _: &Value) -> Result {
s.brush_libraries.rescan();
+ let concealed = concealed_library_ids(s, []);
let libs: Vec = libraries(s)
.into_iter()
.map(|l| {
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
- json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)})
+ let (id, path) = (shown_id(&concealed, &l.id), s.brush_libraries.shown_path(&l.id));
+ json!({"id": id, "name": l.name, "category": l.category, "count": count, "path": path})
})
.collect();
- Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() }))
+ Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.shown_user_dir() }))
}
fn get(s: &mut Session, p: &Value) -> Result {
let (info, lib) = library_param(s, p, "brush.library")?;
let brushes: Vec = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
- Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes}))
+ Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "brushes": brushes}))
}
fn add(s: &mut Session, p: &Value) -> Result {
@@ -545,7 +550,7 @@ fn add(s: &mut Session, p: &Value) -> Result {
}
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
let applied: Vec = paths.iter().map(|id| id.0).collect();
- Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied}))
+ Ok(json!({"library": shown_library_id(s, &info.id), "names": doc_names, "added": added, "existing": existing, "applied": applied}))
}
fn save(s: &mut Session, p: &Value) -> Result {
@@ -571,5 +576,5 @@ fn load(s: &mut Session, p: &Value) -> Result {
}
BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
})?;
- Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
+ Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()}))
}
diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs
index 1677d27f91..b4b231a22b 100644
--- a/crates/engine/src/cmd/brushsym.rs
+++ b/crates/engine/src/cmd/brushsym.rs
@@ -45,7 +45,7 @@ pub(crate) use symbols::{
};
use symbols::{
symbol_adjust, symbol_break_link, symbol_delete, symbol_duplicate, symbol_instance_reset_transform, symbol_list, symbol_new, symbol_options,
- symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_spray, symbol_unused, symbol_update,
+ symbol_place, symbol_replace, symbol_select_instances, symbol_set_current, symbol_sort, symbol_spray, symbol_unused, symbol_update,
};
const SIZES_KEY: &str = vectorcraft_doc::SYMBOL_SIZES;
@@ -312,6 +312,15 @@ pub fn specs() -> Vec {
has_doc,
symbol_unused
),
+ cmd!(
+ "symbol.sortByName",
+ "Sort by Name",
+ ["Window", "Symbols"],
+ None,
+ "{} sort the document's symbols by name, ignoring case (symbols whose names differ only in case keep their order), as one undo step; the current symbol stays current; no undo step is added when they are already in order",
+ has_doc,
+ symbol_sort
+ ),
cmd!(query "symbol.selectInstances", "Select All Instances", [], None, "{name} select every instance of a symbol → {count}", has_doc, symbol_select_instances),
cmd!(
"symbol.spray",
diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs
index 4c5cd89edf..b789f600b4 100644
--- a/crates/engine/src/cmd/brushsym/symbols.rs
+++ b/crates/engine/src/cmd/brushsym/symbols.rs
@@ -140,6 +140,27 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result {
Ok(json!({ "names": names }))
}
+/// `symbol.sortByName`: the symbols in name order, ignoring case; a stable sort, so names that
+/// differ only in case keep their order. The current symbol is stored by name first, so a document
+/// whose current symbol is its first one keeps that symbol current. Nothing is changed, and no undo
+/// step is added, when the symbols are already in order.
+pub(super) fn symbol_sort(s: &mut Session, _: &Value) -> Result {
+ let key = |sym: &Symbol| sym.name.to_lowercase();
+ let d = &s.doc()?.doc;
+ if d.symbols.is_sorted_by_key(key) {
+ return ok();
+ }
+ let current = current_symbol(d).or_else(|| symbol_names(d).into_iter().next());
+ s.edit("Sort by Name", |d, _| {
+ if let Some(name) = current {
+ d.unknown.insert(CURRENT_SYMBOL.into(), json!(name));
+ }
+ d.symbols.sort_by_cached_key(key);
+ Ok(())
+ })?;
+ ok()
+}
+
fn symbol_names(d: &Document) -> Vec {
d.symbols.iter().map(|s| s.name.clone()).collect()
}
diff --git a/crates/engine/src/cmd/colorcmds.rs b/crates/engine/src/cmd/colorcmds.rs
index 65f1056895..bbc56dbc15 100644
--- a/crates/engine/src/cmd/colorcmds.rs
+++ b/crates/engine/src/cmd/colorcmds.rs
@@ -19,8 +19,8 @@ use vectorcraft_doc::{Document, ImageBlob, Node, NodeId, NodeKind};
use super::edit::selected_roots;
use super::{
- CommandSpec, EngineError, Result, Session, always, bad, bool_or, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param,
- str_param, unique_name,
+ CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, f64_req, has_selection, ids_param, switch_or,
+ text_param, unique_name,
};
pub fn specs() -> Vec {
@@ -166,13 +166,15 @@ pub(crate) struct Scope {
}
impl Scope {
- pub(crate) fn of(p: &Value) -> Self {
- Self {
- fill: bool_or(p, "fill", true),
- stroke: bool_or(p, "stroke", true),
- images: bool_or(p, "includeImages", true),
- patterns: bool_or(p, "includePatterns", true),
- }
+ /// The scope `p` gives; each switch left out (or null) is on. A switch that is not true or false,
+ /// such as `"false"`, is an error that names `cmd`.
+ pub(crate) fn of(p: &Value, cmd: &str) -> Result {
+ Ok(Self {
+ fill: switch_or(p, "fill", true, cmd)?,
+ stroke: switch_or(p, "stroke", true, cmd)?,
+ images: switch_or(p, "includeImages", true, cmd)?,
+ patterns: switch_or(p, "includePatterns", true, cmd)?,
+ })
}
}
@@ -414,18 +416,18 @@ impl ColorVisitor for Visit<'_, '_> {
}
pub(crate) fn recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result {
- run_pass(s, p, cmd, label, Recolor::new(Scope::of(p), f))
+ run_pass(s, p, cmd, label, Recolor::new(Scope::of(p, cmd)?, f))
}
/// [`recolor`] where `f` gives gray colors, so embedded images are stored with one gray channel.
fn recolor_gray(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color) -> Result {
- run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p), f) })
+ run_pass(s, p, cmd, label, Recolor { gray_images: true, ..Recolor::new(Scope::of(p, cmd)?, f) })
}
/// [`recolor`] with solid colours and gradient stops mapped through `links`, with their swatch
/// link and tint.
pub(crate) fn recolor_links(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn(Color) -> Color, links: &LinkMap) -> Result {
- run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p), f, links))
+ run_pass(s, p, cmd, label, Recolor::with_links(Scope::of(p, cmd)?, f, links))
}
/// Run `pass` on the `ids` param's objects (default: the selection) as one undo step named `label`;
@@ -548,8 +550,9 @@ fn saturate(s: &mut Session, p: &Value) -> Result {
fn adjust_balance(s: &mut Session, p: &Value) -> Result {
const C: &str = "edit.colors.adjustBalance";
check_numbers(p, &["r", "g", "b", "c", "m", "y", "k", "gray", "tint"], C)?;
+ let convert = switch_or(p, "convert", false, C)?;
let given = |keys: &[&str]| keys.iter().any(|k| p.get(*k).is_some());
- let mode = match str_param(p, "mode") {
+ let mode = match text_param(p, "mode", C)? {
Some(m) => m.to_ascii_lowercase(),
None if given(&["c", "m", "y", "k"]) => "cmyk".into(),
None if given(&["gray"]) => "gray".into(),
@@ -592,11 +595,10 @@ fn adjust_balance(s: &mut Session, p: &Value) -> Result {
(*tint, *c) = (t, base.tinted(t));
true
};
- return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p), &shift));
+ return run_pass(s, p, C, "Adjust Colors", Recolor::links(Scope::of(p, C)?, &shift));
}
other => return Err(bad(C, format!("unknown mode `{other}` (rgb|cmyk|gray|global)"))),
};
- let convert = bool_or(p, "convert", false);
let f = move |c| {
let out = adjust(c);
if convert { out } else { keep_model(c, out) }
@@ -703,7 +705,7 @@ fn blend(s: &mut Session, order: BlendOrder) -> Result {
fn harmony(s: &mut Session, p: &Value) -> Result {
const C: &str = "color.harmony";
let base = p.get("color").and_then(color_value).ok_or_else(|| bad(C, "missing or invalid `color`"))?;
- let rule = str_param(p, "rule").ok_or_else(|| bad(C, "missing `rule`"))?;
+ let rule = text_param(p, "rule", C)?.ok_or_else(|| bad(C, "missing `rule`"))?;
let rule = Harmony::parse(rule).ok_or_else(|| {
let ids: Vec = Harmony::ALL.iter().map(|h| h.id()).collect();
bad(C, format!("unknown rule `{rule}` ({})", ids.join("|")))
@@ -713,7 +715,7 @@ fn harmony(s: &mut Session, p: &Value) -> Result {
if let Some(n) = p.get("steps").and_then(Value::as_u64) {
opts.steps = n.min(u32::MAX as u64) as u32;
}
- if let Some(v) = str_param(p, "variation") {
+ if let Some(v) = text_param(p, "variation", C)? {
opts.variation = Variation::parse(v).ok_or_else(|| bad(C, format!("unknown variation `{v}` (tintsShades|warmCool|vividMuted)")))?;
}
if let Some(a) = p.get("amount").and_then(Value::as_f64) {
diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs
index 973c82af53..f265c3ff3d 100644
--- a/crates/engine/src/cmd/create.rs
+++ b/crates/engine/src/cmd/create.rs
@@ -109,7 +109,7 @@ pub fn specs() -> Vec {
"Create Text",
[],
None,
- "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
+ "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -752,7 +752,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result {
let w = f64_or(a, "width", 200.0);
let h = f64_or(a, "height", 100.0);
t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) };
- t.area.fit = new_area_fit(s, a, "text.create")?;
+ new_area_fit(s, a, "text.create", &mut t)?;
}
t.system_layout = s.doc()?.doc.setup.system_layout;
if bool_or(p, "placeholder", false) {
@@ -827,11 +827,16 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut
Ok(())
}
-/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
-/// them), else Auto Size when the "Auto Size New Area Type" preference is on.
-pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result {
+/// The fit new area type `t` gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes
+/// them, `block` turning Dynamic Text on), else Auto Size when the "Auto Size New Area Type"
+/// preference is on; and Block's `wordGap` and `lineGap`.
+pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) -> Result<()> {
let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None };
- Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default))
+ let (word_gap, line_gap) = super::typecmd::block_gaps(p, c)?;
+ (t.area.fit, t.dynamic_text) = super::typecmd::fit_param(p, default, false, c)?.unwrap_or((default, false));
+ t.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
+ t.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
+ Ok(())
}
/// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB
diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs
index cb1bb86fbd..7499e14943 100644
--- a/crates/engine/src/cmd/docinfo.rs
+++ b/crates/engine/src/cmd/docinfo.rs
@@ -18,7 +18,7 @@ pub fn specs() -> Vec {
"Document Info",
["Window", "Document Info"],
None,
- "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
+ "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
has_doc,
info
),
@@ -42,7 +42,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [
("brushes", "Brushes"),
("spotColors", "Spot Colors"),
("patterns", "Pattern Objects"),
- ("gradients", "Gradient Swatches"),
+ ("gradients", "Gradient Objects"),
("symbols", "Symbols"),
("fonts", "Fonts"),
("fontDetails", "Font Details"),
@@ -131,7 +131,8 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S
/// The Document Info categories of `d` (only `category` when given) from `info` (what
/// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the
-/// rows of its objects filled or stroked with a pattern.
+/// rows of its objects filled or stroked with a pattern and with a gradient.
+#[allow(clippy::too_many_arguments)]
fn sections(
d: &Document,
info: &Value,
@@ -139,6 +140,7 @@ fn sections(
images: &[ImageRow],
repeats: &[(String, String)],
pattern_objects: &[(String, String)],
+ gradient_objects: &[(String, String)],
category: Option<&str>,
) -> Vec {
let names = |k: &str| -> Vec<(String, String)> {
@@ -183,7 +185,7 @@ fn sections(
"brushes" => names("brushNames"),
"spotColors" => names("spotColors"),
"patterns" => pattern_objects.to_vec(),
- "gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(),
+ "gradients" => gradient_objects.to_vec(),
"symbols" => names("symbols"),
"fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(),
"fontDetails" => {
@@ -254,19 +256,37 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result {
Ok(v["text"].as_str().unwrap_or_default().to_string())
}
-/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a
-/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and
-/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the
-/// type object's own fills and strokes paint on its characters, so only those runs paint. The type
-/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out.
+/// The pattern paint `p` uses: the pattern's name.
+fn pattern_label(p: &Paint) -> Option {
+ match p {
+ Paint::Pattern { pattern, .. } => Some(pattern.clone()),
+ _ => None,
+ }
+}
+
+/// The gradient paint `p` uses: the name of the gradient swatch it is linked to, else its kind
+/// ("Linear gradient", "Radial gradient" or "Freeform gradient").
+fn gradient_label(p: &Paint) -> Option {
+ match p {
+ Paint::Gradient(g) => Some(g.swatch.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("{} gradient", g.gradient.kind.label()))),
+ _ => None,
+ }
+}
+
+/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient:
+/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough
+/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and
+/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs
+/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the
+/// renderer lays it out.
fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet)> {
let NodeKind::Text(t) = &n.kind else { return None };
- let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. });
+ let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_));
let own = n.appearance.items.iter().any(|i| match i {
- vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint),
- vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint),
+ vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint),
+ vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint),
});
- if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) {
+ if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) {
return None;
}
let db = vectorcraft_text::FontDb::global();
@@ -277,42 +297,38 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T
Some((t, painted))
}
-/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke
-/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide
-/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint
-/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint
-/// only where an effect gives them a shape.
-fn own_patterns<'a>(
+/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own
+/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint
+/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound
+/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose
+/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect
+/// gives them a shape.
+fn own_paints(
d: &Document,
- n: &'a Node,
+ n: &Node,
members: &HashSet<*const Node>,
painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet)>,
-) -> Vec<&'a str> {
+ label: fn(&Paint) -> Option,
+) -> Vec {
if matches!(n.kind, NodeKind::Path { guide: true, .. })
|| members.contains(&std::ptr::from_ref(n))
|| painted_runs.is_some_and(|(_, r)| r.is_empty())
+ || !n.appearance.items.iter().any(|i| label(i.paint()).is_some())
{
return vec![];
}
- // The patterns an image's shaped fills and strokes paint (their effects can transform the
- // pattern, so they are matched by name).
- let shaped: Option> = matches!(n.kind, NodeKind::Image(_)).then(|| {
- vectorcraft_render::effects::image_paint(Some(d), n)
- .into_iter()
- .filter_map(|(_, _, item)| match item.paint() {
- Paint::Pattern { pattern, .. } => Some(pattern.clone()),
- _ => None,
- })
- .collect()
- });
- let mut out: Vec<&str> = vec![];
+ // The patterns or gradients an image's shaped fills and strokes paint (their effects can
+ // transform the paint, so they are matched by label).
+ let shaped: Option> = matches!(n.kind, NodeKind::Image(_))
+ .then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect());
+ let mut out: Vec = vec![];
for item in &n.appearance.items {
- let Paint::Pattern { pattern, .. } = item.paint() else { continue };
+ let Some(name) = label(item.paint()) else { continue };
let paints = item.visible()
&& !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0)
- && shaped.as_ref().is_none_or(|s| s.contains(pattern));
- if paints && !out.contains(&pattern.as_str()) {
- out.push(pattern);
+ && shaped.as_ref().is_none_or(|s| s.contains(&name));
+ if paints && !out.contains(&name) {
+ out.push(name);
}
}
out
@@ -354,6 +370,11 @@ fn info(s: &mut Session, p: &Value) -> Result {
// `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order.
let mut pattern_objects: Vec = vec![];
let mut pattern_rows: Vec<(String, String)> = vec![];
+ // `gradient_objects`, `gradient_rows` and `gradients` hold the `gradientObjects` entries, the rows of the objects filled or stroked
+ // with a gradient, in walk order, and the gradients they use.
+ let mut gradient_objects: Vec = vec![];
+ let mut gradient_rows: Vec<(String, String)> = vec![];
+ let mut gradients = BTreeSet::new();
// The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once.
// The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two.
let mut seen: HashSet<*const Node> = HashSet::new();
@@ -412,27 +433,17 @@ fn info(s: &mut Session, p: &Value) -> Result {
if let Some(k) = k {
*counts.entry(k).or_default() += 1;
}
- // The paint kinds this object's fills and strokes use, each once.
- let mut kinds = BTreeSet::new();
- // The patterns this object's fills and strokes use, each once.
- let mut used_patterns: Vec<&str> = vec![];
- let painted_runs = painted_runs(d, n);
- for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) {
- patterns.insert(pattern.to_string());
- used_patterns.push(pattern);
- }
for item in &n.appearance.items {
- let paint = item.paint();
- // Objects counts an object with a pattern when Pattern Objects lists it, below.
- if let Paint::Gradient(_) = paint {
- kinds.insert("gradients");
- }
- if let Paint::Solid { swatch: Some(name), .. } = paint
+ if let Paint::Solid { swatch: Some(name), .. } = item.paint()
&& d.swatch(name).is_some_and(|s| s.spot)
{
spot.insert(name.clone());
}
}
+ // The patterns and the gradients this object's fills and strokes paint, each once.
+ let painted_runs = painted_runs(d, n);
+ let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label);
+ let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label);
// The characters' own paints: an inline graphic draws no outline and does not take its
// run's paint (a list marker set in its run does), and a stroke with no width paints
// nothing.
@@ -440,23 +451,32 @@ fn info(s: &mut Session, p: &Value) -> Result {
for run in painted.iter().filter_map(|i| t.runs.get(*i)) {
let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke);
for paint in std::iter::once(&run.style.fill).chain(stroke) {
- if let Paint::Pattern { pattern, .. } = paint {
- patterns.insert(pattern.clone());
- if !used_patterns.contains(&pattern.as_str()) {
- used_patterns.push(pattern);
+ for (used, label) in
+ [(&mut used_patterns, pattern_label as fn(&Paint) -> Option), (&mut used_gradients, gradient_label)]
+ {
+ if let Some(name) = label(paint)
+ && !used.contains(&name)
+ {
+ used.push(name);
}
}
}
}
}
+ // Objects counts the objects that Pattern Objects and Gradient Objects list.
if !used_patterns.is_empty() {
let name = n.display_name();
+ patterns.extend(used_patterns.iter().cloned());
+ pattern_rows.push((name.clone(), used_patterns.join(", ")));
pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns }));
- pattern_rows.push((name, used_patterns.join(", ")));
- kinds.insert("patterns");
+ *counts.entry("patterns").or_default() += 1;
}
- for k in kinds {
- *counts.entry(k).or_default() += 1;
+ if !used_gradients.is_empty() {
+ let name = n.display_name();
+ gradients.extend(used_gradients.iter().cloned());
+ gradient_rows.push((name.clone(), used_gradients.join(", ")));
+ gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients }));
+ *counts.entry("gradients").or_default() += 1;
}
if n.extras().mask.is_some() {
*counts.entry("opacityMasks").or_default() += 1;
@@ -506,10 +526,12 @@ fn info(s: &mut Session, p: &Value) -> Result {
"patterns": d.patterns.len(),
"patternNames": patterns,
"patternObjects": pattern_objects,
+ "gradientNames": gradients,
+ "gradientObjects": gradient_objects,
});
// The document's name: its file's, else its title.
out["document"]["name"] = json!(st.title());
- let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category);
+ let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category);
if text {
return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) }));
}
@@ -583,12 +605,14 @@ mod tests {
&json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
)
.unwrap();
- s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap();
+ let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone();
let i = s.execute("document.info", &json!({})).unwrap();
+ // The type's characters take the current gradient fill, so it is a gradient object too.
assert_eq!(
(i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()),
- (Some(1), Some(1), Some(1))
+ (Some(1), Some(1), Some(2))
);
+ assert_eq!((i["gradientObjects"][0]["id"].clone(), i["gradientObjects"][1]["id"].clone()), (r.clone(), t));
assert_eq!(i["fonts"][0], "Source Sans 3 Regular");
assert_eq!(i["document"]["artboards"][0]["width"], 200.0);
s.execute("select.set", &json!({"ids": [r]})).unwrap();
@@ -842,6 +866,124 @@ mod tests {
assert!(!text.contains("Unused"), "{text}");
}
+ /// Document Info › Gradient Objects lists each object filled or stroked with a gradient once,
+ /// with the gradients it uses (a linked swatch by name, else the gradient's kind), one in a
+ /// group and a type object whose characters use a gradient included; a gradient swatch no art
+ /// uses adds no row, paint that draws nothing is left out by the rules Pattern Objects follows,
+ /// and Objects counts the listed objects. With Selection Only it lists the objects in the
+ /// selection, each once, and the report writes the same rows.
+ #[test]
+ fn info_lists_the_gradient_objects() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
+ let square =
+ |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
+ let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
+ s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp("linear")})).unwrap();
+ s.execute("swatch.new", &json!({"name": "Spare", "gradient": ramp("radial")})).unwrap();
+ let (a, b, c, f) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0), square(&mut s, 0.0));
+ s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ramp"})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [a], "gradient": ramp("linear")})).unwrap();
+ s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [b], "gradient": ramp("radial")})).unwrap();
+ s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("freeform")})).unwrap();
+ s.execute("select.set", &json!({"ids": [b, c]})).unwrap();
+ let group = s.execute("object.group", &json!({})).unwrap()["id"].clone();
+ // A type object whose characters are filled with the gradient.
+ let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone();
+ s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ramp"})).unwrap();
+ s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap();
+ // A hidden gradient fill and a gradient stroke with no width paint nothing, so neither object is listed.
+ let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0));
+ s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap();
+ s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ramp"})).unwrap();
+ s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap();
+ s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [e], "gradient": ramp("linear")})).unwrap();
+ s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap();
+ // Type with no characters, or of only spaces and a line break, paints nothing, and neither
+ // does a guide made from a path with a gradient.
+ let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone();
+ s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ramp"})).unwrap();
+ s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap();
+ let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone();
+ s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ramp"})).unwrap();
+ let guide = square(&mut s, 300.0);
+ s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ramp"})).unwrap();
+ s.execute("select.set", &json!({"ids": [guide]})).unwrap();
+ s.execute("view.guides.make", &json!({})).unwrap();
+ // Nor does a compound path's member's own gradient fill, or an image's gradient fill
+ // without an effect that gives it a shape.
+ let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0));
+ s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
+ let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone();
+ s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap();
+ s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap();
+ let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone();
+ let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance);
+ let pic = square(&mut s, 360.0);
+ s.execute("select.set", &json!({"ids": [pic]})).unwrap();
+ s.execute("object.rasterize", &json!({"ppi": 72})).unwrap();
+ let image = s.doc().unwrap().selection.objects[0];
+ s.edit("own paint", |d, _| {
+ d.node_mut(member).unwrap().appearance = paint.clone();
+ d.node_mut(image).unwrap().appearance = paint;
+ Ok(())
+ })
+ .unwrap();
+ // Underlined spaces draw a bar in the gradient, so that type object is listed.
+ let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone();
+ s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Ramp"})).unwrap();
+ s.execute("select.set", &json!({"ids": [bar]})).unwrap();
+ s.execute("text.setFormat", &json!({"underline": true})).unwrap();
+ s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap();
+ let i = s.execute("document.info", &json!({})).unwrap();
+ assert_eq!(
+ i["gradientObjects"],
+ json!([
+ {"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]},
+ {"id": b, "name": "", "gradients": ["Radial gradient"]},
+ {"id": f, "name": "", "gradients": ["Freeform gradient"]},
+ {"id": t, "name": "Type", "gradients": ["Ramp"]},
+ {"id": bar, "name": "Bar", "gradients": ["Ramp"]},
+ ])
+ );
+ assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"]));
+ // Objects counts the objects that Gradient Objects lists.
+ assert_eq!(i["objects"]["gradients"].as_u64(), Some(5), "{}", i["objects"]);
+ s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap();
+ let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap();
+ assert!(i["objects"]["gradients"].is_null() && i["gradientObjects"] == json!([]), "{}", i["objects"]);
+ let i = s.execute("document.info", &json!({"category": "gradients"})).unwrap();
+ assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("gradients"), Some("Gradient Objects")));
+ assert_eq!(
+ i["sections"][0]["rows"],
+ json!([
+ ["Both", "Ramp, Linear gradient"],
+ ["", "Radial gradient"],
+ ["", "Freeform gradient"],
+ ["Type", "Ramp"],
+ ["Bar", "Ramp"]
+ ])
+ );
+ // A selection that holds the group and the object inside it lists that object once.
+ for ids in [json!([group, b]), json!([b, group])] {
+ s.execute("select.set", &json!({"ids": ids})).unwrap();
+ let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
+ assert_eq!(i["sections"][0]["rows"], json!([["", "Radial gradient"]]), "{ids}");
+ assert_eq!(i["objects"]["gradients"].as_u64(), Some(1), "{ids}");
+ }
+ s.execute("select.set", &json!({"ids": [t]})).unwrap();
+ let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap();
+ assert_eq!((i["sections"][0]["rows"].clone(), i["gradientNames"].clone()), (json!([["Type", "Ramp"]]), json!(["Ramp"])));
+ let text = s.execute("document.info", &json!({"category": "gradients", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string();
+ assert!(
+ text.contains("\nGRADIENT OBJECTS\nBoth: Ramp, Linear gradient\n: Radial gradient\n: Freeform gradient\nType: Ramp\nBar: Ramp\n"),
+ "{text}"
+ );
+ assert!(!text.contains("Spare"), "{text}");
+ }
+
/// Document Info › Objects counts an object with a gradient or a pattern on both its fill and
/// its stroke once, and with Selection Only a selection that holds a group and an object inside
/// it counts that object once.
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index 7a8a91f0af..26d0f4d247 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -184,7 +184,7 @@ pub fn specs() -> Vec {
"Paste in Front",
["Edit"],
Some("Cmd+F"),
- "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
+ "{swatchConflict?, artboard?: index (the active artboard: the objects go where they were on the artboard they were copied from, on this one), artboards?: [index…] (a copy on each of these artboards, placed as on `artboard`, the copies in artboard order; `artboard` wins when both are given; default while the Artboard tool is chosen with several artboards selected: those; art copied from no artboard keeps its place on the first and its offset to it on the others; an index the document lacks, a repeated one or an empty list is an error)} paste in place just above the top selected object, or on top of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Front)
),
@@ -193,7 +193,7 @@ pub fn specs() -> Vec {
"Paste in Back",
["Edit"],
Some("Cmd+B"),
- "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
+ "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste in place just below the bottom selected object, or at the bottom of the current layer when nothing is selected (resources and layers as edit.paste) → {ids, added, merged, renamed}",
has_clipboard,
|s, p| paste(s, p, PasteMode::Back)
),
@@ -202,7 +202,7 @@ pub fn specs() -> Vec {
"Paste in Place",
["Edit"],
Some("Cmd+Shift+V"),
- "{swatchConflict?, artboard?: index (as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
+ "{swatchConflict?, artboard?: index, artboards?: [index…] (both as edit.pasteInFront)} paste where the objects were copied (resources, layers and drawing modes as edit.paste) → {ids, added, merged, renamed}",
has_clipboard,
|s, p| paste(s, p, PasteMode::InPlace)
),
@@ -1246,15 +1246,79 @@ pub(crate) fn place_clip(s: &mut Session, clip: &Clipboard, center: vectorcraft_
paste_clip(s, &json!({ "center": [center.x, center.y] }), PasteMode::Library, clip, &choices)
}
-/// Paste in Place, in Front or in Back onto artboard `artboard` (the active one, #693): where the
-/// objects were on the artboard they were copied from, on that one; without it (or a copy from no
-/// artboard), where they were.
-fn onto_artboard(doc: &Document, p: &Value, clip: &Clipboard) -> Affine {
- let target = p.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).and_then(|i| doc.artboards.get(i));
- match (target, clip.source_artboard) {
- (Some(t), Some(src)) => Affine::translate(t.rect.origin() - src.origin()),
- _ => Affine::IDENTITY,
+/// The artboards Paste in Place, in Front or in Back puts a copy on, in artboard order: `artboard`
+/// (the active one, #693), else `artboards`, else, while the Artboard tool is chosen with several
+/// artboards selected, those (noted in the journal as `artboards`, so a replay pastes on the same
+/// ones); `None` when none is named. A named index that is not an artboard of the document, a
+/// repeated one or an empty list is an error.
+fn paste_targets(s: &mut Session, p: &Value, cmd: &str) -> Result