mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 01:10:54 +01:00
Merge remote-tracking branch 'origin/main' into fix/5111-kern-paragraph-start
# Conflicts: # docs/target-app-parity.md # docs/type-parity.md
This commit is contained in:
commit
46e8f576cc
228 files changed
+9967
-1039
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 | |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><defs><clipPath id="c"><rect x="3.5" y="3.5" width="17" height="17"/></clipPath></defs><g clip-path="url(#c)" stroke="none" fill="white"><path d="M12 12L26 12L21.9 21.9Z" fill-opacity="0.1"/><path d="M12 12L21.9 21.9L12 26Z" fill-opacity="0.23"/><path d="M12 12L12 26L2.1 21.9Z" fill-opacity="0.36"/><path d="M12 12L2.1 21.9L-2 12Z" fill-opacity="0.49"/><path d="M12 12L-2 12L2.1 2.1Z" fill-opacity="0.61"/><path d="M12 12L2.1 2.1L12 -2Z" fill-opacity="0.74"/><path d="M12 12L12 -2L21.9 2.1Z" fill-opacity="0.87"/><path d="M12 12L21.9 2.1L26 12Z"/></g><rect x="3.5" y="3.5" width="17" height="17" stroke="currentColor" stroke-width="1"/></svg>
|
||||
|
After Width: | Height: | Size: 826 B |
@@ -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
|
||||
|
||||
+118
-10
@@ -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<Self> {
|
||||
[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<Affine> {
|
||||
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<Point>, 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<Item = [u8; 4]> + 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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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<String> =
|
||||
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(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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| {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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<PatternTiles<'a>>,
|
||||
/// 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<Node>], 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)
|
||||
{
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<ParaStyle> {
|
||||
(0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect()
|
||||
|
||||
@@ -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<Node> {
|
||||
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<Node> {
|
||||
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<Node> {
|
||||
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<Node> {
|
||||
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<Node> {
|
||||
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<Node> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<R>(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`]).
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
@@ -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<BrushLibrary>
|
||||
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<Value> {
|
||||
s.brush_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = 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<Value> {
|
||||
let (info, lib) = library_param(s, p, "brush.library")?;
|
||||
let brushes: Vec<Value> = 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<Value> {
|
||||
@@ -545,7 +550,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
|
||||
let applied: Vec<u64> = 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<Value> {
|
||||
@@ -571,5 +576,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
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()}))
|
||||
}
|
||||
@@ -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<CommandSpec> {
|
||||
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",
|
||||
|
||||
@@ -140,6 +140,27 @@ pub(super) fn symbol_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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<String> {
|
||||
d.symbols.iter().map(|s| s.name.clone()).collect()
|
||||
}
|
||||
|
||||
@@ -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<CommandSpec> {
|
||||
@@ -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<Self> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
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<Value> {
|
||||
fn adjust_balance(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
(*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<Value> {
|
||||
fn harmony(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<String> = 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<Value> {
|
||||
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) {
|
||||
|
||||
@@ -109,7 +109,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Value> {
|
||||
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<vectorcraft_doc::AreaFit> {
|
||||
/// 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
|
||||
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<Section> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<usize>)> {
|
||||
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<usize>)>,
|
||||
) -> Vec<&'a str> {
|
||||
label: fn(&Paint) -> Option<String>,
|
||||
) -> Vec<String> {
|
||||
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<Vec<String>> = 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<Vec<String>> = 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<String> = 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<Value> {
|
||||
// `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<Value> = 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<Value> = 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<Value> {
|
||||
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<Value> {
|
||||
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<String>), (&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<Value> {
|
||||
"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": "<Rectangle>", "gradients": ["Radial gradient"]},
|
||||
{"id": f, "name": "<Rectangle>", "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"],
|
||||
["<Rectangle>", "Radial gradient"],
|
||||
["<Rectangle>", "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!([["<Rectangle>", "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<Rectangle>: Radial gradient\n<Rectangle>: 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.
|
||||
|
||||
@@ -184,7 +184,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<Option<Vec<usize>>> {
|
||||
let n = s.doc()?.doc.artboards.len();
|
||||
let one = |v: &Value| v.as_u64().and_then(|i| usize::try_from(i).ok()).filter(|i| *i < n);
|
||||
let single = match p.get("artboard") {
|
||||
Some(v) => Some(one(v).ok_or_else(|| bad(cmd, "`artboard` must be the index of an artboard of the document"))?),
|
||||
None => None,
|
||||
};
|
||||
let listed = match p.get("artboards") {
|
||||
Some(v) => {
|
||||
let list = v.as_array().filter(|a| !a.is_empty()).ok_or_else(|| bad(cmd, "`artboards` must be a list of artboard indices"))?;
|
||||
let mut all = list
|
||||
.iter()
|
||||
.map(one)
|
||||
.collect::<Option<Vec<usize>>>()
|
||||
.ok_or_else(|| bad(cmd, "`artboards` names an artboard the document does not have"))?;
|
||||
all.sort_unstable();
|
||||
if all.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err(bad(cmd, "`artboards` names an artboard twice"));
|
||||
}
|
||||
Some(all)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if let Some(i) = single {
|
||||
return Ok(Some(vec![i]));
|
||||
}
|
||||
if listed.is_some() {
|
||||
return Ok(listed);
|
||||
}
|
||||
let picked = artboard_tool_picks(s);
|
||||
if picked.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
s.note_journal("artboards", json!(picked));
|
||||
Ok(Some(picked))
|
||||
}
|
||||
|
||||
/// The artboards of the active document the Artboard tool has selected, in artboard order, while
|
||||
/// that tool is chosen with two or more of them selected; otherwise none. Indices the document
|
||||
/// does not have are left out.
|
||||
pub(crate) fn artboard_tool_picks(s: &Session) -> Vec<usize> {
|
||||
if s.tool_id() != "artboard" {
|
||||
return Vec::new();
|
||||
}
|
||||
let n = s.active().map_or(0, |d| d.doc.artboards.len());
|
||||
let mut picked: Vec<usize> = s.tool_options_of("artboard")["selected"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_u64().and_then(|i| usize::try_from(i).ok()))
|
||||
.filter(|i| *i < n)
|
||||
.collect();
|
||||
picked.sort_unstable();
|
||||
picked.dedup();
|
||||
if picked.len() < 2 {
|
||||
picked.clear();
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front or in Back onto artboards `targets`: one copy on each, where the objects
|
||||
/// were on the artboard they were copied from. A copy from no artboard keeps its place on the first
|
||||
/// target and its offset to that one on the others; without targets, the objects go where they were.
|
||||
fn onto_artboards(doc: &Document, targets: Option<&[usize]>, clip: &Clipboard) -> Vec<Affine> {
|
||||
let rects: Vec<_> = targets.unwrap_or_default().iter().filter_map(|i| doc.artboards.get(*i)).map(|a| a.rect.origin()).collect();
|
||||
let Some(first) = rects.first().copied() else { return vec![Affine::IDENTITY] };
|
||||
let src = clip.source_artboard.map_or(first, |r| r.origin());
|
||||
rects.iter().map(|o| Affine::translate(*o - src)).collect()
|
||||
}
|
||||
|
||||
/// Insert clipboard resources atomically in the active editable context using the requested placement mode.
|
||||
@@ -1268,6 +1332,12 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let targets = match mode {
|
||||
PasteMode::Front => paste_targets(s, p, "edit.pasteInFront")?,
|
||||
PasteMode::Back => paste_targets(s, p, "edit.pasteInBack")?,
|
||||
PasteMode::InPlace => paste_targets(s, p, "edit.pasteInPlace")?,
|
||||
_ => None,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
let same_doc = clip.source_doc == Some(st.uid);
|
||||
let parent = st.target_parent_for_path()?;
|
||||
@@ -1321,8 +1391,9 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho
|
||||
let src = clip.source_artboard.or_else(|| st.doc.artboards.first().map(|a| a.rect)).map(|r| r.origin()).unwrap_or_default();
|
||||
st.doc.artboards.iter().map(|a| Affine::translate(a.rect.origin() - src)).collect()
|
||||
}
|
||||
// In place, in front, in back: onto the active artboard when the UI names it.
|
||||
_ => vec![onto_artboard(&st.doc, p, clip)],
|
||||
// In place, in front, in back: onto the active artboard when the UI names it, or onto each
|
||||
// artboard the Artboard tool has selected.
|
||||
_ => onto_artboards(&st.doc, targets.as_deref(), clip),
|
||||
};
|
||||
// Guides alone don't follow a plain paste's offset or the view centre: they stay where they
|
||||
// were. With objects they move as the objects do.
|
||||
|
||||
@@ -36,6 +36,9 @@ pub const MAX_STEPS: u32 = 1000;
|
||||
const FREEFORM_MESH: u32 = 8;
|
||||
/// Columns (around the centre) of the mesh a radial gradient expands to.
|
||||
const RADIAL_MESH_COLS: usize = 8;
|
||||
/// Largest turn between a conic gradient's mesh columns, so their straight outer edges stay
|
||||
/// close enough to a circle to reach past the box.
|
||||
const CONIC_MESH_GAP: f64 = 1.0 / 32.0;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -44,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Expand…",
|
||||
["Object"],
|
||||
None,
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
"{object?: true (symbol instances without effects (their fills' and strokes' included) and not in perspective → their art, as Break Link to Symbol places it (the instances that art holds stay instances), type → outlines, live shapes → paths, effects baked, blends → groups of their steps, repeats → groups of their instances, Intertwine groups → groups of their objects and of the parts drawn over the others (clip groups), envelopes → their distorted content, placed documents → editable copies of their art, as placing the file without link gives, its symbols, patterns, swatches and images joining the document), fill?: true (gradient fills → `gradient` art, pattern fills → their tiles in a clip group shaped like the object), stroke?: true (strokes → filled outlines, the stroked paths that baking effects leaves included), gradient?: \"objects\" (default: `steps` solid strips, concentric ellipses for radial gradients, wedges around the center for conic ones) | \"mesh\" (a gradient mesh); both in a clip group shaped like the object (freeform gradients always become a mesh shaped like it), steps?: 1..1000 (255)} one undo step; a dimension whose art an option changes becomes a plain group of its art, except one selected with art it measures, directly or in groups without fills, strokes or effects of their own: its lines and label stay as they are, and if the new art no longer fits its link it stays where it was, no longer linked → {ids}",
|
||||
has_selection,
|
||||
expand
|
||||
),
|
||||
@@ -1279,7 +1282,10 @@ fn breaks(g: &Gradient, t0: f64, t1: f64, max_gap: f64) -> Vec<(f64, (Color, f32
|
||||
/// end, the vector across it (radial: the ellipse's other axis), and the parameter ranges that
|
||||
/// cover the box (linear: along the vector `t0..t1` and across it `s0..s1` in points; radial:
|
||||
/// `0..t1`, each level's ellipse centred on the way from the focal point to the start).
|
||||
/// A conic gradient also has its placement, the box and the radius in its frame that reaches
|
||||
/// past the box's corners ([`Frame::pieces`] and [`Frame::mesh`] go around its center).
|
||||
struct Frame {
|
||||
conic: Option<(vectorcraft_color::GradientGeom, Rect, f64)>,
|
||||
radial: bool,
|
||||
start: Point,
|
||||
focal: Point,
|
||||
@@ -1309,7 +1315,15 @@ impl Frame {
|
||||
}
|
||||
// Keep a sliver of span so the art maps back invertibly.
|
||||
t1 = t1.max(t0 + 1e-6);
|
||||
Self { radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
|
||||
let conic = (g.gradient.kind == GradientKind::Conic).then(|| {
|
||||
let to_unit = geom.conic_frame().inverse();
|
||||
let reach = corners.iter().map(|c| (to_unit * *c).to_vec2().hypot()).fold(0.0f64, f64::max).max(1e-6);
|
||||
// Past the corners, and far enough out that the chords between columns at most
|
||||
// CONIC_MESH_GAP of a turn apart stay outside them.
|
||||
let reach = if reach.is_finite() { reach * 1.01 / (std::f64::consts::PI * CONIC_MESH_GAP).cos() } else { 1.0 };
|
||||
(geom, bounds, reach)
|
||||
});
|
||||
Self { conic, radial, start: geom.start, focal: geom.focal_point(), along, across, t0, t1, s0, s1 }
|
||||
}
|
||||
|
||||
/// Linear: the point at parameter `t` along and `s` across. Radial: the point at parameter `t`
|
||||
@@ -1325,6 +1339,18 @@ impl Frame {
|
||||
/// A gradient mesh covering the box: columns (linear) or rings (radial) where the colour
|
||||
/// changes, so it paints the gradient exactly.
|
||||
fn mesh(&self, g: &Gradient) -> GradientMesh {
|
||||
if let Some((geom, _, reach)) = &self.conic {
|
||||
// Columns around the center where the color changes, at most CONIC_MESH_GAP of a turn
|
||||
// apart so the outer edge stays past the box; the seam is two columns in one place.
|
||||
let br = breaks(g, 0.0, 1.0, CONIC_MESH_GAP);
|
||||
let us: Vec<f64> = br.iter().map(|(t, _)| *t).collect();
|
||||
let frame = geom.conic_frame();
|
||||
let at = |u: f64, v: f64| {
|
||||
let a = u * std::f64::consts::TAU;
|
||||
frame * Point::new(reach * v * a.cos(), reach * v * a.sin())
|
||||
};
|
||||
return GradientMesh::from_grid(&us, &[0.0, 1.0], &at, &|_, c, _| br[c].1);
|
||||
}
|
||||
// Rings as close as the columns around them, so the mesh draws smoothly.
|
||||
let gap = if self.radial { (self.t1 - self.t0) / RADIAL_MESH_COLS as f64 } else { f64::INFINITY };
|
||||
let br = breaks(g, self.t0, self.t1, gap);
|
||||
@@ -1340,13 +1366,21 @@ impl Frame {
|
||||
|
||||
/// `n` solid shapes covering the box in paint order, each coloured as the gradient in the
|
||||
/// middle of its band: for a linear gradient, rectangles from each band's start to the far
|
||||
/// end, for a radial one, nested ellipses (largest first). Each paints over the ones
|
||||
/// below except its band, so no seam shows between bands. With translucent stops each shape
|
||||
/// is just its band, so nothing doubles up.
|
||||
/// end, for a radial one, nested ellipses (largest first), for a conic one, wedges around the
|
||||
/// center from each band's start to the seam. Each paints over the ones below except its
|
||||
/// band, so no seam shows between bands. With translucent stops each shape is just its band,
|
||||
/// so nothing doubles up.
|
||||
fn pieces(&self, g: &Gradient, n: usize) -> Vec<(PathData, (Color, f32))> {
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if let Some((geom, b, _)) = &self.conic {
|
||||
return geom
|
||||
.conic_wedges(*b, n, opaque)
|
||||
.into_iter()
|
||||
.map(|(pts, t)| (PathData::single(SubPath::polyline(&pts, true)), g.sample_keep_model(t as f32)))
|
||||
.collect();
|
||||
}
|
||||
let step = (self.t1 - self.t0) / n as f64;
|
||||
let color = |k: usize| g.sample_keep_model((self.t0 + (k as f64 + 0.5) * step) as f32);
|
||||
let opaque = g.stops.iter().all(|s| s.opacity >= 1.0);
|
||||
if self.radial {
|
||||
let ellipse = |t: f64| {
|
||||
let c = self.focal + (self.start - self.focal) * t;
|
||||
|
||||
@@ -716,6 +716,11 @@ fn collect_files(folder: &str, include_subdirs: bool, depth: usize) -> Result<Ve
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
// Names that are not valid text come back lossily, so different names can give one path: each
|
||||
// folder is listed once.
|
||||
files.dedup();
|
||||
subdirs.sort();
|
||||
subdirs.dedup();
|
||||
for sub in subdirs {
|
||||
let mut nested = collect_files(&sub, true, depth + 1)?;
|
||||
files.append(&mut nested);
|
||||
@@ -749,6 +754,22 @@ mod tests {
|
||||
d
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn folders_whose_names_alias_after_lossy_conversion_are_listed_once() {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
let root = tmp("alias");
|
||||
// `a\u{FFFD}` is a real folder; two others with bytes that aren't text give the same name.
|
||||
let real = root.join("a\u{FFFD}");
|
||||
std::fs::create_dir_all(&real).unwrap();
|
||||
write_svg(&real, "x.svg", "red");
|
||||
for bad in [b"a\xFF", b"a\xFE"] {
|
||||
let _ = std::fs::create_dir_all(root.join(std::ffi::OsStr::from_bytes(bad)));
|
||||
}
|
||||
let files = collect_files(&root.to_string_lossy(), true, 0).unwrap();
|
||||
assert_eq!(files.len(), 1, "{files:?}");
|
||||
}
|
||||
|
||||
fn write_svg(dir: &std::path::Path, name: &str, fill: &str) -> std::path::PathBuf {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(
|
||||
|
||||
@@ -188,17 +188,24 @@ impl Builder {
|
||||
let kind = match g.kind {
|
||||
AfKind::Linear => GradientKind::Linear,
|
||||
AfKind::Radial => GradientKind::Radial,
|
||||
AfKind::Conical => {
|
||||
self.warn("conical gradients import as radial gradients");
|
||||
GradientKind::Radial
|
||||
}
|
||||
AfKind::Conical => GradientKind::Conic,
|
||||
};
|
||||
let (u, v): (Vec2, Vec2) = (x - o, y - o);
|
||||
if kind == GradientKind::Radial && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
if kind.is_centered() && u.hypot() > 0.0 && (u.dot(v) / (u.hypot() * v.hypot().max(1e-12))).abs() > 0.01 {
|
||||
self.warn("skewed elliptical gradients import as upright ellipses");
|
||||
}
|
||||
let aspect = if u.hypot() > 0.0 { (v.hypot() / u.hypot()).clamp(0.01, 100.0) } else { 1.0 };
|
||||
let geom = GradientGeom { start: o, end: x, aspect: if kind == GradientKind::Radial { aspect } else { 1.0 }, focal: None };
|
||||
let geom = match kind {
|
||||
// A conic sweeps from unit +x towards unit +y: its unit frame carried onto the
|
||||
// page as a transform carries it (mirrored when the transform is a reflection).
|
||||
GradientKind::Conic => {
|
||||
let mut geom = GradientGeom { start: Point::ZERO, end: Point::new(1.0, 0.0), aspect: 1.0, focal: None };
|
||||
geom.transform(m, GradientKind::Conic);
|
||||
geom
|
||||
}
|
||||
GradientKind::Radial => GradientGeom { start: o, end: x, aspect, focal: None },
|
||||
_ => GradientGeom { start: o, end: x, aspect: 1.0, focal: None },
|
||||
};
|
||||
let mut gp = GradientPaint::new(Gradient::new(kind, stops));
|
||||
gp.angle = (-(u.y)).atan2(u.x).to_degrees();
|
||||
gp.geom = Some(geom);
|
||||
|
||||
@@ -76,7 +76,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// starts (one for all the steps in that document), so a step may open, switch or close documents.
|
||||
/// A step that acts on the active artboard ([`crate::ON_ACTIVE_ARTBOARD`]) and names none gets
|
||||
/// `artboard`, as the Artboards panel shows it in the document the step runs in: past that
|
||||
/// document's last artboard, the last one. A step that resizes the active artboard
|
||||
/// document's last artboard, the last one; a Paste in Place, in Front or in Back step that names
|
||||
/// `artboards` keeps them, and one that names neither, while the Artboard tool is chosen with
|
||||
/// several artboards selected, pastes on those. A step that resizes the active artboard
|
||||
/// ([`crate::FIT_ACTIVE_ARTBOARD`]) and names no `index` gets that artboard as its `index`.
|
||||
/// `grouped` gets each step's undo groups, as [`Session::batch_steps`] keeps them.
|
||||
fn run_steps(
|
||||
@@ -104,9 +106,14 @@ fn run_steps(
|
||||
} else {
|
||||
crate::FIT_ACTIVE_ARTBOARD.contains(&id.as_str()).then_some("index")
|
||||
};
|
||||
// A paste step that names its `artboards` keeps them; one that names neither key, while the
|
||||
// Artboard tool is chosen with several artboards selected, pastes on those.
|
||||
let names_artboards = id.starts_with("edit.pasteIn")
|
||||
&& (params.get("artboards").is_some() || (params.get("artboard").is_none() && !crate::cmd::edit::artboard_tool_picks(s).is_empty()));
|
||||
if let Some(a) = artboard
|
||||
&& let Some(key) = key
|
||||
&& params.get(key).is_none()
|
||||
&& !names_artboards
|
||||
&& let Some(last) = s.active().and_then(|d| d.doc.artboards.len().checked_sub(1))
|
||||
&& let Some(o) = params.as_object_mut()
|
||||
{
|
||||
|
||||
@@ -9,14 +9,14 @@ use vectorcraft_doc::{Document, Node, NodeId, NodeKind, SymbolBoxes};
|
||||
|
||||
use crate::DocState;
|
||||
|
||||
use super::super::{Result, Session, bad, bool_or, edit, f64_or, str_param};
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
|
||||
};
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(str_param(p, "format").unwrap_or("vectorcraft")), None)?;
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
|
||||
@@ -53,11 +53,11 @@ pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let path = str_param(p, "path");
|
||||
let path = text_param(p, "path", "document.export")?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", str_param(p, "format"), path)?;
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
|
||||
@@ -86,7 +86,7 @@ pub fn export_doc<'a>(st: &'a DocState, f: &Format, p: &Value) -> Result<Cow<'a,
|
||||
/// The document an export of `st` writes: the whole document, or with `selectedOnly` just the
|
||||
/// selected objects, each in its layers and groups (a clipping group keeps its clipping path).
|
||||
pub fn export_source<'a>(st: &'a DocState, p: &Value) -> Result<Cow<'a, Document>> {
|
||||
if !bool_or(p, "selectedOnly", false) {
|
||||
if !switch_or(p, "selectedOnly", false, "document.export")? {
|
||||
return Ok(Cow::Borrowed(&*st.doc));
|
||||
}
|
||||
let keep: HashSet<NodeId> = edit::roots_of(&st.doc, st.selection.in_paint_order(&st.doc)).into_iter().collect();
|
||||
@@ -237,7 +237,8 @@ fn expand_presets<'a>(s: &Session, cmd: &str, p: &'a Value) -> Result<Cow<'a, Va
|
||||
/// The document an export of `f` writes: the active one (see [`export_source`]), or for text
|
||||
/// with `selectionOnly` the selected objects alone.
|
||||
fn source<'a>(s: &'a mut Session, f: &Format, p: &Value, cmd: &str) -> Result<(Cow<'a, Document>, bool)> {
|
||||
if f.id == "txt" && bool_or(p, "selectionOnly", false) {
|
||||
check_switches(p, &["selectedOnly"], cmd)?;
|
||||
if switch_or(p, "selectionOnly", false, cmd)? && f.id == "txt" {
|
||||
let doc = selection(s, cmd, true)?.0;
|
||||
let display_doc_title = super::has_own_title(&doc);
|
||||
return Ok((Cow::Owned(doc), display_doc_title));
|
||||
@@ -309,11 +310,11 @@ pub(crate) fn isolated(doc: &Document, ids: &[NodeId], name: &str) -> Option<(Do
|
||||
/// are guides, not artwork, and are left out.
|
||||
pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportSelection";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let f = writable(C, str_param(p, "format"), path)?;
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
let (d, bounds) = selection(s, C, f.id == "txt")?;
|
||||
@@ -327,11 +328,12 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `transparent`, with the encoder's warnings.
|
||||
pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "document.exportForOffice";
|
||||
if let Some(path) = str_param(p, "path") {
|
||||
let path = text_param(p, "path", C)?;
|
||||
if let Some(path) = path {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let path = str_param(p, "path");
|
||||
let ppi = f64_or(p, "ppi", 150.0);
|
||||
let ppi = number_or(p, "ppi", 150.0, C)?;
|
||||
let transparent = switch_or(p, "transparent", false, C)?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let artboard = match p.get("artboard") {
|
||||
None | Some(Value::Null) => 0,
|
||||
@@ -340,7 +342,7 @@ pub(super) fn export_for_office(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if artboard >= doc.artboards.len() {
|
||||
return Err(bad(C, format!("no artboard {artboard} (0-based; the document has {})", doc.artboards.len())));
|
||||
}
|
||||
let background = if bool_or(p, "transparent", false) { "transparent" } else { "white" };
|
||||
let background = if transparent { "transparent" } else { "white" };
|
||||
let opts = with_black_output(s, &json!({ "ppi": ppi, "background": background, "artboard": artboard }));
|
||||
let (bytes, warnings) = encode_with_warnings(doc, "png", &opts)?;
|
||||
// The pixel size, from the PNG header.
|
||||
|
||||
@@ -99,7 +99,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "longPagesInPoints",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version",
|
||||
description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files from 1.5 on keep the UserUnit)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "createLayers",
|
||||
@@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export PDF",
|
||||
[],
|
||||
None,
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5; apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is
Line truncated
|
||||
"{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files from 1.5 on keep the UserUnit); apps that keep to the limit cut it to 200 in), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIn
Line truncated
|
||||
has_doc,
|
||||
export_pdf
|
||||
),
|
||||
|
||||
@@ -267,6 +267,66 @@ mod native {
|
||||
synth::container(&[("doc.dat", &doc, method)], Some(&png()))
|
||||
}
|
||||
|
||||
/// A version-12 document at 144 ppi holding a 100 px square filled with a red-to-blue conical
|
||||
/// gradient centered at (50, 40) px, 40 px across: its unit +y points down the page, or up
|
||||
/// (`mirror`).
|
||||
fn conical_document(mirror: bool) -> Vec<u8> {
|
||||
let stop = |id: u32, c: F| F::Def(id, vec![tag(b"RGBA")], vec![(tag(b"_col"), c)]);
|
||||
let positions = [[0.0f32, 0.5], [1.0, 0.5]].iter().map(|p| p.iter().flat_map(|v| v.to_le_bytes()).collect()).collect();
|
||||
let grad = F::Obj(
|
||||
tag(b"Grad"),
|
||||
vec![
|
||||
(tag(b"Cols"), F::Shared(vec![stop(23, rgba(1.0, 0.0, 0.0, 1.0)), stop(24, rgba(0.0, 0.0, 1.0, 1.0))])),
|
||||
(tag(b"Posn"), F::Records(8, positions)),
|
||||
],
|
||||
);
|
||||
let fill = F::Def(22, vec![tag(b"FilG")], vec![(tag(b"Type"), F::Enum(3, 0)), (tag(b"Grad"), grad)]);
|
||||
let unit = F::F64s(vec![40.0, 0.0, 50.0, 0.0, if mirror { -40.0 } else { 40.0 }, 40.0]);
|
||||
let gradient = F::Def(21, vec![tag(b"FDsc")], vec![(tag(b"FDeX"), unit), (tag(b"FDeF"), fill)]);
|
||||
let square = F::Def(
|
||||
20,
|
||||
vec![tag(b"ShpN")],
|
||||
vec![
|
||||
(tag(b"Shpe"), F::Def(25, vec![tag(b"ShNR")], vec![])),
|
||||
(tag(b"ShpB"), F::F64s(vec![0.0, 0.0, 100.0, 100.0])),
|
||||
(tag(b"BFFl"), F::Shared(vec![gradient])),
|
||||
],
|
||||
);
|
||||
let spread =
|
||||
F::Def(2, vec![tag(b"Sprd")], vec![(tag(b"SprB"), F::F64s(vec![0.0, 0.0, 200.0, 200.0])), (tag(b"Chld"), F::Shared(vec![square]))]);
|
||||
let doc = synth::stream(&[
|
||||
(tag(b"UVCn"), F::Obj(tag(b"UVCn"), vec![(tag(b"UPPI"), F::F64(144.0))])),
|
||||
(tag(b"DocR"), F::Def(1, vec![tag(b"DocN")], vec![(tag(b"Chld"), F::Shared(vec![spread]))])),
|
||||
]);
|
||||
synth::container(&[("doc.dat", &doc, Method::Stored)], Some(&png()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conical_gradients_open_as_conic_gradients() {
|
||||
use vectorcraft_color::{GradientKind, Paint};
|
||||
for mirror in [false, true] {
|
||||
let mut s = Session::new();
|
||||
let r = open_bytes(&mut s, "conic.af", &conical_document(mirror), None).unwrap();
|
||||
assert!(r["warnings"].as_array().unwrap().iter().all(|w| !w.as_str().unwrap().contains("conical")), "{r}");
|
||||
let mut paint = None;
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.fill_paint() {
|
||||
paint = Some(g.clone());
|
||||
}
|
||||
});
|
||||
let g = paint.expect("a gradient fill");
|
||||
assert_eq!(g.gradient.kind, GradientKind::Conic);
|
||||
let geom = g.geom.unwrap();
|
||||
// At 144 ppi: centered at (25, 20) pt, 20 pt across, red where the sweep starts.
|
||||
assert!(geom.start.distance(kurbo::Point::new(25.0, 20.0)) < 1e-9 && (geom.length() - 20.0).abs() < 1e-9, "{geom:?}");
|
||||
assert_eq!(geom.is_mirrored(), mirror, "{geom:?}");
|
||||
// A quarter turn on lies along the unit +y: below the center, or above it mirrored.
|
||||
let quarter = kurbo::Point::new(25.0, if mirror { 10.0 } else { 30.0 });
|
||||
assert!((geom.param_at(GradientKind::Conic, quarter) - 0.25).abs() < 1e-9, "{geom:?}");
|
||||
assert_eq!(g.gradient.stops[0].color.to_hex(), "#ff0000");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_artboards_curves_and_paints_open_as_editable_art() {
|
||||
for method in [Method::Stored, Method::Zlib, Method::Zstd] {
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient",
|
||||
["Window", "Gradient"],
|
||||
None,
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|freeform (freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear or radial, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right), aspect?: %, reverse?: bool, dither?: bool (fills only: a linear or radial gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
"{stroke?: bool (default: the targeted item's kind, else the active proxy), kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical, sweeps the stops once around the center, clockwise from the vector, with a seam where the last stop meets the first; freeform places points on each object, coloured along the stops), mode?: points|lines (freeform: how the Gradient tool adds points), method?: classic|perceptual (how the colours between the stops mix: in display RGB, or perceptually (OKLab) so the steps look even; SVG exports draw a Perceptual gradient as an image, and PDF exports do too unless it is linear, radial or conic, has spot color stops, every other stop is paper white or written in CMYK or gray (an export that converts colors to a CMYK destination profile writes RGB and Lab stops in CMYK, and so does a CMYK document unless the export converts colors to an RGB destination profile), it is not a dithered fill and its curve does not have too many stops: then PDF writes tints of one spot ink as a Separation shading in that ink, and spot inks mixed with other spot, CMYK or gray inks as a DeviceN shading; freeform gradients mix their own way), stops?: [{offset 0..1, color? (needed without swatch; #rrggbbaa and #rgba are refused), opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: colour swatch name (a global or spot colour or tint swatch links the stop, so swatch edits recolour it and a spot stop prints on its plate; a process colour just gives its colour), tint?: 0..100 (% of the linked swatch; default 100, or a tint swatch's own)}] (at least 2; a freeform gradient's points are recoloured along them), keepModel?: bool (as paint.setFill; a stop color the gradient already has keeps its model), angle?: deg counter-clockwise (0: the gradient runs left to right; radial and conic: the vector turns about the center), aspect?: % (radial and conic; a negative one mirrors a conic's sweep and is an error for the other kinds), reverse?: bool, dither?: bool (fills only: a linear, radial or conic gradient fill is drawn with fine noise that hides banding, and as pixels in SVG and PDF exports), item?: fill/stroke item index|null (omitted: the Appearance panel's active item when it is of the edited kind), ids?|id?, strokeMode?: within|along|across (strokes only: the gradient lies on the page and shows through the stroke, runs from the start of each subpath to its end, or runs from the stroke's left edge to its right all along it; with nothing selected, for the next object drawn; type characters' own strokes always paint within), target?: \"object\"|\"contents\"} edit the gradient in place (keeps its placement); solid/none paints become the default gradient",
|
||||
has_doc,
|
||||
edit_gradient
|
||||
),
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Gradient Vector",
|
||||
[],
|
||||
None,
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial: the extent ellipse's height / width; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)",
|
||||
"{start?: [x,y], end?: [x,y] (document coordinates; both or neither: omitted, the vector stays), aspect?: % (radial and conic: the extent ellipse's height / width, a negative one mirroring a conic's sweep and an error for the other kinds; default: kept), focal?: [x,y] (document coordinates) | null (radial: the focal point, where the first stop sits, pulled inside the extent ellipse; null centres it; default: it keeps its place in the ellipse; an error on a conic gradient), ids?|id?, stroke?: bool (default: the targeted item's kind, else the active proxy), item?: fill/stroke item index|null (alias: index; omitted: the Appearance panel's active item when it is of the edited kind), target?: \"object\"|\"contents\", index?: appearance item index (as item)} set the gradient vector, aspect ratio and focal point (solid paints become the default gradient; type objects set it on their runs, in text space)",
|
||||
has_doc,
|
||||
set_gradient_geom
|
||||
),
|
||||
@@ -118,7 +118,7 @@ type Parsed<T> = std::result::Result<T, String>;
|
||||
|
||||
/// Parse a kind name.
|
||||
fn parse_kind(k: &str) -> Parsed<GradientKind> {
|
||||
GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, freeform)"))
|
||||
GradientKind::parse(k).ok_or_else(|| format!("unknown gradient kind `{k}` (linear, radial, conic, freeform)"))
|
||||
}
|
||||
|
||||
/// The `method` param of `p`, if given: how the colours between the stops mix.
|
||||
@@ -274,9 +274,16 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
gp.angle = f64_or(g, "angle", 0.0);
|
||||
gp.swatch = str_param(g, "swatch").map(str::to_string);
|
||||
let geom = GeomEdit::parse(g)?;
|
||||
let aspect = geom.aspect.map(|a| aspect_for(kind, a)).transpose()?;
|
||||
if kind == GradientKind::Conic {
|
||||
no_focal(&geom)?;
|
||||
}
|
||||
if let Some((start, end)) = geom.vector {
|
||||
let mut g = GradientGeom { start, end, aspect: geom.aspect.unwrap_or(1.0), focal: None };
|
||||
g.set_focal(geom.focal.flatten());
|
||||
let mut g = GradientGeom { start, end, aspect: aspect.unwrap_or(1.0), focal: None };
|
||||
// Only a radial gradient has a focal point (as `paint.setGradientGeom` keeps it).
|
||||
if kind == GradientKind::Radial {
|
||||
g.set_focal(geom.focal.flatten());
|
||||
}
|
||||
gp.angle = g.angle_deg();
|
||||
gp.geom = Some(g);
|
||||
}
|
||||
@@ -286,13 +293,36 @@ pub(crate) fn parse_gradient(g: &Value) -> Parsed<GradientPaint> {
|
||||
Ok(gp)
|
||||
}
|
||||
|
||||
/// The `aspect` param (a percentage) as a ratio.
|
||||
/// The `aspect` param (a percentage) as a ratio of 0.005 to 327.67, its sign kept: a negative one
|
||||
/// mirrors a conic gradient's sweep ([`aspect_for`]).
|
||||
fn aspect_param(p: &Value) -> Parsed<Option<f64>> {
|
||||
p.get("aspect")
|
||||
.map(|v| v.as_f64().map(|a| (a / 100.0).clamp(0.005, 327.67)).ok_or_else(|| "`aspect` must be a number (%)".to_string()))
|
||||
.map(|v| {
|
||||
v.as_f64()
|
||||
.filter(|a| a.is_finite())
|
||||
.map(|a| (a.abs() / 100.0).clamp(0.005, 327.67).copysign(a))
|
||||
.ok_or_else(|| "`aspect` must be a number (%)".to_string())
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// Aspect ratio `a` ([`aspect_param`]) for a gradient of `kind`: a negative one mirrors a conic's
|
||||
/// sweep, and is an error for the other kinds.
|
||||
fn aspect_for(kind: GradientKind, a: f64) -> Parsed<f64> {
|
||||
if a < 0.0 && kind != GradientKind::Conic {
|
||||
return Err("a negative `aspect` applies to conic gradients".into());
|
||||
}
|
||||
Ok(a)
|
||||
}
|
||||
|
||||
/// An error when `e` gives a focal point: a conic gradient has none (`null` is allowed).
|
||||
fn no_focal(e: &GeomEdit) -> Parsed<()> {
|
||||
match e.focal {
|
||||
Some(Some(_)) => Err("`focal` applies to radial gradients".into()),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `paint` without the placement it had on the art it came from (a swatch, or the default paint
|
||||
/// for new art): a placed gradient keeps its angle and fits each object it lands on (freeform
|
||||
/// points are placed afresh, coloured along the stops, which follow the points' colours).
|
||||
@@ -400,7 +430,7 @@ fn apply_gradient_edit_in_model(
|
||||
if let Some(g) = &mut gp.geom {
|
||||
let r = a.to_radians();
|
||||
let dir = vectorcraft_geom::Vec2::new(r.cos(), -r.sin());
|
||||
if gp.gradient.kind == GradientKind::Radial {
|
||||
if gp.gradient.kind.is_centered() {
|
||||
g.end = g.start + dir * g.length();
|
||||
} else {
|
||||
let c = g.start.midpoint(g.end);
|
||||
@@ -411,6 +441,7 @@ fn apply_gradient_edit_in_model(
|
||||
}
|
||||
}
|
||||
if let Some(asp) = aspect_param(p)? {
|
||||
let asp = aspect_for(gp.gradient.kind, asp)?;
|
||||
if gp.geom.is_none()
|
||||
&& let Some(b) = bounds
|
||||
{
|
||||
@@ -472,7 +503,20 @@ fn edit_gradient(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let p = &link_stops(&s.doc()?.doc, p).map_err(|e| bad(C, e))?;
|
||||
// Validate against the defaults first so bad params fail without touching the document.
|
||||
let default_paint = if stroke { s.paint.stroke.clone() } else { s.paint.fill.clone() };
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(p, &default_paint, &stored), None, &|_| true, model)
|
||||
// A negative aspect for selected conic gradients gives a default of another kind its size.
|
||||
let default_kind = str_param(p, "kind").and_then(GradientKind::parse).or(match &default_paint {
|
||||
Paint::Gradient(g) => Some(g.gradient.kind),
|
||||
_ => None,
|
||||
});
|
||||
let for_default = match p.get("aspect").and_then(Value::as_f64) {
|
||||
Some(a) if a < 0.0 && !ids.is_empty() && default_kind != Some(GradientKind::Conic) => {
|
||||
let mut q = p.clone();
|
||||
q["aspect"] = json!(-a);
|
||||
std::borrow::Cow::Owned(q)
|
||||
}
|
||||
_ => std::borrow::Cow::Borrowed(p),
|
||||
};
|
||||
let new_default = apply_gradient_edit_in_model(&default_paint, &with_stored_stops(&for_default, &default_paint, &stored), None, &|_| true, model)
|
||||
.map_err(|e| bad(C, e))?;
|
||||
let freeform = str_param(p, "kind").and_then(GradientKind::parse) == Some(GradientKind::Freeform);
|
||||
edit_items(s, &ids, item, C, "Gradient", !stroke, |n, index| {
|
||||
@@ -599,11 +643,23 @@ impl GeomEdit {
|
||||
|
||||
/// `cur` with the vector, aspect and focal point of `e` (given in the document). `to_doc` maps
|
||||
/// the paint's space (text space for type runs) to the document and `bounds` (in that space) fits
|
||||
/// an unplaced gradient, so what the document shows carries over where `e` keeps it.
|
||||
fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>, model: Option<vectorcraft_color::cms::Model>) -> Option<Paint> {
|
||||
let from_doc = invert(to_doc)?;
|
||||
/// an unplaced gradient, so what the document shows carries over where `e` keeps it. An error
|
||||
/// when `e` gives what the gradient's kind can't take (a negative aspect other than a conic's, or
|
||||
/// a conic's focal point).
|
||||
fn vector_paint(
|
||||
cur: &Paint,
|
||||
e: &GeomEdit,
|
||||
to_doc: Affine,
|
||||
bounds: Option<Rect>,
|
||||
model: Option<vectorcraft_color::cms::Model>,
|
||||
) -> Parsed<Option<Paint>> {
|
||||
let mut gp = gradient_for_edit(cur, model);
|
||||
let kind = gp.gradient.kind;
|
||||
let edit_aspect = e.aspect.map(|a| aspect_for(kind, a)).transpose()?;
|
||||
if kind == GradientKind::Conic {
|
||||
no_focal(e)?;
|
||||
}
|
||||
let Some(from_doc) = invert(to_doc) else { return Ok(None) };
|
||||
let map = |mut g: GradientGeom, a: Affine| {
|
||||
if a != Affine::IDENTITY {
|
||||
g.transform(a, kind);
|
||||
@@ -611,8 +667,8 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>,
|
||||
g
|
||||
};
|
||||
let shown = gp.geom.or_else(|| bounds.map(|b| gp.resolve(b))).map(|g| map(g, to_doc));
|
||||
let (start, end) = e.vector.or_else(|| shown.map(|g| (g.start, g.end)))?;
|
||||
let aspect = e.aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0);
|
||||
let Some((start, end)) = e.vector.or_else(|| shown.map(|g| (g.start, g.end))) else { return Ok(None) };
|
||||
let aspect = edit_aspect.or_else(|| shown.map(|g| g.aspect)).unwrap_or(1.0);
|
||||
let mut geom = GradientGeom { start, end, aspect, focal: None };
|
||||
match (e.focal, shown) {
|
||||
_ if kind != GradientKind::Radial => {}
|
||||
@@ -623,7 +679,7 @@ fn vector_paint(cur: &Paint, e: &GeomEdit, to_doc: Affine, bounds: Option<Rect>,
|
||||
let geom = map(geom, from_doc);
|
||||
gp.angle = geom.angle_deg();
|
||||
gp.geom = Some(geom);
|
||||
Some(Paint::Gradient(Box::new(gp)))
|
||||
Ok(Some(Paint::Gradient(Box::new(gp))))
|
||||
}
|
||||
|
||||
fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -658,14 +714,15 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
run_stroke_weight(&mut r.style);
|
||||
}
|
||||
let (paint, b) = run_paint_mut(r, stroke, lb);
|
||||
if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model) {
|
||||
if let Some(np) = vector_paint(paint, &edit, xf, Some(b), model).map_err(|e| bad(C, e))? {
|
||||
*paint = np;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let b = item_paint_bounds(n, index, !stroke);
|
||||
if let Some(np) = vector_paint(n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None), &edit, Affine::IDENTITY, b, model) {
|
||||
let cur = n.appearance.paint_at(index, !stroke).unwrap_or(&Paint::None);
|
||||
if let Some(np) = vector_paint(cur, &edit, Affine::IDENTITY, b, model).map_err(|e| bad(C, e))? {
|
||||
n.appearance.set_paint_at(index, !stroke, np);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -17,7 +17,9 @@ use vectorcraft_doc::{
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, Point, Rect, shapes};
|
||||
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, f64_req, has_doc, has_selection, named_id, ok, str_param};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, cmd, f64_req, has_doc, has_selection, named_id, number_or, ok, str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
mod axis;
|
||||
mod columns;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{GraphSpec, Value};
|
||||
use super::{GraphSpec, Result, Value, bad};
|
||||
|
||||
pub(super) const LABEL_SIZE: f64 = 9.0;
|
||||
|
||||
@@ -22,6 +22,16 @@ pub(super) fn count_param(p: &Value, key: &str, max: u64) -> Option<usize> {
|
||||
usize::try_from(n.min(max)).ok()
|
||||
}
|
||||
|
||||
/// [`count_param`], or `None` when `p` leaves `key` out or gives null. A negative number is an error, and so is any
|
||||
/// other value, such as `"5"`.
|
||||
pub(super) fn count_given(p: &Value, key: &str, max: u64, cmd: &str) -> Result<Option<usize>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(v) if !v.is_number() => Err(bad(cmd, format!("`{key}` must be a number, not {v}"))),
|
||||
Some(_) => count_param(p, key, max).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be 0 or more"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A "nice" axis: (min, max, step).
|
||||
pub(super) fn nice_axis(lo: f64, hi: f64, ticks: usize) -> (f64, f64, f64) {
|
||||
let (lo, hi) = if (hi - lo).abs() < 1e-12 { (lo.min(0.0), lo.max(0.0) + 1.0) } else { (lo, hi) };
|
||||
|
||||
@@ -12,7 +12,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Graph",
|
||||
[],
|
||||
None,
|
||||
"{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label",
|
||||
"{type: column|stackedColumn|bar|stackedBar|line|area|scatter|pie|radar, x, y, width, height, series?: [..], categories?: [..], rows?: [[number|null]], csv?} → {id}; an empty CSV cell or a null is a blank value, a number in straight quotes is a label; a `type` that is not a string, a `width` or `height` that is not a number, and data of the wrong type (as `graph.setData` reads it) are refused",
|
||||
has_doc,
|
||||
create
|
||||
),
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Data…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; no data → the current {csv, series, categories, rows}",
|
||||
"{id?, series?, categories?, rows?, csv?: first row = series labels (first cell empty); then one row per category: label; values…; an empty cell or a null is a blank value; a quoted number a label; a `|` in a label a line break, transpose?: true swaps rows and columns (Transpose row/column), switchXY?: true swaps each scatter series' y and x columns (Switch x/y)} replace the graph's data; a `csv` that is not a string, `series` or `categories` that are not lists, `rows` that are not lists of numbers and nulls, or a `transpose` or `switchXY` that is not true or false is refused and the graph stays as it was; no data → the current {csv, series, categories, rows}",
|
||||
has_selection,
|
||||
set_data
|
||||
),
|
||||
@@ -30,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Type…",
|
||||
["Object", "Graph"],
|
||||
None,
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?, axisMax?, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); no options → the current ones",
|
||||
"{id?, type?, seriesIndexes?: [index], columnWidth?: % (1–1000; past 100 columns overlap), clusterWidth?: % (1–1000), legend?: bool, markPoints?: bool, connectPoints?: bool, edgeToEdge?: bool (line graphs: true runs the lines across the whole plot, false puts the points at the centres of their categories), ticks?: n, axisMin?: number|null (null = calculated), axisMax?: number|null, valueAxis?: left|right|both (the bar graphs' value axis stays along the bottom), separateScales?: bool, rightTicks?: n, rightAxisMin?, rightAxisMax?, tickLength?: none|short|full, tickMarks?: n per division, rightTickLength?, rightTickMarks?, categoryTickLength?: none|short|full, categoryTickMarks?: n, ticksBetweenLabels?: bool, prefix?, suffix?, rightPrefix?, rightSuffix?: text around the value axis numbers, firstRowInFront?: bool, firstColumnInFront?: bool (which overlapping columns are drawn on top: the first category over the next within each series, the first series over the others), filledLines?: bool (Draw Filled Lines: connecting lines as 3 pt bands filled with the series colour), dropShadow?: bool (Add Drop Shadow: a translucent black shadow down and right of the columns, bars, lines and pie wedges), legendAcrossTop?: bool (Add Legend Across Top: the legend in rows above the plot), pieLegend?: none|standard|wedges (Legends in Wedges: the series labels inside their wedges), piePosition?: ratio|even|stacked (several pies sized by their totals, at one size (the default), or stacked), pieSort?: all|first|none (wedges largest first in each pie, in the first pie's order, or in data order (the default)); the query lists the pie options for pie graphs} change the graph type and options; with `seriesIndexes`, or (no `id`) with only series selected with Group Selection, `type` goes to those series only and `valueAxis` (left|right; both is refused) puts them on that value axis, while the other options still apply to the whole graph (Combine different graph types: column, stacked column, line and area mix, and so do bar and stacked bar; a series given the graph's type follows the graph again) (axisMin and axisMax together override the calculated value axis: exactly that range in `ticks` divisions, 5 when 0; with the value axis on both sides, separateScales gives the series on the right axis a scale of their own, set the same way with rightTicks, rightAxisMin and rightAxisMax); a value of the wrong type, such as \"10\" for a number or \"true\" for a bool, or a negative count, is refused and the graph stays as it was; a null is read as a key left out, except that a null axis bound goes back to the calculated value; no options → the current ones",
|
||||
has_selection,
|
||||
set_type
|
||||
),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::edit::{regenerate, spec_of, target};
|
||||
use super::series::{switch_xy, transpose};
|
||||
use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, bool_or, json, str_param};
|
||||
use super::{Document, EngineError, GraphKind, GraphSpec, NodeId, Result, Session, Value, bad, json, switch_or, text_param};
|
||||
|
||||
// ---------- data ----------
|
||||
|
||||
@@ -101,7 +101,7 @@ pub(crate) fn apply_csv(d: &mut Document, id: NodeId, csv: &str) -> Result<()> {
|
||||
return Err(bad("graph.applyCsv", format!("node {} is not a graph", id.0)));
|
||||
};
|
||||
let mut spec = current.clone();
|
||||
apply_data(&mut spec, &json!({ "csv": csv }));
|
||||
apply_data(&mut spec, &json!({ "csv": csv }), "graph.applyCsv")?;
|
||||
keep_right_series(&mut spec);
|
||||
if spec == *current {
|
||||
return Ok(());
|
||||
@@ -115,34 +115,58 @@ fn keep_right_series(g: &mut GraphSpec) {
|
||||
g.right_series.retain(|i| *i < count);
|
||||
}
|
||||
|
||||
pub(super) fn apply_data(g: &mut GraphSpec, p: &Value) -> bool {
|
||||
/// Apply the data `p` gives (`csv`, `series`, `categories`, `rows`) to `g`; true when it gave any. A null is read as a
|
||||
/// key left out. A `csv` that is not a string, a `series` or `categories` that is not a list, and `rows` that are not
|
||||
/// lists of numbers and nulls are errors, and `g` is left as it was.
|
||||
pub(super) fn apply_data(g: &mut GraphSpec, p: &Value, cmd: &str) -> Result<bool> {
|
||||
let list = |key: &str| -> Result<Option<&Vec<Value>>> {
|
||||
match p.get(key) {
|
||||
None | Some(Value::Null) => Ok(None),
|
||||
Some(Value::Array(a)) => Ok(Some(a)),
|
||||
Some(v) => Err(bad(cmd, format!("`{key}` must be a list, not {v}"))),
|
||||
}
|
||||
};
|
||||
let csv = text_param(p, "csv", cmd)?;
|
||||
let strings = |a: &Vec<Value>| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>();
|
||||
let series = list("series")?.map(strings);
|
||||
let categories = list("categories")?.map(strings);
|
||||
// A null is a blank cell.
|
||||
let rows = list("rows")?
|
||||
.map(|rows| {
|
||||
rows.iter()
|
||||
.map(|r| {
|
||||
let bad_row = || bad(cmd, format!("`rows` must be lists of numbers or nulls, not {r}"));
|
||||
r.as_array()
|
||||
.ok_or_else(bad_row)?
|
||||
.iter()
|
||||
.map(|v| if v.is_null() { Ok(None) } else { v.as_f64().map(|v| Some(v).filter(|v| v.is_finite())).ok_or_else(bad_row) })
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
})
|
||||
.transpose()?;
|
||||
let mut changed = false;
|
||||
if let Some(csv) = str_param(p, "csv") {
|
||||
if let Some(csv) = csv {
|
||||
let (s, c, r) = parse_csv(csv);
|
||||
g.series = s;
|
||||
g.categories = c;
|
||||
g.set_cells(r);
|
||||
changed = true;
|
||||
}
|
||||
let strings =
|
||||
|v: &Value| v.as_array().map(|a| a.iter().map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string())).collect::<Vec<_>>());
|
||||
if let Some(s) = p.get("series").and_then(strings) {
|
||||
if let Some(s) = series {
|
||||
g.series = s;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(c) = p.get("categories").and_then(strings) {
|
||||
if let Some(c) = categories {
|
||||
g.categories = c;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(rows) = p.get("rows").and_then(Value::as_array) {
|
||||
// `null` (or anything that isn't a finite number) is a blank cell.
|
||||
g.set_cells(
|
||||
rows.iter().map(|r| r.as_array().map(|a| a.iter().map(|v| v.as_f64().filter(|v| v.is_finite())).collect()).unwrap_or_default()).collect(),
|
||||
);
|
||||
if let Some(rows) = rows {
|
||||
g.set_cells(rows);
|
||||
changed = true;
|
||||
}
|
||||
drop_empty_rows(g);
|
||||
changed
|
||||
Ok(changed)
|
||||
}
|
||||
|
||||
/// Drop rows with neither a value nor a label; a label-only row stays, its values blank. Each kept row keeps its own
|
||||
@@ -184,13 +208,13 @@ pub(super) fn set_data(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.setData";
|
||||
let id = target(s, p, C)?;
|
||||
let mut spec = spec_of(s, id)?;
|
||||
let flip = bool_or(p, "transpose", false);
|
||||
let swap = bool_or(p, "switchXY", false);
|
||||
let flip = switch_or(p, "transpose", false, C)?;
|
||||
let swap = switch_or(p, "switchXY", false, C)?;
|
||||
if swap && spec.kind != GraphKind::Scatter {
|
||||
return Err(bad(C, "Switch x/y is for scatter graphs"));
|
||||
}
|
||||
// Transpose and Switch x/y act after any new data in the same call.
|
||||
let changed = apply_data(&mut spec, p);
|
||||
let changed = apply_data(&mut spec, p, C)?;
|
||||
if flip {
|
||||
// The categories become series: at most as many as a graph has series.
|
||||
if spec.cells().len() > vectorcraft_doc::MAX_GRAPH_SERIES {
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
use super::axis::{MAX_TICK_MARKS, count_param, one_line};
|
||||
use super::axis::{MAX_TICK_MARKS, count_given, one_line};
|
||||
use super::data::apply_data;
|
||||
use super::generate::{children_bounds, generate};
|
||||
use super::series::{picked_series, reselect_series};
|
||||
use super::{
|
||||
Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, bool_or, f64_or,
|
||||
f64_req, json, named_id, str_param,
|
||||
Affine, Document, EngineError, GraphKind, GraphSpec, Node, NodeId, Rect, Result, Session, TickLength, Value, ValueAxisSide, bad, f64_req, json,
|
||||
named_id, number_or, switch_or, text_param,
|
||||
};
|
||||
|
||||
/// An axis bound `p` gives for `key`: `None` when left out, `Some(None)` for null (calculated from the data), or the
|
||||
/// number. Any other value, such as `"10"`, is an error.
|
||||
fn bound_param(p: &Value, key: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
match p.get(key) {
|
||||
None => Ok(None),
|
||||
Some(Value::Null) => Ok(Some(None)),
|
||||
Some(v) => v.as_f64().map(|x| Some(Some(x))).ok_or_else(|| bad(cmd, format!("`{key}` must be a number or null, not {v}"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Regenerate graph `id` from `spec` (adjusting the plot rect for any move/scale since the last
|
||||
/// generation, which is recorded in the spec's `placed` bounds).
|
||||
pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> {
|
||||
@@ -33,12 +43,14 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R
|
||||
|
||||
pub(super) fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graph.create";
|
||||
let kind =
|
||||
str_param(p, "type").map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))).transpose()?.unwrap_or_default();
|
||||
let kind = text_param(p, "type", C)?
|
||||
.map(|t| GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`"))))
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let (x, y) = (f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let (w, h) = (f64_or(p, "width", 200.0).abs().max(1.0), f64_or(p, "height", 150.0).abs().max(1.0));
|
||||
let (w, h) = (number_or(p, "width", 200.0, C)?.abs().max(1.0), number_or(p, "height", 150.0, C)?.abs().max(1.0));
|
||||
let mut spec = GraphSpec { kind, rect: Rect::new(x, y, x + w, y + h), ..GraphSpec::default() };
|
||||
if !apply_data(&mut spec, p) {
|
||||
if !apply_data(&mut spec, p, C)? {
|
||||
// Starter data so the new graph shows something (edit it with Object → Graph → Data…).
|
||||
spec.series = vec!["Series 1".into(), "Series 2".into()];
|
||||
spec.categories = vec!["A".into(), "B".into(), "C".into(), "D".into()];
|
||||
@@ -150,7 +162,8 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
spec.right_series.retain(|i| *i < count);
|
||||
spec.right_series.sort_unstable();
|
||||
spec.right_series.dedup();
|
||||
if p.get("seriesIndexes").is_some() && str_param(p, "type").is_none() && str_param(p, "valueAxis").is_none() {
|
||||
let (new_type, new_axis) = (text_param(p, "type", C)?, text_param(p, "valueAxis", C)?);
|
||||
if p.get("seriesIndexes").is_some() && new_type.is_none() && new_axis.is_none() {
|
||||
return Err(bad(C, "`seriesIndexes` needs a `type` or a `valueAxis`"));
|
||||
}
|
||||
let picked = picked_series(s, p, id, count, C)?;
|
||||
@@ -196,7 +209,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Series picked with Group Selection stay selected through the regeneration (their groups are new nodes).
|
||||
let reselect: Vec<u32> = if p.get("seriesIndexes").is_none() { picked.iter().filter_map(|i| u32::try_from(*i).ok()).collect() } else { vec![] };
|
||||
if let Some(t) = str_param(p, "type") {
|
||||
if let Some(t) = new_type {
|
||||
let kind = GraphKind::parse(t).ok_or_else(|| bad(C, format!("unknown graph type `{t}`")))?;
|
||||
if picked.is_empty() {
|
||||
spec.kind = kind;
|
||||
@@ -215,7 +228,7 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = str_param(p, "valueAxis") {
|
||||
if let Some(v) = new_axis {
|
||||
let side = ValueAxisSide::parse(v).ok_or_else(|| bad(C, format!("unknown value axis `{v}` (left, right or both)")))?;
|
||||
if picked.is_empty() {
|
||||
spec.value_axis = side;
|
||||
@@ -231,54 +244,58 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
spec.separate_scales = bool_or(p, "separateScales", spec.separate_scales);
|
||||
spec.separate_scales = switch_or(p, "separateScales", spec.separate_scales, C)?;
|
||||
for (key, slot) in [
|
||||
("tickLength", &mut spec.tick_length),
|
||||
("rightTickLength", &mut spec.right_tick_length),
|
||||
("categoryTickLength", &mut spec.category_tick_length),
|
||||
] {
|
||||
if let Some(v) = str_param(p, key) {
|
||||
if let Some(v) = text_param(p, key, C)? {
|
||||
*slot = TickLength::parse(v).ok_or_else(|| bad(C, format!("unknown {key} `{v}` (none, short or full)")))?;
|
||||
}
|
||||
}
|
||||
for (key, slot) in
|
||||
[("tickMarks", &mut spec.tick_marks), ("rightTickMarks", &mut spec.right_tick_marks), ("categoryTickMarks", &mut spec.category_tick_marks)]
|
||||
{
|
||||
*slot = count_param(p, key, MAX_TICK_MARKS as u64).map_or(*slot, |n| n.max(1));
|
||||
*slot = count_given(p, key, MAX_TICK_MARKS as u64, C)?.map_or(*slot, |n| n.max(1));
|
||||
}
|
||||
spec.ticks_between_labels = bool_or(p, "ticksBetweenLabels", spec.ticks_between_labels);
|
||||
if let Some(v) = str_param(p, "piePosition") {
|
||||
spec.ticks_between_labels = switch_or(p, "ticksBetweenLabels", spec.ticks_between_labels, C)?;
|
||||
if let Some(v) = text_param(p, "piePosition", C)? {
|
||||
spec.pie_position =
|
||||
vectorcraft_doc::PiePosition::parse(v).ok_or_else(|| bad(C, format!("unknown piePosition `{v}` (even, ratio or stacked)")))?;
|
||||
}
|
||||
if let Some(v) = str_param(p, "pieSort") {
|
||||
if let Some(v) = text_param(p, "pieSort", C)? {
|
||||
spec.pie_sort = vectorcraft_doc::PieSort::parse(v).ok_or_else(|| bad(C, format!("unknown pieSort `{v}` (none, all or first)")))?;
|
||||
}
|
||||
for (key, slot) in
|
||||
[("prefix", &mut spec.prefix), ("suffix", &mut spec.suffix), ("rightPrefix", &mut spec.right_prefix), ("rightSuffix", &mut spec.right_suffix)]
|
||||
{
|
||||
if let Some(v) = str_param(p, key) {
|
||||
if let Some(v) = text_param(p, key, C)? {
|
||||
// A label, not a paragraph: one line, at most MAX_AFFIX characters.
|
||||
*slot = one_line(v);
|
||||
}
|
||||
}
|
||||
spec.right_ticks = count_param(p, "rightTicks", 100).unwrap_or(spec.right_ticks);
|
||||
if let Some(v) = p.get("rightAxisMin") {
|
||||
spec.right_axis_min = v.as_f64();
|
||||
spec.right_ticks = count_given(p, "rightTicks", 100, C)?.unwrap_or(spec.right_ticks);
|
||||
for (key, slot) in [
|
||||
("rightAxisMin", &mut spec.right_axis_min),
|
||||
("rightAxisMax", &mut spec.right_axis_max),
|
||||
("axisMin", &mut spec.axis_min),
|
||||
("axisMax", &mut spec.axis_max),
|
||||
] {
|
||||
if let Some(v) = bound_param(p, key, C)? {
|
||||
*slot = v;
|
||||
}
|
||||
}
|
||||
if let Some(v) = p.get("rightAxisMax") {
|
||||
spec.right_axis_max = v.as_f64();
|
||||
}
|
||||
spec.column_width = f64_or(p, "columnWidth", spec.column_width).clamp(1.0, 1000.0);
|
||||
spec.cluster_width = f64_or(p, "clusterWidth", spec.cluster_width).clamp(1.0, 1000.0);
|
||||
spec.legend = bool_or(p, "legend", spec.legend);
|
||||
spec.drop_shadow = bool_or(p, "dropShadow", spec.drop_shadow);
|
||||
spec.first_row_in_front = bool_or(p, "firstRowInFront", spec.first_row_in_front);
|
||||
spec.first_column_in_front = bool_or(p, "firstColumnInFront", spec.first_column_in_front);
|
||||
spec.filled_lines = bool_or(p, "filledLines", spec.filled_lines);
|
||||
spec.legend_across_top = bool_or(p, "legendAcrossTop", spec.legend_across_top);
|
||||
spec.column_width = number_or(p, "columnWidth", spec.column_width, C)?.clamp(1.0, 1000.0);
|
||||
spec.cluster_width = number_or(p, "clusterWidth", spec.cluster_width, C)?.clamp(1.0, 1000.0);
|
||||
spec.legend = switch_or(p, "legend", spec.legend, C)?;
|
||||
spec.drop_shadow = switch_or(p, "dropShadow", spec.drop_shadow, C)?;
|
||||
spec.first_row_in_front = switch_or(p, "firstRowInFront", spec.first_row_in_front, C)?;
|
||||
spec.first_column_in_front = switch_or(p, "firstColumnInFront", spec.first_column_in_front, C)?;
|
||||
spec.filled_lines = switch_or(p, "filledLines", spec.filled_lines, C)?;
|
||||
spec.legend_across_top = switch_or(p, "legendAcrossTop", spec.legend_across_top, C)?;
|
||||
// After `legend`, which the Graph Type dialog sends too.
|
||||
if let Some(v) = str_param(p, "pieLegend") {
|
||||
if let Some(v) = text_param(p, "pieLegend", C)? {
|
||||
(spec.legend, spec.pie_legend_in_wedges) = match v.to_ascii_lowercase().as_str() {
|
||||
"none" => (false, false),
|
||||
"standard" => (true, false),
|
||||
@@ -286,16 +303,10 @@ pub(super) fn set_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, format!("unknown pieLegend `{v}` (none, standard or wedges)"))),
|
||||
};
|
||||
}
|
||||
spec.mark_points = bool_or(p, "markPoints", spec.mark_points);
|
||||
spec.connect_points = bool_or(p, "connectPoints", spec.connect_points);
|
||||
spec.edge_to_edge = bool_or(p, "edgeToEdge", spec.edge_to_edge);
|
||||
spec.ticks = count_param(p, "ticks", 100).unwrap_or(spec.ticks);
|
||||
if let Some(v) = p.get("axisMin") {
|
||||
spec.axis_min = v.as_f64();
|
||||
}
|
||||
if let Some(v) = p.get("axisMax") {
|
||||
spec.axis_max = v.as_f64();
|
||||
}
|
||||
spec.mark_points = switch_or(p, "markPoints", spec.mark_points, C)?;
|
||||
spec.connect_points = switch_or(p, "connectPoints", spec.connect_points, C)?;
|
||||
spec.edge_to_edge = switch_or(p, "edgeToEdge", spec.edge_to_edge, C)?;
|
||||
spec.ticks = count_given(p, "ticks", 100, C)?.unwrap_or(spec.ticks);
|
||||
let label = format!("{} Graph", spec.kind.label());
|
||||
s.edit("Graph Type", |d, sel| {
|
||||
regenerate(d, id, spec)?;
|
||||
|
||||
@@ -2638,9 +2638,12 @@ fn counts_come_back_from_the_dialog_as_floats_and_are_capped() {
|
||||
s.execute("graph.setType", &json!({"tickMarks": 3.0, "ticks": 4.0, "categoryTickMarks": 2.6})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
assert_eq!((g.tick_marks, g.ticks, g.category_tick_marks), (3, 4, 3));
|
||||
s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300, "rightTicks": -2.0})).unwrap();
|
||||
s.execute("graph.setType", &json!({"categoryTickMarks": 0, "rightTickMarks": 1e300})).unwrap();
|
||||
let g = spec(&s, id);
|
||||
assert_eq!((g.category_tick_marks, g.right_tick_marks, g.right_ticks), (1, 20, 0));
|
||||
// A negative count is refused.
|
||||
s.execute("graph.setType", &json!({"rightTicks": -2.0})).unwrap_err();
|
||||
assert_eq!(spec(&s, id).right_ticks, 0);
|
||||
// A file's values come back as drawn.
|
||||
let mut fields = s.execute("graph.setType", &json!({})).unwrap();
|
||||
assert_eq!(fields["rightTickMarks"], 20);
|
||||
@@ -4498,3 +4501,93 @@ fn a_legend_label_with_kept_negative_space_before_stays_below_the_entry_above_it
|
||||
let (first, next) = (bounds("2024"), bounds("20\n25"));
|
||||
assert!(next.y0 >= first.y1, "the second legend label starts below the first one: {first:?} {next:?}");
|
||||
}
|
||||
|
||||
/// A graph command given a value of the wrong type refuses it, naming the key, and leaves the graph and the undo
|
||||
/// history as they were; a null axis bound still goes back to the calculated value.
|
||||
#[test]
|
||||
fn graph_commands_refuse_params_of_the_wrong_type() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = graph(&mut s, "line");
|
||||
s.execute("graph.setType", &json!({"id": id.0, "axisMin": 0, "axisMax": 10})).unwrap();
|
||||
let spec = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().extras().graph.as_deref().cloned().unwrap();
|
||||
let undo_len = |s: &Session| s.doc().unwrap().history.undo.len();
|
||||
let (before, steps) = (spec(&s), undo_len(&s));
|
||||
let refused = |s: &mut Session, cmd: &str, p: serde_json::Value, msg: &str| {
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(msg), "{cmd} {p}: {e}");
|
||||
};
|
||||
for (key, v, msg) in [
|
||||
("axisMin", json!("10"), "`axisMin` must be a number or null, not \"10\""),
|
||||
("axisMax", json!(true), "`axisMax` must be a number or null"),
|
||||
("rightAxisMin", json!([1]), "`rightAxisMin` must be a number or null"),
|
||||
("rightAxisMax", json!({}), "`rightAxisMax` must be a number or null"),
|
||||
("columnWidth", json!("50"), "`columnWidth` must be a number, not \"50\""),
|
||||
("clusterWidth", json!(false), "`clusterWidth` must be a number"),
|
||||
("ticks", json!("5"), "`ticks` must be a number, not \"5\""),
|
||||
("ticks", json!(-2), "`ticks` must be 0 or more"),
|
||||
("rightTicks", json!("5"), "`rightTicks` must be a number"),
|
||||
("tickMarks", json!("2"), "`tickMarks` must be a number"),
|
||||
("rightTickMarks", json!(-1), "`rightTickMarks` must be 0 or more"),
|
||||
("categoryTickMarks", json!(true), "`categoryTickMarks` must be a number"),
|
||||
("legend", json!("false"), "`legend` must be true or false"),
|
||||
("markPoints", json!(0), "`markPoints` must be true or false"),
|
||||
("connectPoints", json!("no"), "`connectPoints` must be true or false"),
|
||||
("edgeToEdge", json!(1), "`edgeToEdge` must be true or false"),
|
||||
("separateScales", json!("true"), "`separateScales` must be true or false"),
|
||||
("ticksBetweenLabels", json!(1), "`ticksBetweenLabels` must be true or false"),
|
||||
("firstRowInFront", json!("yes"), "`firstRowInFront` must be true or false"),
|
||||
("firstColumnInFront", json!(0), "`firstColumnInFront` must be true or false"),
|
||||
("filledLines", json!("on"), "`filledLines` must be true or false"),
|
||||
("dropShadow", json!(1), "`dropShadow` must be true or false"),
|
||||
("legendAcrossTop", json!("x"), "`legendAcrossTop` must be true or false"),
|
||||
("type", json!(5), "`type` must be a string"),
|
||||
("valueAxis", json!(true), "`valueAxis` must be a string"),
|
||||
("tickLength", json!(1), "`tickLength` must be a string"),
|
||||
("rightTickLength", json!(1), "`rightTickLength` must be a string"),
|
||||
("categoryTickLength", json!(1), "`categoryTickLength` must be a string"),
|
||||
("prefix", json!(1), "`prefix` must be a string"),
|
||||
("suffix", json!(true), "`suffix` must be a string"),
|
||||
("rightPrefix", json!([]), "`rightPrefix` must be a string"),
|
||||
("rightSuffix", json!(2), "`rightSuffix` must be a string"),
|
||||
("pieLegend", json!(1), "`pieLegend` must be a string"),
|
||||
("piePosition", json!(1), "`piePosition` must be a string"),
|
||||
("pieSort", json!(1), "`pieSort` must be a string"),
|
||||
] {
|
||||
refused(&mut s, "graph.setType", json!({"id": id.0, key: v}), msg);
|
||||
}
|
||||
for (key, v, msg) in [
|
||||
("csv", json!(5), "`csv` must be a string"),
|
||||
("series", json!("a"), "`series` must be a list, not \"a\""),
|
||||
("categories", json!({}), "`categories` must be a list"),
|
||||
("rows", json!("1,2"), "`rows` must be a list"),
|
||||
("rows", json!([1, 2]), "`rows` must be lists of numbers or nulls, not 1"),
|
||||
("rows", json!([[1, "2"]]), "`rows` must be lists of numbers or nulls"),
|
||||
("transpose", json!("true"), "`transpose` must be true or false"),
|
||||
("switchXY", json!(1), "`switchXY` must be true or false"),
|
||||
] {
|
||||
refused(&mut s, "graph.setData", json!({"id": id.0, key: v}), msg);
|
||||
}
|
||||
assert_eq!(spec(&s), before);
|
||||
assert_eq!(undo_len(&s), steps);
|
||||
let count = |s: &Session| s.doc().unwrap().doc.node_count();
|
||||
let objects = count(&s);
|
||||
for (key, v, msg) in [
|
||||
("type", json!(1), "`type` must be a string"),
|
||||
("width", json!("300"), "`width` must be a number, not \"300\""),
|
||||
("height", json!(true), "`height` must be a number"),
|
||||
("csv", json!(1), "`csv` must be a string"),
|
||||
("rows", json!([[true]]), "`rows` must be lists of numbers or nulls"),
|
||||
] {
|
||||
let mut p = json!({"type": "column", "x": 0, "y": 0, "width": 100, "height": 100});
|
||||
p[key] = v;
|
||||
refused(&mut s, "graph.create", p, msg);
|
||||
}
|
||||
assert_eq!((count(&s), undo_len(&s)), (objects, steps));
|
||||
// A null is a key left out, except for an axis bound, where it goes back to the calculated value.
|
||||
s.execute("graph.setType", &json!({"id": id.0, "legend": null, "ticks": null, "prefix": null, "axisMin": null})).unwrap();
|
||||
assert_eq!(spec(&s).axis_min, None);
|
||||
assert_eq!(spec(&s).axis_max, Some(10.0));
|
||||
s.execute("graph.setData", &json!({"id": id.0, "rows": [[1, null], [2, 3]], "series": null, "transpose": null})).unwrap();
|
||||
assert_eq!(spec(&s).cells(), vec![vec![Some(1.0), None], vec![Some(2.0), Some(3.0)]]);
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use vectorcraft_doc::Node;
|
||||
use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes};
|
||||
|
||||
use super::edit::selected_roots;
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, color_value, f64_or, has_selection, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
@@ -27,28 +27,28 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
fn halftone(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.vectorHalftone";
|
||||
let shape = match str_param(p, "shape") {
|
||||
let shape = match text_param(p, "shape", C)? {
|
||||
Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?,
|
||||
None => DotShape::Circle,
|
||||
};
|
||||
let frequency = f64_or(p, "frequency", 20.0);
|
||||
let frequency = number_or(p, "frequency", 20.0, C)?;
|
||||
if !(1.0..=300.0).contains(&frequency) {
|
||||
return Err(bad(C, "frequency must be between 1 and 300 lines per inch"));
|
||||
}
|
||||
let angle = f64_or(p, "angle", 45.0);
|
||||
let angle = number_or(p, "angle", 45.0, C)?;
|
||||
if !angle.is_finite() {
|
||||
return Err(bad(C, "invalid angle"));
|
||||
}
|
||||
let mono = match str_param(p, "mode").unwrap_or("mono") {
|
||||
let mono = match text_param(p, "mode", C)?.unwrap_or("mono") {
|
||||
"mono" => true,
|
||||
"cmyk" => false,
|
||||
other => return Err(bad(C, format!("unknown mode `{other}` (mono|cmyk)"))),
|
||||
};
|
||||
let color = match p.get("color") {
|
||||
None | Some(Value::Null) => Color::BLACK,
|
||||
Some(v) => color_value(v).ok_or_else(|| bad(C, "invalid color"))?,
|
||||
None => Color::BLACK,
|
||||
};
|
||||
let (invert, clip, keep) = (bool_or(p, "invert", false), bool_or(p, "clip", true), bool_or(p, "keepOriginal", false));
|
||||
let (invert, clip, keep) = (switch_or(p, "invert", false, C)?, switch_or(p, "clip", true, C)?, switch_or(p, "keepOriginal", false, C)?);
|
||||
let ht = Halftone { shape, frequency, angle, mono, color, from_art: false, invert, clip };
|
||||
|
||||
let roots = selected_roots(s)?;
|
||||
|
||||
@@ -36,6 +36,8 @@ pub(crate) use arrange::group_nodes;
|
||||
pub(crate) use bounds::{bounds_rewrite, object_bounds_transform};
|
||||
pub use commands::specs;
|
||||
pub(super) use compound::{as_clipping_path, make_clipping_path, release_clip};
|
||||
pub(crate) use pixelgrid::{keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned};
|
||||
pub(crate) use pixelgrid::{
|
||||
can_align, keep_aligned_in, keep_compound_aligned, keep_pixel_aligned, refresh as refresh_pixel_aligned, resnap, snap_if_aligned,
|
||||
};
|
||||
pub(super) use shape::recut;
|
||||
pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects};
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_geom::FillRule;
|
||||
|
||||
use super::appearance::{ItemTarget, item_target};
|
||||
use super::edit::selected_roots;
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, f64_or, has_doc, ids_param, targets};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, ids_param, number_or, switch_or, targets};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -221,15 +221,16 @@ fn overprint_black_tree(n: &mut Node, op: &OverprintBlack, spots: &[String]) ->
|
||||
}
|
||||
|
||||
pub(crate) fn overprint_black(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "edit.colors.overprintBlack";
|
||||
let op = OverprintBlack {
|
||||
remove: bool_or(p, "remove", false),
|
||||
min_k: (f64_or(p, "percentage", 100.0) / 100.0).clamp(0.0, 1.0) as f32,
|
||||
fill: bool_or(p, "fill", true),
|
||||
stroke: bool_or(p, "stroke", true),
|
||||
rich: bool_or(p, "includeCmyBlacks", false),
|
||||
spot: bool_or(p, "includeSpotBlacks", false),
|
||||
remove: switch_or(p, "remove", false, C)?,
|
||||
min_k: (number_or(p, "percentage", 100.0, C)? / 100.0).clamp(0.0, 1.0) as f32,
|
||||
fill: switch_or(p, "fill", true, C)?,
|
||||
stroke: switch_or(p, "stroke", true, C)?,
|
||||
rich: switch_or(p, "includeCmyBlacks", false, C)?,
|
||||
spot: switch_or(p, "includeSpotBlacks", false, C)?,
|
||||
};
|
||||
let ids = match ids_param(p, "ids", "edit.colors.overprintBlack")? {
|
||||
let ids = match ids_param(p, "ids", C)? {
|
||||
Some(v) => v,
|
||||
None => selected_roots(s)?,
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::fileio::{create_dir, write_file};
|
||||
use super::links::LinkBase;
|
||||
use super::{CommandSpec, Result, Session, bad, bool_or, cmd, has_doc, str_param, unique_name};
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name};
|
||||
|
||||
const C: &str = "file.package";
|
||||
|
||||
@@ -451,19 +451,20 @@ impl Session {
|
||||
/// name, the report's Document Info text and the document.
|
||||
fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
|
||||
let o = Options {
|
||||
copy_links: bool_or(p, "copyLinks", true),
|
||||
links_folder: bool_or(p, "linksFolder", true),
|
||||
relink: bool_or(p, "relink", true),
|
||||
copy_fonts: bool_or(p, "copyFonts", true),
|
||||
report: bool_or(p, "report", true),
|
||||
copy_links: switch_or(p, "copyLinks", true, C)?,
|
||||
links_folder: switch_or(p, "linksFolder", true, C)?,
|
||||
relink: switch_or(p, "relink", true, C)?,
|
||||
copy_fonts: switch_or(p, "copyFonts", true, C)?,
|
||||
report: switch_or(p, "report", true, C)?,
|
||||
};
|
||||
let given_name = text_param(p, "name", C)?;
|
||||
let folder = text_param(p, "folder", C)?;
|
||||
let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?;
|
||||
let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
|
||||
let name = str_param(p, "name").map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string);
|
||||
if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||
return Err(bad(C, format!("`{name}` can't name a folder")));
|
||||
}
|
||||
let folder = str_param(p, "folder");
|
||||
let root = folder.map(|f| Path::new(f).join(&name));
|
||||
let info = if o.report { Some(super::docinfo::report(s, false)?) } else { None };
|
||||
let doc = s.doc()?.doc.clone();
|
||||
|
||||
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Fill",
|
||||
[],
|
||||
None,
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|freeform, method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits), dither?: bool (linear and radial fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear or radial `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector), method?: classic|perceptual (as paint.editGradient; default classic), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial and conic; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic), dither?: bool (linear, radial and conic fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), ids?|id?, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial or conic `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid colour recolours only the gradient mesh point last clicked with the Mesh tool or Direct Selection; while the Type tool has characters selected (and no ids or item are given), the paint goes to those characters only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern) → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed)}",
|
||||
has_doc,
|
||||
|s, p| set_paint(s, p, true)
|
||||
),
|
||||
@@ -641,7 +641,7 @@ fn paint_new_art(s: &mut Session, paint: &Paint, fill: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `p` ask for `span: "selection"` (#2127)? Only a linear or radial gradient the targets
|
||||
/// Does `p` ask for `span: "selection"` (#2127)? Only a linear, radial or conic gradient the targets
|
||||
/// would each fit to their own bounds can span them: one with its own vector (`start`/`end`),
|
||||
/// a freeform one or a gradient swatch already has its placement.
|
||||
fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String> {
|
||||
@@ -656,7 +656,7 @@ fn spans_targets(p: &Value, paint: &Paint) -> std::result::Result<bool, String>
|
||||
return Err("span: \"selection\" places a `gradient`, not a swatch".into());
|
||||
}
|
||||
if g.gradient.kind == vectorcraft_color::GradientKind::Freeform || g.freeform.is_some() {
|
||||
return Err("span: \"selection\" places a linear or radial gradient, not a freeform one".into());
|
||||
return Err("span: \"selection\" places a linear, radial or conic gradient, not a freeform one".into());
|
||||
}
|
||||
if g.geom.is_some() {
|
||||
return Err(
|
||||
|
||||
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Close Path",
|
||||
[],
|
||||
None,
|
||||
"{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor), independent?: bool}",
|
||||
"{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}",
|
||||
has_doc,
|
||||
close
|
||||
),
|
||||
@@ -202,14 +202,18 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Close the active open subpath of `id`, optionally setting the incoming handle of the first anchor.
|
||||
/// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The
|
||||
/// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only
|
||||
/// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape.
|
||||
fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?;
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
|
||||
let h_in = match p.get("in").filter(|h| !h.is_null()) {
|
||||
None => None,
|
||||
Some(h) => Some(finite_numbers(h).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.close", "`in` must be [x, y]"))?),
|
||||
let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) {
|
||||
None => Ok(None),
|
||||
Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))),
|
||||
};
|
||||
let h_in = handle("in")?;
|
||||
let h_out = handle("out")?;
|
||||
let independent = switch_or(p, "independent", false, "path.close")?;
|
||||
s.edit("Close Path", |d, sel| {
|
||||
let path = path_mut(d, id)?;
|
||||
@@ -218,11 +222,13 @@ fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => path.subpaths.iter_mut().rev().find(|s| !s.closed).ok_or_else(|| EngineError::Other("path is already closed".into()))?,
|
||||
};
|
||||
sp.closed = true;
|
||||
if let (Some(h), Some(first)) = (h_in, sp.anchors.first_mut()) {
|
||||
first.h_in = h;
|
||||
if !independent {
|
||||
first.h_out = first.p - (h - first.p);
|
||||
first.kind = AnchorKind::Smooth;
|
||||
if let Some(first) = sp.anchors.first_mut() {
|
||||
if let Some(h) = h_in {
|
||||
first.set_handle(false, h, independent);
|
||||
}
|
||||
if let Some(h) = h_out {
|
||||
first.h_out = h;
|
||||
first.kind = AnchorKind::Corner;
|
||||
}
|
||||
}
|
||||
let top = compound_or_self(d, id);
|
||||
|
||||
@@ -47,7 +47,10 @@ use vectorcraft_geom::{Affine, Point, Rect, shapes};
|
||||
use vectorcraft_pdf::CropTo;
|
||||
|
||||
use super::fileio::{self, Format, RasterImage};
|
||||
use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, finite_numbers, has_doc, object_param, str_param, unique_name};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, bool_or, check_numbers, check_switches, cmd, finite_numbers, has_doc, object_param, str_param,
|
||||
switch_or, unique_name,
|
||||
};
|
||||
use crate::{EngineError, MAX_COORD};
|
||||
|
||||
const PLACE: &str = "file.place";
|
||||
@@ -556,8 +559,9 @@ fn place(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn prepare(s: &Session, p: &Value) -> Result<PlaceJob> {
|
||||
let replace = bool_or(p, "replace", false);
|
||||
let template = bool_or(p, "template", false);
|
||||
let replace = switch_or(p, "replace", false, PLACE)?;
|
||||
let template = switch_or(p, "template", false, PLACE)?;
|
||||
check_switches(p, &["link"], PLACE)?;
|
||||
let at = at_param(p)?;
|
||||
let rect = rect_param(p)?;
|
||||
if replace && (template || at.is_some() || rect.is_some()) {
|
||||
@@ -778,6 +782,8 @@ impl Session {
|
||||
/// desktop the Place dialog's OK with several files does this off the UI thread).
|
||||
pub fn prepare_place_queue(&self, params: &Value) -> Result<QueueJob> {
|
||||
has_doc(self).map_err(|why| EngineError::Disabled(QUEUE.into(), why))?;
|
||||
check_switches(params, &["link", "template"], QUEUE)?;
|
||||
check_numbers(params, &["thumbnail"], QUEUE)?;
|
||||
Ok(QueueJob { params: params.clone(), files: queued_files(params)? })
|
||||
}
|
||||
|
||||
@@ -846,6 +852,8 @@ fn info(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `file.place.info` with `p`, without the session (on the desktop the Place dialog reads its
|
||||
/// files' lines this way off the UI thread).
|
||||
pub fn read_info(p: &Value) -> Result<Value> {
|
||||
check_switches(p, &["link"], "file.place.info")?;
|
||||
check_numbers(p, &["thumbnail"], "file.place.info")?;
|
||||
// A PDF/.ai page linked or not has the same size and art.
|
||||
let mut l = load(p, "file.place.info", None, false)?;
|
||||
let natural = l.natural;
|
||||
|
||||
@@ -1096,7 +1096,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Remove Plug-in",
|
||||
[],
|
||||
None,
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
"{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}",
|
||||
always,
|
||||
remove
|
||||
),
|
||||
|
||||
@@ -396,6 +396,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"paraStyle.apply",
|
||||
"paraStyle.delete",
|
||||
"paraStyle.duplicate",
|
||||
"paraStyle.edit",
|
||||
"paraStyle.list",
|
||||
"paraStyle.new",
|
||||
"paraStyle.redefine",
|
||||
@@ -484,6 +485,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"select.object.brushStrokes",
|
||||
"select.object.clippingMasks",
|
||||
"select.object.directionHandles",
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"select.object.pointText",
|
||||
"select.object.slices",
|
||||
"select.object.strayPoints",
|
||||
@@ -578,6 +580,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"symbol.replace",
|
||||
"symbol.selectInstances",
|
||||
"symbol.setCurrent",
|
||||
"symbol.sortByName",
|
||||
"symbol.spray",
|
||||
"symbol.unused",
|
||||
"symbol.update",
|
||||
|
||||
@@ -13,9 +13,7 @@ use vectorcraft_doc::swatches::{node_colors, node_paints, override_paints};
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::colorcmds::{NotChanged, Recolor, Scope, left_out};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, check_switches, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param,
|
||||
};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, color_value, has_doc, index, str_param, switch_or, text_param};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
@@ -566,8 +564,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if ids.is_empty() && group.is_none() {
|
||||
return Err(bad(C, "select artwork to recolour, or give a colour `group`"));
|
||||
}
|
||||
check_switches(p, &["includeImages", "includePatterns"], C)?;
|
||||
let scope = Scope { fill: true, stroke: true, ..Scope::of(p) };
|
||||
let scope =
|
||||
Scope { fill: true, stroke: true, images: switch_or(p, "includeImages", true, C)?, patterns: switch_or(p, "includePatterns", true, C)? };
|
||||
let label = if ids.is_empty() { "Edit Color Group" } else { "Recolor Artwork" };
|
||||
// `model`: keep each colour's model (default), take the new colour's own, or the document's.
|
||||
// A given `model` must be a string; only a missing one means "keep". A row's own `model`
|
||||
|
||||
@@ -7,6 +7,7 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Document, LockedArtboards, Node, NodeId, NodeKind};
|
||||
use vectorcraft_tools::builder::is_live_paint;
|
||||
|
||||
use super::object::can_align;
|
||||
use super::wand::{fill_of, stroke_of};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, checked_id, checked_ids_param, cmd, color_value, has_doc, has_selection, index, ok, str_param,
|
||||
@@ -178,6 +179,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
cmd!("select.object.openPaths", "Open Paths", ["Select", "Object"], None, "{}", has_doc, |s, _| by_kind(s, |n| n
|
||||
.path_data()
|
||||
.is_some_and(|p| !p.is_closed()))),
|
||||
cmd!(
|
||||
"select.object.notAlignedToPixelGrid",
|
||||
"Not Aligned to Pixel Grid",
|
||||
["Select", "Object"],
|
||||
None,
|
||||
"{} the paths (not guides) and compound paths whose pixel-aligned property (object.setPixelAligned) is off, looking into groups but not into compound paths → {count}",
|
||||
has_doc,
|
||||
not_pixel_aligned
|
||||
),
|
||||
cmd!(
|
||||
"select.same.graphicStyle",
|
||||
"Graphic Style",
|
||||
@@ -865,3 +875,19 @@ fn by_kind(s: &mut Session, f: fn(&Node) -> bool) -> Result<Value> {
|
||||
// The objects selected, after Lock Guides has left out guide paths.
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
|
||||
/// Select › Object › Not Aligned to Pixel Grid: the objects that can take the pixel-aligned
|
||||
/// property ([`can_align`]) and do not have it. A compound path counts as one object, so the walk
|
||||
/// does not look at the paths inside it.
|
||||
fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let st = s.doc()?;
|
||||
let mut ids = vec![];
|
||||
walk_selectable(&st.doc, st.isolation, |n| {
|
||||
if can_align(n) && !n.extras().pixel_aligned {
|
||||
ids.push(n.id);
|
||||
}
|
||||
!matches!(n.kind, NodeKind::Compound { .. })
|
||||
});
|
||||
s.select(|_, sel| sel.set(ids))?;
|
||||
Ok(json!({ "count": s.doc()?.selection.objects.len() }))
|
||||
}
|
||||
@@ -14,7 +14,9 @@ use vectorcraft_doc::style_libs::{self, STYLE_LIBRARIES, STYLES_EXT, builtin_sty
|
||||
use vectorcraft_doc::{Document, GraphicStyle, PatternDef, StyleLibrary};
|
||||
|
||||
use super::menucmds::squash;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, names_param, stem};
|
||||
use super::swatchlib::{
|
||||
FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, names_param, shown_id, shown_library_id, stem,
|
||||
};
|
||||
use super::{CommandSpec, Result, Session, always, bad, checked_ids_param, cmd, has_doc, str_param, switch_or, text_param, unique_name};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -94,6 +96,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<StyleLibrary>
|
||||
if let Some(found) = s.style_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.style_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = STYLE_LIBRARIES.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_style_library(key)?));
|
||||
}
|
||||
@@ -108,20 +113,22 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.style_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = 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.style_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.style_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.style_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.style_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "graphicStyle.library")?;
|
||||
let styles: Vec<Value> = lib.styles.iter().map(super::style::style_json).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "styles": styles}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "styles": styles}))
|
||||
}
|
||||
|
||||
/// Pattern `name` of `lib` in `d`: the document's own when it has the same pattern (under any
|
||||
@@ -192,7 +199,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let doc_name = |lib_name: &str| added.iter().find(|(l, _)| l == lib_name).map_or_else(|| lib_name.to_string(), |(_, n)| n.clone());
|
||||
let mut out = json!({
|
||||
"library": info.id,
|
||||
"library": shown_library_id(s, &info.id),
|
||||
"added": added.iter().map(|(_, n)| n).collect::<Vec<_>>(),
|
||||
"existing": existing.iter().map(|g| &g.name).collect::<Vec<_>>(),
|
||||
});
|
||||
@@ -238,5 +245,5 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
})?;
|
||||
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()}))
|
||||
}
|
||||
@@ -347,6 +347,7 @@ fn gradient_key(g: &Gradient) -> Option<GradientKey<'_>> {
|
||||
GradientKind::Linear => 0,
|
||||
GradientKind::Radial => 1,
|
||||
GradientKind::Freeform => 2,
|
||||
GradientKind::Conic => 3,
|
||||
};
|
||||
let method = match g.method {
|
||||
GradientMethod::Classic => 0,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! pattern) into the document; `swatch.library.save` writes the document's ([`palette_io`]).
|
||||
//! `swatch.library.copyToUser` copies a loaded library into the user library folder.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{BTreeSet, HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
@@ -211,6 +211,22 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
self.extra.iter().find(|e| e.info.id == id).and_then(|e| e.path.as_deref())
|
||||
}
|
||||
|
||||
/// The ids [`Libraries::get`] finds: the User Defined and loaded libraries', and the loaded ids of
|
||||
/// libraries copied into the user library folder.
|
||||
fn ids(&self) -> impl Iterator<Item = String> + '_ {
|
||||
self.extra.iter().map(|e| e.info.id.clone()).chain(self.copied.iter().map(|(loaded, _)| loaded.clone()))
|
||||
}
|
||||
|
||||
/// The file library `id` was read from, when the request being served may read it.
|
||||
pub fn shown_path(&self, id: &str) -> Option<&str> {
|
||||
self.path(id).filter(|p| readable(p))
|
||||
}
|
||||
|
||||
/// The user library folder, when the request being served may read it.
|
||||
pub fn shown_user_dir(&self) -> Option<&str> {
|
||||
self.user_dir().filter(|d| readable(d))
|
||||
}
|
||||
|
||||
/// The User Defined library whose file has the extension of file name `file` and holds `bytes`.
|
||||
fn user_file(&self, file: &str, bytes: &[u8]) -> Option<&Extra<L>> {
|
||||
let ext = extension(file);
|
||||
@@ -281,7 +297,10 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
self.saved_as
|
||||
.insert(format!("user/{file}").to_lowercase(), SavedAs { name: name.to_string(), hash: vectorcraft_doc::links::hash_bytes(bytes) });
|
||||
self.rescan();
|
||||
out["path"] = json!(path);
|
||||
// The folder is the app's own: a confined request sees the file only inside its read roots.
|
||||
if readable(&path) {
|
||||
out["path"] = json!(path);
|
||||
}
|
||||
out["library"] = json!(format!("user/{file}"));
|
||||
} else if let Some(path) = path {
|
||||
write_file(path, bytes)?;
|
||||
@@ -349,6 +368,10 @@ impl<L: LibraryFile> Libraries<L> {
|
||||
.ok_or_else(|| bad(cmd, format!("`{id}` isn't a loaded library")))?;
|
||||
let (file, bytes) = match source.filter(|p| L::EXTS.contains(&extension(p).as_str())) {
|
||||
Some(p) => {
|
||||
// Outside the request's read roots: the error names no path.
|
||||
if !readable(&p) {
|
||||
return Err(bad(cmd, "the library's file is outside the read roots"));
|
||||
}
|
||||
let ext = extension(&p);
|
||||
let base = file_name(&p);
|
||||
// A sandbox copy of an import often lands as tmp….tmp.acb (#2996): store it under the
|
||||
@@ -446,6 +469,72 @@ fn file_name(path: &str) -> String {
|
||||
std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string())
|
||||
}
|
||||
|
||||
/// May the request being served read `path` ([`crate::file_access::check_read`])? Always, without
|
||||
/// roots in force.
|
||||
fn readable(path: &str) -> bool {
|
||||
crate::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// The loaded library ids (`loaded/<path>`) whose file the request being served may not read, each
|
||||
/// with the id a reply shows instead: `loaded/<file name>`, as a library loaded without a path is
|
||||
/// named. The ids are those of the session's swatch, brush, symbol and graphic style libraries, then
|
||||
/// `others` (ids the UI state refers to). When another id already is or shows that id, the next free
|
||||
/// one of `loaded/<file name> (2)`, `(3)` and so on is shown, so that two libraries stay two. The
|
||||
/// session's libraries are numbered first, in the sorted order of their full ids, so a library shows
|
||||
/// the same id whatever `others` holds; then `others`, in the same order. Without roots in force, none.
|
||||
pub fn concealed_library_ids(s: &Session, others: impl IntoIterator<Item = String>) -> Vec<(String, String)> {
|
||||
if crate::file_access::current().is_none() {
|
||||
return vec![];
|
||||
}
|
||||
let session: BTreeSet<String> =
|
||||
s.swatch_libraries.ids().chain(s.brush_libraries.ids()).chain(s.symbol_libraries.ids()).chain(s.style_libraries.ids()).collect();
|
||||
let others: BTreeSet<String> = others.into_iter().filter(|id| !session.contains(id)).collect();
|
||||
let mut hidden = Vec::new();
|
||||
let mut taken = BTreeSet::new();
|
||||
for ids in [session, others] {
|
||||
for id in ids {
|
||||
let name = id.strip_prefix("loaded/").filter(|path| !path.is_empty()).map(|path| (file_name(path), path));
|
||||
match name {
|
||||
Some((name, path)) if name != path && !readable(path) => hidden.push((id, name)),
|
||||
_ => {
|
||||
taken.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hidden
|
||||
.into_iter()
|
||||
.map(|(id, name)| {
|
||||
let mut shown = format!("loaded/{name}");
|
||||
let mut n = 2;
|
||||
while taken.contains(&shown) {
|
||||
shown = format!("loaded/{name} ({n})");
|
||||
n += 1;
|
||||
}
|
||||
taken.insert(shown.clone());
|
||||
(id, shown)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The id a reply shows for library `id`, given the [`concealed_library_ids`] in force.
|
||||
pub(crate) fn shown_id(concealed: &[(String, String)], id: &str) -> String {
|
||||
concealed.iter().find(|(own, _)| own == id).map_or_else(|| id.to_string(), |(_, shown)| shown.clone())
|
||||
}
|
||||
|
||||
/// The id a reply shows for library `id` ([`concealed_library_ids`]).
|
||||
pub(crate) fn shown_library_id(s: &Session, id: &str) -> String {
|
||||
shown_id(&concealed_library_ids(s, []), id)
|
||||
}
|
||||
|
||||
/// The library id behind `key` when `key` is the id a reply shows for a concealed loaded library.
|
||||
pub(crate) fn concealed_library_id(s: &Session, key: &str) -> Option<String> {
|
||||
if !key.starts_with("loaded/") {
|
||||
return None;
|
||||
}
|
||||
concealed_library_ids(s, []).into_iter().find(|(_, shown)| shown == key).map(|(own, _)| own)
|
||||
}
|
||||
|
||||
/// `name` without its extension.
|
||||
pub(crate) fn stem(name: &str) -> &str {
|
||||
name.rsplit_once('.').map_or(name, |(s, _)| s)
|
||||
@@ -479,6 +568,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SwatchLibrary
|
||||
if let Some(found) = s.swatch_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.swatch_libraries.get(&id)) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = builtins().find(|(_, b)| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
@@ -556,14 +648,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.swatch_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = 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.swatch_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.swatch_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.swatch_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.swatch_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
/// The document's swatches `names` (swatches or colour groups; empty: all) as a library named
|
||||
@@ -619,7 +713,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
document_library(&loaded.doc, &[], stem(file).to_string(), C)
|
||||
}
|
||||
})?;
|
||||
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()}))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -629,7 +723,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let groups: Vec<Value> =
|
||||
lib.groups.iter().map(|g| json!({"name": g.name, "swatches": g.swatches.iter().map(|w| &w.name).collect::<Vec<_>>()})).collect();
|
||||
Ok(
|
||||
json!({"id": info.id, "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}),
|
||||
json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "swatches": ungrouped.chain(grouped).collect::<Vec<_>>(), "groups": groups}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -652,7 +746,7 @@ fn copy_to_user(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"user" => (info, lib, false),
|
||||
_ => return Err(bad(C, format!("`{}` is built in and always listed", info.name))),
|
||||
};
|
||||
let path = s.swatch_libraries.path(&info.id);
|
||||
let path = s.swatch_libraries.shown_path(&info.id);
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len(), "path": path, "copied": copied}))
|
||||
}
|
||||
|
||||
@@ -792,7 +886,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?
|
||||
};
|
||||
let names = |list: &[(String, String)]| list.iter().map(|(_, n)| n.clone()).collect::<Vec<_>>();
|
||||
let mut out = json!({"library": info.id, "added": names(&added), "existing": names(&existing)});
|
||||
let mut out = json!({"library": shown_library_id(s, &info.id), "added": names(&added), "existing": names(&existing)});
|
||||
if let (Some(cmd), Some((_, first))) = (apply, picked.first()) {
|
||||
let name = added.iter().chain(&existing).find(|(l, _)| *l == first.name).map_or(first.name.clone(), |(_, n)| n.clone());
|
||||
s.execute(cmd, &json!({"swatch": name, "focus": focus}))?;
|
||||
|
||||
@@ -19,7 +19,7 @@ use super::brushsym::{CURRENT_SYMBOL, natural_size, normalize, place_xf, set_nat
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
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, number_or, str_param};
|
||||
|
||||
/// The extension of saved symbol libraries: native documents.
|
||||
@@ -386,6 +386,9 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<SymbolLibrary
|
||||
if let Some(found) = s.symbol_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(found) = concealed_library_id(s, key).and_then(|id| s.symbol_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)?));
|
||||
}
|
||||
@@ -400,14 +403,16 @@ fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.symbol_libraries.rescan();
|
||||
let concealed = concealed_library_ids(s, []);
|
||||
let libs: Vec<Value> = 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.symbol_libraries.path(&l.id)})
|
||||
let (id, path) = (shown_id(&concealed, &l.id), s.symbol_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.symbol_libraries.user_dir() }))
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.symbol_libraries.shown_user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -421,7 +426,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
json!({"name": sym.name, "size": [w, h], "registration": d.symbol_registration(&sym.name).0, "exportType": d.symbol_export_type(&sym.name).id()})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "symbols": symbols}))
|
||||
Ok(json!({"id": shown_library_id(s, &info.id), "name": info.name, "category": info.category, "symbols": symbols}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -456,7 +461,7 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO);
|
||||
let at = if place { Some(Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?)) } else { None };
|
||||
let parent = if place { st.target_parent()? } else { None };
|
||||
let mut out = json!({ "library": info.id });
|
||||
let mut out = json!({ "library": shown_library_id(s, &info.id) });
|
||||
if imported.added > 0 || place {
|
||||
let placed = s.edit("Add to Symbols", |d, sel| {
|
||||
let imported = clip.import_into(d, &choices, false)?;
|
||||
@@ -512,7 +517,7 @@ fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
SymbolLibrary::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()}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -85,7 +85,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area / Path Type",
|
||||
[],
|
||||
None,
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
"{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}",
|
||||
has_doc,
|
||||
create_in_path
|
||||
),
|
||||
@@ -1644,7 +1644,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
super::create::new_type_alignment(s, p, C, &mut t)?;
|
||||
if !on_path {
|
||||
t.area.fit = super::create::new_area_fit(s, p, C)?;
|
||||
super::create::new_area_fit(s, p, C, &mut t)?;
|
||||
}
|
||||
t.system_layout = s.doc()?.doc.setup.system_layout;
|
||||
if bool_or(p, "placeholder", false) {
|
||||
|
||||
@@ -143,7 +143,21 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|s, p| edit_style(s, p, Kind::Char),
|
||||
true,
|
||||
));
|
||||
v.extend(style_cmds!(Kind::Para, "paraStyle", "Paragraph Styles", "Paragraph", ""));
|
||||
v.extend(style_cmds!(
|
||||
Kind::Para,
|
||||
"paraStyle",
|
||||
"Paragraph Styles",
|
||||
"Paragraph",
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
|
||||
));
|
||||
v.push(spec(
|
||||
"paraStyle.edit",
|
||||
"Edit Paragraph Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
|
||||
|s, p| edit_style(s, p, Kind::Para),
|
||||
true,
|
||||
));
|
||||
v.push(spec("textStyle.loadAll", "Load All Styles…", &["Window", "Type"], LOAD_PARAMS, |s, p| load(s, p, &[Kind::Char, Kind::Para]), true));
|
||||
v
|
||||
}
|
||||
@@ -562,7 +576,11 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => para_attrs(&with_attrs(&ParaStyle::default(), m, &c)?),
|
||||
Kind::Para => {
|
||||
let st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
para_attrs(&st)
|
||||
}
|
||||
};
|
||||
Ok(Some(m.keys().filter_map(|k| full.get(k).map(|v| (k.clone(), v.clone()))).collect()))
|
||||
}
|
||||
@@ -570,6 +588,82 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a paragraph style's indents, space before and space after, and Hyphenation Zone (pt),
|
||||
/// as `text.setFormat` keeps them.
|
||||
const PARA_DISTANCE: f64 = 1296.0;
|
||||
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
};
|
||||
let changed = |key: &str| attrs.contains_key(key) && kept.and_then(|k| k.get(key)) != attrs.get(key);
|
||||
let nested_changed = |key: &str, field: &str| {
|
||||
changed(key) && attrs.get(key).and_then(|v| v.get(field)) != kept.and_then(|k| k.get(key)).and_then(|v| v.get(field))
|
||||
};
|
||||
for (key, value) in [
|
||||
("left_indent", st.left_indent),
|
||||
("right_indent", st.right_indent),
|
||||
("first_line_indent", st.first_line_indent),
|
||||
("space_before", st.space_before),
|
||||
("space_after", st.space_after),
|
||||
] {
|
||||
if changed(key) {
|
||||
within(key, value, -PARA_DISTANCE, PARA_DISTANCE)?;
|
||||
}
|
||||
}
|
||||
let h = &st.hyphenation;
|
||||
for (field, value, lo, hi) in [
|
||||
("words_longer_than", f64::from(h.words_longer_than), 1.0, 25.0),
|
||||
("after_first", f64::from(h.after_first), 1.0, 15.0),
|
||||
("before_last", f64::from(h.before_last), 1.0, 15.0),
|
||||
("hyphen_limit", f64::from(h.hyphen_limit), 0.0, 25.0),
|
||||
("zone", h.zone, 0.0, PARA_DISTANCE),
|
||||
] {
|
||||
if nested_changed("hyphenation", field) {
|
||||
within(&format!("hyphenation.{field}"), value, lo, hi)?;
|
||||
}
|
||||
}
|
||||
// Read as given: a paragraph's attributes keep justification options in range as they load.
|
||||
if let Some(given) = attrs.get("justification").filter(|_| changed("justification")) {
|
||||
let j: vectorcraft_doc::JustificationOptions = serde_json::from_value(given.clone()).map_err(|e| bad(c, e.to_string()))?;
|
||||
for (field, values, (lo, hi)) in [
|
||||
("word_spacing", j.word_spacing, vectorcraft_doc::JustificationOptions::WORD_SPACING),
|
||||
("letter_spacing", j.letter_spacing, vectorcraft_doc::JustificationOptions::LETTER_SPACING),
|
||||
("glyph_scaling", j.glyph_scaling, vectorcraft_doc::JustificationOptions::GLYPH_SCALING),
|
||||
] {
|
||||
if !nested_changed("justification", field) {
|
||||
continue;
|
||||
}
|
||||
let name = format!("justification.{field}");
|
||||
for value in values {
|
||||
within(&name, value, lo, hi)?;
|
||||
}
|
||||
if !(values[0] <= values[1] && values[1] <= values[2]) {
|
||||
return Err(bad(c, format!("`{name}`: Minimum must not exceed Desired, nor Desired Maximum")));
|
||||
}
|
||||
}
|
||||
if nested_changed("justification", "auto_leading") {
|
||||
let (lo, hi) = vectorcraft_doc::JustificationOptions::AUTO_LEADING;
|
||||
within("justification.auto_leading", j.auto_leading, lo, hi)?;
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs: Vec<f64> = kept
|
||||
.and_then(|k| k.get("tabs"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
|
||||
.unwrap_or_default();
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
|
||||
within("tabs.position", stop.position, 0.0, 100_000.0)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
|
||||
@@ -1587,3 +1587,147 @@ fn para_style_range_capture_samples_start_paragraph() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paras(s: &Session, id: u64) -> Vec<ParaStyle> {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.paragraph_styles(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `paraStyle.edit` renames a paragraph style and replaces its attributes in one undo step: every
|
||||
/// paragraph using it takes the new values, a paragraph's local override stays, and the saved file
|
||||
/// keeps the sparse definition.
|
||||
#[test]
|
||||
fn paragraph_style_options_edit_applies_to_users_and_is_one_saved_undo_step() {
|
||||
use vectorcraft_doc::Composer;
|
||||
let (mut s, id) = session_with_text("One\nTwo\nThree");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0, "composer": "everyLine", "tabs": [{"position": 36.0}]}}))
|
||||
.unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Body", "id": id, "start": 0, "end": 7})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"id": id, "start": 4, "end": 4, "leftIndent": 20.0})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let attrs = json!({"left_indent": 12.0, "composer": "singleLine", "tabs": [{"position": 36.0}],
|
||||
"hyphenation": {"words_longer_than": 8}, "justification": {"word_spacing": [70.0, 90.0, 120.0]}});
|
||||
s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Text", "attrs": attrs})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
|
||||
let p = paras(&s, id);
|
||||
assert_eq!(
|
||||
p.iter().map(|p| (p.style_name.as_deref(), p.left_indent, p.composer)).collect::<Vec<_>>(),
|
||||
[(Some("Text"), 12.0, Composer::SingleLine), (Some("Text"), 20.0, Composer::SingleLine), (None, 0.0, Composer::EveryLine)]
|
||||
);
|
||||
assert_eq!(p[0].hyphenation.words_longer_than, 8);
|
||||
assert_eq!(p[1].justification.word_spacing, [70.0, 90.0, 120.0]);
|
||||
let def = s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs.clone();
|
||||
let mut keys: Vec<&str> = def.keys().map(String::as_str).collect();
|
||||
keys.sort_unstable();
|
||||
assert_eq!(keys, ["composer", "hyphenation", "justification", "left_indent", "tabs"]);
|
||||
let saved = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!(saved.para_styles.iter().find(|d| d.name == "Text").unwrap().attrs, def);
|
||||
let changed = s.doc().unwrap().doc.clone();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc, changed);
|
||||
// The Normal style, an empty or a taken name and an unknown style are errors.
|
||||
s.execute("paraStyle.new", &json!({"name": "Other"})).unwrap();
|
||||
for (params, why) in [
|
||||
(json!({"name": "Text", "to": " ", "attrs": {}}), "give the style a name"),
|
||||
(json!({"name": "Text", "to": "Other", "attrs": {}}), "already exists"),
|
||||
(json!({"name": "Missing", "to": "Missing", "attrs": {}}), "no style `Missing`"),
|
||||
(json!({"name": NORMAL_PARA, "to": NORMAL_PARA, "attrs": {}}), "can't be edited"),
|
||||
] {
|
||||
let error = s.execute("paraStyle.edit", ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(why), "{params}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A changed paragraph attribute outside the range `text.setFormat` keeps it to is an error for
|
||||
/// `paraStyle.edit`, `paraStyle.setAttrs` and `paraStyle.new`, with no change to the document; the
|
||||
/// ends of each range are accepted, and an out-of-range value the style already has can be kept.
|
||||
#[test]
|
||||
fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"left_indent": 6.0}})).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
for (attrs, key) in [
|
||||
(json!({"left_indent": -1296.1}), "left_indent"),
|
||||
(json!({"right_indent": 1296.1}), "right_indent"),
|
||||
(json!({"first_line_indent": 1e300}), "first_line_indent"),
|
||||
(json!({"space_before": 1296.1}), "space_before"),
|
||||
(json!({"space_after": -1296.1}), "space_after"),
|
||||
(json!({"hyphenation": {"words_longer_than": 0}}), "hyphenation.words_longer_than"),
|
||||
(json!({"hyphenation": {"words_longer_than": 4000000000_u64}}), "hyphenation.words_longer_than"),
|
||||
(json!({"hyphenation": {"after_first": 16}}), "hyphenation.after_first"),
|
||||
(json!({"hyphenation": {"before_last": 0}}), "hyphenation.before_last"),
|
||||
(json!({"hyphenation": {"hyphen_limit": 26}}), "hyphenation.hyphen_limit"),
|
||||
(json!({"hyphenation": {"zone": -1.0}}), "hyphenation.zone"),
|
||||
(json!({"hyphenation": {"zone": 1296.1}}), "hyphenation.zone"),
|
||||
(json!({"justification": {"word_spacing": [80.0, 100.0, 1000.1]}}), "justification.word_spacing"),
|
||||
(json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}}), "justification.word_spacing"),
|
||||
(json!({"justification": {"letter_spacing": [-100.1, 0.0, 0.0]}}), "justification.letter_spacing"),
|
||||
(json!({"justification": {"letter_spacing": [0.0, 10.0, 5.0]}}), "justification.letter_spacing"),
|
||||
(json!({"justification": {"glyph_scaling": [49.0, 100.0, 100.0]}}), "justification.glyph_scaling"),
|
||||
(json!({"justification": {"auto_leading": 500.1}}), "justification.auto_leading"),
|
||||
(json!({"tabs": [{"position": 100000.1}]}), "tabs.position"),
|
||||
(json!({"tabs": [{"position": -1.0}]}), "tabs.position"),
|
||||
] {
|
||||
for cmd in ["paraStyle.edit", "paraStyle.setAttrs", "paraStyle.new"] {
|
||||
let params = match cmd {
|
||||
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": attrs}),
|
||||
"paraStyle.new" => json!({"name": "Other", "attrs": attrs}),
|
||||
_ => json!({"name": "Body", "attrs": attrs}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("`{key}`")), "{cmd} {attrs}: {error}");
|
||||
}
|
||||
}
|
||||
// Malformed values are errors too.
|
||||
for attrs in [json!({"hyphenation": {"words_longer_than": -1}}), json!({"justification": {"word_spacing": [1.0, 2.0]}}), json!({"tabs": 3})] {
|
||||
assert!(s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Body", "attrs": attrs})).is_err(), "{attrs}");
|
||||
}
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo);
|
||||
|
||||
let ends = json!({
|
||||
"left_indent": -1296.0, "right_indent": 1296.0, "first_line_indent": 0.0, "space_before": 1296.0, "space_after": -1296.0,
|
||||
"hyphenation": {"words_longer_than": 25, "after_first": 1, "before_last": 15, "hyphen_limit": 0, "zone": 1296.0},
|
||||
"justification": {"word_spacing": [0.0, 0.0, 1000.0], "letter_spacing": [-100.0, 0.0, 500.0], "glyph_scaling": [50.0, 100.0, 200.0], "auto_leading": 500.0},
|
||||
"tabs": [{"position": 0.0}, {"position": 100000.0}]
|
||||
});
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": ends})).unwrap();
|
||||
// A style that already holds a value out of range (one read from a file) can be renamed with it.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("left_indent".into(), json!(2000.0));
|
||||
s.execute("paraStyle.edit", &json!({"name": "Body", "to": "Renamed", "attrs": {"left_indent": 2000.0}})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.para_styles.iter().any(|d| d.name == "Renamed"));
|
||||
// Such a Hyphenation, Justification or tab value is kept while another option of its group changes,
|
||||
// and a changed option is still checked.
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let held = json!({
|
||||
"hyphenation": {"words_longer_than": 40, "after_first": 2},
|
||||
"justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 120.0},
|
||||
"tabs": [{"position": 200000.0}]
|
||||
});
|
||||
let attrs = &mut doc.para_styles.iter_mut().find(|d| d.name == "Renamed").unwrap().attrs;
|
||||
attrs.extend(held.as_object().unwrap().clone());
|
||||
let edited = json!({
|
||||
"hyphenation": {"words_longer_than": 40, "after_first": 3},
|
||||
"justification": {"letter_spacing": [0.0, 0.0, 600.0], "auto_leading": 150.0},
|
||||
"tabs": [{"position": 200000.0}, {"position": 72.0}]
|
||||
});
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": edited})).unwrap();
|
||||
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Renamed").unwrap().attrs.clone();
|
||||
assert_eq!(def(&s)["hyphenation"]["after_first"], json!(3));
|
||||
assert_eq!(def(&s)["justification"]["auto_leading"], json!(150.0));
|
||||
for (attrs, key) in [
|
||||
(json!({"hyphenation": {"words_longer_than": 40, "after_first": 16}}), "hyphenation.after_first"),
|
||||
(json!({"justification": {"auto_leading": 501.0}}), "justification.auto_leading"),
|
||||
(json!({"tabs": [{"position": 200000.0}, {"position": 72.0}, {"position": 100001.0}]}), "tabs.position"),
|
||||
] {
|
||||
let error = s.execute("paraStyle.setAttrs", &json!({"name": "Renamed", "attrs": attrs})).unwrap_err().to_string();
|
||||
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Area Type Options…",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText, fitMinPercent?: 10..100, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit (none given: query) → the first object's options, plus overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
"{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)",
|
||||
has_selection,
|
||||
area_options
|
||||
),
|
||||
@@ -304,11 +304,13 @@ fn ruby(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing
|
||||
/// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo
|
||||
/// step as the edit.
|
||||
/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text, and Dynamic Text's Block
|
||||
/// (`dynamic_text` on area type, [`block::block_fit`]) sizes each line to the frame: part of the
|
||||
/// same undo step as the edit.
|
||||
pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
// Edits that changed the paragraph count keep one paragraph style per paragraph.
|
||||
t.normalize_paras();
|
||||
block::block_fit(t);
|
||||
auto_height(t);
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
t.cached_bounds = Some(lay.bounds);
|
||||
@@ -320,6 +322,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) {
|
||||
/// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again.
|
||||
pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) {
|
||||
t.normalize_paras();
|
||||
block::block_fit(t);
|
||||
auto_height(t);
|
||||
let stamp = vectorcraft_text::LayoutStamp::now();
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
@@ -1026,7 +1029,7 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje
|
||||
}
|
||||
|
||||
/// Area type's text, if `n` is area type.
|
||||
fn area_text(n: Option<&Node>) -> Option<&TextObject> {
|
||||
pub(crate) fn area_text(n: Option<&Node>) -> Option<&TextObject> {
|
||||
match n.map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) => Some(t),
|
||||
_ => None,
|
||||
@@ -1059,10 +1062,15 @@ fn size_area(t: &mut TextObject, w: Option<f64>, h: Option<f64>) -> bool {
|
||||
reshape_area_with(t, |t| t.transform_area(a))
|
||||
}
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent`
|
||||
/// while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaFit>> {
|
||||
/// A fit `p` asks for: the Area Type Options fit, and whether Dynamic Text's Block
|
||||
/// ([`TextObject::dynamic_text`]) is on. Block's fit is [`AreaFit::None`]: it replaces Auto Size
|
||||
/// and Shrink Text to Fit.
|
||||
pub(crate) type FitChoice = (AreaFit, bool);
|
||||
|
||||
/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText|block or `{"shrinkText": {"minPercent"}}`,
|
||||
/// `fitMinPercent`), starting from `cur` (`block`: Block is on). None when `p` sets neither (or only
|
||||
/// `fitMinPercent` while the fit isn't Shrink Text).
|
||||
pub(crate) fn fit_param(p: &Value, cur: AreaFit, block: bool, c: &str) -> Result<Option<FitChoice>> {
|
||||
check_numbers(p, &["fitMinPercent"], c)?;
|
||||
let min = p.get("fitMinPercent").and_then(Value::as_f64);
|
||||
let cur_min = match cur {
|
||||
@@ -1071,21 +1079,48 @@ pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result<Option<AreaF
|
||||
};
|
||||
let fit = match p.get("fit") {
|
||||
None | Some(Value::Null) => match (cur, min) {
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m },
|
||||
(AreaFit::ShrinkText { .. }, Some(m)) if !block => AreaFit::ShrinkText { min_percent: m },
|
||||
_ => return Ok(None),
|
||||
},
|
||||
Some(Value::String(id)) if is_block_id(id) => return Ok(Some((AreaFit::None, true))),
|
||||
Some(Value::String(id)) => {
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))?
|
||||
AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText|block, got {id}")))?
|
||||
}
|
||||
Some(v) => match serde_json::from_value::<AreaFit>(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
};
|
||||
Ok(Some(match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
}))
|
||||
Ok(Some((
|
||||
match fit {
|
||||
AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) },
|
||||
f => f,
|
||||
},
|
||||
false,
|
||||
)))
|
||||
}
|
||||
|
||||
/// Whether a `fit` id names Dynamic Text's Block (case, spaces, dashes and underscores ignored).
|
||||
fn is_block_id(id: &str) -> bool {
|
||||
matches!(id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "block" | "dynamictext")
|
||||
}
|
||||
|
||||
/// The `fit` id area type reports: `block` while Dynamic Text's Block is on, else its fit's.
|
||||
pub(crate) fn fit_id(t: &TextObject) -> &'static str {
|
||||
if t.dynamic_text { "block" } else { t.area.fit.id() }
|
||||
}
|
||||
|
||||
/// Dynamic Text's Block gaps `p` gives: `wordGap` (% of a word space, 0..1000) and `lineGap` (pt,
|
||||
/// -1296..1296). A value that is not a number, or is outside its range, is an error.
|
||||
pub(crate) fn block_gaps(p: &Value, c: &str) -> Result<(Option<f64>, Option<f64>)> {
|
||||
let gap = |key: &str, (lo, hi): (f64, f64)| -> Result<Option<f64>> {
|
||||
match number_given(p, key, c)? {
|
||||
Some(v) if !(v.is_finite() && (lo..=hi).contains(&v)) => Err(bad(c, format!("`{key}` must be from {lo} to {hi}, not {v}"))),
|
||||
v => Ok(v),
|
||||
}
|
||||
};
|
||||
use vectorcraft_doc::AreaOptions as O;
|
||||
Ok((gap("wordGap", O::WORD_GAP)?, gap("lineGap", O::LINE_GAP)?))
|
||||
}
|
||||
|
||||
/// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as
|
||||
@@ -1095,7 +1130,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
o.insert("fit".into(), json!(t.area.fit.id()));
|
||||
o.insert("fit".into(), json!(fit_id(t)));
|
||||
o.insert("flow".into(), json!(t.area.flow));
|
||||
// The gutter between rows, the gutter's when the rows have none of their own.
|
||||
o.insert("rowGutter".into(), json!(t.area.row_gutter.unwrap_or(t.area.gutter)));
|
||||
@@ -1104,6 +1139,9 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result<Value> {
|
||||
_ => AreaFit::DEFAULT_MIN_PERCENT,
|
||||
};
|
||||
o.insert("fitMinPercent".into(), json!(min));
|
||||
let (word_gap, line_gap) = t.area.block_gaps();
|
||||
o.insert("wordGap".into(), json!(word_gap));
|
||||
o.insert("lineGap".into(), json!(line_gap));
|
||||
if let Some((w, h, _)) = area_size(t) {
|
||||
o.insert("width".into(), json!(w));
|
||||
o.insert("height".into(), json!(h));
|
||||
@@ -1132,8 +1170,9 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Checked once up front (its errors don't depend on the frame); each frame resolves `fit`
|
||||
// against its own setting below.
|
||||
let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default();
|
||||
fit_param(p, cur.fit, C)?;
|
||||
let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null());
|
||||
fit_param(p, cur.fit, false, C)?;
|
||||
let (word_gap, line_gap) = block_gaps(p, C)?;
|
||||
let fit_given = ["fit", "fitMinPercent", "wordGap", "lineGap"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null()));
|
||||
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0));
|
||||
let (w, h) = (size("width"), size("height"));
|
||||
let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect();
|
||||
@@ -1142,7 +1181,7 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
// Each area type takes the options given over its own (#3759): setting one option on several
|
||||
// frames leaves their other options as they were.
|
||||
let merged = |own: &vectorcraft_doc::AreaOptions| -> Result<vectorcraft_doc::AreaOptions> {
|
||||
let merged = |own: &vectorcraft_doc::AreaOptions, block: bool| -> Result<(vectorcraft_doc::AreaOptions, bool)> {
|
||||
let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?;
|
||||
if let Some(o) = v.as_object_mut() {
|
||||
for (k, val) in &given {
|
||||
@@ -1162,17 +1201,29 @@ fn area_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
opts.inset = finite(opts.inset).clamp(0.0, 10_000.0);
|
||||
opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0);
|
||||
// Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames).
|
||||
opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit);
|
||||
Ok(opts)
|
||||
let (fit, block) = fit_param(p, own.fit, block, C)?.unwrap_or((own.fit, block));
|
||||
opts.fit = fit;
|
||||
opts.word_gap = word_gap.unwrap_or(own.word_gap);
|
||||
opts.line_gap = line_gap.unwrap_or(own.line_gap);
|
||||
Ok((opts, block))
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids
|
||||
let planned: Vec<(NodeId, (vectorcraft_doc::AreaOptions, bool))> = ids
|
||||
.iter()
|
||||
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area)))
|
||||
.map(|(id, own)| merged(own).map(|o| (id, o)))
|
||||
.filter_map(|id| area_text(d.node(*id)).map(|t| (*id, t)))
|
||||
.map(|(id, t)| merged(&t.area, t.dynamic_text).map(|o| (id, o)))
|
||||
.collect::<Result<_>>()?;
|
||||
let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| {
|
||||
// Dynamic Text's Block is refused for threaded frames, as `type.dynamicText` refuses it.
|
||||
let frames: Vec<String> =
|
||||
planned.iter().filter(|(id, (_, block))| *block && !super::threads::story_of(d, *id).is_empty()).map(|(id, _)| id.0.to_string()).collect();
|
||||
if !frames.is_empty() {
|
||||
let frames = frames.join(", ");
|
||||
return Err(bad(C, format!("area type in a thread cannot use Dynamic Text: {frames}")));
|
||||
}
|
||||
let apply = |t: &mut TextObject, (opts, block): &(vectorcraft_doc::AreaOptions, bool)| {
|
||||
t.area = opts.clone();
|
||||
// Block off keeps the sizes it wrote into the characters.
|
||||
t.dynamic_text = *block;
|
||||
// Auto Size sets the height (Illustrator's dialog turns the Height field off).
|
||||
let h = if opts.fit == AreaFit::AutoHeight { None } else { h };
|
||||
// A resized frame has laid its text out again; otherwise the new options do here.
|
||||
@@ -1313,6 +1364,9 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod area_tests;
|
||||
mod block;
|
||||
#[cfg(test)]
|
||||
mod block_tests;
|
||||
|
||||
/// Width of the first line and of the space it can fill, with `tracking` on the first paragraph.
|
||||
/// The third value is where the first line ends in the plain text.
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
//! Dynamic Text's Block for area type ([`TextObject::dynamic_text`] on area type): each line as
|
||||
//! typed is set to the frame's width by changing its font size, after every edit
|
||||
//! ([`super::refresh_bounds`]).
|
||||
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
|
||||
/// The font size range a line's first character is fitted within, in document points (the
|
||||
/// Character panel's).
|
||||
const SIZES: (f64, f64) = (0.1, 1296.0);
|
||||
|
||||
/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures
|
||||
/// the lines and runs at most one more area layout.
|
||||
pub(crate) const BLOCK_PASSES: usize = 4;
|
||||
|
||||
/// One line as typed: `start..content` is its text, `content..end` the `\n` or U+2028 that ends it
|
||||
/// (empty for the last line). `para` is the index of its paragraph, and `para_start` whether it
|
||||
/// starts that paragraph.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct TypedLine {
|
||||
start: usize,
|
||||
content: usize,
|
||||
end: usize,
|
||||
para: usize,
|
||||
para_start: bool,
|
||||
}
|
||||
|
||||
/// The lines as typed: the text split after each `\n` and U+2028.
|
||||
fn typed_lines(text: &str) -> Vec<TypedLine> {
|
||||
let mut out = vec![];
|
||||
let (mut start, mut para, mut para_start) = (0, 0, true);
|
||||
for (i, c) in text.char_indices() {
|
||||
if c == '\n' || c == '\u{2028}' {
|
||||
let end = i + c.len_utf8();
|
||||
out.push(TypedLine { start, content: i, end, para, para_start });
|
||||
start = end;
|
||||
para_start = c == '\n';
|
||||
if c == '\n' {
|
||||
para += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(TypedLine { start, content: text.len(), end: text.len(), para, para_start });
|
||||
out
|
||||
}
|
||||
|
||||
/// The stored size of the character at `byte` (the run that holds it, not the one before it).
|
||||
pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 {
|
||||
let mut off = 0;
|
||||
for r in runs {
|
||||
let end = off + r.text.len();
|
||||
if (off..end).contains(&byte) {
|
||||
return r.style.size;
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
vectorcraft_text::edit::style_at(runs, byte).size
|
||||
}
|
||||
|
||||
/// The stored size of each line's first character, in one pass over the runs.
|
||||
fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(lines.len());
|
||||
let (mut ri, mut off) = (0, 0);
|
||||
for l in lines {
|
||||
while let Some(r) = runs.get(ri) {
|
||||
if l.start < off + r.text.len() {
|
||||
break;
|
||||
}
|
||||
off += r.text.len();
|
||||
ri += 1;
|
||||
}
|
||||
out.push(runs.get(ri).map_or_else(|| size_at(runs, l.start), |r| r.style.size));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Each line's content width (trailing spaces left out) by its first byte, with `t` laid out as
|
||||
/// point type, where no line wraps, with the word spacing `t`'s layout uses.
|
||||
fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collections::HashMap<usize, f64> {
|
||||
let mut probe = t.clone();
|
||||
for p in probe.para_styles_mut() {
|
||||
p.justification = t.layout_justification(p);
|
||||
}
|
||||
probe.kind = TextKind::Point;
|
||||
let laid = vectorcraft_text::layout(db, &probe);
|
||||
let mut out = std::collections::HashMap::with_capacity(laid.lines.len());
|
||||
for m in &laid.lines {
|
||||
out.entry(m.start).or_insert(m.x1 - m.x0);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing
|
||||
/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down
|
||||
/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its
|
||||
/// size rounded down to tenths, and None when that is its size, so fitting again changes nothing.
|
||||
/// Room taken entirely by indents gives the smallest size.
|
||||
fn refit(size: f64, width: f64, avail: f64, slope: f64) -> Option<f64> {
|
||||
if width <= avail + 1e-6 && width + 0.1 * slope > avail {
|
||||
let rounded = tenths(size);
|
||||
return ((rounded - size).abs() > 1e-9).then_some(rounded);
|
||||
}
|
||||
Some(tenths(size + (avail.max(0.0) - width) / slope))
|
||||
}
|
||||
|
||||
/// A size in document points rounded down to a whole number of tenths and kept within [`SIZES`].
|
||||
fn tenths(points: f64) -> f64 {
|
||||
((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1)
|
||||
}
|
||||
|
||||
/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word
|
||||
/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line
|
||||
/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to
|
||||
/// 1,296 pt, the line's other characters keeping their proportions to it) at which its width
|
||||
/// equals the frame's width less the inset, the gutters and the paragraph's indents, and each
|
||||
/// character's leading is its size plus the line gap. An empty line or one of only spaces keeps
|
||||
/// its size. Nothing changes when the frame has no width along the lines or the type's transform
|
||||
/// has no size. A line that still wraps at its first fit is made smaller, in at most
|
||||
/// [`BLOCK_PASSES`] more passes. True when the text changed.
|
||||
pub(crate) fn block_fit(t: &mut TextObject) -> bool {
|
||||
if !t.dynamic_text {
|
||||
return false;
|
||||
}
|
||||
let TextKind::Area { frame } = &t.kind else { return false };
|
||||
let (_, line_gap) = t.area.block_gaps();
|
||||
let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false };
|
||||
let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false };
|
||||
let before = t.runs.clone();
|
||||
|
||||
// The room along a line in one cell of the frame, before indents.
|
||||
let a = &t.area;
|
||||
let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) };
|
||||
let cells = cells.max(1) as f64;
|
||||
let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells;
|
||||
if !(cell.is_finite() && cell > 1e-9) {
|
||||
return t.runs != before;
|
||||
}
|
||||
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let text = t.plain_text();
|
||||
let lines = typed_lines(&text);
|
||||
let widths = line_widths(db, t);
|
||||
let sizes = first_sizes(&t.runs, &lines);
|
||||
// Per line: (factor applied to its sizes, the room it fills, the last size measured and its
|
||||
// width), or None to keep its size.
|
||||
let mut fits: Vec<Option<(f64, f64, f64, f64)>> = lines
|
||||
.iter()
|
||||
.zip(&sizes)
|
||||
.map(|(l, size)| {
|
||||
if l.content == l.start {
|
||||
return None;
|
||||
}
|
||||
let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?;
|
||||
let para = t.para_at(l.para);
|
||||
let first = if l.para_start { para.first_line_indent } else { 0.0 };
|
||||
let avail = cell - para.left_indent - para.right_indent - first;
|
||||
let size = size * points;
|
||||
if !(size.is_finite() && size > 0.0) {
|
||||
return None;
|
||||
}
|
||||
Some((refit(size, width, avail, width / size).map_or(1.0, |n| n / size), avail, size, width))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let gap = line_gap / points;
|
||||
let min_leading = SIZES.0 / points;
|
||||
// Always from the sizes the refit started with, so each pass sets a line's size once: the runs
|
||||
// are split where the lines end and each piece scaled by its line's factor, in one pass.
|
||||
let apply = |t: &mut TextObject, from: &[TextRun], fits: &[Option<(f64, f64, f64, f64)>]| {
|
||||
let mut out = Vec::with_capacity(from.len() + lines.len());
|
||||
let (mut off, mut li) = (0, 0);
|
||||
for r in from {
|
||||
let end = off + r.text.len();
|
||||
let mut at = off;
|
||||
loop {
|
||||
while lines.get(li).is_some_and(|l| l.end <= at && li + 1 < lines.len()) {
|
||||
li += 1;
|
||||
}
|
||||
let stop = lines.get(li).map_or(end, |l| l.end.clamp(at, end));
|
||||
let stop = if stop == at { end } else { stop };
|
||||
let f = fits.get(li).copied().flatten().map_or(1.0, |(f, ..)| f);
|
||||
let mut piece = TextRun { text: r.text.get(at - off..stop - off).unwrap_or_default().to_string(), ..r.clone() };
|
||||
if at > off {
|
||||
piece.style.glyph_alternate = None;
|
||||
}
|
||||
let st = &mut piece.style;
|
||||
st.size *= f;
|
||||
st.baseline_shift *= f;
|
||||
st.tcy_up_down *= f;
|
||||
st.tcy_left_right *= f;
|
||||
st.leading = Some((st.size + gap).max(min_leading));
|
||||
if let Some(art) = &mut piece.inline {
|
||||
art.baseline_shift *= f;
|
||||
}
|
||||
out.push(piece);
|
||||
at = stop;
|
||||
if at >= end {
|
||||
break;
|
||||
}
|
||||
}
|
||||
off = end;
|
||||
}
|
||||
vectorcraft_text::edit::normalize(&mut out);
|
||||
t.runs = out;
|
||||
};
|
||||
let start = t.runs.clone();
|
||||
apply(t, &start, &fits);
|
||||
|
||||
// Each pass measures the lines again: a line whose width did not follow its size (a tab to a
|
||||
// fixed stop) is fitted again from its measured width, and when every line measures right, a
|
||||
// line the frame's shape or a list marker still wraps is made smaller, by what the line the
|
||||
// layout gave it holds.
|
||||
// Per line: the smallest size measured too wide, which a later pass never goes back to.
|
||||
let mut too_wide = vec![f64::INFINITY; lines.len()];
|
||||
for _ in 0..BLOCK_PASSES {
|
||||
let now_widths = line_widths(db, t);
|
||||
let mut again = false;
|
||||
for (((l, fit), size), wide) in lines.iter().zip(fits.iter_mut()).zip(&sizes).zip(too_wide.iter_mut()) {
|
||||
let Some((f, avail, last_size, last_width)) = fit else { continue };
|
||||
let size = size * points;
|
||||
let now = size * *f;
|
||||
let Some(width) = now_widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9) else { continue };
|
||||
if width > *avail + 1e-6 {
|
||||
*wide = wide.min(now);
|
||||
}
|
||||
// The slope between the last two sizes measured, where they differ: a line whose width
|
||||
// has a part that stays as the size changes is fitted in one step.
|
||||
let slope = Some((width - *last_width) / (now - *last_size))
|
||||
.filter(|s| (now - *last_size).abs() > 1e-9 && s.is_finite() && *s > 1e-9)
|
||||
.unwrap_or(width / now);
|
||||
(*last_size, *last_width) = (now, width);
|
||||
let next = refit(now, width, *avail, slope).map(|n| if n >= *wide - 1e-9 { tenths(*wide - 0.1) } else { n });
|
||||
if let Some(next) = next.filter(|n| (n - now).abs() > 1e-9) {
|
||||
*f = next / size;
|
||||
again = true;
|
||||
}
|
||||
}
|
||||
if !again {
|
||||
let laid = vectorcraft_text::layout(db, t);
|
||||
// Per typed line: how many laid-out lines it took, and the room of its first.
|
||||
let mut parts: Vec<(usize, f64)> = vec![(0, 0.0); lines.len()];
|
||||
for m in &laid.lines {
|
||||
let i = lines.partition_point(|l| l.start <= m.start).saturating_sub(1);
|
||||
if let Some(p) = parts.get_mut(i) {
|
||||
if p.0 == 0 {
|
||||
p.1 = m.avail.1 - m.avail.0;
|
||||
}
|
||||
p.0 += 1;
|
||||
}
|
||||
}
|
||||
for (((l, fit), (count, room)), size) in lines.iter().zip(fits.iter_mut()).zip(&parts).zip(&sizes) {
|
||||
let Some((f, ..)) = fit else { continue };
|
||||
if *count < 2 {
|
||||
continue;
|
||||
}
|
||||
let size = size * points;
|
||||
let now = size * *f;
|
||||
if now <= SIZES.0 + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let width = now_widths.get(&l.start).copied().unwrap_or(f64::INFINITY);
|
||||
let smaller = if room.is_finite() && *room > 0.0 && *room < width { tenths(now * room / width) } else { now };
|
||||
*f = smaller.min(tenths(now - 0.1)) / size;
|
||||
again = true;
|
||||
}
|
||||
}
|
||||
if !again {
|
||||
break;
|
||||
}
|
||||
apply(t, &start, &fits);
|
||||
}
|
||||
t.runs != before
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn typed_lines_split_after_returns_and_forced_breaks() {
|
||||
let l = typed_lines("ab\ncd\u{2028}e\n");
|
||||
let spans: Vec<_> = l.iter().map(|l| (l.start, l.content, l.end, l.para, l.para_start)).collect();
|
||||
assert_eq!(spans, vec![(0, 2, 3, 0, true), (3, 5, 8, 1, true), (8, 9, 10, 1, false), (10, 10, 10, 2, true)]);
|
||||
assert_eq!(typed_lines("").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fitting_line_keeps_its_size_in_tenths() {
|
||||
// 100 pt wide at 12 pt, 100.5 pt of room: a tenth larger would not fit.
|
||||
assert_eq!(refit(12.0, 100.0, 100.5, 100.0 / 12.0), None);
|
||||
assert_eq!(refit(12.34, 100.0, 100.5, 100.0 / 12.34), Some(12.3), "a size between tenths is rounded down");
|
||||
// Room for twice the width: twice the size.
|
||||
assert_eq!(refit(12.0, 100.0, 200.0, 100.0 / 12.0), Some(24.0));
|
||||
// A part of the width that stays (a slope below width / size) needs more size.
|
||||
assert_eq!(refit(12.0, 100.0, 150.0, 5.0), Some(22.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_round_down_to_tenths_within_the_range() {
|
||||
assert_eq!(tenths(23.99), 23.9);
|
||||
assert_eq!(tenths(24.0 - 1e-9), 24.0);
|
||||
assert_eq!(tenths(0.01), 0.1);
|
||||
assert_eq!(tenths(5000.0), 1296.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
//! Dynamic Text's Block for area type: `type.dynamicText`, Area Type Options › Block and the refit
|
||||
//! after edits.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{AreaFit, NodeId, NodeKind, TextKind, TextObject};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn area(s: &mut Session, w: f64, h: f64, text: &str) -> u64 {
|
||||
let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": {"width": w, "height": h}, "text": text})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
fn text(s: &Session, id: u64) -> TextObject {
|
||||
match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
k => panic!("not text: {k:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The size of the character at `byte`.
|
||||
fn size_at(t: &TextObject, byte: usize) -> f64 {
|
||||
super::block::size_at(&t.runs, byte)
|
||||
}
|
||||
|
||||
/// Each laid-out line's (start byte, content width, room): the room is the frame's span less the
|
||||
/// indents.
|
||||
fn lines(t: &TextObject) -> Vec<(usize, f64, f64)> {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
lay.lines.iter().map(|l| (l.start, l.x1 - l.x0, l.avail.1 - l.avail.0)).collect()
|
||||
}
|
||||
|
||||
/// Every typed line is one laid-out line whose width is within one 0.1 pt size step of its room.
|
||||
fn assert_block(t: &TextObject) {
|
||||
let typed: Vec<usize> = std::iter::once(0).chain(t.plain_text().match_indices(['\n', '\u{2028}']).map(|(i, c)| i + c.len())).collect();
|
||||
let laid = lines(t);
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), typed, "one laid-out line per typed line: {laid:?}");
|
||||
for &(start, width, room) in &laid {
|
||||
let size = size_at(t, start);
|
||||
if width <= 1e-9 || size >= 1296.0 - 1e-9 || size <= 0.1 + 1e-9 {
|
||||
continue;
|
||||
}
|
||||
assert!(width <= room + 0.01, "line at {start} is wider than its room: {width} > {room}");
|
||||
assert!(width >= room * (size - 0.1) / size - 0.01, "line at {start} at {size} pt is short of its room: {width} < {room}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_sets_each_typed_line_to_the_frame_width_by_its_size() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one");
|
||||
let n = undo_len(&s);
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r, json!({"on": true, "ids": [id], "fitScale": 1.0, "wordGap": 100.0, "lineGap": 0.0}));
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!(t.area.fit, AreaFit::None);
|
||||
assert_block(&t);
|
||||
let (big, long, mid) = (size_at(&t, 0), size_at(&t, 4), size_at(&t, 31));
|
||||
assert!(big > mid && mid > long, "a shorter line is set larger: {big} {mid} {long}");
|
||||
for size in [big, long, mid] {
|
||||
assert!(((size * 10.0).round() - size * 10.0).abs() < 1e-6, "{size} is a whole number of tenths");
|
||||
}
|
||||
// Each character's leading is its size (line gap 0).
|
||||
assert!(t.runs.iter().all(|r| r.style.leading == Some(r.style.size)), "{:?}", t.runs);
|
||||
// Inspect reports it.
|
||||
let doc = s.execute("document.inspect", &json!({})).unwrap();
|
||||
let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone();
|
||||
assert_eq!((node["dynamicText"].as_bool(), node["fit"].as_str()), (Some(true), Some("block")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_keeps_the_proportions_inside_a_line_and_fits_again_after_edits() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "one two three\nfour");
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "size": 24})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_block(&t);
|
||||
let ratio = size_at(&t, 0) / size_at(&t, 4);
|
||||
assert!((ratio - 2.0).abs() < 0.02, "the first word stays twice the size of the rest: {ratio}");
|
||||
let four = size_at(&t, 14);
|
||||
// Typing into the first line makes it smaller, in the edit's own undo step; the second line stays.
|
||||
let first = size_at(&t, 4);
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 13, "end": 13, "insert": " and more words"})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, id);
|
||||
assert_block(&t);
|
||||
assert!(size_at(&t, 4) < first, "{} < {first}", size_at(&t, 4));
|
||||
assert_eq!(size_at(&t, t.plain_text().find("four").unwrap()), four);
|
||||
// A narrower frame sets every line smaller.
|
||||
s.execute("text.areaOptions", &json!({"width": 150})).unwrap();
|
||||
let narrow = text(&s, id);
|
||||
assert_block(&narrow);
|
||||
let f = size_at(&narrow, narrow.plain_text().find("four").unwrap()) / four;
|
||||
assert!((f - 0.5).abs() < 0.02, "half the width, half the size: {f}");
|
||||
// Undo brings the wider frame's sizes back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(text(&s, id).runs, t.runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes() {
|
||||
let mut s = session();
|
||||
// The tab goes to a stop that stays where it is as the size changes.
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand\tme too");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let fitted = text(&s, id).runs;
|
||||
let laid = lines(&text(&s, id));
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 7], "{laid:?}");
|
||||
assert!(laid.iter().all(|l| l.1 <= l.2 + 0.01 && l.1 > l.2 * 0.95), "each line fills its room: {laid:?}");
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("type.dynamicText", &json!({"on": true})).unwrap()["on"], true);
|
||||
assert_eq!(undo_len(&s), n, "already on: no undo step");
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["on"], false);
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, id);
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, fitted, "off keeps the sizes it was drawn at");
|
||||
// Edits no longer fit the lines.
|
||||
s.execute("text.areaOptions", &json!({"width": 100})).unwrap();
|
||||
assert_eq!(text(&s, id).runs, fitted);
|
||||
assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["on"], false);
|
||||
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_other_type_are_refused() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me");
|
||||
for bad in [
|
||||
json!({"on": "yes"}),
|
||||
json!({"on": 1}),
|
||||
json!({"wordGap": "wide"}),
|
||||
json!({"wordGap": -1}),
|
||||
json!({"wordGap": 1001}),
|
||||
json!({"lineGap": 1297}),
|
||||
json!({"lineGap": -1297}),
|
||||
json!({"lineGap": true}),
|
||||
] {
|
||||
assert!(s.execute("type.dynamicText", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert!(!text(&s, id).dynamic_text);
|
||||
let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [point]})).unwrap();
|
||||
let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("select type on a path or area type"), "{e}");
|
||||
// With point type selected too, only the area type changes.
|
||||
s.execute("select.set", &json!({"ids": [id, point]})).unwrap();
|
||||
let r = s.execute("type.dynamicText", &json!({})).unwrap();
|
||||
assert_eq!(r["ids"], json!([id]));
|
||||
assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text);
|
||||
// A gap with only type on a path selected is an error, and nothing changes.
|
||||
let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap();
|
||||
let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [along]})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
for gap in [json!({"wordGap": 300}), json!({"on": false, "lineGap": 2})] {
|
||||
let e = s.execute("type.dynamicText", &gap).unwrap_err().to_string();
|
||||
assert!(e.contains("need area type"), "{e}");
|
||||
}
|
||||
assert_eq!(undo_len(&s), n);
|
||||
assert!(!text(&s, along).dynamic_text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaps_set_word_spacing_and_leading() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "two words\nthree more words");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let plain = text(&s, id);
|
||||
let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 6})).unwrap();
|
||||
assert_eq!((r["on"].as_bool(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some(true), Some(300.0), Some(6.0)));
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!((t.area.word_gap, t.area.line_gap), (300.0, 6.0));
|
||||
// The layout uses the gap as the Desired word spacing; the paragraph keeps its own.
|
||||
assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]);
|
||||
assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]);
|
||||
assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs);
|
||||
assert_block(&t);
|
||||
assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room");
|
||||
// (own, used by the layout) word spacing of the first paragraph.
|
||||
let spacing = |s: &Session| {
|
||||
let t = text(s, id);
|
||||
(t.para_at(0).justification.word_spacing, t.layout_justification(t.para_at(0)).word_spacing)
|
||||
};
|
||||
// Minimum and Maximum move out only as far as the current gap needs, and the paragraph's own
|
||||
// values apply again when Block is off.
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 1000.0, 1000.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 0})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [0.0, 0.0, 133.0]));
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0]));
|
||||
// A paragraph's own values, outside the default range and equal to Desired too, stay through
|
||||
// gap changes and refits after edits.
|
||||
s.execute("text.setFormat", &json!({"wordSpacing": [20, 20, 150]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true, "wordGap": 20})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 1000.0, 1000.0]));
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap();
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 0, "end": 0, "insert": "a "})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 100.0, 150.0]));
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0]));
|
||||
// A gap alone on a frame without Block turns it on.
|
||||
let other = area(&mut s, 200.0, 200.0, "x y");
|
||||
let r = s.execute("type.dynamicText", &json!({"lineGap": -2})).unwrap();
|
||||
assert_eq!(r["on"], true);
|
||||
let t = text(&s, other);
|
||||
assert!(t.dynamic_text);
|
||||
assert_eq!((t.area.word_gap, t.area.line_gap), (100.0, -2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_type_options_offer_block_with_its_gaps() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too");
|
||||
let q = s.execute("text.areaOptions", &json!({})).unwrap();
|
||||
assert_eq!((q["wordGap"].as_f64(), q["lineGap"].as_f64()), (Some(100.0), Some(0.0)));
|
||||
// Gaps alone are kept for Block, without turning it on or changing the text.
|
||||
let (n, runs) = (undo_len(&s), text(&s, id).runs);
|
||||
s.execute("text.areaOptions", &json!({"wordGap": 200})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!((undo_len(&s), t.dynamic_text, t.area.word_gap), (n + 1, false, 200.0));
|
||||
assert_eq!(t.runs, runs);
|
||||
let r = s.execute("text.areaOptions", &json!({"fit": "block", "lineGap": 4})).unwrap();
|
||||
assert_eq!((r["fit"].as_str(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some("block"), Some(200.0), Some(4.0)));
|
||||
assert!(text(&s, id).dynamic_text);
|
||||
assert_block(&text(&s, id));
|
||||
// The reply passed back (as the dialog does) changes nothing; naming Block again keeps the gaps.
|
||||
let n = undo_len(&s);
|
||||
assert_eq!(s.execute("text.areaOptions", &r).unwrap(), r);
|
||||
s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap();
|
||||
assert_eq!(undo_len(&s), n);
|
||||
s.execute("text.areaOptions", &json!({"lineGap": 2})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 200.0, 2.0));
|
||||
assert!(s.execute("text.areaOptions", &json!({"lineGap": 5000})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"wordGap": 2000})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"wordGap": "wide"})).is_err());
|
||||
assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).unwrap_err().to_string().contains("shrinkText|block"));
|
||||
// Shrink Text to Fit replaces Block, keeping the sizes.
|
||||
let runs = text(&s, id).runs;
|
||||
s.execute("text.areaOptions", &json!({"fit": "shrinkText"})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, runs);
|
||||
// Block replaces Shrink Text to Fit and Auto Size.
|
||||
s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap();
|
||||
assert_eq!(text(&s, id).area.fit, AreaFit::None);
|
||||
// New area type can start with it.
|
||||
let made = s
|
||||
.execute(
|
||||
"text.create",
|
||||
&json!({"x": 10, "y": 300, "size": 12, "area": {"width": 200, "height": 200, "fit": "block", "wordGap": 150}, "text": "made"}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let t = text(&s, made);
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 150.0, 0.0));
|
||||
assert_block(&t);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_round_trips_through_the_native_format() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too");
|
||||
s.execute("type.dynamicText", &json!({"wordGap": 120, "lineGap": 3})).unwrap();
|
||||
let doc = s.doc().unwrap().doc.clone();
|
||||
let bytes = vectorcraft_format::save(&doc, false);
|
||||
let back = vectorcraft_format::load(&bytes).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 120.0, 3.0));
|
||||
assert_eq!(t.runs, text(&s, id).runs, "the fitted sizes are saved in the characters");
|
||||
// Saved as `dynamicText` with the gaps beside the area options; missing gaps read as their
|
||||
// defaults, which are left out when saved.
|
||||
let saved = serde_json::to_value(&**t).unwrap();
|
||||
assert_eq!((&saved["dynamicText"], &saved["area"]["wordGap"], &saved["area"]["lineGap"]), (&json!(true), &json!(120.0), &json!(3.0)));
|
||||
let plain = serde_json::from_value::<vectorcraft_doc::AreaOptions>(json!({})).unwrap();
|
||||
assert_eq!((plain.word_gap, plain.line_gap), (100.0, 0.0));
|
||||
let plain: Value = serde_json::to_value(&plain).unwrap();
|
||||
assert!(plain.get("wordGap").is_none() && plain.get("lineGap").is_none(), "{plain}");
|
||||
// Turned off, it opens off with the sizes it had.
|
||||
s.execute("type.dynamicText", &json!({"on": false})).unwrap();
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") };
|
||||
assert!(!t.dynamic_text);
|
||||
assert_eq!(t.runs, text(&s, id).runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_cases_fit_without_failing() {
|
||||
let mut s = session();
|
||||
// Empty text, an empty line and a line of spaces keep their sizes.
|
||||
let empty = area(&mut s, 300.0, 400.0, "");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, empty), 0), 12.0);
|
||||
let gaps = area(&mut s, 300.0, 400.0, "top\n\n \nbottom line");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, gaps);
|
||||
assert_eq!((size_at(&t, 4), size_at(&t, 5)), (12.0, 12.0));
|
||||
assert_block(&t);
|
||||
// One word.
|
||||
let word = area(&mut s, 300.0, 400.0, "Word");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_block(&text(&s, word));
|
||||
// A wide frame stops at 1,296 pt; a very long line in a narrow frame stops at 0.1 pt and wraps.
|
||||
let wide = area(&mut s, 100_000.0, 400.0, "i");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, wide), 0), 1296.0);
|
||||
let narrow = area(&mut s, 1.0, 400.0, &"long words ".repeat(40));
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, narrow);
|
||||
assert_eq!(size_at(&t, 0), 0.1);
|
||||
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "at 0.1 pt the line still does not fit");
|
||||
// A frame inset so far that it has no width keeps the sizes.
|
||||
let inset = area(&mut s, 50.0, 400.0, "Inset");
|
||||
s.execute("text.areaOptions", &json!({"inset": 30})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_eq!(size_at(&text(&s, inset), 0), 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_fits_columns_lists_vertical_and_right_to_left_type() {
|
||||
let mut s = session();
|
||||
// Two columns: each line is set to a column's width.
|
||||
let cols = area(&mut s, 400.0, 600.0, "left column\nsecond");
|
||||
s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 20})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, cols);
|
||||
assert_block(&t);
|
||||
assert!(lines(&t).iter().all(|l| (l.2 - 190.0).abs() < 1e-6), "{:?}", lines(&t));
|
||||
// A bulleted list: each item stays one line, the marker and its tab taking their room before
|
||||
// the text (the room the layout reports takes in the marker's too).
|
||||
let list = area(&mut s, 300.0, 400.0, "first item\nsecond item here");
|
||||
s.execute("text.setFormat", &json!({"list": "bullet"})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, list);
|
||||
let laid = lines(&t);
|
||||
assert_eq!(laid.iter().map(|l| l.0).collect::<Vec<_>>(), vec![0, 11], "{laid:?}");
|
||||
assert!(laid.iter().all(|l| l.1 <= l.2), "{laid:?}");
|
||||
assert!(size_at(&t, 0) > size_at(&t, 11), "the shorter item is larger");
|
||||
// Right-to-left text.
|
||||
let rtl = area(&mut s, 300.0, 400.0, "שלום עולם\nטקסט ארוך יותר בשורה");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
assert_block(&text(&s, rtl));
|
||||
// Vertical type: each column of text is set to the frame's height.
|
||||
let v = s
|
||||
.execute(
|
||||
"text.create",
|
||||
&json!({"x": 40, "y": 40, "size": 12, "vertical": true, "area": {"width": 300, "height": 200}, "text": "縦書き\nもっと長い縦書きの行"}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [v]})).unwrap();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let t = text(&s, v);
|
||||
assert!(t.vertical);
|
||||
assert_block(&t);
|
||||
assert!(lines(&t).iter().all(|l| (l.2 - 200.0).abs() < 1e-6), "{:?}", lines(&t));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threaded_frames_are_refused_and_threading_turns_block_off() {
|
||||
let mut s = session();
|
||||
let a = area(&mut s, 200.0, 300.0, "Fit me\nand me too");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let fitted = text(&s, a).runs;
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 40, "width": 200, "height": 300})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
let n = undo_len(&s);
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1);
|
||||
let t = text(&s, a);
|
||||
assert!(!t.dynamic_text, "threading turns Block off");
|
||||
assert_eq!(t.runs, fitted, "the text keeps its sizes");
|
||||
s.execute("select.set", &json!({"ids": [a]})).unwrap();
|
||||
let e = s.execute("type.dynamicText", &json!({"on": true})).unwrap_err().to_string();
|
||||
assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}");
|
||||
let runs = text(&s, a).runs;
|
||||
let e = s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap_err().to_string();
|
||||
assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}");
|
||||
assert_eq!(text(&s, a).runs, runs, "Area Type Options refuses it too, changing nothing");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(text(&s, a).dynamic_text, "undo brings it back with the thread gone");
|
||||
assert!(matches!(text(&s, a).kind, TextKind::Area { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_text_fits_in_a_bounded_number_of_layouts() {
|
||||
let mut s = session();
|
||||
let story: String = (0..300).map(|i| format!("line number {i} {}\n", "x".repeat(i % 17))).collect();
|
||||
let id = area(&mut s, 300.0, 100_000.0, &story);
|
||||
let before = vectorcraft_text::test_fonts::layouts_on_this_thread();
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before;
|
||||
assert_block(&text(&s, id));
|
||||
// The command fits the object to compare and to apply (each a measure, at most two layouts a
|
||||
// pass and the caches), plus the reply's own.
|
||||
let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4;
|
||||
assert!(used <= bound, "{used} layouts");
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Type menu long tail (Change Case, Smart Punctuation, Convert To Area/Point Type, Type on a Path
|
||||
//! Options, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) and the text
|
||||
//! commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting).
|
||||
//! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters)
|
||||
//! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::object::choice;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::typecmd::{area_text, block_gaps, refresh_bounds};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or,
|
||||
switch_or, targets, text_param,
|
||||
@@ -65,8 +65,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Dynamic Text",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?, on?: bool} turn Dynamic Text on or off for the selected type on a path (on omitted: the opposite of the first object's setting). On, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. Off, the text keeps the sizes it was drawn at. Point type and area type in the selection are left as they are; a selection holding type on a path in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When every object already has the setting, nothing changes and no undo step is recorded → {on, ids, fitScale (the first object's factor, 1 when off)}",
|
||||
has_free_path_type,
|
||||
"{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}",
|
||||
has_dynamic_type,
|
||||
dynamic_text
|
||||
),
|
||||
cmd!(
|
||||
@@ -520,26 +520,40 @@ fn path_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
options(s)
|
||||
}
|
||||
|
||||
/// Whether type on a path `id` is a frame of a thread.
|
||||
/// Whether type `id` is a frame of a thread.
|
||||
fn threaded(d: &Document, id: NodeId) -> bool {
|
||||
!super::threads::story_of(d, id).is_empty()
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path, none of it in a thread.
|
||||
fn has_free_path_type(s: &Session) -> std::result::Result<(), String> {
|
||||
/// Type on a path or area type: the type Dynamic Text works on.
|
||||
fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> {
|
||||
path_text(n).or_else(|| area_text(n))
|
||||
}
|
||||
|
||||
/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it
|
||||
/// in a thread.
|
||||
fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> {
|
||||
has_selection(s)?;
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
let d = &st.doc;
|
||||
let selected: Vec<NodeId> = st.selection.objects.to_vec();
|
||||
let paths: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect();
|
||||
if paths.is_empty() {
|
||||
return Err("select type on a path".into());
|
||||
let types: Vec<NodeId> = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect();
|
||||
if types.is_empty() {
|
||||
return Err("select type on a path or area type".into());
|
||||
}
|
||||
threaded_refusal(d, &types).map_or(Ok(()), Err)
|
||||
}
|
||||
|
||||
/// Why Dynamic Text is refused for `ids`: the frames among them that are in a thread, type on a
|
||||
/// path first; None when none is.
|
||||
fn threaded_refusal(d: &Document, ids: &[NodeId]) -> Option<String> {
|
||||
let (paths, areas): (Vec<NodeId>, Vec<NodeId>) = ids.iter().copied().partition(|id| path_text(d.node(*id)).is_some());
|
||||
let frames = threaded_ids(d, &paths);
|
||||
if !frames.is_empty() {
|
||||
return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
|
||||
return Some(format!("type on a path in a thread cannot use Dynamic Text: {frames}"));
|
||||
}
|
||||
Ok(())
|
||||
let frames = threaded_ids(d, &areas);
|
||||
(!frames.is_empty()).then(|| format!("area type in a thread cannot use Dynamic Text: {frames}"))
|
||||
}
|
||||
|
||||
/// The ids among `ids` of frames of threads, as a list for a message; empty when there are none.
|
||||
@@ -547,32 +561,60 @@ fn threaded_ids(d: &Document, ids: &[NodeId]) -> String {
|
||||
ids.iter().filter(|id| threaded(d, **id)).map(|id| id.0.to_string()).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting) on the
|
||||
/// selected type on a path, in one undo step, and none when every object already has it. Turning
|
||||
/// it off keeps the sizes the text was drawn at ([`bake_dynamic_text`]).
|
||||
/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on
|
||||
/// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in
|
||||
/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn
|
||||
/// at ([`bake_dynamic_text`]).
|
||||
fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "type.dynamicText";
|
||||
let (ids, on, changing) = {
|
||||
let (word_gap, line_gap) = block_gaps(p, C)?;
|
||||
let (ids, on, planned) = {
|
||||
let d = &s.doc()?.doc;
|
||||
let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect();
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select type on a path"))?;
|
||||
let frames = threaded_ids(d, &ids);
|
||||
if !frames.is_empty() {
|
||||
return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}")));
|
||||
let ids: Vec<NodeId> = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect();
|
||||
let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?;
|
||||
if let Some(why) = threaded_refusal(d, &ids) {
|
||||
return Err(bad(C, why));
|
||||
}
|
||||
let on = switch_or(p, "on", !path_text(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
let changing: Vec<NodeId> = ids.iter().copied().filter(|id| path_text(d.node(*id)).is_some_and(|t| t.dynamic_text != on)).collect();
|
||||
(ids, on, changing)
|
||||
let gap_given = word_gap.is_some() || line_gap.is_some();
|
||||
if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) {
|
||||
return Err(bad(C, "wordGap and lineGap need area type in the selection"));
|
||||
}
|
||||
let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?;
|
||||
// Each object as the command leaves it, and only those it changes.
|
||||
let mut planned: Vec<(NodeId, TextObject)> = vec![];
|
||||
for id in &ids {
|
||||
let Some(t) = dynamic_type(d.node(*id)) else { continue };
|
||||
let mut after = t.clone();
|
||||
if matches!(t.kind, TextKind::Area { .. }) {
|
||||
after.area.word_gap = word_gap.unwrap_or(t.area.word_gap);
|
||||
after.area.line_gap = line_gap.unwrap_or(t.area.line_gap);
|
||||
}
|
||||
match (on, t.dynamic_text) {
|
||||
(true, true) => refresh_bounds(&mut after),
|
||||
(true, false) => {
|
||||
after.dynamic_text = true;
|
||||
// Block replaces Auto Size and Shrink Text to Fit.
|
||||
if matches!(t.kind, TextKind::Area { .. }) {
|
||||
after.area.fit = AreaFit::None;
|
||||
}
|
||||
refresh_bounds(&mut after);
|
||||
}
|
||||
(false, true) => {
|
||||
bake_dynamic_text(&mut after);
|
||||
}
|
||||
(false, false) => {}
|
||||
}
|
||||
if after != *t {
|
||||
planned.push((*id, after));
|
||||
}
|
||||
}
|
||||
(ids, on, planned)
|
||||
};
|
||||
if !changing.is_empty() {
|
||||
if !planned.is_empty() {
|
||||
s.edit("Dynamic Text", |d, _| {
|
||||
for id in &changing {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue };
|
||||
if on {
|
||||
t.dynamic_text = true;
|
||||
refresh_bounds(t);
|
||||
} else {
|
||||
bake_dynamic_text(t);
|
||||
for (id, after) in &planned {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
**t = after.clone();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -581,7 +623,13 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let fit =
|
||||
ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale);
|
||||
Ok(json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit}))
|
||||
let mut reply = json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "fitScale": fit});
|
||||
if let Some(t) = ids.iter().find_map(|id| area_text(d.node(*id))) {
|
||||
let (w, l) = t.area.block_gaps();
|
||||
reply["wordGap"] = json!(w);
|
||||
reply["lineGap"] = json!(l);
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
/// Turn Dynamic Text off on `t`, keeping the sizes its layout draws it at: every run's size,
|
||||
|
||||
@@ -25,10 +25,10 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo
|
||||
/// `(command, param)` pairs the journal records only so a replay reproduces the original run
|
||||
/// (dates from the clock: `cmd::clock_date`; the artboards the app passes to the
|
||||
/// [`ON_ACTIVE_ARTBOARD`] and [`FIT_ACTIVE_ARTBOARD`] commands and to a batch; the artboards the
|
||||
/// Artboard tool had selected for its commands; the artboards and art Cut and Copy took with that
|
||||
/// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that
|
||||
/// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out
|
||||
/// ([`Session::journal_for_action`]).
|
||||
const REPLAY_ONLY: [(&str, &str); 26] = [
|
||||
const REPLAY_ONLY: [(&str, &str); 29] = [
|
||||
("file.new", "created"),
|
||||
("edit.newDocumentFromState", "created"),
|
||||
("document.save", "modified"),
|
||||
@@ -36,6 +36,9 @@ const REPLAY_ONLY: [(&str, &str); 26] = [
|
||||
("edit.pasteInPlace", "artboard"),
|
||||
("edit.pasteInFront", "artboard"),
|
||||
("edit.pasteInBack", "artboard"),
|
||||
("edit.pasteInPlace", "artboards"),
|
||||
("edit.pasteInFront", "artboards"),
|
||||
("edit.pasteInBack", "artboards"),
|
||||
("object.align", "artboard"),
|
||||
("object.distribute", "artboard"),
|
||||
("object.distributeSpacing", "artboard"),
|
||||
|
||||
@@ -463,7 +463,10 @@ impl ScriptScope {
|
||||
let real = match std::fs::canonicalize(path) {
|
||||
Ok(real) => real,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
return Err(if std::fs::symlink_metadata(path).is_ok() { ScriptRead::Refused } else { ScriptRead::Missing });
|
||||
if std::fs::symlink_metadata(path).is_ok() || !self.missing_inside(path) {
|
||||
return Err(ScriptRead::Refused);
|
||||
}
|
||||
return Err(ScriptRead::Missing);
|
||||
}
|
||||
Err(e) => return Err(ScriptRead::Failed(e.to_string())),
|
||||
};
|
||||
@@ -473,6 +476,18 @@ impl ScriptScope {
|
||||
Ok(real)
|
||||
}
|
||||
|
||||
/// Is the missing `path` inside a granted folder: does the nearest folder above it that exists
|
||||
/// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is
|
||||
/// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too,
|
||||
/// so a script cannot tell whether the folder a link leads to exists.
|
||||
fn missing_inside(&self, path: &Path) -> bool {
|
||||
path.ancestors()
|
||||
.skip(1)
|
||||
.find(|a| std::fs::symlink_metadata(a).is_ok())
|
||||
.and_then(|a| std::fs::canonicalize(a).ok())
|
||||
.is_some_and(|real| self.roots.iter().any(|r| inside(&real, r)))
|
||||
}
|
||||
|
||||
/// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it.
|
||||
pub(crate) fn stat(&self, path: &Path) -> Result<ScriptEntry, ScriptRead> {
|
||||
let real = self.locate(path)?;
|
||||
|
||||
@@ -99,14 +99,15 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts, symbols: &SymbolBoxes) ->
|
||||
NodeKind::Text(t) => {
|
||||
v["text"] = json!(t.plain_text());
|
||||
// Area type and type on a path: does the text fit (the red overflow "+")? Area type
|
||||
// also reports its fit and Shrink Text's factor (1 unshrunk), and type on a path its
|
||||
// Dynamic Text setting and factor (1 when off).
|
||||
// also reports its fit (`block` for Dynamic Text's Block) and Shrink Text's factor (1
|
||||
// unshrunk), and type on a path its factor (1 when off); both report Dynamic Text.
|
||||
if !matches!(t.kind, vectorcraft_doc::TextKind::Point) {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
v["overflow"] = json!(lay.overflow);
|
||||
if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) {
|
||||
v["fit"] = json!(t.area.fit.id());
|
||||
v["fit"] = json!(crate::cmd::typecmd::fit_id(t));
|
||||
v["fitScale"] = json!(lay.fit_scale);
|
||||
v["dynamicText"] = json!(t.dynamic_text);
|
||||
} else {
|
||||
v["dynamicText"] = json!(t.dynamic_text);
|
||||
v["fitScale"] = json!(lay.fit_scale);
|
||||
|
||||
@@ -347,6 +347,15 @@ pub(crate) fn adding_fonts() -> std::sync::MutexGuard<'static, ()> {
|
||||
FONTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Whether the tests that run every command with `{}` run command `id`. `plugin.clearCache` is
|
||||
/// left out: without an id it empties the cache of every plug-in installed in the process, which
|
||||
/// includes the caches that the plug-in storage tests check while they run.
|
||||
/// `tests/plugin_clear_cache.rs` runs it with `{}` in a test binary of its own.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn runs_with_empty_params(id: &str) -> bool {
|
||||
id != "plugin.clearCache"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
use tests::{
|
||||
adjust as tests_adjust, clip as tests_clip, colormgmt as tests_colormgmt, expand as tests_expand, large_edits as tests_large_edits,
|
||||
|
||||
+153
-25
@@ -190,6 +190,12 @@ fn lock_disabled(_: &Path) -> Option<std::fs::File> {
|
||||
thread_local! {
|
||||
/// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume.
|
||||
pub(crate) static PUT_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: moving a plug-in's settings and cache back from `<folder>.removed` ([`move_back`])
|
||||
/// fails on this thread, as when another program holds a file in the folder.
|
||||
pub(crate) static MOVE_BACK_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`])
|
||||
/// fails on this thread, as on a full volume.
|
||||
pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted.
|
||||
@@ -590,26 +596,34 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without
|
||||
/// one, nowhere (its storage calls then fail as unavailable).
|
||||
/// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal
|
||||
/// kept are moved back first ([`plugin_storage`]).
|
||||
pub(crate) fn attach_plugin_storage(&self, id: &str) {
|
||||
vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id));
|
||||
}
|
||||
|
||||
/// Does the attached plug-in store have a folder of settings and cache for plug-in `id`? A
|
||||
/// folder behind a `storage` folder that is a link is not counted: the plug-in's storage calls
|
||||
/// can't reach it and removing the plug-in leaves it.
|
||||
/// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one
|
||||
/// that a removal kept ([`aside_paths`], [`is_kept`])? A folder behind a `storage` folder
|
||||
/// that is a link is not counted: the plug-in's storage calls can't reach it and removing the
|
||||
/// plug-in leaves it.
|
||||
pub(crate) fn has_plugin_storage(&self, id: &str) -> bool {
|
||||
self.plugin_dir
|
||||
.as_deref()
|
||||
.is_some_and(|dir| !is_link(&dir.join(PLUGIN_DATA_DIR)) && std::fs::symlink_metadata(plugin_data_dir(dir, id)).is_ok())
|
||||
self.plugin_dir.as_deref().is_some_and(|dir| {
|
||||
let path = plugin_data_dir(dir, id);
|
||||
!is_link(&dir.join(PLUGIN_DATA_DIR)) && (std::fs::symlink_metadata(&path).is_ok() || aside_paths(&path).iter().any(|a| is_kept(a)))
|
||||
})
|
||||
}
|
||||
|
||||
/// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it.
|
||||
/// The folder is first renamed out of the way (`<folder>.removed`), and that fails, leaving it
|
||||
/// as it was, when the rename does; what the deletion then leaves stays under that name, with a
|
||||
/// log record. A later call for the id tries to delete it again. `forget` runs once the folder is
|
||||
/// out of the way, before anything is deleted: when it returns `false`, the folder is renamed
|
||||
/// back and this fails.
|
||||
/// Settings and cache that an earlier removal kept ([`is_kept`]) are first moved back when the
|
||||
/// folder is missing ([`restore_removed`]); what earlier deletions left is deleted. The folder is
|
||||
/// then renamed out of the way ([`aside_paths`]: `<folder>.removed`, or `<folder>.removing` while
|
||||
/// `<folder>.removed` holds kept settings), and that fails, leaving it as it was, when the rename
|
||||
/// does. `forget` runs once the folder is out of the way, before anything is deleted: when it
|
||||
/// returns `false`, the folder is renamed back and this fails, and the kept settings stay. When
|
||||
/// that rename fails too, the error also names both paths and the reason, and the next attach or
|
||||
/// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the
|
||||
/// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log
|
||||
/// record, and a later call for the id tries to delete it again.
|
||||
pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> {
|
||||
let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string());
|
||||
vectorcraft_plugins::registry::set_storage(id, None);
|
||||
@@ -636,28 +650,45 @@ impl Session {
|
||||
close();
|
||||
return Ok(());
|
||||
}
|
||||
let mut aside = path.clone().into_os_string();
|
||||
aside.push(".removed");
|
||||
let aside = PathBuf::from(aside);
|
||||
let _ = std::fs::remove_dir_all(&aside);
|
||||
match std::fs::rename(&path, &aside) {
|
||||
let asides = aside_paths(&path);
|
||||
if std::fs::symlink_metadata(&path).is_err()
|
||||
&& let Err(e) = restore_removed(&path)
|
||||
{
|
||||
log::warn!("can't move the settings and cache of {} back: {e}", path.display());
|
||||
}
|
||||
for aside in asides.iter().filter(|a| !is_kept(a)) {
|
||||
delete_aside(aside);
|
||||
}
|
||||
let target = if std::fs::symlink_metadata(&path).is_err() {
|
||||
asides.iter().rev().find(|a| is_kept(a)).unwrap_or(&asides[0])
|
||||
} else if !is_kept(&asides[0]) {
|
||||
&asides[0]
|
||||
} else if std::fs::symlink_metadata(&asides[1]).is_err() {
|
||||
&asides[1]
|
||||
} else {
|
||||
return Err(StorageError::Io(format!("{}: {} and {} are in the way", path.display(), asides[0].display(), asides[1].display())));
|
||||
};
|
||||
match std::fs::rename(&path, target) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))),
|
||||
Ok(()) => {}
|
||||
}
|
||||
if !forget() {
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::rename(&aside, &path)
|
||||
if std::fs::symlink_metadata(target).is_ok()
|
||||
&& let Err(e) = move_back(target, &path)
|
||||
{
|
||||
log::warn!("can't move {} back: {e}", aside.display());
|
||||
log::warn!("can't move {} back: {e}", target.display());
|
||||
return Err(StorageError::Io(format!(
|
||||
"{GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {} to {}: {e}",
|
||||
target.display(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
return Err(not_forgotten());
|
||||
}
|
||||
close();
|
||||
if std::fs::symlink_metadata(&aside).is_ok()
|
||||
&& let Err(e) = std::fs::remove_dir_all(&aside)
|
||||
{
|
||||
log::warn!("can't delete {}: {e}", aside.display());
|
||||
for aside in &asides {
|
||||
delete_aside(aside);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -688,10 +719,107 @@ pub(crate) fn plugin_data_dir(dir: &Path, id: &str) -> PathBuf {
|
||||
dir.join(PLUGIN_DATA_DIR).join(format!("id-{}", case_safe(id)))
|
||||
}
|
||||
|
||||
/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`.
|
||||
/// `path` with `suffix` added to its last part.
|
||||
fn suffixed(path: &Path, suffix: &str) -> PathBuf {
|
||||
let mut named = path.as_os_str().to_os_string();
|
||||
named.push(suffix);
|
||||
PathBuf::from(named)
|
||||
}
|
||||
|
||||
/// Where [`Session::remove_plugin_storage`] moves the plug-in folder `path` out of the way:
|
||||
/// `<path>.removed`, and `<path>.removing` while `<path>.removed` holds settings and cache an
|
||||
/// earlier removal kept ([`is_kept`]). The second one, when it is there, is the newer.
|
||||
fn aside_paths(path: &Path) -> [PathBuf; 2] {
|
||||
[suffixed(path, ".removed"), suffixed(path, ".removing")]
|
||||
}
|
||||
|
||||
/// `<aside>.delete`: an empty file written next to the folder `aside` before it is deleted, so
|
||||
/// that what a failed deletion leaves there is not taken for settings a removal kept.
|
||||
fn delete_marker(aside: &Path) -> PathBuf {
|
||||
suffixed(aside, ".delete")
|
||||
}
|
||||
|
||||
/// Does `aside` hold settings and cache that a removal kept: a folder, or a link in place of one,
|
||||
/// without a [`delete_marker`] beside it?
|
||||
fn is_kept(aside: &Path) -> bool {
|
||||
std::fs::symlink_metadata(aside).is_ok_and(|m| !m.is_file()) && std::fs::symlink_metadata(delete_marker(aside)).is_err()
|
||||
}
|
||||
|
||||
/// Write the empty file `marker` ([`delete_marker`]).
|
||||
fn write_delete_marker(marker: &Path) -> std::io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if MARKER_WRITE_FAILS.get() {
|
||||
return Err(std::io::Error::other("the volume is full"));
|
||||
}
|
||||
std::fs::write(marker, b"")
|
||||
}
|
||||
|
||||
/// Delete the folder `aside` (a file there is left), writing its [`delete_marker`] first and
|
||||
/// removing it once the folder is gone; what the deletion can't remove stays, with a log record.
|
||||
/// When the marker can't be written, nothing is deleted, so that the folder stays whole.
|
||||
fn delete_aside(aside: &Path) {
|
||||
let marker = delete_marker(aside);
|
||||
match std::fs::symlink_metadata(aside) {
|
||||
Err(_) => {
|
||||
let _ = std::fs::remove_file(&marker);
|
||||
return;
|
||||
}
|
||||
Ok(m) if m.is_file() => return,
|
||||
Ok(_) => {}
|
||||
}
|
||||
if let Err(e) = write_delete_marker(&marker) {
|
||||
log::warn!("can't save {}: {e}; {} is left as it is", marker.display(), aside.display());
|
||||
return;
|
||||
}
|
||||
match std::fs::remove_dir_all(aside) {
|
||||
Err(e) => log::warn!("can't delete {}: {e}", aside.display()),
|
||||
Ok(()) => {
|
||||
if let Err(e) = std::fs::remove_file(&marker) {
|
||||
log::warn!("can't remove {}: {e}", marker.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rename the plug-in folder at `aside` back to `path`.
|
||||
fn move_back(aside: &Path, path: &Path) -> std::io::Result<()> {
|
||||
#[cfg(test)]
|
||||
if MOVE_BACK_FAILS.get() {
|
||||
return Err(std::io::Error::other("the folder is in use"));
|
||||
}
|
||||
std::fs::rename(aside, path)
|
||||
}
|
||||
|
||||
/// Move the newest settings and cache that a removal kept ([`aside_paths`], [`is_kept`]) back to
|
||||
/// the plug-in folder `path` when there is none. When `path` is there, it is used and the kept
|
||||
/// folders are left as they are, with a log record, until the plug-in's removal deletes them.
|
||||
/// Called under [`PLUGIN_DATA_LOCK`].
|
||||
fn restore_removed(path: &Path) -> std::io::Result<()> {
|
||||
let asides = aside_paths(path);
|
||||
let mut kept = asides.iter().rev().filter(|a| is_kept(a));
|
||||
if std::fs::symlink_metadata(path).is_ok() {
|
||||
for aside in kept {
|
||||
log::warn!("{} is used: the settings and cache in {} are left as they are", path.display(), aside.display());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
kept.next().map_or(Ok(()), |aside| move_back(aside, path))
|
||||
}
|
||||
|
||||
/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. Settings and cache
|
||||
/// that a removal kept are moved back first ([`restore_removed`]); when that fails, the failure is
|
||||
/// logged and there is no storage (its calls fail as unavailable), so that nothing the plug-in
|
||||
/// writes takes their place. A later attach or load tries again.
|
||||
fn plugin_storage(dir: Option<&Path>, id: &str) -> Option<Arc<dyn Storage>> {
|
||||
let dir = dir?;
|
||||
let data = plugin_data_dir(dir, id);
|
||||
if !is_link(&dir.join(PLUGIN_DATA_DIR)) {
|
||||
let _held = PLUGIN_DATA_LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Err(e) = restore_removed(&data) {
|
||||
log::warn!("can't move the settings and cache of {} back: {e}", data.display());
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let state = PLUGIN_DATA_OPEN.lock().unwrap_or_else(|e| e.into_inner()).entry(data.clone()).or_default().clone();
|
||||
Some(Arc::new(PluginStorage { root: dir.to_path_buf(), dir: data, state }))
|
||||
}
|
||||
|
||||
@@ -90,6 +90,7 @@ mod layerclip;
|
||||
mod layers;
|
||||
mod legacy_ai;
|
||||
mod library;
|
||||
mod library_roots;
|
||||
mod link_paths;
|
||||
mod linked_stops;
|
||||
mod linkfiles;
|
||||
@@ -3161,7 +3162,7 @@ fn every_command_survives_empty_params() {
|
||||
// The view toggles among them flip the process-wide proof view.
|
||||
let _proof_view = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner());
|
||||
for sel in [false, true] {
|
||||
for c in command_specs() {
|
||||
for c in command_specs().iter().filter(|c| crate::runs_with_empty_params(c.id)) {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
rect(&mut s, 20.0, 0.0, 10.0, 10.0);
|
||||
|
||||
@@ -1951,3 +1951,63 @@ fn symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several() {
|
||||
}
|
||||
assert_eq!(names(&s).len(), 6);
|
||||
}
|
||||
|
||||
/// Symbols panel › Sort by Name: the document's symbols in name order, ignoring case, with names
|
||||
/// that differ only in case kept in their order, as one undo step that keeps the current symbol
|
||||
/// and every instance; sorting symbols already in order adds no undo step.
|
||||
#[test]
|
||||
fn symbol_sort_by_name_orders_the_symbols_in_one_undo_step() {
|
||||
let mut s = session();
|
||||
let names = |s: &mut Session| -> Vec<String> {
|
||||
let list = s.execute("symbol.list", &json!({})).unwrap();
|
||||
list["symbols"].as_array().unwrap().iter().map(|x| x["name"].as_str().unwrap_or_default().to_string()).collect()
|
||||
};
|
||||
let current = |s: &mut Session| s.execute("symbol.list", &json!({})).unwrap()["current"].clone();
|
||||
let made = ["leaf", "Badge", "apple", "Leaf", "Zed"];
|
||||
for (i, name) in made.into_iter().enumerate() {
|
||||
rect(&mut s, 20.0 * i as f64, 0.0, 10.0, 10.0);
|
||||
s.execute("symbol.new", &json!({"name": name})).unwrap();
|
||||
}
|
||||
// No current symbol stored: the first one is current.
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).unknown.remove("currentSymbol");
|
||||
assert_eq!(current(&mut s), "leaf");
|
||||
let instances = |s: &Session| {
|
||||
let mut v = vec![];
|
||||
s.doc().unwrap().doc.walk(|n| {
|
||||
if let NodeKind::SymbolInstance { symbol, .. } = &n.kind {
|
||||
v.push((n.id, symbol.clone()));
|
||||
}
|
||||
});
|
||||
v
|
||||
};
|
||||
let placed = instances(&s);
|
||||
assert_eq!(placed.len(), 5);
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
s.execute("symbol.sortByName", &json!({})).unwrap();
|
||||
assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]);
|
||||
assert_eq!(current(&mut s), "leaf", "the current symbol stays current");
|
||||
assert_eq!(instances(&s), placed, "every instance keeps its symbol");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before + 1, "one undo step");
|
||||
// Already in order: nothing changes and no undo step is added.
|
||||
let revision = s.doc().unwrap().revision;
|
||||
s.execute("symbol.sortByName", &json!({})).unwrap();
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), s.doc().unwrap().revision), (before + 1, revision));
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(names(&mut s), made);
|
||||
assert_eq!(current(&mut s), "leaf");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]);
|
||||
// An explicitly current symbol stays current too.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("symbol.setCurrent", &json!({"name": "Zed"})).unwrap();
|
||||
s.execute("symbol.sortByName", &json!({})).unwrap();
|
||||
assert_eq!(current(&mut s), "Zed");
|
||||
// Run as a batch step it sorts as well, and with no symbols it adds no undo step.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("command.batch", &json!({"commands": [{"command": "symbol.sortByName", "params": {}}]})).unwrap();
|
||||
assert_eq!(names(&mut s), ["apple", "Badge", "leaf", "Leaf", "Zed"]);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
let before = s.doc().unwrap().history.undo.len();
|
||||
s.execute("symbol.sortByName", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), before);
|
||||
}
|
||||
@@ -710,12 +710,133 @@ fn in_place_pastes_go_onto_the_artboard_named() {
|
||||
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 15.0), "{cmd}");
|
||||
let ids = ids_of(&s.execute(cmd, &json!({})).unwrap());
|
||||
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[0].x0 + 10.0, boards[0].y0 + 15.0), "{cmd} without one");
|
||||
// An artboard that isn't there: where they were.
|
||||
let ids = ids_of(&s.execute(cmd, &json!({"artboard": 9})).unwrap());
|
||||
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[0].x0 + 10.0, boards[0].y0 + 15.0), "{cmd} on no artboard");
|
||||
// An artboard that isn't there, or a value that isn't an index: an error, and nothing pasted.
|
||||
let before = doc(&s).clone();
|
||||
for bad in [json!(9), json!(-1), json!(1.5), json!("1")] {
|
||||
assert!(s.execute(cmd, &json!({"artboard": bad})).is_err(), "{cmd} with artboard {bad}");
|
||||
}
|
||||
assert_eq!(doc(&s), &before, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Paste in Place, in Front and in Back onto several artboards (the Artboard tool's selection, which
|
||||
/// the app passes as `artboards`): a copy on each, where the objects were on the artboard they were
|
||||
/// copied from, the copies in artboard order and in their own paint order, all selected, in one undo
|
||||
/// step.
|
||||
#[test]
|
||||
fn in_place_pastes_put_a_copy_on_each_artboard_named() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 4})).unwrap();
|
||||
let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect();
|
||||
let a = rect(&mut s, boards[1].x0 + 10.0, boards[1].y0 + 15.0, 20.0, 20.0);
|
||||
let b = rect(&mut s, boards[1].x0 + 50.0, boards[1].y0 + 5.0, 10.0, 10.0);
|
||||
copy(&mut s, &[a, b]);
|
||||
for cmd in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let before = doc(&s).clone();
|
||||
let ids = ids_of(&s.execute(cmd, &json!({"artboards": [3, 0]})).unwrap());
|
||||
assert_eq!(ids.len(), 4, "{cmd}: two objects on each of two artboards");
|
||||
for (pair, board) in ids.chunks(2).zip([boards[0], boards[3]]) {
|
||||
assert_eq!(doc(&s).bounds_of(&pair[..1], false).unwrap().origin(), Point::new(board.x0 + 10.0, board.y0 + 15.0), "{cmd}");
|
||||
assert_eq!(doc(&s).bounds_of(&pair[1..], false).unwrap().origin(), Point::new(board.x0 + 50.0, board.y0 + 5.0), "{cmd}");
|
||||
}
|
||||
let layer: Vec<NodeId> = doc(&s).layers[0].children().into_iter().flatten().map(|n| n.id).collect();
|
||||
let at: Vec<usize> = ids.iter().map(|id| layer.iter().position(|n| n == id).unwrap()).collect();
|
||||
assert!(at.windows(2).all(|w| w[0] < w[1]), "{cmd}: in paint order, artboard by artboard: {at:?}");
|
||||
assert_eq!(s.doc().unwrap().selection.in_paint_order(doc(&s)), ids, "{cmd}: the copies are selected");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{cmd}: one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), &before, "{cmd}: undo takes every copy away");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s).layers[0].children().into_iter().flatten().count(), layer.len(), "{cmd}: redo");
|
||||
// `artboard` wins over `artboards`.
|
||||
let ids = ids_of(&s.execute(cmd, &json!({"artboard": 2, "artboards": [0, 3]})).unwrap());
|
||||
assert_eq!(doc(&s).bounds_of(&ids, false).unwrap().origin(), Point::new(boards[2].x0 + 10.0, boards[2].y0 + 5.0), "{cmd}");
|
||||
// A list that is empty, names an artboard the document lacks or names one twice, or isn't a
|
||||
// list: an error, and nothing pasted.
|
||||
let before = doc(&s).clone();
|
||||
for bad in [json!([]), json!([0, 4]), json!([1, 1]), json!([0, -1]), json!(2), json!("0,1")] {
|
||||
assert!(s.execute(cmd, &json!({"artboards": bad})).is_err(), "{cmd} with artboards {bad}");
|
||||
}
|
||||
assert!(s.execute(cmd, &json!({"artboard": 1, "artboards": [7]})).is_err(), "{cmd}: a bad list with `artboard`");
|
||||
assert_eq!(doc(&s), &before, "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Artboard tool chosen and several artboards selected, Paste in Place, in Front and in
|
||||
/// Back put a copy on each without naming them; the journal notes them, so a replay pastes on the
|
||||
/// same artboards, and a recorded action leaves them out. With one selected, or another tool, the
|
||||
/// objects go where they were.
|
||||
#[test]
|
||||
fn in_place_pastes_follow_the_artboard_tool_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect();
|
||||
let r = rect(&mut s, boards[0].x0 + 10.0, boards[0].y0 + 15.0, 20.0, 20.0);
|
||||
copy(&mut s, &[r]);
|
||||
let origins = |s: &Session, ids: &[NodeId]| ids.iter().map(|id| doc(s).bounds_of(&[*id], false).unwrap().origin()).collect::<Vec<_>>();
|
||||
let on = |b: &[usize]| b.iter().map(|i| Point::new(boards[*i].x0 + 10.0, boards[*i].y0 + 15.0)).collect::<Vec<_>>();
|
||||
s.select_tool("artboard", ViewInfo::default()).unwrap();
|
||||
for cmd in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
s.set_tool_option("selected", &json!([2, 1]));
|
||||
let start = s.journal.len();
|
||||
let ids = ids_of(&s.execute(cmd, &json!({})).unwrap());
|
||||
assert_eq!(origins(&s, &ids), on(&[1, 2]), "{cmd}");
|
||||
assert_eq!(s.journal.since(start).last().map(|(_, p)| p["artboards"].clone()), Some(json!([1, 2])), "{cmd}: journaled");
|
||||
assert!(s.journal_for_action(start).iter().all(|(_, p)| p.get("artboards").is_none()), "{cmd}: not in an action");
|
||||
// A stale index in the tool's selection is passed over.
|
||||
s.set_tool_option("selected", &json!([0, 9]));
|
||||
let ids = ids_of(&s.execute(cmd, &json!({})).unwrap());
|
||||
assert_eq!(origins(&s, &ids), on(&[0]), "{cmd}: one left");
|
||||
s.set_tool_option("selected", &json!([1]));
|
||||
let ids = ids_of(&s.execute(cmd, &json!({})).unwrap());
|
||||
assert_eq!(origins(&s, &ids), on(&[0]), "{cmd}: one selected, where it was");
|
||||
}
|
||||
s.set_tool_option("selected", &json!([1, 2]));
|
||||
s.select_tool("selection", ViewInfo::default()).unwrap();
|
||||
let ids = ids_of(&s.execute("edit.pasteInPlace", &json!({})).unwrap());
|
||||
assert_eq!(origins(&s, &ids), on(&[0]), "another tool: where it was");
|
||||
}
|
||||
|
||||
/// Art copied from no artboard onto several: it keeps its place on the first and its offset to the
|
||||
/// first on the others. Guides alone go on each artboard named.
|
||||
#[test]
|
||||
fn in_place_pastes_onto_several_artboards_of_art_off_them_and_guides() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
let boards: Vec<Rect> = doc(&s).artboards.iter().map(|a| a.rect).collect();
|
||||
let r = rect(&mut s, boards[0].x0 - 100.0, boards[0].y0 + 15.0, 20.0, 20.0);
|
||||
copy(&mut s, &[r]);
|
||||
assert_eq!(s.clipboard.source_artboard, None);
|
||||
let ids = ids_of(&s.execute("edit.pasteInPlace", &json!({"artboards": [1, 2]})).unwrap());
|
||||
let at: Vec<Point> = ids.iter().map(|id| doc(&s).bounds_of(&[*id], false).unwrap().origin()).collect();
|
||||
let first = Point::new(boards[0].x0 - 100.0, boards[0].y0 + 15.0);
|
||||
assert_eq!(at, [first, first + (boards[2].origin() - boards[1].origin())]);
|
||||
// Guides alone, copied from artboard 1: one on each artboard named, 30 pt into it.
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": boards[0].x0 + 30.0})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("guide.select", &json!({"indexes": [0]})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let r = s.execute("edit.pasteInFront", &json!({"artboards": [1, 2]})).unwrap();
|
||||
assert_eq!(r["guides"], 2);
|
||||
let mut guides: Vec<f64> = doc(&s).ruler_guides().iter().map(|g| g.pos).collect();
|
||||
guides.sort_by(f64::total_cmp);
|
||||
assert_eq!(guides, [boards[0].x0 + 30.0, boards[1].x0 + 30.0, boards[2].x0 + 30.0]);
|
||||
}
|
||||
|
||||
/// Artboards on the clipboard come back once, where they were, whichever artboards are named.
|
||||
#[test]
|
||||
fn in_place_pastes_of_copied_artboards_ignore_the_artboards_named() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
rect(&mut s, 10.0, 10.0, 20.0, 20.0);
|
||||
s.execute("artboard.copy", &json!({"index": 0, "art": true})).unwrap();
|
||||
let r = s.execute("edit.pasteInPlace", &json!({"artboards": [1, 2]})).unwrap();
|
||||
assert_eq!(r["artboards"], json!([3]));
|
||||
assert_eq!(ids_of(&r).len(), 1);
|
||||
assert_eq!(doc(&s).artboards[3].rect, doc(&s).artboards[0].rect);
|
||||
}
|
||||
|
||||
/// Art copied from beside the artboards goes back where it was, whichever artboard is active (#1924).
|
||||
#[test]
|
||||
fn in_place_pastes_of_art_off_the_artboards_stay_where_it_was() {
|
||||
|
||||
@@ -60,6 +60,18 @@ fn harmony_refuses_steps_or_amount_that_is_not_a_number() {
|
||||
assert_eq!(r["grid"][0].as_array().unwrap().len(), 9, "a null is read as a key left out");
|
||||
}
|
||||
|
||||
/// The Color Guide refuses a `rule` or `variation` that is not a string; a `variation` such as 5
|
||||
/// would otherwise be dropped and the default variation used.
|
||||
#[test]
|
||||
fn harmony_refuses_rule_or_variation_that_is_not_a_string() {
|
||||
let mut s = Session::new();
|
||||
for p in [json!({"color": "#ff0000", "rule": 5}), json!({"color": "#ff0000", "rule": "triad", "variation": 5})] {
|
||||
let e = s.execute("color.harmony", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("must be a string"), "{p}: {e}");
|
||||
}
|
||||
s.execute("color.harmony", &json!({"color": "#ff0000", "rule": "triad", "variation": null})).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_swatch_saves_several_colours_in_one_step() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -3146,7 +3146,7 @@ fn shift_reshapes_the_closing_segment_of_a_rotated_square_and_undoes() {
|
||||
fn pen_drag_from_the_first_anchor_closes_the_path() {
|
||||
// #501: closing a path by dragging out of its first anchor flickered between a close and a new
|
||||
// path, and released at the wrong moment left the shape open. The press decides: the drag
|
||||
// shapes the closing curve, symmetric, and the release closes the path wherever it ends.
|
||||
// shapes the closing curve, and the release closes the path wherever it ends.
|
||||
let none = Mods::default();
|
||||
let v = view();
|
||||
let mut s = session();
|
||||
@@ -3167,13 +3167,119 @@ fn pen_drag_from_the_first_anchor_closes_the_path() {
|
||||
let sp = &path(&s, id).subpaths[0];
|
||||
assert!(sp.closed && sp.anchors.len() == 3, "{sp:?}");
|
||||
let a = sp.anchors[0];
|
||||
assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(160.0, 252.0)), "symmetric");
|
||||
assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(100.0, 300.0)), "only the closing segment curves");
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
// The next click starts a new path.
|
||||
gesture(&mut s, &[(500.0, 500.0)], none);
|
||||
assert_eq!(paths(&s).len(), 2);
|
||||
}
|
||||
|
||||
/// #6634: closing a path by dragging on its first anchor does not give that anchor symmetric
|
||||
/// handles. Its incoming handle mirrors the pointer; its outgoing handle stays where it is on a
|
||||
/// corner, so the first segment keeps its shape, and on a smooth anchor turns to stay in line at
|
||||
/// its own length. Alt keeps the outgoing handle where it was when Alt went down, Shift keeps the
|
||||
/// drag to 45° steps, and a click leaves the anchor a corner with the closing segment straight
|
||||
/// into it. Each close is one undo step.
|
||||
#[test]
|
||||
fn pen_closing_drag_does_not_make_the_first_anchor_symmetric() {
|
||||
use vectorcraft_geom::AnchorKind;
|
||||
let (none, alt, shift) = (Mods::default(), Mods { alt: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() });
|
||||
let v = view();
|
||||
// Draws a path from (100, 300), dragged out to `start` when given (a smooth anchor), through
|
||||
// (200, 200) and (300, 300), and returns it with its first anchor as drawn.
|
||||
let draw = |s: &mut Session, start: Option<(f64, f64)>| {
|
||||
s.select_tool("pen", v).unwrap();
|
||||
let first = match start {
|
||||
Some(out) => vec![(100.0, 300.0), out],
|
||||
None => vec![(100.0, 300.0)],
|
||||
};
|
||||
gesture(s, &first, none);
|
||||
gesture(s, &[(200.0, 200.0)], none);
|
||||
gesture(s, &[(300.0, 300.0)], none);
|
||||
let id = s.doc().unwrap().selection.objects[0];
|
||||
let anchor = path(s, id).subpaths[0].anchors[0];
|
||||
(id, anchor)
|
||||
};
|
||||
let first = |s: &Session, id: NodeId| {
|
||||
let sp = &path(s, id).subpaths[0];
|
||||
assert!(sp.closed, "{sp:?}");
|
||||
sp.anchors[0]
|
||||
};
|
||||
|
||||
// A corner: the first segment stays straight however the drag turns.
|
||||
let mut s = session();
|
||||
let (id, before) = draw(&mut s, None);
|
||||
assert_eq!(gesture(&mut s, &[(100.0, 300.0), (80.0, 250.0), (60.0, 200.0)], none), 1, "one undo step");
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(140.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!path(&s, id).subpaths[0].closed, "the undo opens the path again");
|
||||
|
||||
// A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 50.
|
||||
let mut s = session();
|
||||
let (id, before) = draw(&mut s, Some((150.0, 300.0)));
|
||||
assert_eq!((before.h_out, before.kind), (Point::new(150.0, 300.0), AnchorKind::Smooth));
|
||||
gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], none);
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(100.0, 400.0), AnchorKind::Smooth), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(100.0, 250.0)), "in line, at its own length: {a:?}");
|
||||
|
||||
// Alt held from the press: a corner, its outgoing handle where it was.
|
||||
let mut s = session();
|
||||
let (id, before) = draw(&mut s, Some((150.0, 300.0)));
|
||||
gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], alt);
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}");
|
||||
|
||||
// Alt pressed mid-drag: the outgoing handle stays where the drag had turned it.
|
||||
let mut s = session();
|
||||
let (id, _) = draw(&mut s, Some((150.0, 300.0)));
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 200.0), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 200.0).with_mods(alt), v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 200.0).with_mods(alt), v).unwrap();
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.kind), (Point::new(70.0, 400.0), AnchorKind::Corner), "{a:?}");
|
||||
assert!(near(a.h_out, Point::new(100.0, 250.0)), "{a:?}");
|
||||
|
||||
// Shift: the drag keeps to 45° steps (straight up here), at the pointer's distance from the
|
||||
// anchor, mirrored into the incoming handle.
|
||||
let mut s = session();
|
||||
let (id, before) = draw(&mut s, None);
|
||||
gesture(&mut s, &[(100.0, 300.0), (95.0, 250.0), (90.0, 200.0)], shift);
|
||||
let a = first(&s, id);
|
||||
assert!(near(a.h_in, Point::new(100.0, 300.0 + 10f64.hypot(100.0))) && a.h_out == before.h_out, "{a:?}");
|
||||
|
||||
// A click: the closing segment comes straight in, and a smooth anchor keeps its outgoing
|
||||
// handle and becomes a corner.
|
||||
let mut s = session();
|
||||
let (id, before) = draw(&mut s, Some((150.0, 300.0)));
|
||||
assert_eq!(gesture(&mut s, &[(100.0, 300.0)], none), 1);
|
||||
let a = first(&s, id);
|
||||
assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 300.0), before.h_out, AnchorKind::Corner), "{a:?}");
|
||||
}
|
||||
|
||||
/// Close Path's `in` moves the first anchor's incoming handle as Move Direction Handle does, and
|
||||
/// `out` places its outgoing handle, making it a corner; `out` that is not [x, y] is refused.
|
||||
#[test]
|
||||
fn close_path_places_the_first_anchors_handles() {
|
||||
use vectorcraft_geom::AnchorKind;
|
||||
let mut s = session();
|
||||
let id = curve(&mut s);
|
||||
let a = path(&s, id).subpaths[0].anchors[0];
|
||||
assert!(a.has_out() && a.kind == AnchorKind::Corner, "{a:?}");
|
||||
for h in [json!("1, 2"), json!([1]), json!([1, "2"])] {
|
||||
refuses_with(&mut s, "path.close", &json!({"id": id.0, "out": h}), "`out` must be [x, y]");
|
||||
}
|
||||
s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0]})).unwrap();
|
||||
let b = path(&s, id).subpaths[0].anchors[0];
|
||||
assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), a.h_out, AnchorKind::Corner), "a corner keeps its outgoing handle");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0], "out": [120.0, 60.0]})).unwrap();
|
||||
let b = path(&s, id).subpaths[0].anchors[0];
|
||||
assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), Point::new(120.0, 60.0), AnchorKind::Corner));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() {
|
||||
// #504: while drawing, Alt-click on a smooth anchor of the path makes it a corner and Alt-drag
|
||||
|
||||
@@ -1309,7 +1309,7 @@ fn a_lent_selection_tool_moves_the_instance_of_a_picked_object() {
|
||||
#[test]
|
||||
fn read_only_commands_read_the_instance_of_a_picked_object() {
|
||||
let mut failures = Vec::new();
|
||||
for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal) {
|
||||
for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal && crate::runs_with_empty_params(c.id)) {
|
||||
let mut s = session();
|
||||
let inst = pair(&mut s, "dynamic");
|
||||
s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap();
|
||||
|
||||
@@ -88,14 +88,10 @@ fn dynamic_text_refuses_bad_params_and_other_type() {
|
||||
assert!(err(s.execute("type.dynamicText", &json!({"on": 1}))).contains("on"));
|
||||
assert_eq!(undo_len(&s), before);
|
||||
assert!(!text(&s, id).dynamic_text);
|
||||
// Point type and area type alone: refused.
|
||||
// Point type alone: refused (area type takes Block, `typecmd::block_tests`).
|
||||
let point = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].as_u64().unwrap();
|
||||
let area =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].as_u64().unwrap();
|
||||
for other in [point, area] {
|
||||
s.execute("select.set", &json!({"ids": [other]})).unwrap();
|
||||
assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path"));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [point]})).unwrap();
|
||||
assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path or area type"));
|
||||
let empty = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [empty]})).unwrap();
|
||||
assert!(s.execute("type.dynamicText", &json!({})).is_err());
|
||||
|
||||
@@ -124,6 +124,35 @@ fn adjust_balance_refuses_a_channel_that_is_not_a_number() {
|
||||
assert_eq!(fill_of(&s, a).to_hex(), "#b38080");
|
||||
}
|
||||
|
||||
/// The Edit Colors commands refuse a scope switch, `convert` or `mode` of the wrong type, which they
|
||||
/// would otherwise replace with the default: `{"fill": "false"}` recolored the fills.
|
||||
#[test]
|
||||
fn edit_colors_refuse_a_param_of_the_wrong_type() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, json!("#ff0000"));
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
let cases = [
|
||||
("edit.colors.invert", json!({"fill": "false"}), "`fill` must be true or false"),
|
||||
("edit.colors.toCMYK", json!({"stroke": 0}), "`stroke` must be true or false"),
|
||||
("edit.colors.toGrayscale", json!({"fill": "false"}), "`fill` must be true or false"),
|
||||
("edit.colors.toRGB", json!({"includeImages": "no"}), "`includeImages` must be true or false"),
|
||||
("edit.colors.saturate", json!({"intensity": 50, "includePatterns": 1}), "`includePatterns` must be true or false"),
|
||||
("edit.colors.adjustBalance", json!({"r": 20, "fill": "false"}), "`fill` must be true or false"),
|
||||
("edit.colors.adjustBalance", json!({"tint": 20, "convert": "true"}), "`convert` must be true or false"),
|
||||
("edit.colors.adjustBalance", json!({"tint": 20, "fill": "false"}), "`fill` must be true or false"),
|
||||
("edit.colors.adjustBalance", json!({"mode": 1, "r": 20}), "`mode` must be a string"),
|
||||
];
|
||||
for (id, p, want) in cases {
|
||||
let e = s.execute(id, &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{id} {p}: {e}");
|
||||
}
|
||||
assert_eq!(fill_of(&s, a).to_hex(), "#ff0000");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
// A null is read as a switch left out.
|
||||
s.execute("edit.colors.invert", &json!({"fill": null, "stroke": null})).unwrap();
|
||||
assert_eq!(fill_of(&s, a).to_hex(), "#00ffff");
|
||||
}
|
||||
|
||||
// ---------- meshes, images and patterns ----------
|
||||
|
||||
fn mesh_colors(s: &Session, id: NodeId) -> Vec<Color> {
|
||||
|
||||
@@ -405,3 +405,210 @@ fn new_envelopes_distort_appearance_and_old_ones_keep_their_look() {
|
||||
let e = arch(&mut s, 50.0, json!({}));
|
||||
assert!(matches!(node(&s, e).kind, NodeKind::Envelope { options, .. } if options == EnvelopeOptions::NEW));
|
||||
}
|
||||
|
||||
/// What strokes the object in [`squeezed`].
|
||||
#[derive(Clone, Copy)]
|
||||
enum Stroked {
|
||||
/// Nothing.
|
||||
No,
|
||||
/// The characters of type, or a path's own stroke.
|
||||
Own,
|
||||
/// A stroke on type's own appearance (Appearance panel), the characters unstroked.
|
||||
Appearance,
|
||||
}
|
||||
|
||||
/// The weight of the strokes in [`squeezed`].
|
||||
const SQUEEZED_WEIGHT: f64 = 8.0;
|
||||
|
||||
/// `make`'s object, stroked by `stroked` with a red stroke [`SQUEEZED_WEIGHT`] wide, in a one-patch
|
||||
/// mesh envelope with Distort Appearance on whose right column is moved in to squeeze the object to
|
||||
/// half its width (a horizontal squeeze, the same everywhere): the session, the envelope and the
|
||||
/// height of the envelope's middle.
|
||||
fn squeezed(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> (Session, NodeId, f64) {
|
||||
use vectorcraft_doc::live::EnvelopeKind;
|
||||
let mut s = session();
|
||||
let a = make(&mut s);
|
||||
sel(&mut s, &[a]);
|
||||
match stroked {
|
||||
Stroked::No => {}
|
||||
Stroked::Own => {
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [a.0], "weight": SQUEEZED_WEIGHT})).unwrap();
|
||||
}
|
||||
Stroked::Appearance => {
|
||||
s.edit("appearance stroke", |d, _| {
|
||||
let n = d.node_mut(a).unwrap();
|
||||
let mut appearance = (*n.appearance).clone();
|
||||
appearance
|
||||
.items
|
||||
.push(AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), SQUEEZED_WEIGHT)));
|
||||
n.appearance = appearance.into();
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let e = id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap());
|
||||
let NodeKind::Envelope { options, .. } = &node(&s, e).kind else { panic!("an envelope") };
|
||||
assert!(options.distort_appearance, "new envelopes distort appearance");
|
||||
let mut middle = 0.0;
|
||||
s.edit("squeeze", |d, _| {
|
||||
let NodeKind::Envelope { kind, .. } = &mut d.node_mut(e).unwrap().kind else { panic!("an envelope") };
|
||||
let EnvelopeKind::Mesh { points, handles, .. } = &mut **kind else { panic!("a mesh") };
|
||||
let (left, right) = (points[0].x, points[1].x);
|
||||
points[1].x = left + (right - left) / 2.0;
|
||||
points[3].x = points[1].x;
|
||||
handles.clear();
|
||||
middle = (points[0].y + points[2].y) / 2.0;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
(s, e, middle)
|
||||
}
|
||||
|
||||
/// Where the ink of the page of `s` starts and ends across height `y`, as the canvas draws it.
|
||||
fn ink_across(s: &Session, y: f64) -> (f64, f64) {
|
||||
let scale = 8.0;
|
||||
let region = Rect::new(0.0, y - 0.5, 800.0, y + 0.5);
|
||||
let r = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, region, scale, true);
|
||||
let row = (r.height / 2) as usize;
|
||||
let inked: Vec<usize> = (0..r.width as usize).filter(|i| r.pixels[(row * r.width as usize + i) * 4..][..3].iter().any(|c| *c < 128)).collect();
|
||||
let (first, last) = (inked.first().unwrap(), inked.last().unwrap());
|
||||
(*first as f64 / scale, (last + 1) as f64 / scale)
|
||||
}
|
||||
|
||||
/// How wide the ink is across the middle of `make`'s object in [`squeezed`].
|
||||
fn squeezed_ink(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> f64 {
|
||||
let (s, _, middle) = squeezed(make, stroked);
|
||||
let (first, last) = ink_across(&s, middle);
|
||||
last - first
|
||||
}
|
||||
|
||||
/// A capital I set 300 points tall at (100, 400), filled black.
|
||||
fn tall_i(s: &mut Session) -> NodeId {
|
||||
id_of(&s.execute("text.create", &json!({"x": 100, "y": 400, "text": "I", "size": 300})).unwrap())
|
||||
}
|
||||
|
||||
/// With Distort Appearance on, the characters' stroke of type in an envelope paints along the bent
|
||||
/// glyph outlines at its own weight, as `.ai` files draw it (#6644): squeezed to half its width, the
|
||||
/// stem of an I still has half the weight of stroke on each side, not a quarter.
|
||||
#[test]
|
||||
fn type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope() {
|
||||
let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Own));
|
||||
let past = stroked - plain;
|
||||
assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})");
|
||||
}
|
||||
|
||||
/// A stroke on type's own appearance paints at its own weight too (#6644).
|
||||
#[test]
|
||||
fn a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope() {
|
||||
let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Appearance));
|
||||
let past = stroked - plain;
|
||||
assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})");
|
||||
}
|
||||
|
||||
/// A path's stroke still bends with the art: squeezed to half its width, it reaches half as far past
|
||||
/// the path's left and right sides.
|
||||
#[test]
|
||||
fn a_paths_stroke_still_bends_in_a_squeezed_envelope() {
|
||||
let (plain, stroked) = (squeezed_ink(rect, Stroked::No), squeezed_ink(rect, Stroked::Own));
|
||||
let past = stroked - plain;
|
||||
assert!(
|
||||
(past - SQUEEZED_WEIGHT / 2.0).abs() < 0.5,
|
||||
"the stroke reaches {past} pt past the squeezed rectangle, both sides together ({plain} → {stroked})"
|
||||
);
|
||||
}
|
||||
|
||||
/// The type's stroke paints past the envelope's grid, where the glyphs reach its edge: the
|
||||
/// envelope's visual bounds hold it (#6644).
|
||||
#[test]
|
||||
fn the_visual_bounds_of_an_envelope_hold_its_types_strokes() {
|
||||
let (s, e, middle) = squeezed(tall_i, Stroked::Own);
|
||||
let n = node(&s, e);
|
||||
let (visual, grid) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap());
|
||||
let (first, last) = ink_across(&s, middle);
|
||||
assert!(first < grid.x0 - 1.0, "the stroke paints past the grid: {first} vs {grid:?}");
|
||||
// The ink is measured to whole pixels (an eighth of a point); miter spikes don't count, as in
|
||||
// type's own visual bounds.
|
||||
let pixel = 0.125;
|
||||
assert!(visual.x0 <= first + pixel && visual.x1 >= last - pixel, "{visual:?} holds the ink from {first} to {last}");
|
||||
assert!(first - visual.x0 < 1.0 && visual.x1 - last < 1.0, "{visual:?} reaches no further than the ink from {first} to {last}");
|
||||
}
|
||||
|
||||
/// A repeat of stroked type reaches past its copies by as far as the characters' strokes paint
|
||||
/// past their glyphs: half the weight of a centred stroke, as type's own visual bounds (#6644).
|
||||
#[test]
|
||||
fn the_visual_bounds_of_a_repeat_of_stroked_type_grow_by_half_the_stroke() {
|
||||
let mut s = session();
|
||||
let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "I", "size": 100})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap();
|
||||
let r = id_of(&s.execute("object.repeat.grid", &json!({"ids": [t.0], "rows": 2, "cols": 2})).unwrap());
|
||||
let n = node(&s, r);
|
||||
let (visual, geometric) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap());
|
||||
let grown = [geometric.x0 - visual.x0, geometric.y0 - visual.y0, visual.x1 - geometric.x1, visual.y1 - geometric.y1];
|
||||
assert!(grown.iter().all(|g| (g - SQUEEZED_WEIGHT / 2.0).abs() < 1e-6), "{grown:?}");
|
||||
}
|
||||
|
||||
/// An I stroked by `stroked` in a one-patch mesh envelope that leaves it as it is: the envelope.
|
||||
fn enveloped_i(s: &mut Session, stroked: bool) -> NodeId {
|
||||
let t = tall_i(s);
|
||||
if stroked {
|
||||
s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap();
|
||||
}
|
||||
sel(s, &[t]);
|
||||
id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap())
|
||||
}
|
||||
|
||||
/// Type's stroke in an envelope inside an envelope also paints at its own weight: the outer
|
||||
/// envelope squeezes the inner one's type to half its width, and the stem still has half the weight
|
||||
/// of stroke on each side (#6644).
|
||||
#[test]
|
||||
fn type_strokes_paint_at_their_own_weight_in_an_envelope_inside_an_envelope() {
|
||||
let (plain, stroked) = (squeezed_ink(|s| enveloped_i(s, false), Stroked::No), squeezed_ink(|s| enveloped_i(s, true), Stroked::No));
|
||||
let past = stroked - plain;
|
||||
assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})");
|
||||
}
|
||||
|
||||
/// An opacity mask on type bends as other art does (#6644): with Distort Appearance its stroke
|
||||
/// becomes its bent outline, as on a path, while the type's own stroke stays a stroke.
|
||||
#[test]
|
||||
fn an_opacity_mask_on_type_bends_as_other_art() {
|
||||
let mut s = session();
|
||||
let t = tall_i(&mut s);
|
||||
s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap();
|
||||
let m = id_of(&s.execute("shape.rectangle", &json!({"x": 90, "y": 150, "width": 120, "height": 300})).unwrap());
|
||||
s.execute("paint.setStroke", &json!({"ids": [m.0], "color": "#ffffff"})).unwrap();
|
||||
s.execute("stroke.set", &json!({"ids": [m.0], "weight": SQUEEZED_WEIGHT})).unwrap();
|
||||
sel(&mut s, &[t, m]);
|
||||
s.execute("transparency.makeOpacityMask", &json!({})).unwrap();
|
||||
assert!(node(&s, t).extras().mask.is_some(), "the type has the mask");
|
||||
sel(&mut s, &[t]);
|
||||
let e = arch(&mut s, 60.0, json!({"distortAppearance": true}));
|
||||
let (mut masks, mut kept) = (vec![], 0);
|
||||
for n in &evaluated(&s, e) {
|
||||
n.walk(&mut |c| {
|
||||
kept += c.appearance.painted_strokes().count();
|
||||
masks.extend(c.extras().mask.as_ref().map(|m| m.art.clone()));
|
||||
});
|
||||
}
|
||||
assert_eq!(masks.len(), 1, "the mask goes with the type");
|
||||
let mut in_mask = 0;
|
||||
masks[0].walk(&mut |c| in_mask += c.appearance.painted_strokes().count());
|
||||
assert_eq!(in_mask, 0, "the mask's stroke became its bent outline");
|
||||
assert_eq!(kept, 1, "the type's stroke stays a stroke");
|
||||
}
|
||||
|
||||
/// Expand turns an envelope of stroked type into its bent glyph outlines with the stroke on them,
|
||||
/// at its own weight, as it draws (#6644).
|
||||
#[test]
|
||||
fn expanding_an_envelope_of_stroked_type_keeps_the_stroke_at_its_weight() {
|
||||
let (mut s, e, _) = squeezed(tall_i, Stroked::Own);
|
||||
sel(&mut s, &[e]);
|
||||
s.execute("object.envelope.expand", &json!({})).unwrap();
|
||||
let mut weights = vec![];
|
||||
node(&s, e).walk(&mut |c| weights.extend(c.appearance.painted_strokes().map(|st| st.width)));
|
||||
assert_eq!(weights, [SQUEEZED_WEIGHT]);
|
||||
}
|
||||
@@ -61,6 +61,35 @@ fn serialize_and_reopen() {
|
||||
assert!(png.len() > 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_params_of_the_wrong_type_are_refused_and_null_keeps_the_default() {
|
||||
let mut s = session();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hello"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 100, "width": 80, "height": 40})).unwrap();
|
||||
for (cmd, p, msg) in [
|
||||
("document.serialize", json!({"format": 5}), "`format` must be a string"),
|
||||
("document.serialize", json!({"format": "svg", "selectedOnly": "true"}), "`selectedOnly` must be true or false"),
|
||||
("document.serialize", json!({"format": "txt", "selectionOnly": 1}), "`selectionOnly` must be true or false"),
|
||||
("document.serialize", json!({"format": "txt", "selectionOnly": true, "selectedOnly": "false"}), "`selectedOnly` must be true or false"),
|
||||
("document.export", json!({"format": "svg", "path": 5}), "`path` must be a string"),
|
||||
("document.exportSelection", json!({"format": "png", "path": 5}), "`path` must be a string"),
|
||||
("document.exportSelection", json!({"format": 5}), "`format` must be a string"),
|
||||
("document.exportForOffice", json!({"ppi": "300"}), "`ppi` must be a number"),
|
||||
("document.exportForOffice", json!({"transparent": "true"}), "`transparent` must be true or false"),
|
||||
("document.exportForOffice", json!({"path": 5}), "`path` must be a string"),
|
||||
] {
|
||||
let e = match s.execute(cmd, &p) {
|
||||
Ok(r) => panic!("{cmd} {p} gave {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains(msg), "{cmd} {p}: {e}");
|
||||
}
|
||||
let r = s.execute("document.serialize", &json!({"format": null, "selectedOnly": null})).unwrap();
|
||||
assert_eq!(r, s.execute("document.serialize", &json!({})).unwrap());
|
||||
let r = s.execute("document.exportForOffice", &json!({"ppi": null, "transparent": null, "path": null})).unwrap();
|
||||
assert_eq!(r, s.execute("document.exportForOffice", &json!({})).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_open_path() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -32,7 +32,7 @@ fn fill_gradient(s: &Session, id: NodeId) -> GradientPaint {
|
||||
|
||||
#[test]
|
||||
fn new_gradient_defaults_follow_the_cmyk_document_mode() {
|
||||
for kind in ["linear", "radial", "freeform"] {
|
||||
for kind in ["linear", "radial", "conic", "freeform"] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":200,"height":200,"colorMode":"cmyk"})).unwrap();
|
||||
let id = rect(&mut s, 10.0, 10.0, 100.0, 100.0);
|
||||
@@ -123,7 +123,7 @@ fn bad_gradients_are_rejected_without_editing() {
|
||||
json!({"stops": [{"offset": 0, "color": "#ff0000"}, {"color": "#000000"}]}),
|
||||
json!({"stops": [{"offset": "a", "color": "#ff0000"}, {"offset": 1, "color": "#000000"}]}),
|
||||
json!({"stops": "red"}),
|
||||
json!({"kind": "conic"}),
|
||||
json!({"kind": "spiral"}),
|
||||
json!({"start": [0, 0]}),
|
||||
json!({"aspect": "wide"}),
|
||||
] {
|
||||
@@ -565,3 +565,185 @@ fn method_is_a_gradient_option_that_saves_and_loads() {
|
||||
let back = fill_gradient(&s, id);
|
||||
assert!(back.gradient.dither && back.gradient.method == GradientMethod::Perceptual);
|
||||
}
|
||||
|
||||
/// A conic gradient through `paint.setFill`, the Gradient panel's edits, transforms, the params
|
||||
/// agents and swatches read, and the native format.
|
||||
#[test]
|
||||
fn a_conic_gradient_is_set_edited_transformed_and_saved() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic"}})).unwrap();
|
||||
let g = fill_gradient(&s, id);
|
||||
assert_eq!(g.gradient.kind, GradientKind::Conic);
|
||||
// Unplaced, it sweeps from the right about the box's center.
|
||||
let geom = g.resolve(node(&s, id).geometric_bounds().unwrap());
|
||||
assert_eq!(geom.start, Point::new(200.0, 150.0));
|
||||
assert!((geom.param_at(GradientKind::Conic, Point::new(200.0, 190.0)) - 0.25).abs() < 1e-9);
|
||||
// `angle` and `conical` name it too.
|
||||
for name in ["angle", "conical", "CONICAL"] {
|
||||
s.execute("paint.editGradient", &json!({"kind": "linear"})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": name})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).gradient.kind, GradientKind::Conic, "{name}");
|
||||
}
|
||||
let e = s.execute("paint.editGradient", &json!({"kind": "spiral"})).unwrap_err().to_string();
|
||||
assert!(e.contains("(linear, radial, conic, freeform)"), "{e}");
|
||||
// Placed, an angle turns the vector about the center.
|
||||
s.execute("paint.setGradientGeom", &json!({"start": [200, 150], "end": [260, 150], "aspect": 50})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"angle": 90})).unwrap();
|
||||
let g = fill_geom(&s, id);
|
||||
assert!(g.start.distance(Point::new(200.0, 150.0)) < 1e-9 && g.end.distance(Point::new(200.0, 90.0)) < 1e-9, "{g:?}");
|
||||
// A reflection mirrors the sweep (a negative aspect): each point keeps its color.
|
||||
let p = Point::new(230.0, 170.0);
|
||||
let before = g.param_at(GradientKind::Conic, p);
|
||||
s.execute("object.reflect", &json!({"axis": "vertical"})).unwrap();
|
||||
let m = fill_geom(&s, id);
|
||||
assert!(m.is_mirrored(), "{m:?}");
|
||||
assert!((m.param_at(GradientKind::Conic, Point::new(170.0, 170.0)) - before).abs() < 1e-9);
|
||||
// An aspect edit sets what it is given: the Gradient panel sends a mirrored conic's sign.
|
||||
s.execute("paint.editGradient", &json!({"aspect": -80})).unwrap();
|
||||
assert_eq!(fill_geom(&s, id).aspect, -0.8);
|
||||
s.execute("paint.setGradientGeom", &json!({"aspect": 40})).unwrap();
|
||||
assert_eq!(fill_geom(&s, id).aspect, 0.4);
|
||||
// A rotation carries it along.
|
||||
let g = fill_geom(&s, id);
|
||||
let before = g.param_at(GradientKind::Conic, p);
|
||||
s.execute("object.rotate", &json!({"angle": 30, "origin": [200, 150]})).unwrap();
|
||||
let r = vectorcraft_geom::Affine::rotate_about(-30f64.to_radians(), Point::new(200.0, 150.0));
|
||||
let after = fill_geom(&s, id).param_at(GradientKind::Conic, r * p);
|
||||
assert!((after - before).abs() < 1e-9, "{before} vs {after}");
|
||||
// The params give it back, and the native format keeps it.
|
||||
s.execute("paint.editGradient", &json!({"aspect": -60})).unwrap();
|
||||
let want = fill_gradient(&s, id);
|
||||
let params = vectorcraft_tools::params::gradient_params(&want);
|
||||
assert_eq!((params["kind"].as_str(), params["aspect"].as_f64()), (Some("conic"), Some(-60.0)));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("paint.setFill", &json!({ "gradient": params })).unwrap();
|
||||
let got = fill_gradient(&s, id);
|
||||
assert_eq!((&got.gradient, got.geom), (&want.gradient, want.geom));
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
let Paint::Gradient(g) = back.node(id).unwrap().appearance.fill_paint() else { panic!("the gradient is lost") };
|
||||
assert_eq!((g.gradient.kind, g.geom), (GradientKind::Conic, want.geom));
|
||||
}
|
||||
|
||||
/// A free distort that is not affine moves a conic as it moves a radial gradient: by the warp
|
||||
/// near its center, not near the middle of its vector.
|
||||
#[test]
|
||||
fn a_warp_moves_a_conic_by_its_center() {
|
||||
let warped = |kind: &str| {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [20, 30], "end": [90, 30], "aspect": 60}})).unwrap();
|
||||
s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [140, 130], [-20, 100]]})).unwrap();
|
||||
fill_geom(&s, id)
|
||||
};
|
||||
let (conic, radial, linear) = (warped("conic"), warped("radial"), warped("linear"));
|
||||
assert!(conic.start.distance(radial.start) < 1e-9, "{conic:?} vs {radial:?}");
|
||||
assert!(conic.start.distance(linear.start) > 0.1, "a linear gradient moves by its middle: {linear:?}");
|
||||
}
|
||||
|
||||
/// A negative aspect mirrors a conic's sweep where the gradient is given one, and a mirrored
|
||||
/// conic swatch lands mirrored on other art. Other kinds refuse a negative aspect, and a conic
|
||||
/// refuses a focal point.
|
||||
#[test]
|
||||
fn a_negative_aspect_mirrors_only_a_conic() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "aspect": -50}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).geom.map(|g| g.aspect), Some(-0.5));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [0, 0], "end": [10, 0], "aspect": -200}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id).geom.map(|g| g.aspect), Some(-2.0));
|
||||
let mut q = gradient_param(&fill_gradient(&s, id));
|
||||
q["name"] = json!("Mirrored");
|
||||
s.execute("swatch.new", &q).unwrap();
|
||||
let b = rect(&mut s, 500.0, 300.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"swatch": "Mirrored"})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-2.0));
|
||||
// Radial (and linear) gradients have no mirror: a negative aspect is an error, whichever
|
||||
// command gives it, and the gradient stays as it was.
|
||||
let before = fill_gradient(&s, b);
|
||||
for kind in ["radial", "linear"] {
|
||||
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "aspect": -50}})).unwrap_err().to_string();
|
||||
assert!(e.contains("aspect"), "{kind}: {e}");
|
||||
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": kind, "start": [0, 0], "end": [10, 0], "aspect": -50}})).unwrap_err();
|
||||
assert!(e.to_string().contains("aspect"), "{kind}: {e}");
|
||||
}
|
||||
assert_eq!(fill_gradient(&s, b), before);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial", "aspect": 50}})).unwrap();
|
||||
let radial = fill_gradient(&s, b);
|
||||
assert!(s.execute("paint.editGradient", &json!({"aspect": -50})).is_err());
|
||||
assert!(s.execute("paint.setGradientGeom", &json!({"aspect": -50})).is_err());
|
||||
assert!(s.execute("paint.editGradient", &json!({"kind": "linear", "aspect": -50})).is_err());
|
||||
assert_eq!(fill_gradient(&s, b), radial);
|
||||
// Turned conic in the same edit, a negative aspect mirrors it.
|
||||
s.execute("paint.editGradient", &json!({"kind": "conic", "aspect": -50})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-0.5));
|
||||
// A conic has no focal point: one given is an error, and null is allowed.
|
||||
let e = s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [500, 300], "end": [550, 300], "focal": [510, 300]}}));
|
||||
assert!(e.unwrap_err().to_string().contains("focal"));
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [500, 300], "end": [550, 300], "focal": null}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, b).geom.unwrap().focal, None);
|
||||
assert!(s.execute("paint.setGradientGeom", &json!({"focal": [510, 300]})).unwrap_err().to_string().contains("focal"));
|
||||
// A selected conic takes a negative aspect while the default paint is linear: the default
|
||||
// takes its size.
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"kind": "conic"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear"}})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("paint.editGradient", &json!({"aspect": -70})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, b).geom.map(|g| g.aspect), Some(-0.7));
|
||||
// A linear gradient keeps no focal point, as paint.setGradientGeom leaves it.
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [500, 300], "end": [550, 300], "focal": [510, 300]}})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, b).geom.unwrap().focal, None);
|
||||
}
|
||||
|
||||
/// Saved as `.ai`, as PDF with its editing data and as SVG with its editing data, then opened, a
|
||||
/// mirrored, squashed conic comes back as it was; a PDF without editing data gives it back from
|
||||
/// its sweep shading.
|
||||
#[test]
|
||||
fn a_conic_survives_saving_as_ai_pdf_and_svg() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "conic", "start": [180, 140], "end": [240, 110], "aspect": -60}})).unwrap();
|
||||
let want = fill_gradient(&s, id);
|
||||
let reopened = |s: &mut Session, format: &str, p: Value| {
|
||||
let mut p = p;
|
||||
p["format"] = json!(format);
|
||||
let r = s.execute("file.saveCopy", &p).unwrap();
|
||||
let mut back = session();
|
||||
back.execute("document.open", &json!({"name": format!("t.{format}"), "dataBase64": r["dataBase64"]})).unwrap();
|
||||
let mut found = None;
|
||||
back.doc().unwrap().doc.walk(|n| {
|
||||
if let (None, Paint::Gradient(g)) = (&found, n.appearance.fill_paint()) {
|
||||
found = Some(*g.clone());
|
||||
}
|
||||
});
|
||||
found.unwrap_or_else(|| panic!("{format}: the gradient is lost"))
|
||||
};
|
||||
for (format, p) in [("ai", json!({})), ("pdf", json!({"preserveEditing": true})), ("svg", json!({"preserveEditing": true}))] {
|
||||
let got = reopened(&mut s, format, p);
|
||||
assert_eq!((got.gradient.kind, got.geom), (GradientKind::Conic, want.geom), "{format}");
|
||||
}
|
||||
let got = reopened(&mut s, "pdf", json!({"preserveEditing": false}));
|
||||
assert_eq!(got.gradient.kind, GradientKind::Conic);
|
||||
let (g, w) = (got.geom.unwrap(), want.geom.unwrap());
|
||||
assert!(g.is_mirrored() && g.start.distance(w.start) < 0.05, "{g:?}");
|
||||
for p in [Point::new(120.0, 120.0), Point::new(280.0, 180.0), Point::new(200.0, 105.0)] {
|
||||
assert!((g.param_at(GradientKind::Conic, p) - w.param_at(GradientKind::Conic, p)).abs() < 2e-3, "{p:?}: {g:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Turning a gradient conic is one undo step, and undoing it gives the gradient back as it was.
|
||||
#[test]
|
||||
fn making_a_gradient_conic_is_one_undo_step() {
|
||||
let mut s = session();
|
||||
let id = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "radial"}})).unwrap();
|
||||
let (before, steps) = (fill_gradient(&s, id), s.doc().unwrap().history.undo.len());
|
||||
s.execute("paint.editGradient", &json!({"kind": "conic", "angle": 45})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(fill_gradient(&s, id), before);
|
||||
}
|
||||
@@ -65,3 +65,29 @@ fn halftone_options() {
|
||||
assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halftone_refuses_a_param_of_the_wrong_type() {
|
||||
for bad in [
|
||||
json!({"frequency": "60"}),
|
||||
json!({"angle": "30"}),
|
||||
json!({"shape": 1}),
|
||||
json!({"mode": true}),
|
||||
json!({"invert": "true"}),
|
||||
json!({"clip": "false"}),
|
||||
json!({"keepOriginal": 1}),
|
||||
json!({"color": 0}),
|
||||
] {
|
||||
let mut s = session();
|
||||
let id = red_rect(&mut s);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}");
|
||||
assert_eq!(s.doc().unwrap().doc, before, "{bad} changed the document");
|
||||
assert!(s.doc().unwrap().doc.node(id).is_some());
|
||||
}
|
||||
// Null stands for an omitted value.
|
||||
let mut s = session();
|
||||
red_rect(&mut s);
|
||||
let p = json!({"frequency": null, "angle": null, "shape": null, "mode": null, "color": null, "invert": null, "clip": null, "keepOriginal": null});
|
||||
assert!(s.execute("object.vectorHalftone", &p).is_ok());
|
||||
}
|
||||
@@ -128,6 +128,39 @@ fn a_batch_passes_its_artboard_to_each_step_when_it_runs() {
|
||||
assert_eq!(s.doc().unwrap().doc.artboards.len(), 1, "in the new document");
|
||||
}
|
||||
|
||||
/// A Paste in Place, in Front or in Back step that names `artboards` keeps them inside a batch
|
||||
/// given `artboard`, and pastes a copy on each; one that names neither takes the batch's artboard,
|
||||
/// unless the Artboard tool is chosen with several artboards selected: then it pastes on those.
|
||||
#[test]
|
||||
fn a_batch_keeps_the_artboards_a_paste_step_names() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 3})).unwrap();
|
||||
let boards: Vec<_> = s.doc().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
|
||||
s.execute("shape.rectangle", &json!({"x": boards[0].x0 + 10.0, "y": boards[0].y0 + 10.0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("edit.copy", &json!({})).unwrap();
|
||||
let step = |command: &str, params: Value| json!({"command": command, "params": params});
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
let origins = |r: &Value, s: &Session| {
|
||||
let ids = r["results"][0]["ids"].as_array().unwrap().iter().map(|i| vectorcraft_doc::NodeId(i.as_u64().unwrap())).collect::<Vec<_>>();
|
||||
ids.iter().map(|i| s.doc().unwrap().doc.bounds_of(&[*i], false).unwrap().origin().x).collect::<Vec<_>>()
|
||||
};
|
||||
let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({"artboards": [0, 2]}))]})).unwrap();
|
||||
assert_eq!(origins(&r, &s), [boards[0].x0 + 10.0, boards[2].x0 + 10.0], "{id}");
|
||||
let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({}))]})).unwrap();
|
||||
assert_eq!(origins(&r, &s), [boards[1].x0 + 10.0], "{id}: the batch's artboard");
|
||||
}
|
||||
s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap();
|
||||
s.set_tool_option("selected", &json!([2, 0]));
|
||||
for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] {
|
||||
let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({}))]})).unwrap();
|
||||
let ids = r["results"][0]["ids"].as_array().unwrap().iter().map(|i| vectorcraft_doc::NodeId(i.as_u64().unwrap())).collect::<Vec<_>>();
|
||||
let xs: Vec<f64> = ids.iter().map(|i| s.doc().unwrap().doc.bounds_of(&[*i], false).unwrap().origin().x).collect();
|
||||
assert_eq!(xs, [boards[0].x0 + 10.0, boards[2].x0 + 10.0], "{id}: the Artboard tool's selection");
|
||||
let r = s.execute("command.batch", &json!({"artboard": 1, "commands": [step(id, json!({"artboard": 1}))]})).unwrap();
|
||||
assert_eq!(r["results"][0]["ids"].as_array().map(Vec::len), Some(1), "{id}: a step's own `artboard` wins");
|
||||
}
|
||||
}
|
||||
|
||||
/// A batch passes its `artboard` to each Fit to Artwork Bounds and Fit to Selected Art step that
|
||||
/// names no `index`, as their `index` (past the document's last artboard, the last one), and a
|
||||
/// step's own `index` is kept. A recorded action leaves out the `index` or `indices` the app
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! The swatch, brush, symbol and graphic style library commands under automation roots: a confined
|
||||
//! request sees a library's file, the user library folder and the path in a loaded library's id only
|
||||
//! inside its read roots, and the id it is shown finds the library.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn text(p: &Path) -> String {
|
||||
p.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
/// A fresh scratch folder for one test, with the folders `in`, `out`, `a`, `b` and `user`.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-library-roots-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
for sub in ["in", "out", "a", "b", "user"] {
|
||||
std::fs::create_dir_all(dir.join(sub)).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// One kind of library and its commands.
|
||||
struct Kind {
|
||||
name: &'static str,
|
||||
list: &'static str,
|
||||
get: &'static str,
|
||||
save: &'static str,
|
||||
load: &'static str,
|
||||
ext: &'static str,
|
||||
/// Adds an item named by the second argument to the document.
|
||||
add: fn(&mut Session, &str),
|
||||
set_user_dir: fn(&mut Session, Option<String>),
|
||||
}
|
||||
|
||||
fn rectangle(s: &mut Session) -> u64 {
|
||||
run(s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].as_u64().unwrap()
|
||||
}
|
||||
|
||||
const SWATCHES: Kind = Kind {
|
||||
name: "swatches",
|
||||
list: "swatch.library.list",
|
||||
get: "swatch.library.get",
|
||||
save: "swatch.library.save",
|
||||
load: "swatch.library.load",
|
||||
ext: "vcswatches",
|
||||
add: |s, name| {
|
||||
run(s, "swatch.new", json!({"name": name, "color": "#3366cc"}));
|
||||
},
|
||||
set_user_dir: |s, dir| s.swatch_libraries.set_user_dir(dir),
|
||||
};
|
||||
|
||||
const BRUSHES: Kind = Kind {
|
||||
name: "brushes",
|
||||
list: "brush.libraries",
|
||||
get: "brush.library",
|
||||
save: "brush.saveLibrary",
|
||||
load: "brush.loadLibrary",
|
||||
ext: crate::cmd::brushlib::BRUSHES_EXT,
|
||||
add: |s, name| {
|
||||
run(s, "brush.new", json!({"type": "calligraphic", "name": name, "params": {"angle": 20, "roundness": 40, "size": 7}}));
|
||||
},
|
||||
set_user_dir: |s, dir| s.brush_libraries.set_user_dir(dir),
|
||||
};
|
||||
|
||||
const SYMBOLS: Kind = Kind {
|
||||
name: "symbols",
|
||||
list: "symbol.libraries",
|
||||
get: "symbol.library",
|
||||
save: "symbol.saveLibrary",
|
||||
load: "symbol.loadLibrary",
|
||||
ext: crate::cmd::symbollib::SYMBOLS_EXT,
|
||||
add: |s, name| {
|
||||
let id = rectangle(s);
|
||||
run(s, "symbol.new", json!({"name": name, "ids": [id]}));
|
||||
},
|
||||
set_user_dir: |s, dir| s.symbol_libraries.set_user_dir(dir),
|
||||
};
|
||||
|
||||
const STYLES: Kind = Kind {
|
||||
name: "styles",
|
||||
list: "graphicStyle.libraries",
|
||||
get: "graphicStyle.library",
|
||||
save: "graphicStyle.saveLibrary",
|
||||
load: "graphicStyle.loadLibrary",
|
||||
ext: vectorcraft_doc::style_libs::STYLES_EXT,
|
||||
add: |s, name| {
|
||||
let id = rectangle(s);
|
||||
run(s, "graphicStyle.new", json!({"name": name, "id": id}));
|
||||
},
|
||||
set_user_dir: |s, dir| s.style_libraries.set_user_dir(dir),
|
||||
};
|
||||
|
||||
/// The loaded libraries of a list reply: id, path and count.
|
||||
fn loaded(list: &Value) -> Vec<(Value, Value, Value)> {
|
||||
let libs = list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "loaded");
|
||||
libs.map(|l| (l["id"].clone(), l["path"].clone(), l["count"].clone())).collect()
|
||||
}
|
||||
|
||||
/// Does `reply` hold `path` anywhere, as JSON writes it?
|
||||
fn holds(reply: &Value, path: &Path) -> bool {
|
||||
let written = json!(text(path)).to_string();
|
||||
reply.to_string().contains(written.trim_matches('"'))
|
||||
}
|
||||
|
||||
/// Three libraries the person loaded, one inside the client's read root and two outside it in
|
||||
/// different folders under the same file name (the one in `b` holds one more item), and a user
|
||||
/// library folder outside the root. → the session, the folder and the three files.
|
||||
fn three_libraries(kind: &Kind, test: &str) -> (Session, PathBuf, [PathBuf; 3]) {
|
||||
let base = folder(&format!("{}-{test}", kind.name));
|
||||
let file = format!("Kit.{}", kind.ext);
|
||||
let files = [base.join("in").join(&file), base.join("a").join(&file), base.join("b").join(&file)];
|
||||
let mut s = Session::new();
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
(kind.add)(&mut s, "First");
|
||||
for path in &files[..2] {
|
||||
run(&mut s, kind.save, json!({"path": text(path), "name": "Kit"}));
|
||||
}
|
||||
(kind.add)(&mut s, "Second");
|
||||
run(&mut s, kind.save, json!({"path": text(&files[2]), "name": "Kit"}));
|
||||
(kind.set_user_dir)(&mut s, Some(text(&base.join("user"))));
|
||||
for path in &files {
|
||||
run(&mut s, kind.load, json!({"path": text(path)}));
|
||||
}
|
||||
(s, base, files)
|
||||
}
|
||||
|
||||
fn lists_leave_out_paths_outside_the_read_root(kind: &Kind) {
|
||||
let (mut s, base, [inside, a, b]) = three_libraries(kind, "list");
|
||||
let file = format!("Kit.{}", kind.ext);
|
||||
let person = run(&mut s, kind.list, json!({}));
|
||||
let rows = loaded(&person);
|
||||
assert_eq!(rows.len(), 3, "{person}");
|
||||
let (small, large) = (rows[1].2.clone(), rows[2].2.clone());
|
||||
assert_ne!(small, large, "{person}");
|
||||
let row = |p: &Path, count: &Value| (json!(format!("loaded/{}", text(p))), json!(text(p)), count.clone());
|
||||
assert_eq!(rows, [row(&inside, &small), row(&a, &small), row(&b, &large)], "the person sees every path: {person}");
|
||||
assert_eq!(person["userFolder"], json!(text(&base.join("user"))));
|
||||
|
||||
// The client sees the paths inside its read root; the others' rows stay, in the same order,
|
||||
// under the file's name, numbered in the order of their full ids.
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap();
|
||||
let client = confine(roots.as_ref(), || run(&mut s, kind.list, json!({})));
|
||||
let shown = [format!("loaded/{file}"), format!("loaded/{file} (2)")];
|
||||
let hidden = |id: &str, count: &Value| (json!(id), Value::Null, count.clone());
|
||||
assert_eq!(loaded(&client), [row(&inside, &small), hidden(&shown[0], &small), hidden(&shown[1], &large)], "{client}");
|
||||
assert_eq!(client["userFolder"], Value::Null, "{client}");
|
||||
for outside in ["a", "b", "user", "out"] {
|
||||
assert!(!holds(&client, &base.join(outside)), "no path outside the read root: {client}");
|
||||
}
|
||||
let everything = |l: &Value| l["libraries"].as_array().unwrap().iter().map(|l| (l["name"].clone(), l["category"].clone())).collect::<Vec<_>>();
|
||||
assert_eq!(everything(&client), everything(&person), "every library is still listed");
|
||||
|
||||
// The id shown finds its library, and replies about it show that id.
|
||||
let got = confine(roots.as_ref(), || run(&mut s, kind.get, json!({"library": shown[1]})));
|
||||
assert_eq!(got["id"], json!(shown[1]), "{got}");
|
||||
assert!(!holds(&got, &base.join("b")), "{got}");
|
||||
let got = confine(roots.as_ref(), || run(&mut s, kind.get, json!({"library": shown[0]})));
|
||||
assert_eq!(got["id"], json!(shown[0]), "{got}");
|
||||
assert!(s.execute(kind.get, &json!({"library": shown[0]})).is_err(), "the person has no such id");
|
||||
assert_eq!(run(&mut s, kind.list, json!({})), person, "the person's list is not changed");
|
||||
|
||||
// A write root alone lets the client read none of them.
|
||||
let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap();
|
||||
let client = confine(write_only.as_ref(), || run(&mut s, kind.list, json!({})));
|
||||
assert!(loaded(&client).iter().all(|(_, path, _)| path.is_null()), "{client}");
|
||||
assert!(!holds(&client, &base), "{client}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swatch_library_list_leaves_out_paths_outside_the_read_root() {
|
||||
lists_leave_out_paths_outside_the_read_root(&SWATCHES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_libraries_leave_out_paths_outside_the_read_root() {
|
||||
lists_leave_out_paths_outside_the_read_root(&BRUSHES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_libraries_leave_out_paths_outside_the_read_root() {
|
||||
lists_leave_out_paths_outside_the_read_root(&SYMBOLS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphic_style_libraries_leave_out_paths_outside_the_read_root() {
|
||||
lists_leave_out_paths_outside_the_read_root(&STYLES);
|
||||
}
|
||||
|
||||
/// Adding from a concealed library, copying it into the user library folder and saving into that
|
||||
/// folder show neither the library's file nor the folder outside the read root.
|
||||
#[test]
|
||||
fn swatch_library_replies_leave_out_paths_outside_the_read_root() {
|
||||
let (mut s, base, [inside, ..]) = three_libraries(&SWATCHES, "replies");
|
||||
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap();
|
||||
let shown = "loaded/Kit.vcswatches";
|
||||
let added = confine(roots.as_ref(), || run(&mut s, "swatch.library.add", json!({"library": shown, "names": ["First"]})));
|
||||
assert_eq!(added["library"], shown, "{added}");
|
||||
// A library whose file is outside the root is not copied, and the error does not name the file.
|
||||
let refused = confine(roots.as_ref(), || s.execute("swatch.library.copyToUser", &json!({"library": shown})));
|
||||
let message = refused.map(|r| r.to_string()).unwrap_err().to_string();
|
||||
assert!(message.contains("outside the read roots"), "{message}");
|
||||
assert!(!message.contains(&text(&base)) && !message.contains("Kit.vcswatches"), "{message}");
|
||||
assert!(!base.join("user/Kit.vcswatches").exists());
|
||||
// The file inside the root is copied into the user library folder, which is outside it.
|
||||
let mine = format!("loaded/{}", text(&inside));
|
||||
let copied = confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": mine})));
|
||||
assert_eq!((copied["library"].as_str(), copied["copied"].as_bool()), (Some("user/Kit.vcswatches"), Some(true)), "{copied}");
|
||||
assert_eq!(copied["path"], Value::Null, "{copied}");
|
||||
let saved = confine(roots.as_ref(), || run(&mut s, "swatch.library.save", json!({"user": true, "name": "Mine"})));
|
||||
assert_eq!((saved["library"].as_str(), saved.get("path")), (Some("user/Mine.vcswatches"), None), "{saved}");
|
||||
for reply in [&added, &copied, &saved] {
|
||||
assert!(!holds(reply, &base.join("a")) && !holds(reply, &base.join("user")), "{reply}");
|
||||
}
|
||||
// A library loaded from data under the file name keeps its id; each concealed one takes the next
|
||||
// free one, so no two rows share an id.
|
||||
let data = run(&mut s, "swatch.library.save", json!({}))["data"].as_str().unwrap().to_string();
|
||||
run(&mut s, "swatch.library.load", json!({"data": data, "name": "Kit.vcswatches"}));
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)"), json!("loaded/Kit.vcswatches")], "{list}");
|
||||
// Copied into the user library folder, it is still found by that id, which no other library takes.
|
||||
confine(roots.as_ref(), || run(&mut s, "swatch.library.copyToUser", json!({"library": "loaded/Kit.vcswatches"})));
|
||||
let list = confine(roots.as_ref(), || run(&mut s, "swatch.library.list", json!({})));
|
||||
let ids: Vec<Value> = loaded(&list).into_iter().map(|(id, ..)| id).collect();
|
||||
assert_eq!(ids, [json!("loaded/Kit.vcswatches (2)"), json!("loaded/Kit.vcswatches (3)")], "{list}");
|
||||
// The person sees the folder.
|
||||
let saved = run(&mut s, "swatch.library.save", json!({"user": true, "name": "Theirs"}));
|
||||
assert_eq!(saved["path"], json!(text(&base.join("user").join("Theirs.vcswatches"))));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
@@ -321,6 +321,78 @@ fn a_radial_gradient_becomes_concentric_ellipses() {
|
||||
assert!(f.opacity < 1.0 && f.opacity > 0.5, "the centre band is translucent: {}", f.opacity);
|
||||
}
|
||||
|
||||
/// Three opaque stops sweeping once around the center.
|
||||
fn conic_stops() -> Value {
|
||||
json!({"kind": "conic", "stops": [{"offset": 0, "color": "#ffff00"}, {"offset": 0.5, "color": "#ff00ff"}, {"offset": 1, "color": "#004080"}]})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_conic_gradient_becomes_wedges_or_a_mesh_that_paint_it() {
|
||||
// Objects: a wedge per step from the center, together painting what the canvas painted.
|
||||
let mut s = session();
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({"steps": 180}));
|
||||
let g = selected(&s);
|
||||
let (_, wedges) = clip_parts(&g);
|
||||
assert_eq!(wedges.len(), 180);
|
||||
let first = wedges[0].path_data().unwrap().subpaths[0].anchors[0].p;
|
||||
assert!(first.distance(vectorcraft_geom::Point::new(100.0, 100.0)) < 1e-9, "wedges start at the center: {first:?}");
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48));
|
||||
assert!(mean_diff(&before, &after) < 2.0, "{}", mean_diff(&before, &after));
|
||||
// Translucent stops: each wedge is just its share of the turn, ending where the next starts,
|
||||
// so none doubles up (only the anti-aliased seams between them differ from the canvas).
|
||||
let mut s = session();
|
||||
let gr = json!({"kind": "conic", "stops": [{"offset": 0, "color": "#ff0000", "opacity": 0.5}, {"offset": 1, "color": "#0000ff"}]});
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), gr, false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({"steps": 36}));
|
||||
let g = selected(&s);
|
||||
let (_, wedges) = clip_parts(&g);
|
||||
let outline = |n: &Node| n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect::<Vec<_>>();
|
||||
for pair in wedges.windows(2) {
|
||||
let (a, b) = (outline(pair[0]), outline(pair[1]));
|
||||
assert!(a.last().unwrap().distance(b[1]) < 1e-6, "{a:?} then {b:?}");
|
||||
}
|
||||
assert!(mean_diff(&before, &render(&s)) < 4.0, "{}", mean_diff(&before, &render(&s)));
|
||||
// Mesh: columns around the center.
|
||||
let mut s = session();
|
||||
gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false);
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", json!({"gradient": "mesh"}));
|
||||
let g = selected(&s);
|
||||
let (_, content) = clip_parts(&g);
|
||||
let NodeKind::Mesh(m) = &content[0].kind else { panic!("a mesh node: {:?}", content[0].kind) };
|
||||
assert!(m.is_valid());
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 48) < 200, "{}", differing(&before, &after, 48));
|
||||
assert!(mean_diff(&before, &after) < 2.5, "{}", mean_diff(&before, &after));
|
||||
}
|
||||
|
||||
/// A mirrored conic, and one whose extent ellipse is flat (as a file can hold it), expand as the
|
||||
/// canvas draws them.
|
||||
#[test]
|
||||
fn a_mirrored_or_flat_conic_expands_as_the_canvas_draws_it() {
|
||||
for aspect in [-0.6, 0.0] {
|
||||
for how in [json!({"steps": 180}), json!({"gradient": "mesh"})] {
|
||||
let mut s = session();
|
||||
let id = gradient_rect(&mut s, Rect::new(30.0, 40.0, 170.0, 160.0), conic_stops(), false);
|
||||
let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let n = d.node_mut(id).unwrap();
|
||||
let Paint::Gradient(mut g) = n.appearance.fill_paint().clone() else { panic!("a gradient fill") };
|
||||
let (start, end) = (vectorcraft_geom::Point::new(90.0, 110.0), vectorcraft_geom::Point::new(130.0, 80.0));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect, focal: None });
|
||||
n.appearance.set_fill(Paint::Gradient(g));
|
||||
let before = render(&s);
|
||||
run(&mut s, "object.expand", how.clone());
|
||||
let after = render(&s);
|
||||
assert!(differing(&before, &after, 48) < 200, "{aspect} {how}: {}", differing(&before, &after, 48));
|
||||
assert!(mean_diff(&before, &after) < 2.5, "{aspect} {how}: {}", mean_diff(&before, &after));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mesh_option_makes_a_mesh_that_paints_the_gradient() {
|
||||
for gradient in [
|
||||
|
||||
@@ -198,6 +198,30 @@ fn overprints(s: &Session, id: NodeId) -> (bool, bool) {
|
||||
(a.fill().unwrap().overprint, a.stroke().unwrap().overprint)
|
||||
}
|
||||
|
||||
/// Overprint Black refuses a switch or `percentage` of the wrong type, which it would otherwise
|
||||
/// replace with the default: `{"fill": "false"}` marked the fills.
|
||||
#[test]
|
||||
fn overprint_black_refuses_a_param_of_the_wrong_type() {
|
||||
let mut s = session();
|
||||
let k = rect(&mut s, [0.0, 0.0, 10.0, 10.0], black_ink(), Some(black_ink()), 1.0);
|
||||
let before = undo_len(&s);
|
||||
for (p, want) in [
|
||||
(json!({"ids": [k.0], "fill": "false"}), "`fill` must be true or false"),
|
||||
(json!({"ids": [k.0], "stroke": 0}), "`stroke` must be true or false"),
|
||||
(json!({"ids": [k.0], "remove": "true"}), "`remove` must be true or false"),
|
||||
(json!({"ids": [k.0], "includeCmyBlacks": "yes"}), "`includeCmyBlacks` must be true or false"),
|
||||
(json!({"ids": [k.0], "includeSpotBlacks": 1}), "`includeSpotBlacks` must be true or false"),
|
||||
(json!({"ids": [k.0], "percentage": "75"}), "`percentage` must be a number"),
|
||||
] {
|
||||
let e = s.execute("edit.colors.overprintBlack", &p).unwrap_err().to_string();
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
assert_eq!((overprints(&s, k), undo_len(&s)), ((false, false), before), "nothing changed, no undo step");
|
||||
// A null is read as a key left out.
|
||||
s.execute("edit.colors.overprintBlack", &json!({"ids": [k.0], "fill": null, "percentage": null})).unwrap();
|
||||
assert_eq!(overprints(&s, k), (true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_black_options() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -98,6 +98,33 @@ fn an_unsaved_document_cant_be_packaged() {
|
||||
assert!(Session::new().execute("file.package", &json!({})).is_err(), "no document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_param_of_the_wrong_type_is_refused_and_null_keeps_the_default() {
|
||||
let dir = Folder::new("package-types");
|
||||
let mut s = poster(&dir);
|
||||
let out = dir.file("out");
|
||||
for (p, msg) in [
|
||||
(json!({"folder": out, "copyLinks": "false"}), "`copyLinks` must be true or false"),
|
||||
(json!({"folder": out, "linksFolder": 0}), "`linksFolder` must be true or false"),
|
||||
(json!({"folder": out, "relink": "no"}), "`relink` must be true or false"),
|
||||
(json!({"folder": out, "copyFonts": "false"}), "`copyFonts` must be true or false"),
|
||||
(json!({"folder": out, "report": 1}), "`report` must be true or false"),
|
||||
(json!({"folder": out, "name": 5}), "`name` must be a string"),
|
||||
(json!({"folder": 5}), "`folder` must be a string"),
|
||||
] {
|
||||
let e = match s.execute("file.package", &p) {
|
||||
Ok(r) => panic!("{p} gave {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains(msg), "{p}: {e}");
|
||||
assert!(!std::path::Path::new(&out).exists(), "{p} wrote nothing");
|
||||
}
|
||||
let r = run(&mut s, "file.package", json!({"folder": null, "name": null, "copyLinks": null, "copyFonts": null, "report": null}));
|
||||
assert_eq!(r["name"], "poster Folder.zip");
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
|
||||
assert_eq!(files, ["poster.vectorcraft", "Links/red.png", "Links/blue.png", "Fonts/SourceSans3-Regular.ttf", "poster Report.txt"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_folder_the_zip_has_the_same_files() {
|
||||
let dir = Folder::new("package-zip");
|
||||
@@ -393,7 +420,7 @@ fn the_document_info_report_has_every_category() {
|
||||
"BRUSHES",
|
||||
"SPOT COLORS",
|
||||
"PATTERN OBJECTS",
|
||||
"GRADIENT SWATCHES",
|
||||
"GRADIENT OBJECTS",
|
||||
"SYMBOLS",
|
||||
"FONTS",
|
||||
"FONT DETAILS",
|
||||
|
||||
@@ -64,7 +64,7 @@ fn edit_gradient_angle_reverse_and_errors() {
|
||||
assert_eq!(g.gradient.stops[0].color.to_hex(), "#0000ff");
|
||||
assert!((g.gradient.stops[0].midpoint - 0.8).abs() < 1e-6, "{:?}", g.gradient.stops);
|
||||
assert!(s.execute("paint.editGradient", &json!({"stops": [{"offset": 0, "color": "#fff"}]})).is_err());
|
||||
assert!(s.execute("paint.editGradient", &json!({"kind": "conic"})).is_err());
|
||||
assert!(s.execute("paint.editGradient", &json!({"kind": "spiral"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -766,3 +766,71 @@ fn objects_on_path_members_stay_on_the_grid() {
|
||||
assert!(whole(&points(&s, a)), "path edited: {:?}", points(&s, a));
|
||||
assert!(points(&s, a).iter().all(|(_, y)| *y > 105.0), "followed the path: {:?}", points(&s, a));
|
||||
}
|
||||
|
||||
fn selected_ids(s: &Session) -> Vec<u64> {
|
||||
let mut ids: Vec<u64> = s.doc().unwrap().selection.objects.iter().map(|i| i.0).collect();
|
||||
ids.sort_unstable();
|
||||
ids
|
||||
}
|
||||
|
||||
/// Select › Object › Not Aligned to Pixel Grid selects the paths and compound paths whose
|
||||
/// property is off, whole coordinates or not, in groups too, and replaces the selection; a compound
|
||||
/// path counts as one object; type, guides and aligned paths stay out; the art, its property and
|
||||
/// the undo history stay as they are.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_selects_paths_without_the_property() {
|
||||
let mut s = new_doc();
|
||||
let fractional = path(&mut s, "M10.3 20.6 L40.7 20.6 L40.7 30.3 L10.3 30.3 Z", 1.0);
|
||||
let whole_but_off = path(&mut s, "M50 50 L60 50 L60 60 L50 60 Z", 1.0);
|
||||
let on = path(&mut s, "M70.4 70 L80 70 L80 80 L70.4 80 Z", 1.0);
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let guide = path(&mut s, "M0 200 L400 200", 1.0);
|
||||
s.execute("view.guides.make", &json!({})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 100, "y": 100, "text": "type"})).unwrap();
|
||||
let m1 = path(&mut s, "M100 100 L120 100 L120 120 L100 120 Z", 1.0);
|
||||
let m2 = path(&mut s, "M130 100 L150 100 L150 120 L130 120 Z", 1.0);
|
||||
s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap();
|
||||
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let grouped = path(&mut s, "M200 200 L210 200 L210 210 L200 210 Z", 1.0);
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [on]})).unwrap();
|
||||
let before = points(&s, fractional);
|
||||
let steps = undo_len(&s);
|
||||
let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap();
|
||||
let mut want = vec![fractional, whole_but_off, compound, grouped];
|
||||
want.sort_unstable();
|
||||
assert_eq!(r["count"], 4);
|
||||
assert_eq!(selected_ids(&s), want);
|
||||
assert!(!selected_ids(&s).contains(&guide));
|
||||
assert_eq!(points(&s, fractional), before);
|
||||
assert!(!aligned(&s, fractional) && aligned(&s, on));
|
||||
assert_eq!(undo_len(&s), steps);
|
||||
// With every such object aligned, nothing is selected.
|
||||
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
|
||||
let r = s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap();
|
||||
assert_eq!(r["count"], 0);
|
||||
assert!(selected_ids(&s).is_empty());
|
||||
}
|
||||
|
||||
/// Not Aligned to Pixel Grid leaves out hidden and locked paths and, in isolation mode, the art
|
||||
/// outside the isolated group.
|
||||
#[test]
|
||||
fn not_aligned_to_pixel_grid_leaves_out_what_cant_be_selected() {
|
||||
let mut s = new_doc();
|
||||
let hidden = path(&mut s, "M10 10 L20 10 L20 20 L10 20 Z", 1.0);
|
||||
s.execute("object.setProps", &json!({"ids": [hidden], "visible": false})).unwrap();
|
||||
let locked = path(&mut s, "M30 10 L40 10 L40 20 L30 20 Z", 1.0);
|
||||
s.execute("object.setProps", &json!({"ids": [locked], "locked": true})).unwrap();
|
||||
let outside = path(&mut s, "M50 10 L60 10 L60 20 L50 20 Z", 1.0);
|
||||
let inside = path(&mut s, "M70 10 L80 10 L80 20 L70 20 Z", 1.0);
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 2);
|
||||
assert_eq!(selected_ids(&s), {
|
||||
let mut v = vec![outside, inside];
|
||||
v.sort_unstable();
|
||||
v
|
||||
});
|
||||
s.execute("object.isolate", &json!({"id": g})).unwrap();
|
||||
assert_eq!(s.execute("select.object.notAlignedToPixelGrid", &json!({})).unwrap()["count"], 1);
|
||||
assert_eq!(selected_ids(&s), vec![inside]);
|
||||
}
|
||||
@@ -954,6 +954,51 @@ fn bad_place_params_are_errors() {
|
||||
assert!(top_children(&s).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn place_params_of_the_wrong_type_are_refused_and_null_keeps_the_default() {
|
||||
let mut s = session();
|
||||
let ok = png(2, 2, [0; 4], None);
|
||||
let with = |extra: Value| {
|
||||
let mut p = file("x.png", &ok);
|
||||
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
p
|
||||
};
|
||||
let queue = |extra: Value| {
|
||||
let mut p = json!({ "files": [file("x.png", &ok)] });
|
||||
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
p
|
||||
};
|
||||
for (cmd, p, msg) in [
|
||||
("file.place", with(json!({"link": "false"})), "`link` must be true or false"),
|
||||
("file.place", with(json!({"replace": 1})), "`replace` must be true or false"),
|
||||
("file.place", with(json!({"template": "true"})), "`template` must be true or false"),
|
||||
("file.place.queue", queue(json!({"link": "false"})), "`link` must be true or false"),
|
||||
("file.place.queue", queue(json!({"template": 1})), "`template` must be true or false"),
|
||||
("file.place.queue", queue(json!({"thumbnail": "8"})), "`thumbnail` must be a number"),
|
||||
("file.place.info", with(json!({"link": "no"})), "`link` must be true or false"),
|
||||
("file.place.info", with(json!({"thumbnail": "8"})), "`thumbnail` must be a number"),
|
||||
] {
|
||||
let e = match s.execute(cmd, &p) {
|
||||
Ok(r) => panic!("{cmd} gave {r}"),
|
||||
Err(e) => e.to_string(),
|
||||
};
|
||||
assert!(e.contains(msg), "{cmd}: {e}");
|
||||
assert_eq!(s.tool_id(), "selection", "{cmd}: the tool stays");
|
||||
assert!(top_children(&s).is_empty(), "{cmd}: nothing placed");
|
||||
}
|
||||
let placed = s.execute("file.place", &with(json!({"link": null, "replace": null, "template": null}))).unwrap();
|
||||
assert_eq!(placed["ids"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(top_children(&s).len(), 1, "placed on the current layer, not a template layer");
|
||||
let info = s.execute("file.place.info", &with(json!({"link": null, "thumbnail": null}))).unwrap();
|
||||
assert!(info.get("thumbnailBase64").is_none(), "{info}");
|
||||
let r = s.execute("file.place.queue", &queue(json!({"link": null, "template": null, "thumbnail": null}))).unwrap();
|
||||
assert_eq!(r["count"], 1, "{r}");
|
||||
}
|
||||
|
||||
/// An SVG placed with `crop: "crop"` given is framed and clipped by its viewBox, as a PDF by its
|
||||
/// page, so art drawn on a shared canvas keeps its place and scale; by default (and with
|
||||
/// "bounding") it is fitted by its art's bounds (#788).
|
||||
|
||||
@@ -1973,6 +1973,125 @@ fn a_grant_that_cannot_be_removed_stops_plugin_remove() {
|
||||
assert!(!std::path::Path::new(&file).exists());
|
||||
}
|
||||
|
||||
/// When `plugin.remove` can't remove the grant and can't move the settings back either, its error
|
||||
/// says where the settings are, and the plug-in gets no storage until they are back. A second
|
||||
/// removal that can't remove the grant moves them back rather than deleting them, and so does the
|
||||
/// next load of the plug-in.
|
||||
#[test]
|
||||
fn settings_that_cannot_be_moved_back_are_reported_and_moved_back_later() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-failed-move-back");
|
||||
let id = "test.engine.permissions.movebackfail";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let grants = folder.0.join("grants.json");
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]}));
|
||||
let recorded = std::fs::read(&grants).unwrap();
|
||||
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
|
||||
let entry = serde_json::from_slice::<Vec<Value>>(&recorded).unwrap().remove(0);
|
||||
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
|
||||
std::fs::write(&grants, &full).unwrap();
|
||||
let data = crate::store::plugin_data_dir(&folder.0, id);
|
||||
let settings = br#"{"zoom":"aGVsbG8="}"#;
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(data.join("settings.json"), settings).unwrap();
|
||||
let mut aside = data.clone().into_os_string();
|
||||
aside.push(".removed");
|
||||
let aside = std::path::PathBuf::from(aside);
|
||||
|
||||
crate::store::MOVE_BACK_FAILS.set(true);
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
crate::store::MOVE_BACK_FAILS.set(false);
|
||||
assert!(refused.contains(crate::store::GRANT_NOT_REMOVED), "{refused}");
|
||||
assert!(refused.contains(&aside.display().to_string()) && refused.contains("the folder is in use"), "{refused}");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in stays installed");
|
||||
assert!(!data.exists());
|
||||
assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings);
|
||||
assert!(vectorcraft_plugins::registry::storage(id).is_none(), "no empty settings take their place");
|
||||
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert_eq!(refused, crate::store::GRANT_NOT_REMOVED);
|
||||
assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), settings, "the second removal moves the settings back");
|
||||
assert!(!aside.exists());
|
||||
|
||||
crate::store::MOVE_BACK_FAILS.set(true);
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err());
|
||||
crate::store::MOVE_BACK_FAILS.set(false);
|
||||
assert!(!data.exists());
|
||||
|
||||
// A folder of the plug-in's own made meanwhile is used, and a removal that can't remove the
|
||||
// grant leaves both.
|
||||
let newer = br#"{"zoom":"bmV3"}"#;
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(data.join("settings.json"), newer).unwrap();
|
||||
let refused = s.execute("plugin.remove", &json!({"id": id})).unwrap_err().to_string();
|
||||
assert_eq!(refused, crate::store::GRANT_NOT_REMOVED);
|
||||
assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), newer);
|
||||
assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings, "the kept settings stay");
|
||||
std::fs::remove_dir_all(&data).unwrap();
|
||||
|
||||
// A restart loads the plug-in again with its settings.
|
||||
std::fs::write(&grants, &recorded).unwrap();
|
||||
vectorcraft_plugins::registry::remove(id);
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_some(), "the plug-in loads");
|
||||
assert_eq!(std::fs::read(data.join("settings.json")).unwrap(), settings, "the load moves the settings back");
|
||||
assert!(!aside.exists());
|
||||
|
||||
run(&mut next, "plugin.remove", json!({"id": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert!(!data.exists() && !aside.exists(), "the removal deletes the settings");
|
||||
assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "nothing is left beside them");
|
||||
}
|
||||
|
||||
/// What a deletion left in a plug-in's renamed settings folder, marked by the `.delete` file beside
|
||||
/// it, isn't moved back. When that file can't be written, nothing is deleted, so the folder stays
|
||||
/// whole and counts as kept settings.
|
||||
#[test]
|
||||
fn a_removal_deletes_only_folders_it_marked() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-store-delete-mark");
|
||||
let id = "test.engine.permissions.deletemark";
|
||||
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
|
||||
let install = json!({"dataBase64": vectorcraft_format::base64_encode(&approved), "grant": ["doc.read"]});
|
||||
let mut next = session();
|
||||
next.attach_plugin_store(folder.0.clone());
|
||||
let data = crate::store::plugin_data_dir(&folder.0, id);
|
||||
let settings = br#"{"zoom":"aGVsbG8="}"#;
|
||||
let mut aside = data.clone().into_os_string();
|
||||
aside.push(".removed");
|
||||
let aside = std::path::PathBuf::from(aside);
|
||||
let mut marker = aside.clone().into_os_string();
|
||||
marker.push(".delete");
|
||||
|
||||
// The next install starts with no settings, and its removal deletes the leftover and the mark.
|
||||
std::fs::create_dir_all(&aside).unwrap();
|
||||
std::fs::write(aside.join("settings.json"), settings).unwrap();
|
||||
std::fs::write(&marker, b"").unwrap();
|
||||
run(&mut next, "plugin.install", install.clone());
|
||||
assert!(!data.exists(), "a leftover of a deletion isn't moved back");
|
||||
run(&mut next, "plugin.remove", json!({"id": id}));
|
||||
assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "the leftover and its mark are deleted");
|
||||
|
||||
// When the mark can't be written, the removal deletes nothing: installing the id again needs
|
||||
// `replace`, and a removal of the id that isn't installed deletes the folder.
|
||||
run(&mut next, "plugin.install", install.clone());
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::write(data.join("settings.json"), settings).unwrap();
|
||||
crate::store::MARKER_WRITE_FAILS.set(true);
|
||||
let removed = next.execute("plugin.remove", &json!({"id": id}));
|
||||
crate::store::MARKER_WRITE_FAILS.set(false);
|
||||
assert_eq!(removed.unwrap(), json!({"removed": id}));
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings, "nothing is deleted without the mark");
|
||||
assert!(!std::path::Path::new(&marker).exists());
|
||||
assert!(next.execute("plugin.install", &install).is_err(), "the kept settings go to a new install only with `replace`");
|
||||
assert!(vectorcraft_plugins::registry::get(id).is_none());
|
||||
assert_eq!(std::fs::read(aside.join("settings.json")).unwrap(), settings);
|
||||
run(&mut next, "plugin.remove", json!({"id": id}));
|
||||
assert_eq!(std::fs::read_dir(data.parent().unwrap()).unwrap().count(), 0, "the removal of the id deletes the kept folder");
|
||||
}
|
||||
|
||||
/// Windows keeps a file another program holds open without delete sharing, so the last grant can't
|
||||
/// be removed by deleting `grants.json`.
|
||||
#[cfg(windows)]
|
||||
@@ -3242,6 +3361,40 @@ fn removing_an_id_that_is_not_installed_deletes_its_storage() {
|
||||
assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "nothing left to remove");
|
||||
}
|
||||
|
||||
/// The `plugin.*` commands that the tests running every command with `{}` run
|
||||
/// ([`crate::runs_with_empty_params`]) leave the cache of an installed plug-in as it is, so
|
||||
/// those tests can run beside the ones here that check a cache. Each command runs with `{}` in a
|
||||
/// document with two rectangles, one or both selected, as `every_command_survives_empty_params`
|
||||
/// runs it.
|
||||
#[test]
|
||||
fn plugin_commands_run_with_empty_params_keep_other_plugins_caches() {
|
||||
let folder = crate::tests_links::Folder::new("plugin-storage-empty-params");
|
||||
let id = "test.engine.storageemptyparams";
|
||||
let mut s = session();
|
||||
s.attach_plugin_store(folder.0.clone());
|
||||
install_storing(&mut s, id, WRITES);
|
||||
run(&mut s, "plugin.run", json!({"id": id, "ids": []}));
|
||||
assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3));
|
||||
let mut ran = vec![];
|
||||
for all in [false, true] {
|
||||
for c in crate::cmd::command_specs().iter().filter(|c| c.id.starts_with("plugin.") && crate::runs_with_empty_params(c.id)) {
|
||||
let mut other = session();
|
||||
let a = rect(&mut other, 10.0, "#ff0000");
|
||||
rect(&mut other, 40.0, "#0000ff");
|
||||
if all {
|
||||
run(&mut other, "select.all", json!({}));
|
||||
} else {
|
||||
run(&mut other, "select.set", json!({"ids": [a.0]}));
|
||||
}
|
||||
let _ = other.execute(c.id, &json!({}));
|
||||
ran.push(c.id);
|
||||
assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3), "after {}", c.id);
|
||||
}
|
||||
}
|
||||
assert!(ran.contains(&"plugin.list"), "{ran:?}");
|
||||
run(&mut s, "plugin.remove", json!({"id": id}));
|
||||
}
|
||||
|
||||
/// The settings file and the cache are checked: a file that doesn't read is moved aside and the
|
||||
/// settings start empty; a write past a cap fails and changes nothing; cache entries whose names
|
||||
/// differ only in case are two files; a removed plug-in's storage takes no more writes.
|
||||
|
||||
@@ -153,6 +153,20 @@ fn script_file_link_escape_refused() {
|
||||
Folder.current.getFiles().map(function (f) { return f.name; }), new Folder('near').alias, new Folder('near').resolve().name]);",
|
||||
);
|
||||
assert_eq!(log, json!([[false, null, DENIED, null, false, false, DENIED, ["inner", "main.jsx", "near", "own.txt"], true, "inner"]]));
|
||||
// A missing file behind the link is refused like an existing one, so nothing tells them apart.
|
||||
let log = logged(&base, "var n = new File('away/nope.txt'); vc.log([n.exists, n.open('r'), n.error]);");
|
||||
assert_eq!(log, json!([[false, false, DENIED]]));
|
||||
// A folder link to an outside folder that does not exist is refused the same way, so a script
|
||||
// cannot tell whether the folder it leads to exists.
|
||||
link_folder(&base.join("gone"), &base.join("main").join("dangling"));
|
||||
let log = logged(
|
||||
&base,
|
||||
"var d = new File('dangling/nope.txt'); var e = new File('dangling/a/b.txt');\n\
|
||||
vc.log([d.exists, d.open('r'), d.error, e.open('r'), e.error]);",
|
||||
);
|
||||
assert_eq!(log, json!([[false, false, DENIED, false, DENIED]]));
|
||||
let dangling = base.join("main").join("dangling");
|
||||
std::fs::remove_dir(&dangling).or_else(|_| std::fs::remove_file(&dangling)).unwrap();
|
||||
#[cfg(unix)]
|
||||
let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok();
|
||||
#[cfg(windows)]
|
||||
@@ -176,6 +190,31 @@ fn script_file_link_escape_refused() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A path whose names differ from the script's folder only in case is that folder where case does
|
||||
/// not matter, and outside it where case matters, whether or not the file is there.
|
||||
#[test]
|
||||
fn script_file_case_variant_folder() {
|
||||
let base = folder("case");
|
||||
write(&base.join("main/own.txt"), b"own");
|
||||
let upper = base.join("MAIN");
|
||||
let source = |name: &str| {
|
||||
let p = format!("{:?}", upper.join(name).to_string_lossy());
|
||||
format!("var f = new File({p}); vc.log([f.exists, f.open('r'), f.error]);")
|
||||
};
|
||||
if upper.exists() {
|
||||
// Case does not matter here: `MAIN` is the script's folder.
|
||||
assert_eq!(logged(&base, &source("own.txt")), json!([[true, true, ""]]));
|
||||
assert_eq!(logged(&base, &source("nope.txt")), json!([[false, false, "Script file does not exist"]]));
|
||||
} else {
|
||||
let denied = json!([[false, false, DENIED]]);
|
||||
assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN does not exist");
|
||||
write(&upper.join("secret.txt"), b"secret");
|
||||
assert_eq!(logged(&base, &source("secret.txt")), denied);
|
||||
assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN exists beside main");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn script_file_oversize_refused_before_read() {
|
||||
let base = folder("oversize");
|
||||
|
||||
@@ -7536,3 +7536,42 @@ fn variable_font_instances_name_their_design_space() {
|
||||
fn style_of(size: f64) -> vectorcraft_doc::CharStyle {
|
||||
style(size, Color::BLACK)
|
||||
}
|
||||
|
||||
/// The data has no conic gradient: a conic fill is a linear gradient along its vector, with the
|
||||
/// same stops, and so is a conic gradient swatch, with a warning.
|
||||
#[test]
|
||||
fn conic_gradients_are_written_as_linear_gradients_with_their_stops() {
|
||||
let stops =
|
||||
vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(0.6, SKY), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops.clone()));
|
||||
let (start, end) = (vectorcraft_geom::Point::new(100.0, 50.0), vectorcraft_geom::Point::new(150.0, 50.0));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start, end, aspect: -0.5, focal: None });
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let id = doc.alloc_id();
|
||||
let l = doc.layers[0].id;
|
||||
let fill = Paint::Gradient(Box::new(g.clone()));
|
||||
doc.insert(Some(l), 0, Node::path(id, shapes::rectangle(Rect::new(20.0, 10.0, 180.0, 90.0)), Appearance::basic(fill.clone(), Paint::None, 0.0)))
|
||||
.unwrap();
|
||||
let mut swatches: Vec<Swatch> = doc.swatches.iter().cloned().collect();
|
||||
swatches.push(Swatch { name: "Sweep".into(), paint: Paint::Gradient(Box::new(GradientPaint { geom: None, ..g })), global: false, spot: false });
|
||||
doc.swatches = swatches.into();
|
||||
let out = export_ai_editing(&doc, &opts()).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w.contains("conic gradients are written as linear gradients")), "{:?}", out.warnings);
|
||||
let back = read_back(&doc);
|
||||
let mut read = None;
|
||||
back.walk(|n| {
|
||||
if let Paint::Gradient(g) = n.appearance.fill_paint() {
|
||||
read = Some(g.clone());
|
||||
}
|
||||
});
|
||||
let read = read.expect("a gradient fill");
|
||||
assert_eq!(read.gradient.kind, GradientKind::Linear);
|
||||
assert_eq!(
|
||||
read.gradient.stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::<Vec<_>>(),
|
||||
stops.iter().map(|s| (s.offset, s.color.to_hex())).collect::<Vec<_>>()
|
||||
);
|
||||
let geom = read.geom.unwrap();
|
||||
assert!(geom.start.distance(start) < 0.01 && geom.end.distance(end) < 0.01, "{geom:?}");
|
||||
let Some(Paint::Gradient(swatch)) = back.swatch("Sweep").map(|s| &s.paint) else { panic!("the swatch is lost") };
|
||||
assert_eq!(swatch.gradient.kind, GradientKind::Linear);
|
||||
}
|
||||
@@ -21,6 +21,8 @@ pub(in crate::ai_editing) const SWATCH_PLACEMENT: &str =
|
||||
"the placement of pattern swatches that move, turn or scale their pattern is left out of the editing data for other apps";
|
||||
pub(in crate::ai_editing) const GRADIENT_MIX: &str =
|
||||
"gradients that mix their colors perceptually or dither are written as classic gradients in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const CONIC: &str =
|
||||
"conic gradients are written as linear gradients along their vector, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const STOP_LINKS: &str =
|
||||
"gradient stops linked to global process colors are written as their colors in the editing data for other apps";
|
||||
/// The length of a linear gradient's caps (`Bc`): the canvas's side.
|
||||
@@ -43,8 +45,8 @@ pub(super) struct PatternOut {
|
||||
used: bool,
|
||||
}
|
||||
|
||||
/// Can `g` be written as a gradient (a linear or radial one with stops, no more than the `.ai`
|
||||
/// reader reads)?
|
||||
/// Can `g` be written as a gradient (a linear, radial or conic one with stops, no more than the
|
||||
/// `.ai` reader reads; a conic is written linear, [`CONIC`])?
|
||||
fn writable_gradient(g: &Gradient) -> bool {
|
||||
g.kind != GradientKind::Freeform && !g.stops.is_empty() && g.stops.len() <= crate::import::MAX_GRADIENT_STOPS
|
||||
}
|
||||
@@ -300,6 +302,9 @@ impl Writer<'_> {
|
||||
if d.gradient.dither || !d.gradient.method.is_classic() {
|
||||
self.warn(GRADIENT_MIX);
|
||||
}
|
||||
if d.gradient.kind == GradientKind::Conic {
|
||||
self.warn(CONIC);
|
||||
}
|
||||
let name = ps::bytes(d.name.as_bytes());
|
||||
let radial = d.gradient.kind == GradientKind::Radial;
|
||||
let _ = writeln!(s, "%AI5_BeginGradient: {name}\n{name} {} {} Bd\n[", u8::from(radial), d.gradient.stops.len());
|
||||
|
||||
@@ -55,7 +55,9 @@ pub(super) enum NotOne {
|
||||
/// it applies to, even within a patch; a mesh starts grey. Besides the device spaces it may be a
|
||||
/// named colour, `[c m y k /DeviceCMYK (name) /Process]` (or `/Spot`), or several process or spot
|
||||
/// inks, `[[ink] [ink] … n /NChannel]` (each ink `[c m y k /DeviceCMYK (name) /Separation]`). A
|
||||
/// corner gives a named colour's tint (1 is the full colour), or each ink's in order.
|
||||
/// corner gives a named color's tint (1 is the full color), or each ink's, process and spot inks
|
||||
/// alike, the last ink listed first: under `[[Yellow] [Magenta] [Cyan] 3 /NChannel]`, `[0 0 1 …]`
|
||||
/// is full yellow.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
enum Space {
|
||||
#[default]
|
||||
@@ -113,10 +115,11 @@ impl Space {
|
||||
Space::Cmyk => Color::cmyk(u(0)?, u(1)?, u(2)?, u(3)?),
|
||||
Space::Inks(inks) => match inks.as_slice() {
|
||||
[one] => one.tinted(u(0)?),
|
||||
// Several inks overprint: their CMYK at their tints, added up.
|
||||
// Several inks overprint: their CMYK at their tints, added up. The tints come in
|
||||
// the opposite order to the inks.
|
||||
many => {
|
||||
let mut sum = [0.0f32; 4];
|
||||
for (i, ink) in many.iter().enumerate() {
|
||||
for (i, ink) in many.iter().rev().enumerate() {
|
||||
let Color::Cmyk { c, m, y, k } = *ink else { return None };
|
||||
let t = u(i)?;
|
||||
for (s, v) in sum.iter_mut().zip([c, m, y, k]) {
|
||||
@@ -911,7 +914,8 @@ mod tests {
|
||||
let mut reader = MeshReader::default();
|
||||
square(&mut reader, [&[0.25, 1.0], &[0.0, 0.0], &[1.0, 1.0], &[0.0, 0.0]], [vec![(channels(2.0), "CS")], vec![], vec![], vec![]]);
|
||||
assert!(!reader.unread);
|
||||
assert_color(reader.patches[0].points[0].color, Color::cmyk(0.0, 1.0, 0.25, 0.0));
|
||||
// The tints come last ink first: 0.25 Magenta, 1 Yellow.
|
||||
assert_color(reader.patches[0].points[0].color, Color::cmyk(0.0, 0.25, 1.0, 0.0));
|
||||
assert_color(reader.patches[0].points[3].color, Color::cmyk(0.0, 1.0, 1.0, 0.0));
|
||||
|
||||
// An ink count that doesn't match its inks, or an ink in a space not read.
|
||||
@@ -923,6 +927,51 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `/NChannel` inks take a corner's tints in the opposite order to their listing, whatever
|
||||
/// order the inks are listed in, spot inks included: under Yellow, Magenta, Cyan `0 0 1` is
|
||||
/// full yellow and `1 0.5 0` full cyan with half magenta; under Cyan, Magenta, Yellow `0 0 1`
|
||||
/// is full cyan; under a spot ink and Cyan, `0.5 1` is the full spot ink with half cyan.
|
||||
#[test]
|
||||
fn inks_take_their_tints_last_listed_first() {
|
||||
let ink = |c: [f64; 4], name: &str| {
|
||||
let mut v: Vec<V> = c.iter().map(|x| V::Num(*x)).collect();
|
||||
v.extend([V::Name("DeviceCMYK".into()), V::Str(name.as_bytes().to_vec()), V::Name("Separation".into())]);
|
||||
V::Arr(v)
|
||||
};
|
||||
let channels = |inks: Vec<V>| {
|
||||
let n = inks.len() as f64;
|
||||
let mut a = inks;
|
||||
a.extend([V::Num(n), V::Name("NChannel".into())]);
|
||||
V::Arr(a)
|
||||
};
|
||||
let (yellow, magenta, cyan) = (ink([0.0, 0.0, 1.0, 0.0], "Yellow"), ink([0.0, 1.0, 0.0, 0.0], "Magenta"), ink([1.0, 0.0, 0.0, 0.0], "Cyan"));
|
||||
let rose = ink([0.1, 0.6, 0.4, 0.2], "Rose");
|
||||
// Two corners' tints (then opacity) under the inks, and the colors they give.
|
||||
let check = |inks: Vec<V>, a: &[f64], b: &[f64], want_a: Color, want_b: Color| {
|
||||
let mut reader = MeshReader::default();
|
||||
square(&mut reader, [a, b, a, b], [vec![(channels(inks), "CS")], vec![], vec![], vec![]]);
|
||||
assert!(!reader.unread);
|
||||
let points = &reader.patches[0].points;
|
||||
assert_color(points[0].color, want_a);
|
||||
assert_color(points[2].color, want_b);
|
||||
};
|
||||
check(
|
||||
vec![yellow.clone(), magenta.clone(), cyan.clone()],
|
||||
&[0.0, 0.0, 1.0, 1.0],
|
||||
&[1.0, 0.5, 0.0, 1.0],
|
||||
Color::cmyk(0.0, 0.0, 1.0, 0.0),
|
||||
Color::cmyk(1.0, 0.5, 0.0, 0.0),
|
||||
);
|
||||
check(
|
||||
vec![cyan.clone(), magenta, yellow],
|
||||
&[0.0, 0.0, 1.0, 1.0],
|
||||
&[1.0, 0.5, 0.0, 1.0],
|
||||
Color::cmyk(1.0, 0.0, 0.0, 0.0),
|
||||
Color::cmyk(0.0, 0.5, 1.0, 0.0),
|
||||
);
|
||||
check(vec![rose, cyan], &[0.5, 1.0, 1.0], &[1.0, 0.0, 1.0], Color::cmyk(0.6, 0.6, 0.4, 0.2), Color::cmyk(1.0, 0.0, 0.0, 0.0));
|
||||
}
|
||||
|
||||
/// A corner holding anything but numbers is unread: skipping it would shift the numbers after
|
||||
/// it into its colour and opacity (two inks' tints `0.25 /bad 0.5`, read as `0.25 0.5` and no
|
||||
/// opacity).
|
||||
|
||||
@@ -5796,7 +5796,8 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its
|
||||
|
||||
/// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its
|
||||
/// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope
|
||||
/// mapping from that box (#3179).
|
||||
/// mapping from that box (#3179). The drawn art strokes the bent outlines at the stroke's own weight,
|
||||
/// as files draw it (#6644).
|
||||
#[test]
|
||||
fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does() {
|
||||
use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin};
|
||||
@@ -5816,7 +5817,7 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_
|
||||
vectorcraft_doc::NodeId(1_000_000),
|
||||
NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() },
|
||||
);
|
||||
let (drawn, page) = drawn_envelope(&shaped);
|
||||
let (drawn, page) = drawn_stroked_envelope(&shaped);
|
||||
let art =
|
||||
native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc);
|
||||
let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap();
|
||||
@@ -5833,6 +5834,101 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_
|
||||
assert_eq!(margin, Some(options.bounds_margin));
|
||||
}
|
||||
|
||||
/// The drawn art of `envelope` (on the page axes), an envelope of type stroked by its characters,
|
||||
/// as the drawn art of `.ai` files strokes type in an envelope: the bent glyph outlines the envelope
|
||||
/// draws of its type unstroked, each filled in its type's color, then each stroked with the type's
|
||||
/// stroke (its weight, color, join and miter limit) whatever the grid does to it, and the page's
|
||||
/// PostScript for them (#6644).
|
||||
fn drawn_stroked_envelope(envelope: &Node) -> (String, String) {
|
||||
let NodeKind::Envelope { content, .. } = &envelope.kind else { panic!("an envelope") };
|
||||
let Some(NodeKind::Text(t)) = content.first().map(|c| &c.kind) else { panic!("type") };
|
||||
let stroke = t.runs[0].style.stroke_layer();
|
||||
let mut unstroked = envelope.clone();
|
||||
if let NodeKind::Envelope { content, .. } = &mut unstroked.kind {
|
||||
for c in content.iter_mut() {
|
||||
if let NodeKind::Text(t) = &mut std::sync::Arc::make_mut(c).kind {
|
||||
t.runs.iter_mut().for_each(|r| r.style.stroke = vectorcraft_color::Paint::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (fills, fill_page) = drawn_envelope(&unstroked);
|
||||
let [r, g, b] = stroke.paint.color().map_or([0.0; 3], |c| c.to_rgb());
|
||||
let join = match stroke.join {
|
||||
vectorcraft_doc::LineJoin::Miter => 0,
|
||||
vectorcraft_doc::LineJoin::Round => 1,
|
||||
vectorcraft_doc::LineJoin::Bevel => 2,
|
||||
};
|
||||
let (w, limit) = (stroke.width, stroke.miter_limit);
|
||||
let mut art = format!("{fills}0 0 0 0 {r} {g} {b} XA\n{w} w\n{join} j\n{limit} M\n");
|
||||
let mut page = format!("{fill_page}{r} {g} {b} setrgbcolor {w} setlinewidth {join} setlinejoin {limit} setmiterlimit\n");
|
||||
let pt = |p: kurbo::Point| {
|
||||
let (x, y) = to_art(p);
|
||||
format!("{x} {y}")
|
||||
};
|
||||
vectorcraft_effects::expand_live_deep(None, &unstroked).walk(&mut |n| {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return };
|
||||
for el in path.to_bezpath().elements() {
|
||||
match *el {
|
||||
kurbo::PathEl::MoveTo(p) => {
|
||||
art += &format!("{} m\n", pt(p));
|
||||
page += &format!("newpath {} moveto ", pt(p));
|
||||
}
|
||||
kurbo::PathEl::LineTo(p) => {
|
||||
art += &format!("{} L\n", pt(p));
|
||||
page += &format!("{} lineto ", pt(p));
|
||||
}
|
||||
kurbo::PathEl::CurveTo(a, c, p) => {
|
||||
art += &format!("{} {} {} C\n", pt(a), pt(c), pt(p));
|
||||
page += &format!("{} {} {} curveto ", pt(a), pt(c), pt(p));
|
||||
}
|
||||
kurbo::PathEl::QuadTo(..) => {}
|
||||
kurbo::PathEl::ClosePath => {
|
||||
art += "s\n";
|
||||
page += "closepath stroke\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
(art, page)
|
||||
}
|
||||
|
||||
/// An envelope of type with a character stroke, Distort Appearance on, whose drawn art strokes the
|
||||
/// bent glyph outlines at the stroke's own weight (as `.ai` files draw the strokes of type in an
|
||||
/// envelope, however much the grid squeezes or stretches it) opens live: VectorCraft draws the
|
||||
/// stroke that way too (#6644).
|
||||
#[test]
|
||||
fn an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live() {
|
||||
let Some(family) = installed_family() else { return };
|
||||
// "FLUX" stroked 1.5 points wide in black with round joins.
|
||||
let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /62 1 /63 1.5";
|
||||
let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked);
|
||||
let mut text = made_envelope_type(&doc);
|
||||
text.visible = true;
|
||||
assert!(
|
||||
matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_width == 1.5 && t.runs[0].style.stroke_join == vectorcraft_doc::LineJoin::Round),
|
||||
"{text:?}"
|
||||
);
|
||||
let shaped = Node::new(
|
||||
vectorcraft_doc::NodeId(1_000_000),
|
||||
NodeKind::Envelope {
|
||||
content: vec![std::sync::Arc::new(text)],
|
||||
kind: Box::new(rising_kind()),
|
||||
fidelity: 50.0,
|
||||
editing: false,
|
||||
options: vectorcraft_doc::live::EnvelopeOptions::NEW,
|
||||
frame: Box::default(),
|
||||
},
|
||||
);
|
||||
let (drawn, page) = drawn_stroked_envelope(&shaped);
|
||||
let art =
|
||||
native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc);
|
||||
let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap();
|
||||
assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings);
|
||||
let (envelopes, loose) = envelopes_and_type(&r.document);
|
||||
assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings);
|
||||
assert!(loose.is_empty(), "{loose:?}");
|
||||
}
|
||||
|
||||
/// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its
|
||||
/// type, hidden, with the note, when its own warp draws apart from that art (#3179).
|
||||
#[test]
|
||||
|
||||
@@ -107,6 +107,9 @@ pub const TITLE_AND_COLOR_NAMES: &str =
|
||||
pub const NAMES: &str = "object names are left out (legacy .ai files name only layers)";
|
||||
const PATTERNS: &str = "pattern fills are written as their tiles, clipped to the shape";
|
||||
const FREEFORM: &str = "freeform gradients are written as their average colour";
|
||||
const CONIC: &str = "conic gradients are written as solid wedges clipped to the shape (legacy .ai files have no conic gradient)";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGES: usize = 360;
|
||||
const STROKES: &str =
|
||||
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
|
||||
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
|
||||
|
||||
@@ -201,7 +201,7 @@ pub(super) fn segment_point(path: &BezPath, fraction: f64) -> f64 {
|
||||
pub(super) fn direct_fill(p: &Paint) -> bool {
|
||||
match p {
|
||||
Paint::Solid { .. } => true,
|
||||
Paint::Gradient(g) => g.gradient.kind != GradientKind::Freeform && !g.gradient.stops.is_empty(),
|
||||
Paint::Gradient(g) => !matches!(g.gradient.kind, GradientKind::Freeform | GradientKind::Conic) && !g.gradient.stops.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,6 +83,33 @@ fn write(doc: &Document) -> LegacyAiOutput {
|
||||
write_with(doc, LegacyAiOptions::default())
|
||||
}
|
||||
|
||||
/// The format has no conic gradient: a conic fill, and a conic stroke (written as its filled
|
||||
/// outline), are solid wedges clipped to the shape, with a warning, and print as the canvas
|
||||
/// draws them ([`write`] runs the file).
|
||||
#[test]
|
||||
fn conic_gradients_are_written_as_wedges_clipped_to_the_shape() {
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom {
|
||||
start: vectorcraft_geom::Point::new(100.0, 50.0),
|
||||
end: vectorcraft_geom::Point::new(140.0, 30.0),
|
||||
aspect: -0.7,
|
||||
focal: None,
|
||||
});
|
||||
let conic = Paint::Gradient(Box::new(g));
|
||||
for (fill, stroke) in [(conic.clone(), Paint::None), (Paint::None, conic)] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let n = shape(&mut doc, shapes::ellipse(Rect::new(20.0, 10.0, 180.0, 90.0)), fill.clone(), stroke.clone());
|
||||
let l = doc.layers[0].id;
|
||||
doc.insert(Some(l), 0, n).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(out.warnings.iter().any(|w| w == CONIC), "{:?}", out.warnings);
|
||||
let text = String::from_utf8_lossy(&out.bytes);
|
||||
assert!(!text.contains("%AI5_BeginGradient"), "no gradient stands in");
|
||||
assert!(text.matches("\nf\n").count() >= CONIC_WEDGES, "a wedge a degree");
|
||||
}
|
||||
}
|
||||
|
||||
/// `doc` written with options `o`. Every file the tests write is also run as a PostScript program
|
||||
/// ([`prints_as`]) and must draw what `doc` draws.
|
||||
fn write_with(doc: &Document, o: LegacyAiOptions) -> LegacyAiOutput {
|
||||
@@ -155,7 +182,10 @@ fn as_printed(doc: &Document, o: &LegacyAiOptions) -> Document {
|
||||
AppearanceItem::Fill(f) => &mut f.paint,
|
||||
AppearanceItem::Stroke(s) => &mut s.paint,
|
||||
};
|
||||
if let Paint::Gradient(g) = paint {
|
||||
// Conic gradients are written as wedges, which print.
|
||||
if let Paint::Gradient(g) = paint
|
||||
&& g.gradient.kind != GradientKind::Conic
|
||||
{
|
||||
*paint = g.gradient.stops.first().map_or(Paint::None, |s| Paint::solid(s.color));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use super::{
|
||||
ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind,
|
||||
TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke,
|
||||
};
|
||||
use super::{CONIC, CONIC_WEDGES};
|
||||
|
||||
pub(super) struct Writer<'a> {
|
||||
doc: &'a Document,
|
||||
@@ -423,6 +424,11 @@ impl<'a> Writer<'a> {
|
||||
if direct_fill(&f.paint) {
|
||||
return self.path_object(path, rule, Some(f), None);
|
||||
}
|
||||
if let Paint::Gradient(g) = &f.paint
|
||||
&& g.gradient.kind == GradientKind::Conic
|
||||
{
|
||||
return self.conic_object(path, rule, f, g);
|
||||
}
|
||||
let Paint::Pattern { pattern, xf } = &f.paint else {
|
||||
// A freeform gradient: its average colour.
|
||||
self.warn(FREEFORM);
|
||||
@@ -461,6 +467,36 @@ impl<'a> Writer<'a> {
|
||||
self.line("Q");
|
||||
}
|
||||
|
||||
/// A conic gradient fill (the format has no conic gradient) as [`CONIC_WEDGES`] solid wedges
|
||||
/// about its center clipped to `path` (filled by `rule`), each running on to the seam under
|
||||
/// the next ([`vectorcraft_color::GradientGeom::conic_wedges`]).
|
||||
fn conic_object(&mut self, path: &PathData, rule: FillRule, f: &FillLayer, g: &GradientPaint) {
|
||||
self.warn(CONIC);
|
||||
if g.gradient.stops.iter().any(|s| s.opacity < 1.0) {
|
||||
self.warn(TRANSPARENCY);
|
||||
}
|
||||
let area = path.to_bezpath().bounding_box();
|
||||
let wedges = g.resolve(area).conic_wedges(area, CONIC_WEDGES, true);
|
||||
self.line("q");
|
||||
self.fill_rule(rule);
|
||||
let several = path.subpaths.len() > 1;
|
||||
if several {
|
||||
self.line("*u");
|
||||
}
|
||||
for sp in path.subpaths.iter().filter(|sp| !sp.anchors.is_empty()) {
|
||||
self.mask(sp);
|
||||
}
|
||||
if several {
|
||||
self.line("*U");
|
||||
}
|
||||
for (pts, t) in wedges {
|
||||
let (color, _) = g.gradient.sample_keep_model(t as f32);
|
||||
let wedge = FillLayer { paint: Paint::solid(color), ..f.clone() };
|
||||
self.path_object(&PathData::single(SubPath::polyline(&pts, true)), FillRule::NonZero, Some(&wedge), None);
|
||||
}
|
||||
self.line("Q");
|
||||
}
|
||||
|
||||
/// A path object painted with `fill` (a colour or a linear or radial gradient) and `stroke`
|
||||
/// (a plain line of a colour) over it; several subpaths make a compound path.
|
||||
fn path_object(&mut self, path: &PathData, rule: FillRule, fill: Option<&FillLayer>, stroke: Option<&StrokeLayer>) {
|
||||
|
||||
+27
-2
@@ -42,6 +42,9 @@ const SPOT_GRADIENTS_L2: &str =
|
||||
"gradients mixing a spot color with other inks are written in process colors at PostScript Level 2 (Level 3 keeps the spot inks)";
|
||||
const SPOT_GRADIENTS_SHARED: &str = "gradients whose spot inks can't share a DeviceN color space are written without the spot inks";
|
||||
const SPOT_GRADIENTS_PERCEPTUAL: &str = "Perceptual gradients of spot colors are written in process colors";
|
||||
const CONIC_WEDGES: &str = "conic gradients are written as solid wedges (EPS has no conic shading)";
|
||||
/// Wedges a conic gradient is written as: one a degree.
|
||||
const CONIC_WEDGE_COUNT: usize = 360;
|
||||
/// The most colorants a DeviceN color space may have (PostScript's limit).
|
||||
const MAX_DEVICE_N: usize = 32;
|
||||
const MISSING_PATTERN: &str = "missing patterns are written as mid-grey";
|
||||
@@ -931,8 +934,9 @@ impl<'a> Scene<'a> {
|
||||
(space, out)
|
||||
}
|
||||
|
||||
/// Paint all of `area` (inside the current clip) with linear or radial gradient `g`, placed on
|
||||
/// `bounds`: a smooth shading at Level 3, else stepped fills.
|
||||
/// Paint all of `area` (inside the current clip) with linear, radial or conic gradient `g`,
|
||||
/// placed on `bounds`: a smooth shading at Level 3, else stepped fills (a conic: wedges at
|
||||
/// both levels).
|
||||
fn gradient(&mut self, g: &GradientPaint, bounds: Rect, area: Rect) {
|
||||
let geom = g.resolve(bounds);
|
||||
let (space, stops) = self.gradient_stops(&g.gradient);
|
||||
@@ -946,6 +950,7 @@ impl<'a> Scene<'a> {
|
||||
let space = &space;
|
||||
let smooth = self.o.level == Level::Three && !self.o.compatible_gradients;
|
||||
match g.gradient.kind {
|
||||
GradientKind::Conic => self.conic_steps(&geom, area, space, &stops),
|
||||
GradientKind::Radial => {
|
||||
let r = geom.length().max(1e-6);
|
||||
let squash = geom.radial_squash();
|
||||
@@ -974,6 +979,26 @@ impl<'a> Scene<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A conic gradient as [`CONIC_WEDGE_COUNT`] solid wedges about its center covering `area`
|
||||
/// (PostScript has no conic shading), each running on to the seam under the next, so no
|
||||
/// hairline shows between neighbors ([`vectorcraft_color::GradientGeom::conic_wedges`]).
|
||||
fn conic_steps(&mut self, geom: &vectorcraft_color::GradientGeom, area: Rect, space: &GradientSpace, stops: &[(f64, Vec<f32>)]) {
|
||||
self.warn(CONIC_WEDGES);
|
||||
let at = |t: f64| match stops.windows(2).find(|w| t <= w[1].0) {
|
||||
Some(w) if w[1].0 > w[0].0 => mix(&w[0].1, &w[1].1, ((t - w[0].0) / (w[1].0 - w[0].0)).clamp(0.0, 1.0) as f32),
|
||||
Some(w) => w[1].1.clone(),
|
||||
None => stops.last().map_or_else(Vec::new, |s| s.1.clone()),
|
||||
};
|
||||
for (pts, t) in geom.conic_wedges(area, CONIC_WEDGE_COUNT, true) {
|
||||
self.set_comps(space, &at(t));
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
push_nums(&mut self.body, &[p.x, p.y]);
|
||||
self.line(if i == 0 { "newpath moveto" } else { "lineto" });
|
||||
}
|
||||
self.line("closepath fill");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Level 3 smooth shading of `kind` (2 axial, 3 radial) at `coords`, extended both ways.
|
||||
fn shading(&mut self, kind: u8, space: &GradientSpace, coords: &[f64], stops: &[(f64, Vec<f32>)]) {
|
||||
let n = space.n();
|
||||
|
||||
@@ -189,6 +189,34 @@ fn gradients_are_smooth_shadings_at_level_3_and_stepped_fills_at_level_2() {
|
||||
assert_eq!(dsc(&ps, "LanguageLevel").as_deref(), Some("2"));
|
||||
}
|
||||
|
||||
/// PostScript has no conic shading: a conic is solid wedges about its center at both levels, each
|
||||
/// running on to the seam, and read back from the PostScript it looks as the canvas paints it.
|
||||
#[test]
|
||||
fn conic_gradients_are_solid_wedges_at_both_levels() {
|
||||
let stops = vec![GradientStop::new(0.0, Color::rgb(1.0, 0.0, 0.0)), GradientStop::new(1.0, Color::rgb(0.0, 0.0, 1.0))];
|
||||
for aspect in [1.0, -0.5] {
|
||||
let mut g = GradientPaint::new(Gradient::new(GradientKind::Conic, stops.clone()));
|
||||
g.geom = Some(vectorcraft_color::GradientGeom { start: Point::new(100.0, 70.0), end: Point::new(150.0, 70.0), aspect, focal: None });
|
||||
let paint = Paint::Gradient(Box::new(g));
|
||||
let d = doc_with(|d| vec![path(d, shapes::rectangle(Rect::new(20.0, 20.0, 180.0, 120.0)), paint, Paint::None, 0.0)]);
|
||||
for o in [opts(&d), EpsOptions { level: Level::Two, ..opts(&d) }] {
|
||||
let out = export(&d, &o, None, None).unwrap();
|
||||
assert!(out.warnings.iter().any(|w| w.contains("conic gradients are written as solid wedges")), "{:?}", out.warnings);
|
||||
let page = page_of(&d, &o);
|
||||
assert!(!page.contains("shfill"), "no shading stands in");
|
||||
assert_eq!(page.matches("closepath fill").count(), 360, "a wedge a degree");
|
||||
}
|
||||
let out = export(&d, &opts(&d), None, None).unwrap();
|
||||
let back = import_with(&out.bytes, false).unwrap().document;
|
||||
vectorcraft_testkit::raster::assert_similar(
|
||||
&vectorcraft_testkit::raster::render_artboard(&d),
|
||||
&vectorcraft_testkit::raster::render_artboard(&back),
|
||||
8.0,
|
||||
0.01,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strokes_keep_their_caps_joins_and_dashes() {
|
||||
let d = doc_with(|d| {
|
||||
|
||||
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user